c# - C# 和 Arduino 之间的串行通信(字节)

标签 c# winforms arduino arduino-uno serial-communication

我正在从 C# winform 应用程序发送一个字节到 Arduino,并在 Winform 应用程序上接收它并将其显示在文本框中。

Arduino代码

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#代码

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.Write(new byte[] { 0x52 }, 0, 1);

        }

这是串口接收函数

        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;
            }));
        }

我正在发送字节 0x052 我希望该字节显示在文本框中,但这将出现在文本框 5650 中。 我不知道我做错了什么。我实际上想从 Arduino 和 C# 发送 3 个字节并接收 3 个字节。我尝试了堆栈溢出的许多答案,但未能在 C# 和 Arduino 之间进行正确且正确的通信。

最佳答案

在 Arduino 端,当您这样做时:

byte data = Serial.read();

即获取正确的值,即 data = 0x52 或十进制的 82

但是当你这样做时:

Serial.print(data);

它正在发送 ascii 格式的值。

Serial.print(82) 发送“82”,“8”= 56(ASCII 码)和“2”= 50(ASCII 码)。这就是为什么在 C# 端最终得到“5650”的原因。

如果您希望该值在 C# 端显示为 0x52/82,则需要使用:

Serial.write(data)

关于c# - C# 和 Arduino 之间的串行通信(字节),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76837870/

相关文章:

c++ - 如何修复 : error: no match for 'operator=' (operand types are 'Estado' and 'Estado*' )

c# - 在另一个 lambda 表达式中使用 lambda 表达式

c# - 扩展方法无法正常工作 C#

c# - 将唯一数组元素移动到前面并对数组进行切片的最快方法

c# - 如何将自定义 IDesigner 移动到同一解决方案中的单独程序集?

winforms - Screen.WorkingArea 的单位

matlab - 是否可以在 Raspberry pi 上嵌入 MATLAB 代码以制作独立的硬件设备?

c# - 签署使用 itext 填充的 pdf 时出错

c# - 当使用 C# 图表 API 绘制的第一个点位于 (0,0) 时,X 轴值自动递增

c++ - 为什么这个按位运算是 "narrowing conversion from ' int' 到 'byte'“? - Arduino