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).
From the 8 Byte the PC receives back from the µC, 4 to 6 of them get mirrored correctly, the other ones are replaced by the hex value "0x3F" (Its always this value). Which bytes are wrong seems to be completly random.
The odd thing is, that the error only occurs, if the data the PC sends in the first place was generated randomly. If I just send a normal string or byte[], everything gets mirrored fine.
I have a hard time wrapping my head around this problem, because the µC always receivs and sends the data back correctly , regardless if it was generated randomly or not (I display all data which the µC receives and sends on an LCD). There has to be something wrong when the PC receivs/displays the data at the end.
I also used two serial terminal tools ( HTerm, Pololu Serial Transmitter) to verify that the µC works fine.
PC sends randomly generated byte[] rnd_values to the µC -> µC receivs and sends rnd_values correctly back to PC -> PC displays incorrect rnd_values.
PC sends non-randomly generated byte[] non_rnd_values to the µC -> µC receivs and sends non_rnd_values correctly back to PC -> PC displays correct non_rnd_values.
Send data:
void SendClick(object sender, EventArgs e)
{
//port.Write("Hello World"); // <------Gets mirrored fine
//byte[] non_rnd_values = new byte[8] { 0x68, 0x69, 0x6b, 0x6a, 0x6f, 0x6a, 0xfe, 0xe3 };
//port.Write(non_rnd_values, 0, 8); <------ gets mirrored fine
port.Write(rnd_values,0,8); // <-----This works not!
}
I generate the random data using:
System.Security.Cryptography.RNGCryptoServiceProvider rand =
new System.Security.Cryptography.RNGCryptoServiceProvider();
I also tried to use the Random class, but the same error occured
Random rand = new Random();
Generate random data and display them in textBox2.
void Create_rndClick(object sender, EventArgs e)
{
byte [] rnd_values = new byte[8];
rand.GetBytes(rnd_values);
hex = BitConverter.ToString(rnd_values);
Invoke(new Action(() => textBox2.AppendText(hex)));
}
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)));
}
Please keep in mind that I am a total newbie in C# and google gave me nothing about this strange behavior.
Aucun commentaire:
Enregistrer un commentaire