英文:
Serial Communication between C# and Arduino (bytes)
问题
I am Sending an byte from C# winform Application to Arduino And Recieving it back on Winform Application and display it on Text box.
Arduino code
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
int numBytes = 1;
void loop()
{
if (Serial.available() > 0)
{
byte data = Serial.read();
Serial.print(data);
delay(1000);
}
}
C# code
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(new byte[] { 0x52 }, 0, 1);
}
This is serial port receiving function
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//read data
byte data = (byte)serialPort1.ReadByte();
this.Invoke(new EventHandler(delegate
{
richTextBox1.Text += data;
}));
}
I am sending byte 0x052
. I want that byte displayed on text box, but this will appear in the textbox as 5650
. I do not know what I am doing wrong. I actually want to send 3 bytes and receive 3 bytes from both Arduino and C#. I tried many answers from Stack Overflow but failed to establish proper and correct communication between C# and Arduino.
英文:
I am Sending an byte from C# winform Application to Arduino And Recieving it back on Winform Application and display it on Text box.
Arduino code
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
int numBytes =1;
void loop()
{
if (Serial.available() > 0)
{
byte data = Serial.read();
Serial.print(data);
delay(1000);
}
}
C# code
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write(new byte[] { 0x52 }, 0, 1);
}
This is serial port receiving function
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//read data
byte data = (byte)serialPort1.ReadByte();
this.Invoke(new EventHandler(delegate
{
richTextBox1.Text += data;
}));
}
I am sending byte 0x052
I want that byte displayed on text box but this will appear in textbox 5650
.
I do not know what I am doing wrong. I actually want to send 3 byte and received 3 byte from both Arduino and C#.I tried many answers from stack overflow but failed to make proper and correct communication between C# and Arduino.
答案1
得分: 2
在Arduino端执行以下代码:
byte data = Serial.read();
这将获取正确的数值,即 data = 0x52
或者十进制为 82
。
但是当你执行以下代码:
Serial.print(data);
它会以ASCII形式发送该数值。
Serial.print(82)
会发送 "82"
,其中 "8"
对应ASCII码为 56
,而 "2"
对应ASCII码为 50
。这就是为什么在C#端你会得到 "5650"
。
如果你想在C#端看到数值以 0x52/82
的形式显示,你需要使用以下代码:
Serial.write(data);
英文:
On the Arduino side when you do:
byte data = Serial.read();
That is getting the proper value, i.e. data = 0x52 or 82 in decimal
But then when you do:
Serial.print(data);
it's sending the value in ascii.
Serial.print(82) sends "82", "8" = 56 in ascii and "2" = 50 in ascii. That's why you end up with "5650" on the C# side.
If you want the value to show up as 0x52/82 on the C# side you instead need to use:
Serial.write(data)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论