0

Having issues with the Serial.read() command on my Arduino code. I have it connected to two 74HC595's shift registers connected to LED's.

I check if there is Serial data, then read two bytes. Then pass these bytes to a method that shifts them both out. When I check the bytes with Serial.print to print them out to the serial moniter I get for example

49
255
50
255

Why am I getting the two 255's I have read the documentation on arduino.cc and it says it reads a single byte only. Any ideas?

The end goal is to read two bytes on the serial line and shift them out to the shift reg's IE is the byte values of decimal 5 & 6 were passed the 1st 3rd LED's would light on one shift register then the 2nd and 3rd would on the other shift register

const int dataPin = 8;
const int latchPin = 9;
const int clockPin = 10;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    byte low = Serial.read();
    byte high = Serial.read();
    Serial.println(low);
    Serial.println(high);
    sendBytes(low,high);
  }
}

void sendBytes(byte l, byte h) {
  digitalWrite(latchPin,LOW);
  shiftOut(dataPin,clockPin,MSBFIRST,l);
  shiftOut(dataPin,clockPin,MSBFIRST,h);
  digitalWrite(latchPin,HIGH);
}

2 Answers 2

7
    if (Serial.available() > 0) {
            byte low = Serial.read();
            byte high = Serial.read();
            //...

This is a bug in your code. Very likely to trip, serial ports are not that fast. So high odds that Serial.available() only returns 1. You'll read the low byte okay but Serial.read() will then return -1 if there is no data to read. Which makes high equal to 0xff. The simple fix is:

    if (Serial.available() >= 2)
Sign up to request clarification or add additional context in comments.

Comments

0

I had the same problem reading from a program...

I had luck both letting the code loop until filled...

and before taking on new Serial data I flush the serial to get the latest bytes

While(Serial.read() != -1);  //clears data in the PC Serial Port

Here's what it looks like all put together

int i = 0;
byte bytes[3];
interval = 150;  //allows for this amount of time to read from serial
long previousMillis = 0;

void loop() {
unsigned long currentMillis = millis();

if(currentMillis - previousMillis < interval && i < 2) {

   if(Serial.available() > 0) {
   bytes[i] = Serial.read(); 
   i++; }
}

if(currentMillis - previousMillis > 1000) {  //waits 1 second to get new serial data
previousMillis = currentMillis;  //resets the timer
i = 0;
While(Serial.read() != -1);  //clears data in the PC Serial Port
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.