Hi everyone, I interfacing Arduino Mega and Arduino Uno through I2C protocol. Doing this thing, My Arduino Mega act as Master and Arduino Uno act as Slave.
In master I am giving array of integer data via Serial monitor that data send to Slave arduino and display the Output of integer data in Slave Serial monitor. I have a doubt in this, My data will not be displayed on slave serial monitor.
Can anybody providing a guidance for me. How to sent array of data from master to slave via i2c.
Below I attached my program,
Master program,
//Master transmit integer data into slave
#include <Wire.h>
int a[5],i;
void setup() {
// put your setup code here, to run once:
Wire.begin();
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for(i=0;i<5;i++){
while(Serial.available()==0){
}
a[i]=Serial.parseInt();
Wire.beginTransmission(8);
Wire.write(a[i]);
Wire.endTransmission();
}
Serial.println(".......END.....");
}
Slave program,
#include <Wire.h>
//
int b[10],j=0;
//Slave read integer data from master
void setup() {
// put your setup code here, to run once:
Wire.begin(8);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
}
void receiveEvent(int data){
while(Wire.available()!=0){
b[j]=Wire.read();
Serial.println(b[j]);
j++;
}
}
Start with something simple. For example sending a byte with a certain value.
Do not use the Serial functions inside the receiveEvent(). Use the Serial functions in the loop().
When a variable is used in both the interrupt function and in the loop(), add the "volatile" keyword to it.
Did you connect the GNDs ?
How long are the wires ? Don't use a flat ribbon cable for SDA and SCL.
When you have doubts if the I2C bus is working at all, start the Slave mode in the Slave and run a I2C Scanner in the Master. For the Slave mode, a "Wire.begin ( 8 )" is enough.
you should first have a look at Serial Input Basics to properly acquire your number in the Serial Console. what you do is likely to work most of the time but is not the best way
now - assuming it worked and you have done correctly youra[i]=Serial.parseInt();what you have in your array at index i is a int = 2 bytes. but you send it usingWire.write(a[i]);and if you look at the documentation for Wire.write(), you'll see that you are actually requesting to only send 1 byte.
You should send it usingWire.write(a[i], sizeof(int));
Now the challenge is on the receiving end. You receive byte by byte, and you need to rebuild an int on 2 bytes - so your code there is not what it needs to be.
To start playing I would suggest you use bytes instead of int for sending data and validate that your hardware setup is correct (including joining grounds)
sterretje:
Wire.write sends a byte, not an int (which is two bytes).
Does Wire.write(datByte) function really transmit (send) the dataByte over the I2C Bus or store the dataByte in a local buffer? The actual transmission begins byte-by-byte starting from ControlByte (slaveAddress + R-W/ bit) under handshaking when the Wire.endTransmission() is executed?
If your master spits out the bytes even slightly more slowly than the slave reads them, this loop will exit early. Like "is there any more data", "nope, no more data", "ok, thks bai", "wait! wait! I got another byte!", "oops, too late, I am already gone LOL!".
If your master spits out the bytes even slightly more slowly than the slave reads them, this loop will exit early. Like "is there any more data", "nope, no more data", "ok, thks bai", "wait! wait! I got another byte!", "oops, too late, I am already gone LOL!".
How can it happen?
The I2C based data transmission between Master and Slave occurs byte-by-byte on handshaking and interrupt basis. The Slave has already received the data (a number of bytes) from the Master and has saved them in a local FIFO type invisible buffer. The user goes to the void onReceive(int howmany) subrouine and comfortably read those data bytes from the unseen FIFO buffer and save them into the visible buffer byte b[n].
The I2C based data transmission between Master and Slave occurs byte-by-byte on handshaking and interrupt basis. The Slave has already received the data (a number of bytes) from the Master and has saved them in a local FIFO type invisible buffer. The user goes to the void onReceive(int howmany) subrouine and comfortably read those data bytes from the unseen FIFO buffer and save them into the visible buffer byte b[n].
What happens if the « unseen FIFO buffer« is full?
J-M-L:
What happens if the « unseen FIFO buffer« is full?
The programmer is expected to know that the FIFO Buffer is only 32-byte. Therefore, only 32-byte data is expected to be transmitted in one GO to avoid buffer overflow.
GolamMostafa:
The programmer is expected to know that the FIFO Buffer is only 32-byte. Therefore, only 32-byte data is expected to be transmitted in one GO to avoid buffer overflow.
actually the sender would get a NAK at the 33rd byte
J-M-L:
actually the sender would get a NAK at the 33rd byte
If we go into data exchange session using register level instructions, the FIFO Buffer is not an issue here; we can exchange any amount of data bytes bounded by available RAM memory. To stop the Master for sending the next data byte to the active Slave (another UNO), we de-activate the TWEA-bit (TWI Enable Acknowledge Bit) of the TWCR Register of the Slave. After receiving the last data byte from the Master, the Slave looks at its counter and accordingly writes LL at the TWEA-bit which in turn generates the NAK signal (no generation of ACK signal). The Master sees no ACK signal on the SDA line and it automatically stops the execution of TWDR = dataByte instruction.
Is there any possibility to receive input from user via serial monitor (Master) for int data and store it in array. The array value will display in (Slave) serial monitor. The transmission is made via I2c protocol.
Ganesh2807:
Is there any possibility to receive input from user via serial monitor (Master) for int data and store it in array. The array value will display in (Slave) serial monitor. The transmission is made via I2c protocol.
Ganesh2807:
Is there any possibility to receive input from user via serial monitor (Master) for int data and store it in array. The array value will display in (Slave) serial monitor. The transmission is made via I2c protocol.
Do you want to mean the following:
1. In the InputBox of the Serial Monitor, you want to enter 1234 (say) and click on the send button with carriage return enabled?
2. The UNO will receive the decimal data of Step-1 and will save its equivalent hex form in an integer type variable or into two byte-oriented locations of an array?
3. The Master will send the data of Step-3 to the Slave using I2C Bus?
In the InputBox of the Serial Monitor, you want to enter 1234 (say) and click on the send button with carriage return enabled?
The UNO will receive the decimal data of Step-1 and will save its equivalent hex form in an integer type variable or into two byte-oriented locations of an array?
The Master will send the data of Step-3 to the Slave using I2C Bus?
@GolamMostafa, yeah exactly. As I provide my program in #1. Kindly check this out.
Hi everyone, I have a doubt in my Slave serial monitor. I given float value in Master arduino board (Arduino Mega) the float is converted into byte and send the byte value to Slave device (Arduino Uno) but I did not get any value from serial monitor of Slave.
Below I attached my program, can anybody providing a solution for this problem,
Master program,
#include <Wire.h>
typedef union{
float v;
int32_t as_int;
byte b[sizeof(float)];
}cracked_float_t;
cracked_float_t floatValue;
void setup() {
// put your setup code here, to run once:
Wire.begin();
Serial.begin(9600);
/*Serial.println("Enter the float value in serial tab:");
while(Serial.available()==0){
}*/
floatValue.v=263.3;
//Serial.print("The given float value is =");
//Serial.println(floatValue.v);
Wire.beginTransmission(8);
Wire.write(floatValue.b[3]);
Wire.write(floatValue.b[2]);
Wire.write(floatValue.b[1]);
Wire.write(floatValue.b[0]);
Wire.endTransmission();
}
void loop() {
// put your main code here, to run repeatedly:
}
Slave program is,
#include <Wire.h>
byte dataArray[4];
int j;
void setup() {
// put your setup code here, to run once:
Wire.begin(8);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
}
void receiveEvent(int howmany){
while(1<Wire.available()){
for(j=howmany-1; j>=0; j--){
dataArray[j]=Wire.read();
Serial.print(dataArray[j]);
}
}
}
I dug an old program for you... I just added the array management to match your case. See if you get what it does:
Arduino MEGA / MASTER
// ARDUINO UNO SLAVE
// ARDUINO MEGA MASTER
// CONNECT UNO A4 to MEGA 20 (SDA)
// CONNECT UNO A5 to MEGA 21 (SCL)
// CONNECT UNO GND to MEGA GND
#include <errno.h>
#include <Wire.h>
const byte slaveAddress = 0x8;
const byte maxMessageSize = 50;
char message[maxMessageSize + 1]; // +1 as we want to have a trailing '\0'
const char endMarker = '\n';
const byte maxData = 10;
long userInput[maxData];
byte currentData = 0;
boolean receiveMessage()
{
static byte indexMessage = 0; // static pour se souvenir de cette variable entre 2 appels consécutifs. initialisée qu'une seule fois.
boolean messageComplete = false;
while (Serial.available() && (!messageComplete)) {
int c = Serial.read();
if (c != -1) {
switch (c) {
case endMarker:
message[indexMessage] = '\0'; // ends the c-string
indexMessage = 0; // get ready for next time
messageComplete = true; // set flag
break;
default:
if (indexMessage <= maxMessageSize - 1) {
if ((char) c != '\r') message[indexMessage++] = (char) c; // store input and get to next char
} else {
Serial.println(F("BUFFER FULL - CHAR IGNORED"));
}
break;
}
}
}
return messageComplete;
}
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(115200);
Serial.println(F("\n--------------------------------"));
Serial.println(F("Type"));
Serial.println(F("P\t\t for (P)rinting the List"));
Serial.println(F("R\t\t for (R)eseting the list"));
Serial.println(F("or numbers to add to the list"));
Serial.println(F("--------------------------------\n"));
}
void loop() {
if (receiveMessage()) {
char * startPtr = message;
char * nextPtr = NULL;
switch (message[0]) {
case 'R': // reset list
currentData = 0;
Serial.println(F("\n(R)eset of the list"));
break;
case 'P': // print list
Serial.println(F("\n(P)rinting List"));
for (byte i = 0; i < currentData; i++) {
Serial.print(i);
Serial.print('\t');
Serial.println(userInput[i]);
}
Serial.println();
break;
default: // add to the list
do {
if (currentData < maxData) {
errno = 0; // to catch a possible error in strtol()
long value = strtol (startPtr, &nextPtr, 10); // http://www.cplusplus.com/reference/cstdlib/strtol/
if ((errno != ERANGE) && (nextPtr != startPtr)) { // if the pointer did not move the entry is not a number
userInput[currentData] = value;
Serial.print(F("Sending: "));
Serial.println(userInput[currentData]);
Wire.beginTransmission(slaveAddress); // start transmit to slave
Wire.write((byte *) & (userInput[currentData]), sizeof(userInput[currentData]));
Wire.endTransmission(); // end of data, start transmitting
currentData++;
startPtr = nextPtr;
} else {
Serial.print(startPtr);
if (errno == ERANGE) Serial.println(F(" => Entry does not fit in a long. ABORT"));
else Serial.println(F(" => Entry is not a number. ABORT"));
break;
}
} else {
Serial.println(F("ARRAY FULL. ABORT"));
break;
}
} while (*nextPtr != '\0');
break;
}
}
}
ARDUINO UNO / SLAVE
// ARDUINO UNO SLAVE
// ARDUINO MEGA MASTER
// CONNECT UNO A4 to MEGA 20 (SDA)
// CONNECT UNO A5 to MEGA 21 (SCL)
// CONNECT UNO GND to MEGA GND
#include <Wire.h>
const byte slaveAddress = 0x8;
volatile boolean dataReceived = false;
long value;
void receiveEvent(int nbBytes)
{
value = 0L;
for (byte i = 0; i < nbBytes ; i++) {
unsigned long b = Wire.read();
value |= (b << (8 * i));
}
dataReceived = (nbBytes == sizeof(value)); // if we did not receive the right number of bytes, the computation is wrong
}
void setup()
{
Wire.begin(slaveAddress); // join i2c bus with address slaveAddress
Serial.begin(115200);
Wire.onReceive(receiveEvent); // register event function
}
void loop()
{
if (dataReceived) {
Serial.print(F("Received: "));
Serial.println(value);
dataReceived = false;
}
}
your console, setup @115200 bauds, needs to send '\n' at the end of the input (and '\r' are ignored)
you can send multiple numbers on the same line like "123 456 -858" from the console
you can type P for printing the current list known on the master
you can type R to reset the list on the master
Slave just prints what it gets, if it was fitting in 4 bytes otherwise it ignores the input
I have modified few things in your programs of Post#17 (both Master and Slave) to ensure that the Master sends the data correctly and the Slave receives/display the data correctly.
#include <Wire.h>
//typedef union
union
{
float v;
uint32_t as_int;
byte b[4];//sizeof(float)];
} myData;//cracked_float_t;
//cracked_float_t floatValue;
void setup()
{
Wire.begin();
Serial.begin(9600);
/*Serial.println("Enter the float value in serial tab:");
while(Serial.available()==0){
}*/
myData.v = 263.30;//floatValue.v = 263.30;
//Serial.print("The given float value is =");
//Serial.println(floatValue.v);
Wire.beginTransmission(8);
Wire.write(myData.b[3]);//(floatValue.b[3]); //0x43
Wire.write(myData.b[2]);//floatValue.b[2]); //0x83
Wire.write(myData.b[1]);//floatValue.b[1]); //0xA6
Wire.write(myData.b[0]);//(floatValue.b[0]); //0x66
Wire.endTransmission();
Serial.println("Transmission Done!");
}
void loop() {
// put your main code here, to run repeatedly:
}