为什么我的Arduino串口给我半随机数?

Kim*_*Kim 3 serial-port arduino arduino-uno

我的Arduino Uno有一个基本问题.
我的示例代码通过串口获取一个数字,并应将其打印回来.

int incomingByte = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Hello World");  
}

void loop() {
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
  }
} 
Run Code Online (Sandbox Code Playgroud)

当我发送0时,我收到48.

0->48
1->49
2->50
3->51

a->97
b->98
A->65
Run Code Online (Sandbox Code Playgroud)

那么为什么不向我发回相同的数字呢?

Bil*_*lla 8

在您的程序中,输出是ASCII等效于Arduino接收的输入.ASCII等价于0为48,1为49,a为97,A为65,依此类推.

原因是您将输入存储到incomingBytevariable(incomingByte = Serial.read();)但是将变量声明incomingByteint.将字符分配给整数变量时,其对应的ASCII值将存储到整数变量中.

因此,如果要打印发送给Arduino的字符,则需要更改int incomingByte = 0;char incomingByte;.