简体   繁体   中英

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.Open();
Arduino.WriteLine("1.5,3.7,2");

After that I receive it with my arduino like this:

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. 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".

I read the serialdata from the arduino with the command:

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).

C# sample

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

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

Its a sample that shows how to do serial comms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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