我的问题是我的 arduino 无法正常工作
这是我的代码:
int data;
void setup(){
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
Serial.println("Hi");
}
void loop(){
delay(500);
while(Serial.available())
{
int data = Serial.read();
Serial.print(data);
}
if (data == 1)
digitalWrite(13, HIGH);
else if (data == 0)
digitalWrite(13,LOW);
}
现在,当我运行代码并发送数据时,arduino 无法正常工作 例如: 我发送 1
我的 arduino 打印:49 \n 10
然后 LED 不会打开
这是打印的文本:
-> Hi
-> 49
-> 10
并且永远不会 data == 1
This is my code:
int data;
void setup(){
Serial.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
Serial.println("Hi");
}
void loop(){
delay(500);
while(Serial.available())
{
int data = Serial.read();
Serial.print(data);
}
if (data == 1)
digitalWrite(13, HIGH);
else if (data == 0)
digitalWrite(13,LOW);
}
Now when I run the code and send a data the arduino don't work correctly
for example:
I send 1
and my arduino prints: 49 \n 10
and then led don't turn ON
This is the printed text :
-> Hi
-> 49
-> 10
And never data == 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的变量
data
是一个int
。 Serial.read() 必须将其数据适合该类型,因此它返回输入的 ASCII 值。 49 是表示 1 的 ASCII,10 是表示 LF 或换行的 ASCII。要获取您输入的字符,请将
data
类型设置为char
。然后应该返回 1。Your variable
data
is anint
. Serial.read() has to fit its data into that type, so it returns the ASCII value of your input. 49 is ASCII for 1 and 10 is ASCII for LF or line feed.To get the character you inputted, set the type of
data
tochar
. This should then return 1.您可以尝试将
int data
更改为char data
并使用
我认为如果您使用
int
,它将从 ASCII 表从字符转换为十进制can you try to change your
int data
tochar data
and use
i think if you using
int
that will convert from character to decimal from ASCII table您初始化的数据是数据的两倍,您无法访问 while 循环内的数据,
请尝试此代码
you initialized the data twice the data you couldn't access the data inside you while loop
try this code