-
Notifications
You must be signed in to change notification settings - Fork 7
/
i2c.nim
50 lines (41 loc) · 1.08 KB
/
i2c.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import teensy
type I2C* = object
const I2CBus* = I2C()
proc init*(bus: static[I2c]) =
# SCL frequence = CPU frequency / (16 + (2 * TWBR * prescaler))
# TWBR = (cpu / scl - 16) / 2
twsr = 0x00
twbr = 0x0C
twcr.set twen, twint
proc start*(_: static[I2c]) =
twcr.set twen, twint, twsta
while not twcr.check twint: discard
proc stop*(_: static[I2c]) {.noinline.} =
twcr.set twen, twint, twsto
delayUs(100)
proc send*(_: static[I2c], data: uint8) =
twdr = data
twcr.set twen, twint
while not twcr.check twint: discard
proc recv*(_: static[I2c], ack: static[bool]): uint8 =
when ack:
twcr.set twen, twint, twea
else:
twcr.set twen, twint
while not twcr.check twint: discard
return twdr
proc writeRegister*(bus: static[I2c], address, register, data: uint8) =
bus.start()
bus.send(address)
bus.send(register)
bus.send(data)
bus.stop()
proc readRegister*(bus: static[I2c], address, register: uint8): uint8 =
bus.start()
bus.send(address)
bus.send(register)
bus.stop()
bus.start()
bus.send(address or 0x01)
result = bus.recv(false)
bus.stop()