Rajeev Kumar
Rajeev Kumar

Reputation: 4963

Serial Port application in console not working

I am trying to make a console application in c# that reads Serial Port and send data over TCP to another machine in network.

I have written the following code

class Program
{

    static SerialPort mPort;
    static void Main(string[] args)
    {
        mPort = new SerialPort();
        mPort.BaudRate = 4800;
        mPort.StopBits = StopBits.One;
        mPort.Parity = Parity.None;
        mPort.Handshake = Handshake.None;
        mPort.DataBits = 8;
        mPort.PortName = "COM4";
        if (!mPort.IsOpen)
        {
            mPort.Open();
        }
        mPort.DataReceived += new SerialDataReceivedEventHandler(mPort_DataReceived);

    }
    private static void mPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (mPort.IsOpen)
            {

            }
        }
        catch
        {

        }
    }
 }

but application closed after hitting mPort.DataReceived += new SerialDataReceivedEventHandler(mPort_DataReceived); line in static void Main(string[] args) function.

Why it is not firing mPort_DataReceived event ??

Upvotes: 0

Views: 510

Answers (3)

Dieter Meemken
Dieter Meemken

Reputation: 1967

The reason is, that your program simply terminates. You need a kind of loop to keep it alive, for example like this. It's running and checking if a key has been pressed, and stopps only if that was 'Escape'.

        // Do initialisation work here

        ConsoleKeyInfo cki = new ConsoleKeyInfo();
        do 
        {
            // Do frequently work here

            if (Console.KeyAvailable)
            {
                cki = Console.ReadKey();
            }
        }
        while (cki.Key != ConsoleKey.Escape);

Upvotes: 0

René Vogt
René Vogt

Reputation: 43886

The line

mPort.DataReceived += new SerialDataReceivedEventHandler(mPort_DataReceived);

is subscribing to the event. But you never wait for an event to occure.

After that line, your Main method returns. As this is the main method of your process, your process terminates after Main returns.

One simple way to keep the process running is to add something like

Console.ReadLine();

at the end of Main, so your program waits for the user to hit a key before it terminates.

Upvotes: 2

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

This is basic console application behaviour. Just add:

    mPort.DataReceived += ...

    /// wait till something happens
    Console.Read();
}

at the end of the main method. Then watch your event to get fired.

This approach is only a workaround for that behaviour.

Upvotes: 2

Related Questions