Hi all,
I'm trying to setup I2C communication between 2 Arduino's, but I'm having some difficulties.
The code for Arduino A (Arduino A listens now for incoming I2C messages) looks like this:
#include <Wire.h>
// Define I2C addresses
#define LocalAddress 0x8
#define RemoteAddress 0x9
// Define I2C variables
#define BUF_LEN 128
#define TERM_CHAR '\n'
int i;
byte incomingChar;
char buf[BUF_LEN];
// Define Serial variables
#define SERIAL_BUFFER_SIZE 25
#define SERIAL_DELIMITER ','
char SerialBuffer[SERIAL_BUFFER_SIZE];
char strValue[SERIAL_BUFFER_SIZE + 1]; // add one for the terminating null
void setup() {
Serial.begin(9600);
Wire.begin(LocalAddress);
Wire.onReceive(receiveEvent);
}
void loop() {
}
void receiveEvent(int howMany){
//clean buffer
memset(buf,'\0',BUF_LEN); i = 0;
// read incoming message
while(Wire.available()){
incomingChar = Wire.receive();
if(incomingChar != TERM_CHAR && i != BUF_LEN)
buf[i++] = incomingChar;
else
break;
}
char* arg1 = subStr(buf, ",", 1);
char* arg2 = subStr(buf, ",", 2);
Serial.print(buf);
Serial.print(" got: ");
Serial.print(arg1);
Serial.print(" and ");
Serial.println(arg2);
}
char* subStr (char* str, char *delim, int index) {
char *act, *sub, *ptr;
static char copy[SERIAL_BUFFER_SIZE];
int i;
strcpy(copy, str);
for (i = 1, act = copy; i <= index; i++, act = NULL) {
//Serial.print(".");
sub = strtok_r(act, delim, &ptr);
if (sub == NULL) break;
}
return sub;
}
Arduino B code: (reads an analog input and sends it over I2C to Arduino A every 2 secs)
#include <Wire.h>
// Define I2C addresses
#define LocalAddress 0x9
#define RemoteAddress 0x8
// Define I2C variables
#define BUF_LEN 128
#define TERM_CHAR '\n'
int i;
char incomingChar, buf[BUF_LEN];
// Define sensor
const int analogInPin = 3;
int sensorValue = 0;
int outputValue = 0;
//Define timings
unsigned long previousMillis;
unsigned long interval = 2000;
void setup() {
Serial.begin(9600);
Wire.begin(LocalAddress);
}
void loop() {
if (millis() - previousMillis > interval) {
previousMillis = millis();
printReading();
}
}
void printReading(){
Wire.beginTransmission(RemoteAddress);
sensorValue = analogRead(analogInPin);
outputValue = map(sensorValue, 0, 1023, 0, 255);
// Only for debugging
Serial.print(sensorValue);
Serial.print(",");
Serial.print(outputValue);
Serial.print("\n");
Wire.send(sensorValue);
Wire.send(",");
Wire.send(outputValue);
Wire.send("\n");
Wire.endTransmission();
}
Now the problem is that i only get strange characters on Arduino A's serial monitor. Could somebody please have a look and tell me where i made a mistake?
Output on Arduino B serial: 844,211
Output on Arduino A serial: ), got: ) and J
Thanks in advance,
EriSan500