/* Title: attiny_i2c_master.ino Author: Lucas Lim Date Created: 29/04/2019 Last Modified: 29/04/2019 Purpose: MASTER receive 'instruction' from PC via serial port (Tx, Rx) MASTER reply acknoledge message back to PC If instruction is to Slave 1/2, MASTER re-route to addressed Slave 1/2 via I2C bus Instruction : '0' MASTER will Blink LED '1' Slave 1 will blink LED '2' Slave 2 will blink LED NOTE! - It is important to use pullups on the SDA & SCL lines on the I2C bas! */ #include #include #define slave1 (1) #define slave2 (2) const int ledPin = 1; //PB1 - Arduino Pin No. 1 const int tx = 3; //PB3 - Arduino Pin No. 3 const int rx = 4; //PB4 - Arduino Pin No. 4 int times = 3; //Number of times that LED will blink SoftwareSerial mySerial(rx, tx); void setup() { // set the data rate for the SoftwareSerial port mySerial.begin(9600); mySerial.println(""); // initialize the led pin as an output. pinMode(ledPin, OUTPUT); // join I2C bas as MASTER TinyWireM.begin(); } void process_incoming_command(char cmd) // Received user command from host PC via Software Serial { switch (cmd) { case '0': // MASTER to blink led blink_led(times); break; case '1': // Slave 1 to blink led TinyWireM.beginTransmission(slave1); TinyWireM.send(times); TinyWireM.endTransmission(); break; case '2': // Slave 2 to blink led TinyWireM.beginTransmission(slave2); TinyWireM.send(times); TinyWireM.endTransmission(); break; } } void blink_led(int times) { while(times--) { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); // for debugging //mySerial.print("Blink times : "); //mySerial.println(times); } } void loop() { // don't read unless there is data, Serial.available() > 0 if(mySerial.available()) { char cmd = mySerial.read(); //User to type '0' for Master, '1' for Slave 1 and '2' for Slave 2" mySerial.print("You typed : "); mySerial.println(cmd); process_incoming_command(cmd); } delay(50); //limit how fast the serial check/update }