0

I want to send randomly generated data from my PC to a µC (ATmega328p) and then mirror it back. For this purpose I wrote a program in C# (my first time working with it).

Every Byte the PC receives back which is >0xF7 gets displayed as 0x3F.

The µController receives and sends the data back correctly(I display all data which the µC receives and sends on an LCD). I also used two serial terminal tools ( HTerm, Pololu Serial Transmitter) to verify that the µC works fine. There has to be something wrong when the PC receivs/displays the data at the end.

Display received data as .hex in textBox1

  private  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e){

        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        string outp = string.Empty;
        char[] value = indata.ToCharArray();
        foreach(char L in value){
        int V = Convert.ToInt32(L);
        outp+= string.Format("{0:x}",V);
        }

        if (outp != String.Empty)
            Invoke(new Action(() => textBox1.AppendText(outp)));
    }

Edit2//

I fixed the problem. Thanks to kunif and gunnerone for the hints! There seemed to be a problem with the encoding of port.ReadExisting(). Instead I know use the port.Read().

private  void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e){

        int bytesToRead = port.BytesToRead;
        byte[] value = new byte[bytesToRead];
        port.Read(value,0,bytesToRead);
        string indata = BitConverter.ToString(value);
        if (indata != String.Empty)
            Invoke(new Action(() => textBox1.AppendText(indata)));
    }
  • 1
    Somewhere your problem is being caused by someone encoding/decoding the bytes. Everything above 0x7F gets changed to a 0x3F (question mark symbol). If your program is sending 0x08 0x09 0x10, that's different than it sending "8910". If you send your uC something like 0xFF what gets echoed back? – gunnerone Jun 08 '18 at 18:06
  • You are right, everything >0x7F gets echoed back as 0x3F. Kind of stupid not to see that, I'll edit my post. – HoneyBadger73 Jun 08 '18 at 20:00

1 Answers1

0

As in this article ASCIIEncoding.ASCII.GetBytes() Returning Unexpected Value, it seems that processing similar to Encoding.ASCII.GetBytes() or ASCIIEncoding.ASCII.GetBytes() is done somewhere (may be indata.ToCharArray()).

Please try change from char[] value = indata.ToCharArray(); to byte[] value = Encoding.GetEncoding("ISO-8859-1").GetBytes(indata);, also change other char[] to byte[].

kunif
  • 4,060
  • 2
  • 10
  • 30