1
votes

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.

1
Your Arduino code is just out-of-sync with the data transmission. You send 10 bytes, not 11. And you also send the linefeed back, but then add two extra bytes by using println(). Proper Arduino code just appends characters to buffer until you get a linefeed ('\n').Hans Passant
Sorry but this was not the problem here. I fixed the issues you pointed out, however the question marks remain with four ???? in front of the string. Could it be that only the first string after I open the Serialport has some sort of "tag"? Don't know how to solve this.DerBenutzer

1 Answers

0
votes

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