0

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);
        }
}
1
  • 1
    Maybe you should slow down the serial printing on the transmitter side. The Arduino will pretty fast fill up the whole buffer and every serial write with a full buffer will result in values, that do not get transmitted. That might also be the problem with Rudy's answer. Try adding a short delay(100);
    – chrisl
    Commented Nov 23, 2018 at 23:55

2 Answers 2

1

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.

sscanf() API

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);
1

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.

About serial communation sync

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.