Hello,
I hope I posted this in the right place.
I have made an I2C connection between an Arduino Uno and an ATMEGA328 working on a breadboard.
I want to send from slave device (ATMEGA328) an unsigned long value to the master (Arduino).
The slave code:
#include <Wire.h>
unsigned long MotPos=0;
unsigned long TimeLimit=1000;
unsigned int time;
unsigned long* MotorPosition = new unsigned long[1];
char* MotorPositionBytes=(char*)MotorPosition;
void setup()
{
Wire.begin(7);
Wire.onRequest(sendRequestedMotorPosition);
}
void loop()
{
time=millis();
if (time>=TimeLimit)
{
*MotorPosition=MotPos;
MotPos++;
TimeLimit=time+1000;
}
}
void sendRequestedMotorPosition()
{
Wire.write(MotorPositionBytes, 4);
}
Master code:
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
unsigned long DECPosition;
Wire.requestFrom(7, 4); // request 4 bytes from slave device #7
if (Wire.available()==4)
{
//Recompose the unsigned long from 4 bytes
DECPosition = (unsigned long) Wire.read();
DECPosition = DECPosition | ((unsigned long) Wire.read() <<8 ) ;
DECPosition = DECPosition | ((unsigned long) Wire.read() << 16);
DECPosition = DECPosition | ((unsigned long) Wire.read() << 24);
Serial.println(DECPosition);
}
else
{
//transmision error
}
delay(500);
}
The connection is working but only for 50-100 requests from the master. After that the transmitted number is wrong. In serial monitor I get something like this:
350, 351, 351, 352, 352, 353, 353, 6536, 22884, 22884, 22885, 22885, 22886, 22886, 22887
I can't figure what is going wrong.