Main Site Documentation

Problem: SerialPort.DataReceived only triggers once


#1
using System.Threading;
using System.IO.Ports;
using System.Text;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.IO;
using GHIElectronics.NETMF.USBHost;
using System.IO;
using System;

namespace MFConsoleApplication1
{

    public class Program
    {
        
        public static void Main()
        {
            
            SerialPort UART = new SerialPort("COM1");
            UART.BaudRate = 115200;
            UART.Parity = Parity.None;
            UART.StopBits = StopBits.One;
            UART.DataBits = 8;
            UART.Handshake = Handshake.None;
            UART.Open();
            UART.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
            UART.ErrorReceived += new SerialErrorReceivedEventHandler(UART_ErrorReceived);
            Thread.Sleep(Timeout.Infinite);
            
        }

        private static void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Debug.Print("trigger");
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            SerialPort UART = new SerialPort("COM1", 115200);
            byte[] chbyte = new byte[1];

            UART.Read(chbyte, 0, 1);
            string myString = new string(enc.GetChars(chbyte));
            Debug.Print(myString);

            if (string.Compare(myString, "p") == 0)
            {
                Debug.Print("ping");
                System.Text.Encoding enc1 = System.Text.Encoding.UTF8;
                byte[] ping = new byte[1];
                ping = enc1.GetBytes("p");
                UART.Write(ping, 0, 1);
            }
        }
        private static void UART_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            Debug.Print("error");
        }
    }
}

Above is the isolated code for “pinging” the Fez Domino.
The Fez will receive “p” via UART and responds with “p” also.

Computer: p
C# debug output: trigger
Fez: p

Computer: p
C# debug output:(none)
Fez: (no response)

Is there something wrong with the code?


#2

I didn’t try your code, but you are re-declaring a UART in your event handler, which doesn’t seem good to me :frowning:

You should declare a global UART in the class before main() and use only this one in all your code.


#3

As Bec says, make your SerialPort a class level instance, reinitialising the COM1 port will lose all your event handlers, which reside on a class instance that no longer has control of a COM port!