0

I'm following this tutorial. The goal is to receive periodic data from the arduino via serial port. I've been struggling with this for a while now. The com port connection is fine as i'm unable to connect with another terminal program to the arduino when my c# app is running ( port is already connected). At this point the SerialListen thread should start but this doesn't happen.

namespace TestReceiveArduino
{
public partial class Form1 : Form
{
    //object serialport to listen usb
    System.IO.Ports.SerialPort Port;

    //variable to check if arduino is connect
    bool IsClosed = false;

    public Form1()
    {
        InitializeComponent();


        //configuration of arduino, you check if com3 is the port correct, 
        //in arduino ide you can make it
        Port = new System.IO.Ports.SerialPort();
        Port.PortName = "COM11";
        Port.BaudRate = 9600;
        Port.ReadTimeout = 500;

        try
        {
            Port.Open();
            Console.WriteLine("open port ");


        }
        catch { }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //A Thread to listen forever the serial port
        Console.WriteLine("start thread ");
        Thread Hilo = new Thread(ListenSerial);
        Hilo.Start();
    }


    private void ListenSerial()
    {
        Console.WriteLine("start listener");
        while (!IsClosed)
        {
            Console.WriteLine("in while");

            try
            {
                //read to data from arduino
                string AString = Port.ReadLine();

                //write the data in something textbox
                txtSomething.Invoke(new MethodInvoker(
                    delegate
                    {
                        txtSomething.Text = AString;
                    }
                    ));

            }
            catch { }
        }
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        //when the form will be closed this line close the serial port
        IsClosed = true;
        if (Port.IsOpen)
            Port.Close();
    }
}
}

My arduino is sending data, i've checked this with terminal software. I'm also using the correct COM port I have some experience with c# but i'm new to threads. What could be the reason for this?

reyntjensm
  • 27
  • 9
  • Just because another, different app is able to communicate doesn't mean your C# app is connecting to the serial port, or reading or writing serial I/O correctly. Q: What is ListenSerial doing? – paulsm4 May 11 '22 at 20:56
  • @paulsm4 i just added the complete code. The ListenSerial should listen continuously for new data from the arduino – reyntjensm May 11 '22 at 21:11
  • Q: So what's the deal with the empty "catch{}" block? Don't you *WANT* to detect legitimate exceptions??? Q: I assume you at least see "open port "? – paulsm4 May 11 '22 at 21:14
  • @paulsm4 i could add a warning here. But it doesn't matter, the code doesn't get to this point. – reyntjensm May 11 '22 at 21:16

1 Answers1

1

OK:

  1. See if these changes help:

    namespace TestReceiveArduino
    {
        public partial class Form1 : Form
        {
            //object serialport to listen usb
            System.IO.Ports.SerialPort Port;
    
            //variable to check if arduino is connect
            bool IsClosed = false;
    
            public Form1()
            {
                InitializeComponent();  
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                try
                {
                    // Connect to Arduino
                    Port = new System.IO.Ports.SerialPort();
                    Port.PortName = "COM11";
                    Port.BaudRate = 9600;
                    Port.ReadTimeout = 500;
                    Port.Open();
                    Console.WriteLine("Port successfully opened: Name: {0}, Baud: {1}, ReadTimeout: {2}", Port.PortName, Port.BaudRate, Port.ReadTimeout);
    
                   //A Thread to listen forever the serial port
                   Console.WriteLine("start thread ");
                   Thread Hilo = new Thread(ListenSerial);
                   Hilo.Start();
                }
                catch (Exception ex)
                { 
                    Console.WriteLine(ex.Message);
                }
            }
            ...
    
  2. I moved "Open Serial Connection" and "Start Listener Thread" to the same place (Form1_Load), and wrapped both in the same try/catch block. You might even want to move the "try/catch" to a higher level (e.g. so you can display any exceptions in your Windows GUI).

  3. I assume you're using Microsoft VisualStudio (e.g. MSVS Express 2019) as your GUI, correct? Definitely familiarize yourself with your IDE's debugger; definitely get in the habit of stepping through the code as you're developing it.

  4. Your next steps:

    • Verify the code gets to "Open Serial Connection", and verify that it opens correctly (e.g.prints "Port successfully opened...").
    • Verify the code then gets to "ListenSerial()", and prints "start listener" and "in while" at least once.

'Hope that helps...

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • Thank you for your feedback. nope, no output on console... – reyntjensm May 11 '22 at 21:47
  • 1
    OK: maybe the problem isn't "Serial I/O" at all. Maybe you're just expecting to see "console output" that simply isn't there :) Look here: https://stackoverflow.com/a/5706780/421195. Q: Are you using Visual Studio (MSVS)? Q: Do you see anything - EVER - in the MSVS "Console" window"? Q: Have you tried setting a breakpoint in Form1_Load() and stepping through the code in the MSVS debugger? – paulsm4 May 11 '22 at 22:08
  • i'm using visual studio 2022 and i already received data in the console while trying other things in the same project. So it should be that the code doesn't reach this point right now – reyntjensm May 11 '22 at 23:06
  • I'm glad you're using Visual Studio 2022 (the "MSVS" compiler IDE, *NOT* the "Visual Studio Code" editor, correct?) Sooooo ... Q: You moved "Port.Open();" into Form1_Load(), per my suggestion above. Correct? Q: Have you stepped through the code in the debugger? Q: Does it get into "Form1_Load()"? Q: How far does it get after that? – paulsm4 May 11 '22 at 23:47
  • PS: I looked at the tutorial you cited. I have several problems with it, including "eating exceptions". Exceptions are your Friend: you NEED to know if something goes wrong. As quickly as possible, with as much information as possible. – paulsm4 May 11 '22 at 23:53
  • I found a solution from another tutorial, this solution doesn't use threads and seems to work for my current application. https://curiousscientist.tech/blog/arduino-serial-terminal – reyntjensm May 12 '22 at 02:13
  • You STILL haven't answered my questions: 1) Did you happen to refactor the code as I suggested? 2) Have you tried setting breakpoints and stepping through the code in the debugger to determine exactly where things "went awry"? My guess is that you never got past "Port.Open()" ... if you got that far. 3) Are you making use of "Exceptions"? Or, alternatively, eliminating your try/catch blocks entirely? *ANYTHING* but "eating exceptions" ("Close()" might be OK ... but "Open()" .. No!!!)? I honestly DON'T believe the problem was related to "Threads"... – paulsm4 May 12 '22 at 03:33