我正在尝试从控制台获取标准输入并将其作为纯ASCII发送到我的Arduino Uno。
\r\n
我使用以下代码获取输入并从中剥离:
String Input = Console.Read().ToString().Replace("\r",string.Empty).Replace("\n",string.Empty);
当我执行doConsole.WriteLine(Input);
时,它输出正确的“72”,但是当我执行时serialPort.Write(Input);
,Arduino 返回“55”,它对所有内容都有效。
我究竟做错了什么?
我的 C# 端(主机/PC)代码:
String Input = Console.Read().ToString().Replace("\r", string.Empty).Replace("\n",string.Empty);
//Console.WriteLine(Input);
//serialPort.Write(Input);
char[] InputChar = Input.ToCharArray();
serialPort.Write(InputChar,0,1);
//byte[] InputByte = Encoding.ASCII.GetBytes(Input);
//Console.WriteLine(Input);
//serialPort.WriteLine(Input);
Thread.Sleep(25); //Wait 0.025 second.
//***************************************************************//
// Read anything from the serial port. //
//***************************************************************//
numBytes = serialPort.BytesToRead;
for (int i = 0; i < numBytes; i++)
rxPacket[i] = (byte)serialPort.ReadByte();
result = new char[numBytes];
for (int i = 0; i < numBytes; i++)
result[i] = (char)rxPacket[i];
Console.Write("Read this from Arduino:");
Console.WriteLine(result);
Console.WriteLine("press Enter to continue");
Console.ReadKey(); //Read nothing.
还有我的 Arduino 草图:
const int ledPin = 13; // The pin that the LED is attached to.
int incomingByte; // A variable to read incoming serial data into.
void setup() {
// Initialize serial communication:
Serial.begin(9600);
// Initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// Read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// If it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
Serial.print(incomingByte);
}
// If it's an L (ASCII 76), turn off the LED:
else if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
Serial.print(incomingByte);
}
else{
Serial.print(incomingByte);
}
}
}
编辑:将代码更改为以下。仍然没有运气;我得到同样的答复。
String Input = Console.Read().ToString().Replace("\r",string.Empty).Replace("\n",string.Empty);
Console.Write(Input,0,1);
//serialPort.Write(Input);
byte[] inputByte = Encoding.ASCII.GetBytes(Input);
serialPort.Write(inputByte,0,1);