Someone asked me the other day if it was possible to have a ‘chat’ between Arduinos using the I2C Wire library. I came up with ‘proof of concept’ code called ‘I2C Wire Chat Between Two Arduinos’. Here is the sketch: I2C Wire Chat Between Two Arduinos
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
/* I2C wire chat From: earl@microcontrollerelectronics.com Analog Pin 5 SCL Analog Pin 4 SDA Common ground */ #include <Wire.h> #define WireDevice 8 String buffer; int mode; void setup() { Serial.begin(9600); } void loop() { while (Serial.available()) { char c = Serial.read(); if (c != '\n') { if (c == '\r') continue; buffer += c; continue; } else { buffer += '\0'; if (buffer[0] == '#') { if (buffer[1] == 'm') { if (mode != 'm') { mode = 'm'; master(); Serial.println("Master mode"); } } if (buffer[1] == 's') { if (mode != 's') { mode = 's'; slave(); Serial.println("Slave mode"); } } buffer = ""; continue; } if (mode == 'm') { Wire.beginTransmission(WireDevice); int i = 0; while (buffer[i]) { Wire.write(buffer[i]); i +=1; } Wire.endTransmission(); } else Serial.println("Invalid Mode"); buffer = ""; } } } void master() { Wire.begin(); Serial.println("Master Initialized"); } void slave() { Wire.begin(8); Wire.onReceive(receiveEvent); Serial.println("Slave Initialized"); } void receiveEvent(int howMany) { while (1 < Wire.available()) { char c = Wire.read(); Serial.print(c); } char c = Wire.read(); Serial.println(c); } |
Setup two Arduinos connected by a length of …
Recent Comments