Hardware Reference
In-Depth Information
Listing 6-8. I2C Simulated Sensor Code
byte address = 112; // address of this sensor
unsigned int manipVar = 0; // variable to change data
byte bytessent = 2 ; // number of bytes to send
byte bytestosend[2] ; // prepare data to send
byte command = 0 ; // command storage
void setup() {
TWAR = (address << 1) | 0b00000001; // set address and general call response
TWCR = 0b01000101; // set TWEA TWEN and TWIE to 1
SREG |= 0b10000000; // enable global interrupt
pinMode(13 , OUTPUT);
} //end void setup()
void loop() {
if (command == 0x50){ // turn ON LED to a command 0x50
digitalWrite (13 , HIGH);
}
if (command == 0x02){ // turn OFF LED to a command 0x02
digitalWrite (13 , LOW);
}
manipVar++; // main variable to manipulate outdata two bytes
bytestosend [0] = manipVar; // prepare manipVar in to HI and LOW bytes
bytestosend [1] = manipVar >> 8 ; // manipVar HI
delay (250); // something else to do while wating
} // end void loop()
ISR (TWI_vect){ // interrupt service routine set to vector
if (TWCR & (1 << TWINT)) { // double-check for proper interrupt
if ((TWSR & 0b11111000) == 0x80){ // incoming data
command = TWDR; // copy command data for future use
TWCR = 0b11000100; // reset back to original config
}
if ((TWSR & 0b11111000) == 0xA8 ) { // request for outgoing data
while (bytessent > 0 ){ // send bytes to master
bytessent--;
TWDR = bytestosend [bytessent]; // send data from HI to LOW byte
TWCR = 0b11000101; // reset for each send
delay (5); // pause a moment on send
}
if (bytessent == 0 ){ // reset byte count check to see if empty
bytessent = 2;
}
} // end if ((TWSR & 0b11111000) == 0xA8 )
TWCR = 0b11000101; // one last reset to make sure
SREG |= 0b10000000; // reenable interrupt
} // end if (TWCR & (1 << TWINT))
} // end ISR (TWI_vect)
 
Search WWH ::




Custom Search