0
\$\begingroup\$

I developed an app which sends data to an Arduino by serial port, but I can’t t understand how to receive the data in the Arduino. I send a string by serial port to the Arduino and the Arduino receives something but my code doesn’t work. In the Arduino the data is received byte by byte.

The C# code which sends the data:

using System;
using System.Windows.Forms;
//
using System.Threading;
using System.IO;
using System.IO.Ports;

pulic class senddata(){

    private void Form1_Load(object sender, System.EventArgs e)
    {
    //Define a Porta Serial
        serialPort1.PortName = textBox2.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.Open();
    }
private void button1_Click(object sender, System.EventArgs e)
{
    serialPort1.Write("1");  //This is a string         
}

} 

The Arduino Code:

#include <Servo.h>

Servo servo;
String incomingString;
int pos;

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    incomingString = "";
}

void loop()
{
   if(Serial.available())
   {
   // Read a byte from the serial buffer.
   char incomingByte = (char)Serial.read();
   incomingString += incomingByte;

     // Checks for null termination of the string.
     if (incomingByte == '\0') {

      if(incomingString == "1"){
                servo.write(90);
          }

       incomingString = "";
    }

  }
}
\$\endgroup\$
1
\$\begingroup\$

You're not terminating your string properly.

The Arduino code is looking for 0x31 0x00.

The PC is sending just 0x31.

You need to send the 1 and a terminating character (say a carriage return) and look for that on the Arduino. That would, for example, be sending 0x31 0x0d, and the Arduino would look for 0x0d as the terminating character.

Or you could tell the PC to transmit a 1 followed by a null character 0x00. I don't know C# but if it follows standard escaping procedures you may be able to send something like "1\000".

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.