我对 UNO 上的硬件串行有问题,在很多情况下它似乎丢失了一个字符(通常是接收到的第一个字符),并且在某些情况下它错过了整个传输。这只发生在 Arduino 从我在串行监视器中键入的计算机接收数据时。当我发送字符串时,我可以看到 RX 灯闪烁,但 arduino 完全忽略了它。
我发送的数据是三个逗号分隔的 8 位无符号整数
#include <Adafruit_NeoPixel.h>
//#include <OneSheeld.h>
#define PIN 6
#define LEDS 5
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDS, PIN, NEO_GRB + NEO_KHZ800);
int leds = LEDS-1;
byte red;
byte green;
byte blue;
int i;
// pins for the LEDs:
//const int red = 3;
//const int green = 5;
//const int blue = 6;
void setup() {
// initialize serial:
Serial.begin(9600);
strip.begin();
strip.setPixelColor(0,12,12,12);
strip.show(); // Initialize all pixels to 'off'
Serial.print("number of LEDS in strip:");
Serial.println(LEDS);
i=0;
// make the pins outputs:
// pinMode(redPin, OUTPUT);
// pinMode(greenPin, OUTPUT);
// pinMode(bluePin, OUTPUT);
}
void loop() {
red = 0;
green=0;
blue= 0;
// i=0;
// if there's any serial available, read it:
while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
red = Serial.parseInt();
// do it again:
green = Serial.parseInt();
// do it again:
blue = Serial.parseInt();
delay(1);
// look for the newline. That's the end of your
// sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
// red = constrain(red, 0, 255);
// green = constrain(green, 0, 255);
// blue = constrain(blue, 0, 255);
Serial.print("LED being served = ");
Serial.println(i);
// fade the red, green, and blue legs of the LED:
// analogWrite(redPin, red);
// analogWrite(greenPin, green);
// analogWrite(bluePin, blue);
strip.setPixelColor(i,red,green,blue);
strip.show();
// print the three numbers in one string as hexadecimal:
Serial.print("R=");
Serial.println(red);
Serial.print("G=");
Serial.println(green);
Serial.print("B=");
Serial.println(blue);
if(i==leds)
i=0;
else
i=i+1;
}
}
}
这是输入以下字符串时串行监视器的一些示例输出:<25,25,25>
输出:
number of LEDS in strip:5
LED being served = 0
R=25
G=25
B=25
LED being served = 1 <<< this transmission got lost the first time it was sent
R=25
G=25
B=25
LED being served = 2
R=25
G=25
B=25
LED being served = 3
R=5
G=25
B=25
LED being served = 4 <<< This transmission got lost the first 4 times it was sent
R=5
G=25
B=25
LED being served = 0
R=25
G=25
B=25
LED being served = 1
R=25
G=25
B=25
LED being served = 2
R=25
G=25
B=25
LED being served = 3
R=25
G=25
B=25
LED being served = 4
R=5
G=25
B=25
LED being served = 0
R=25
G=25
B=25
LED being served = 1
R=5
G=25
B=25
LED being served = 2
R=25
G=25
B=25
LED being served = 3
R=25
G=25
B=25
LED being served = 4
R=25
G=25
B=25
谢谢