我为Arduino Nano 3.0编写了一些代码,如果我通过USB集线器发送1
,我想让LED闪烁。它有效,但我不理解Nano的输出,我希望有人可以向我解释。
这是我的代码:
#define LEDPIN 2
#include <SPI.h>
int Go = 0;
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
digitalWrite(LEDPIN, LOW);
delay(1000);
digitalWrite(LEDPIN, HIGH);
delay(1000);
digitalWrite(LEDPIN, LOW);
while (Go != 1){
Go = Serial.read();
Serial.println(Go); //a 1 will print 49, a 0 should print 48
Go = (Go - '0');
Serial.println(Go);
}
}
void loop() {
if (Serial.available() > 0){
if ( Go == 1)
{
delay(1000);
digitalWrite(LEDPIN, HIGH);
delay(1000);
digitalWrite(LEDPIN, LOW);
}
else {}
}
else
{
digitalWrite(LEDPIN, LOW);
}
}
这是输出:
-1 //this should be a 0
-49
.
.
.
49 //this is because of ASCII
1 // here is my 1 but the programm won't do the stuff in loop()
// instead I have to send another 1 to get LED fun
在节目开始时我收到了-1
???这是因为USB连接还是我做错了什么?
答案 0 :(得分:0)
此代码没有按照您的想法执行。特别是,您编写的循环代码意味着:
在设置中,清除缓冲区。因此,您将需要队列中的另一个char来触发操作。
根据你的写作,我认为你想做的是
为了做到这一点,你需要这样的东西:
#define LEDPIN 2
// #include <SPI.h> Not needed here
byte Go = 0; // Please, use the correct size for variables
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
digitalWrite(LEDPIN, LOW);
delay(1000);
digitalWrite(LEDPIN, HIGH);
delay(1000);
digitalWrite(LEDPIN, LOW);
Go = 0;
}
void loop() {
if (Serial.available() > 0){
// Something was received, so let's check it out
byte tempGo = Serial.read();
Serial.println(Go); //a 1 will print 49, a 0 should print 48
// this way if you did not receive any valid char nothing will change
if (tempGo == '0')
Go = 0;
else if (tempGo == '1')
Go = 1;
Serial.println(Go);
}
if (Go){
delay(1000);
digitalWrite(LEDPIN, HIGH);
delay(1000);
digitalWrite(LEDPIN, LOW);
}else{
digitalWrite(LEDPIN, LOW);
}
}
此外,延误是一个非常糟糕的习惯;你不想在看到正确的输出之前等待两秒钟。为了消除延迟,您可以按照BlinkWithoutDelay示例中的示例进行操作:
#define LEDPIN 2
// #include <SPI.h> Not needed here
byte Go = 0; // Please, use the correct size for variables
unsigned long prevMillis;
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
digitalWrite(LEDPIN, LOW);
delay(1000);
digitalWrite(LEDPIN, HIGH);
delay(1000);
digitalWrite(LEDPIN, LOW);
Go = 0;
}
void loop() {
if (Serial.available() > 0){
// Something was received, so let's check it out
byte tempGo = Serial.read();
Serial.println(Go); //a 1 will print 49, a 0 should print 48
// this way if you did not receive any valid char nothing will change
if (tempGo == '0')
Go = 0;
else if (tempGo == '1') {
if (!Go) prevMillis = millis() - 1000; // This is in order to flash immediately
Go = 1;
}
Serial.println(Go);
}
if (Go){
while ((millis() - prevMillis) >= 1000){
prevMillis += 1000;
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}
}else{
digitalWrite(LEDPIN, LOW);
}
}
免责声明:此代码未经过测试;
中可能存在一些错误