I2C Master Slave I/O
Introduction
This tutorial guides you through setting up I2C communication between a master and a slave device using a NEXTuino. The master reads analog and digital inputs and sends data to the slave; the slave responds with data that controls outputs on the master.
Prerequisites
- Installed Arduino IDE
- NEXTuino board (MINI, MAXI, or MEGA)
- Basic understanding of I2C communication and pin setup
The I2C connection uses the SDA and SCL pins on the X1 connector (same pins for MINI, MAXI and MEGA).
Example Code
Step-by-Step Guide
Step 1: Setup the Arduino Environment
- Connect your NEXTuino board to your computer
- Open the Arduino IDE and select the correct board and port
- Include the Wire and NEXTuino libraries
Step 2: Initialize I2C Communication
In setup():
- Initialize I2C as master:
Wire.begin() - Initialize serial for debugging:
Serial.begin(9600)
Step 3: Configure Digital and Analog Pins
- Digital Inputs:
NEXTuino_D0toNEXTuino_D4as inputs - Relay Outputs:
NEXTuino_R0toNEXTuino_R4as outputs - Analog Inputs:
NEXTuino_A0andNEXTuino_A1 - PWM Outputs: same pins configured as outputs
Step 4: Sending Data to the Slave
In loop():
- Begin transmission:
Wire.beginTransmission(slaveAddress) - Read analog inputs, split each 10-bit value into two bytes, send with
Wire.write() - Read digital input states, pack into one byte using bitwise ops, send with
Wire.write()
Step 5: Receiving Data from the Slave
- End transmission:
Wire.endTransmission() - Request data:
Wire.requestFrom(slaveAddress, 5) - Read digital output states byte, update output pins
- Combine two bytes into integer for analog data, set PWM outputs
Step 6: Slave Setup
The slave initializes with a specific I2C address: Wire.begin(8) (must match master’s slaveAddress).
Pin configuration mirrors the master.
Step 7: Slave Receive Handler (receiveEvent)
When master sends data:
- Reconstruct analog values from two bytes each
- Write values to PWM output pins
- Read digital output states byte and set output pins with
digitalWrite()
Step 8: Slave Request Handler (requestEvent)
When master requests data:
- Read analog inputs, split into two bytes
- Read digital inputs, pack into one byte
- Send all bytes back with
Wire.write()
Troubleshooting
- Ensure slave I2C address matches
slaveAddressin master code - Check SDA and SCL wiring between master and slave
- Verify correct board and port in Arduino IDE
Conclusion
You have established I2C communication between a NEXTuino master and slave. The master reads analog and digital inputs and controls outputs based on data received from the slave, enabling synchronized bidirectional control between two devices.