Main Site Documentation

UART_DataReceived return different bytes length


#1

I simply test the UART on FEZ Cerbuino Bee, connect tx to rx.
Write string “test” to SerialPort.
Read data use UART_DataReceived event.
But only first time I get the string “test”, then get wrong.

Debug.output

test
t
e
st
t
e
st
t
e
st
t
e
st
t
e
st

public partial class Program
    {
        // This method is run when the mainboard is powered up or reset.   
        SerialPort UART;
        void ProgramStarted()
        {
            
              GT.Timer timer = new GT.Timer(1000); // every second (1000ms)
              timer.Tick += new GT.Timer.TickEventHandler(timer_Tick);
               

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");

            UART = new SerialPort("COM3", 19200);
            UART.DataReceived += new SerialDataReceivedEventHandler(UART_DataReceived);
            
            UART.ReadTimeout = 0;
            UART.Open();
            timer.Start();

        }

        void UART_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int btr = UART.BytesToRead;
            
            if (btr == 0) return;
            byte[] bytes = new byte[btr];
            UART.Read(bytes, 0, btr);
           
            string Text = new string(System.Text.Encoding.UTF8.GetChars(bytes));
            Debug.Print(Text);
            
        }

        
        void timer_Tick(GT.Timer timer)
        {
            byte[] tx_data;
           
            tx_data = Encoding.UTF8.GetBytes("test");
            UART.Flush();         
            UART.Write(tx_data, 0, tx_data.Length);           
            // wait to make sure data is transmitted
            Thread.Sleep(100);
        }
    }

#2

Does the problem still have if you remove the Debug.Print in the SerialDataReceived handler? It is probably not good to have that there because not all the bytes have come yet by the time this event happens.

I also do not think the Thread.Sleep after the Uart .Write is a good idea, as it just keeps to processor completelt busy. Your timer is only doing this once a second anyway, so its probably not even necessary.


#3

there is not a problem. this is the way serial ports work. you can not assume you will read all the data in one read.


#4

Thanks.
Now I understand.


#5

Also I don’t think that UART.Flush() is needed, because send buffer will clear on UART.Read().