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