Hello everyone,
it's my first time dealing with serial communication and I am currently stuck understanding/ dealing with sending/reading/converting integers and arrays that I'm hoping someone has a solution for. Sorry in advance for these rather bad coding approaches and my bloody beginner questions.
The idea is to let the slave read data from a sensor (3 digit numbers), store them into arrays and send it to the Master (Mega), as requested. I was thinking about sending the "incoming" values as binary data, but I have no clue how to implement that into the below written "framework" I built. I have read to heaps of posts and tried using the named approaches but nothing really worked.
Also, I do not use any pull up/ down resistors, if this could be an issue.
The below described solution does not yet use the approach of storing the values as array, but I thought someone could help me to understand whit this given in and output, what is actually happening.
Requesting 6 bits, the Master Arduino returns a loop of "0 255 255 255 255 255" on it's serial monitor. What does this say?
Master Code:
#include <Wire.h>
char c[10]={}; //empty array where to put the numbers comming from the slave
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.requestFrom(8, 6);
while (Wire.available()) {
c = Wire.read();
Serial.println(c);
}
}
Slave Code:
#include <Wire.h>
char c[10];
void setup() {
Wire.begin(8);
Wire.onRequest(requestEvent);
Serial.begin(9600); // to validate the output returned by the master
pinMode(13, OUTPUT);
}
void loop() {
int light = analogRead(0);
Serial.println(light);
if (light < 150) { // this remaining code within the loop triggers the LED within the circuit
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
}
void requestEvent() {
Wire.write(light);
}
I then used the following approach (it is full of bugs I guess and has nothing to do yet with storing the data in arrays)
...in the slave code with:
#include <Wire.h>
...
void requestEvent() {
byte light[6];
Wire.write((byte*)&light,sizeof 6); // send response of 4 bits back to master
}
...and in the master code with:
#include <Wire.h>
int response;
...
void loop() {
Wire.requestFrom(8, 6);
while (Wire.available()) {
int c = Wire.readBytes((byte*)response, 6); // store bytes as int
Serial.println(c));
}
}
In this case, I only get "5⸮" as output on the serial master monitor once.
Any help is highly appreciated!!