Skip to content

Commit c928f91

Browse files
committed
add INA219 Bidirectional Current/Power Monitor
1 parent ae139fe commit c928f91

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

‎sensor/INA219/README.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# INA219
2+
3+
Zerø-Drift, Bidirectional Current/Power Monitor With I2C Interface.
4+
5+
![](ina219.jpg)
6+
7+
8+
9+
## description
10+
11+
Calibration Register must be written in order to read the current value. Default Calibration Register value is 4096, which has a significant error and needs to be calibrated according to the actual circuit.
12+
13+
14+
## uasge
15+
16+
```
17+
from machine import Pin, SoftI2C
18+
import ina219
19+
20+
# please modify scl/sda to the actual pins.
21+
i2c = SoftI2C(scl=Pin(pins.pin_SCL), sda=Pin(pins.pin_SDA))
22+
23+
ina = ina219.INA219(i2c)
24+
ina.calreg(3450)
25+
26+
v = ina.volt()
27+
c = ina.current()
28+
p = ina.power()
29+
30+
```
31+
32+
From microbit/micropython Chinese community.
33+
www.micropython.org.cn

‎sensor/INA219/ina219.jpg‎

77 KB
Loading

‎sensor/INA219/ina219.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
mpy drive for INA219 Bidirectional Current/Power Monitor
3+
4+
Author: shaoziyang
5+
Date: 2024.5
6+
7+
http://www.micropython.org.cn
8+
9+
'''
10+
from micropython import const
11+
12+
INA219_ADDR = const(64)
13+
14+
class INA219():
15+
def __init__(self, i2c):
16+
self.i2c = i2c
17+
self.rb = bytearray(2)
18+
self.tb = bytearray(2)
19+
self.setreg(0, 0x8000) # reset
20+
self.setreg(0, 0x3fff)
21+
self.calreg(4096) # default Calibration Register
22+
23+
def setreg(self, reg, dat):
24+
self.tb[0] = dat//256
25+
self.tb[1] = dat
26+
self.i2c.writeto_mem(INA219_ADDR, reg, self.tb)
27+
28+
def getreg(self, reg):
29+
self.i2c.readfrom_mem_into(INA219_ADDR, reg, self.rb)
30+
return self.rb[0]*256+self.rb[1]
31+
32+
def calreg(self, value=None):
33+
if value == None:
34+
return self.getreg(5)
35+
else:
36+
self.setreg(5, value)
37+
38+
def volt(self):
39+
return self.getreg(2)/2000
40+
41+
def current(self):
42+
return self.getreg(4)/10000
43+
44+
def power(self):
45+
return self.getreg(3)/500
46+

0 commit comments

Comments
 (0)