Ash*_*hes 1 serial-port arduino
在我的Arduino代码上遇到Serial.read()命令问题.我把它连接到两个连接到LED的74HC595移位寄存器.
我检查是否有串行数据,然后读取两个字节.然后将这些字节传递给一个将它们都移出的方法.当我使用Serial.print检查字节以将它们打印到串行监视器时,我得到了例如
49
255
50
255
Run Code Online (Sandbox Code Playgroud)
为什么我得到两个255's我已经阅读了arduino.cc上的文档,它说它只读取一个字节.有任何想法吗?
最终目标是读取串行线上的两个字节并将它们移出到移位寄存器IE是小数5和6的字节值通过第一个第3个LED将点亮一个移位寄存器然后第二个和第三个LED将在其他移位寄存器
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);
}
Run Code Online (Sandbox Code Playgroud)
if (Serial.available() > 0) {
byte low = Serial.read();
byte high = Serial.read();
//...
Run Code Online (Sandbox Code Playgroud)
这是您的代码中的错误.很可能会跳闸,串口并不那么快.Serial.available()只返回1的高概率.你会读低字节好,但如果没有数据要读,Serial.read()将返回-1.这使得高等于0xff.简单的解决方法是:
if (Serial.available() >= 2)
Run Code Online (Sandbox Code Playgroud)