CREATE : SENSING : Measuring Current
Texas Instruments make a variety of low-cost, I2C-based current sensors. In this example, I will show you how to interface a Scamp to an INA219 current sensor (datasheet). A number of low-cost modules used on this chip are available. The design is very straightforward (see the datasheet for a schematic). Wire VCC to the Scamp's 3V3, GND to GND, SDA to SDA and SCL to SCL.
Power up your Scamp and enter modules at the prompt. You should see your sensor module in the list.
Power up your Scamp and enter modules at the prompt. You should see your sensor module in the list.
The following words provide the interface to the INA219:
\ INA219 current sensor driver
\ Default I2C address $40 (A0=A1=GND)
\ Assumes 0.1 Ohm shunt (standard on breakout modules)
\ 2A max range
$40 constant INA219 \ sensor address
\ Write 16-bit value to register
: ina219! ( val reg -- )
start
INA219 write drop
send drop \ register pointer
dup 8 rshift $ff and send \ high byte
drop
$ff and send \ low byte
drop
stop ;
\ Read 16-bit value from register
: ina219@ ( reg -- val )
start
INA219 write drop
send drop \ register pointer
repstart
INA219 read
drop
receive ack \ high byte
receive nack \ low byte
stop
swap
8 lshift or ; \ combine to 16-bit value
\ Calibration for 0.1R shunt, 2A max range
\ Cal = 0.04096 / (0.0001 * 0.1) = 4096 = $1000
\ Current LSB = 100uA per bit
: ina219-init ( -- )
$1000 $05 ina219! ;
\ Read current register (signed 16-bit, 100uA per bit)
: ina219-raw ( -- n )
$04 ina219@
;
\ Read current in milliamps
: current ( -- n )
ina219-raw 5 + 10 / ;