TWI on the Arduino Mini
From Code Lab Wiki
[edit] TWI on the Arduino Mini
TWI (I2C) on the Mini requires a little setup. I used this tutorial. Basically, you just delete a couple of object files and modify a header.
TWI is described in the ATmega168 dataseheet.
Here's the little test program I wrote to test out TWI. It works.
/*
* TWI Test
* ES
* 05 April 2008
*
* Trying to get TWI to work. Setup - two arduino minis, one ID6 and one ID7.
* The same code (with a different hard-coded ID) runs on both minis.
* ID6 has a pot attached to pin2, and ID7 has a LED attached to pin13. ID6 sends the pot
* value over TWI to ID7, which receives it and blinks the LED at a corresponding rate.
*
*/
#include <Wire.h>
int nodeID = 6; // set the unique ID of the node
int potPin = 2; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int val = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
Wire.begin(nodeID); // join i2c bus (address optional for master)
Wire.onReceive(receiveEvent); // register event
}
void loop() {
if (nodeID == 6) {
val = analogRead(potPin); // read the value from the sensor
val = val / 4; // analogRead gives us 0-1023, we only want 1 byte
Wire.beginTransmission(7); // transmit to device #4
Wire.send(val); // sends one byte
Wire.endTransmission(); // stop transmitting
}
if (nodeID == 7) {
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(val); // stop the program for some time
digitalWrite(ledPin, LOW); // turn the ledPin off
delay(val); // stop the program for some time
}
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
val = Wire.receive();
}
