I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.
Transmitter Code:
void setup() {
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
}
Receiver Code:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int incomingByte = Serial.read();
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
2 Answers 2
You'll want to get familiar with the standard C function sscanf(). It does exactly what you're looking for, converts an ASCII string into whatever type you like.
The code to read an integer from the serial port would look something like this:
char recv_buf[10]; int recv_int;
Serial.readBytesUntil('\n', recv_buf, 9);
recv_buf[9] = 0; // make sure it's null terminated
sscanf(recv_buf, "%d", &recv_int);
Serial.print("I received: ");
Serial.println(recv_int);
One byte is 8 bits so 2^8 is equal to 255. One byte can hold value up to 255. Since you have value of 1023(max possible) you have to split value into two bytes. Here's an example:
unsigned byte highValueByte(int value)
{
return (value >> 8);
}
unsigned byte lowValueByte(int value)
{
return (value - (highValueByte(value) << 8));
}
int giveValue(unsigned byte highByte, unsigned byte lowByte)
{
return ((highByte << 0) & 0xFF) + ((lowByte << 8) & 0xFFFF);
}
void loop()
{
int senValue = analogRead(/* PIN NUMBER */);
int byteOne = highValueByte(senValue);
senValue = lowValueByte(senValue);
}
Your code Works for one byte(try it), but it doesn't for two bytes value. Because you have two bytes, you have to introduce some kind of buffer.
Example:
unsigned byte buffer[2] = { 0, 0 };
Also be sure you connected pins properly. RX from Arduino #1 goes into TX from Arduino #2 and vice versa.
delay(100);