2

I am Sending an byte from C# winform Application to Arduino And Recieving it back on Winform Application and display it on Text box.

Arduino code

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# code

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

        }

This is serial port receiving function

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

I am sending byte 0x052 I want that byte displayed on text box but this will appear in textbox 5650. I do not know what I am doing wrong. I actually want to send 3 byte and received 3 byte from both Arduino and C#.I tried many answers from stack overflow but failed to make proper and correct communication between C# and Arduino.

  • 1
    Can you please clarify why you *do not* expect 5650 output in the rich text box? The code shown is equivalent of `String.Join("",0x52.ToString().Select(c => (int)c))` which is indeed results in 5650... – Alexei Levenkov Aug 04 '23 at 18:08
  • I am expect byte 0x52 because i am send 0x52 and i also use if case to check the correctness of data that the sending and receiving bytes are same or not : if the data == 0x52 then print "OK " in text box but when i received the byte i doesn't show OK message in textbox this mean the receiving byte is not equal to sending byte – Rehan Faisal Aug 05 '23 at 05:23

1 Answers1

2

On the Arduino side when you do:

byte data = Serial.read();

That is getting the proper value, i.e. data = 0x52 or 82 in decimal

But then when you do:

Serial.print(data);

it's sending the value in ascii.

Serial.print(82) sends "82", "8" = 56 in ascii and "2" = 50 in ascii. That's why you end up with "5650" on the C# side.

If you want the value to show up as 0x52/82 on the C# side you instead need to use:

Serial.write(data)
gunnerone
  • 3,566
  • 2
  • 14
  • 18