简体   繁体   English

c#和arduino之间的Serialdata通信

[英]Serialdata communication between c# and arduino

here is my problem.这是我的问题。 I use thise piece of code to send a string to my arduino with a serialport:我使用这段代码通过串行端口向我的 arduino 发送一个字符串:

Arduino.Open();
Arduino.WriteLine("1.5,3.7,2");

After that I receive it with my arduino like this:之后,我像这样用我的 arduino 收到它:

char buffer[12];
String inc;

void setup()
{
  Serial.begin(115200);
}

void loop()
{
 if (Serial.available() >= 11) 
 {
    for (int i=0; i<11   ; i++) 
    {
      buffer[i] = Serial.read();
      inc += buffer[i];
    }
    memset(buffer, 0, sizeof(buffer));
    Serial.println(inc);
    inc = "";
  }
}

If I use the serial monitor the arduino programm runs as intended, reads all the chars and prints them as one string.如果我使用串行监视器,arduino 程序将按预期运行,读取所有字符并将它们打印为一个字符串。 However if I try to read the string inc from my c# programm I get a format error that looks like this ".7,2????1.5".但是,如果我尝试从我的 c# 程序中读取字符串 inc,我会收到一个类似于“.7,2????1.5”的格式错误。

I read the serialdata from the arduino with the command:我使用以下命令从 arduino 读取串行数据:

GlobaleVariablen.Input = Arduino.ReadLine();

The baudrate is the same, parity is set to none and stopbits on default as well.波特率相同,奇偶校验设置为无,默认设置为停止位。 I hope you can help me, I am getting crazy over this and I just can't find my mistake or why the format is wrong.我希望你能帮助我,我对此感到很疯狂,我找不到我的错误或格式错误的原因。

This works perfectly with Arduino 1.6 on a UNO compatible board (please, note that this code has no error handling at all, so use it as a starting point only). 这可以与UNO兼容板上的Arduino 1.6完美配合(请注意,此代码完全没有错误处理,因此只能将其用作起点)。

C# sample C#示例

using System;
using System.IO.Ports;

namespace SerialPortTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new SerialPort(args[0], 9600, Parity.None, 8, StopBits.One);
            p.Open();

            Console.WriteLine("Sending ({1}) {0}", args[1], args[1].Length);

            p.WriteLine(args[1]);

            Console.WriteLine("Reading back");

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(p.ReadLine());

            Console.ResetColor();
        }
    }
}

Arduino Code Arduino代码

void setup() 
{
    Serial.begin(9600);
}

char buffer[64];
char *p = buffer;

void loop() 
{
    char ch = ' ';
    while (Serial.available() > 0)
    {
       ch = Serial.read();
       *p++ = ch;    

       if (ch == '\n')
       {
         *p = 0;
         Serial.print("got ");
         Serial.println(buffer);      
         p = buffer;
         break;
      }
   }  
}

Take a look at: https://github.com/microsoft/Windows-universal-samples/tree/main/Samples/SerialArduino看看: https : //github.com/microsoft/Windows-universal-samples/tree/main/Samples/SerialArduino

Its a sample that shows how to do serial comms它是一个显示如何进行串行通信的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM