Native bindings for i2c-dev. Plays well with Raspberry Pi and BeagleBone.
npm install i2cRequires Node.js >= 18 and a Linux system with I2C support. The native addon uses Node-API for ABI stability across Node.js versions — no recompilation needed when upgrading Node.js.
constI2C=require('i2c');constaddress=0x18;constwire=newI2C(address,{device: '/dev/i2c-1'});wire.on('open',()=>{// device is readywire.scan((err,data)=>{// data contains an array of detected device addresses});wire.writeByte(byte,(err)=>{});wire.writeBytes(command,[byte0,byte1],(err)=>{});wire.readByte((err,res)=>{// res is a single byte});wire.readBytes(command,length,(err,res)=>{// res contains a buffer of bytes});// plain read/writewire.write([byte0,byte1],(err)=>{});wire.read(length,(err,res)=>{// res contains a buffer of bytes});// continuous streamingwire.on('data',(data)=>{// data contains: { address, data, cmd, length, timestamp }});wire.stream(command,length,delay);// delay in ms (default: 100)wire.stopStream();// stop streaming});Enable I2C on Raspberry Pi OS:
sudo raspi-configNavigate to Interface Options > I2C and select Yes to enable.
Alternatively, enable manually:
sudo dtparam i2c_arm=on
sudo modprobe i2c-devTo load i2c-dev automatically on boot, add it to /etc/modules-load.d/:
echo"i2c-dev"| sudo tee /etc/modules-load.d/i2c.confVerify the I2C bus is available:
ls /dev/i2c-*Install I2C tools for debugging:
sudo apt install i2c-tools
i2cdetect -y 1By default, the I2C device requires root access. To allow non-root users, add your user to the i2c group:
sudo usermod -aG i2c $USERLog out and back in for the group change to take effect.
The default device path is /dev/i2c-1, which is correct for most Raspberry Pi models (2 and later). For the original Raspberry Pi (rev 1), use /dev/i2c-0:
newI2C(address,{device: '/dev/i2c-0'});// RPi rev 1newI2C(address,{device: '/dev/i2c-1'});// RPi 2+ (default)I2C is enabled by default on BeagleBone. Install Node.js and the package:
npm install i2cThe I2C buses are available at /dev/i2c-0, /dev/i2c-1, and /dev/i2c-2 depending on your BeagleBone variant. Use i2cdetect to verify:
i2cdetect -l- bonescript — Physical computing library for BeagleBone (GitHub)
- mpu6050 — MPU-6050 accelerometer/gyroscope (GitHub)
- adxl345 — ADXL345 accelerometer (GitHub)
- mcp3424 — MCP3424 ADC (GitHub)
- blinkm — BlinkM LED controller (GitHub)
Thanks to @alphacharlie, @J-Cat, and all contributors.