Author Topic: [SOLVED] Uart0Receive() Read  (Read 414 times)

kristofferis

  • Sr. Member
  • ****
  • Posts: 287
  • Location: Sweden
    • View Profile
Re: Uart0Receive() Read
« on: June 19, 2016, 03:26:45 am »
I have now remade my code and now everything seems to work. Thanks.

Here is my current code, the big difference is that it now handles if the serial.Read gives -1 when you are waiting for more information from the serial port.
And I also added a simple validation to make sure that we have a complete message before we try to do anything with it.

Code: [Select]
Class UartExample
    Shared serial As Uart
    Shared serialBuf As ListOfByte
    Shared Event Boot()
        // Enable serial communication
        serial = Uart.Create(9600, Pin.Pin3, Pin.Pin1)
        serialBuf = New ListOfByte
    End Event
   
    Shared Event Uart0Receive()
        Dim chr As Integer = serial.Read()
       
        While chr >= 0
           
            //message always starts with a(97) and ends with z(122)
           
            If chr = 97 Then
                //start of message
                serialBuf.Clear
                serialBuf.Add(chr.ToByte)
            ElseIf chr = 122 Then
                //end of message
                serialBuf.Add(chr.ToByte)
            Else
                //add message to Buf
                serialBuf.Add(chr.ToByte)
            End If
           
            chr = serial.Read()
        End While
       
        //check if we have a full message
        If serialBuf.Count = 4 Then
            //Right length verify start and stop possition
            If serialBuf(0) = 97 And serialBuf(3) = 122 Then
                //correct message, do something
                LedGreen = Not LedGreen
            End If
        Else           
        End If       
    End Event
End Class
« Last Edit: June 19, 2016, 12:29:19 pm by kristofferis »