我有以下代码。它旨在通过串口接收数据,然后将其打印回串口。
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Serial.write("Power On");
pinMode(pin, OUTPUT);
}
char getValue()
{
index =0 ;
int code =-1;
while(Serial.available() > 0)
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
code=1;
}
}
return code;
}
主循环:
void loop()
{
char response = getValue();
if(response != -1)
{
Serial.println("ok");
Serial.println( inData);
}
我遇到的问题是我无法弄清楚,如果我发送它“45”它的打印:
"ok
4
ok
5"
而不是“好 45”
为什么是这样?Serial.avalible 返回可供读取的字节数,如果我发送它应该返回 2 45 ?