I have faced this problem for two weeks and still cannot fix it. I press "Read" button to send a command through VB.Net to ATmega to communicate with FPGA and then read registers back. At first, everything looks fine, but after I keep pressing "Read" button for several times(randomly), this error occurs. It returns wrong value(ASCII) with same pattern and the pattern is similar with the correct reading. And after the error occurs, the reading keeps returning this wrong pattern and cannot return correct reading back unless I unplug my serial device and plugin again. I am using Visual Basic 2010 with .Net4.0 . I have tried to use ReadChr/Readbyte functions but the error still occur. Also I tried to communicate with my device using Arduino serial monitor to send code directly and receive reading back. Error didn't occur in about 100+ trials but I can't sure it won't occur or just haven't occured.
Here is the some code of the "Read" button:
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
btnRead.Enabled = False
btnSend.Enabled = False
Dim strTemp As String
Dim Check1 As String
Dim temp As Integer
Dim buffer(16) As Byte
Dim i As Integer = 0
Do While (dgvRegMap.RowCount - 1)
dgvRegMap.Rows.RemoveAt(0)
Loop
dgvRegMap.Refresh()
AxMSComm1.DiscardNull = False
AxMSComm1.BaudRate = 115200
AxMSComm1.Open()
For j = 0 To 15
dgvRegMap.Rows.Add()
strTemp = "1" & FnDec2Bin(j, 4) & TextBox3.Text & "000000000000000000000000"
Check1 = ""
AxMSComm1.Write(strTemp)
AxMSComm1.DiscardOutBuffer()
Thread.Sleep(10)
temp = AxMSComm1.BytesToRead
Convert.ToByte(AxMSComm1.Read(buffer, 0, temp))
Dim s As String = Encoding.GetEncoding("Windows-1252").GetString(buffer)
Check1 = s
For i = 0 To 15
dgvRegMap.Rows(j).Cells("Bit" & CStr(i)).Value = CStr(Mid(Check1, i + 1, 1))
Next
dgvRegMap.Rows(j).Cells("Address").Value = j
dgvRegMap.Refresh()
AxMSComm1.DiscardInBuffer()
Thread.Sleep(10)
Next j
AxMSComm1.Close()
Thread.Sleep(50)
btnRead.Enabled = True
btnSend.Enabled = True
End Sub