Unable to read the Serial bus using C#

Hello dear Arduino community,
I'm currently trying to use an WPF (C#) programm to visualize which LED's I have turned on, but I'm unable to read from the Serial Port by using System.IO.Ports.
Is there anything that have to send first to let the Arduino UNO know that he is able to send data to the Serial bus?
Or is something wrong with Serial.Read() / Serial.ReadExisting() ?
Or am I dumb? If thats the case could you give me some references/sources?

Here you can see a simple code that always writes and reads to the bus.

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");

  pinMode(LED_BUILTIN, OUTPUT);
  
}
int i = 1;
char a;
void loop() {

  i++;
  Serial.println(i);
  delay(500);

  if(Serial.available()){
    a = Serial.read();
    if(a == '1') digitalWrite(LED_BUILTIN, HIGH);
    else if (a == '0') digitalWrite(LED_BUILTIN, LOW);
  }
}

And the code that I use to read the bus via C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


using System.Threading;
using System.IO.Ports;



namespace Read_Serial_Arduino
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    /// 



    public partial class MainWindow : Window
    {

        static public SerialPort sp = new SerialPort();
        static public Thread getStatesThread = new Thread(Read);

        public static bool Connected = false;
        public static String message0;
        public static String message1;

        public MainWindow()
        {
            InitializeComponent();
            Test.Text = "Thats the Serial port:" + message0 + " " + message1;
        }

        //_________________________________Reading Serial___________________________________________________

        private static void Read()
        {
            while (Connected)
            {
                try
                {
                    message0 = sp.ReadLine();
                    message1 = sp.ReadLine();
                }
                catch (TimeoutException)
                {
                    MessageBox.Show("Communication has been cut");
                }
            }


        }


        //___________________________________Serial Connection_______________________________________________

        private void Serial_Connect(object sender, RoutedEventArgs e)
        {
            try
            {
                String portName = comportno.Text;
                sp.PortName = portName;
                sp.BaudRate = 115200;
                sp.Open();
                status.Text = "Connected";
                Connected = true;

            }
            catch (Exception)
            {
                MessageBox.Show("Please give a valid port number or check your connection");
            }
        }

        private void Serial_Disconnect(object sender, RoutedEventArgs e)
        {
            try
            {
                sp.Close();
                status.Text = "Disconnected";
                Connected = false;

            }
            catch (Exception)
            {

                MessageBox.Show("First Connect and then disconnect");
            }
        }


        private void Serial_On(object sender, RoutedEventArgs e)
        {
            sp.WriteLine("1");
        }

        private void Serial_Off(object sender, RoutedEventArgs e)
        {

            sp.WriteLine("0");
            
        }
    }
}
  • XAML Code
<Window x:Class="Read_Serial_Arduino.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Read_Serial_Arduino"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox Name="Test" FontSize="20" HorizontalAlignment="Left" Height="137" Margin="310,90,0,0" TextWrapping="Wrap" Text="Hello World" VerticalAlignment="Top" Width="421"/>
        <Label Content="Serial Connection" FontSize="18" HorizontalAlignment="Left" Margin="44,270,0,0" VerticalAlignment="Top" FontWeight="Bold"/>
        <Button Content="On" HorizontalAlignment="Left" Margin="76,309,0,0" VerticalAlignment="Top" Width="75" Click="Serial_On"/>
        <Button Content="Off" HorizontalAlignment="Left" Margin="166,309,0,0" VerticalAlignment="Top" Width="75" Click="Serial_Off"/>
        <Button Content="Connect" HorizontalAlignment="Left" Margin="258,337,0,0" VerticalAlignment="Top" Width="49" Height="19" Click="Serial_Connect"/>
        <Button Content="Disconnect" HorizontalAlignment="Left" Margin="312,337,0,0" VerticalAlignment="Top" Width="66" Height="19" Click="Serial_Disconnect"/>
        <TextBlock Name="status" Text="Disconnected" HorizontalAlignment="Left" Height="19" Margin="258,361,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="75"/>
        <TextBox Name="comportno" HorizontalAlignment="Left" Height="23" Margin="258,309,0,0" TextWrapping="Wrap" Text="COM13" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

Sending Strings to the Arduino works completly fine but reading is still a Problem.

You could look at the code for PLX-DAQ version 2 - now with 64 bit support! (and further new features) - #464 by okan_sabrioglou which uses an Excel spread sheet to interface with a MCU to see how he did it, perhaps?

Hm.. that doesn't help that much

I have experimented with using the data received handler which runs in a second thread, here it is if it is of any help. It reads a string that is terminated with a newline character. In the snippet there are a few lines commented out that are a binary alternative to reading an ASCII string but you can try it and see if it captures your data. The solution is a Form with 1 RichTextbox and 1 Button.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;


namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {

        SerialPort myport = new SerialPort();
        public delegate void myDelegate(string sData);


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myport.PortName = "COM7";
            myport.Open();
            myport.DataReceived += new SerialDataReceivedEventHandler(myport_DataReceived);
            myport.ReadExisting();
        }

        private void strDebug(string sData)
        {
            richTextBox1.AppendText(sData + "\n");

            //if (sData < 32 && sData != 10) { string s = sData.ToString(); richTextBox1.AppendText('\n' + s + '\n'); }

            //else { char myData = (char)sData; richTextBox1.AppendText(myData.ToString()); }
        }

        private void myport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

        {
           
            myport.ReadTimeout = 20;
           
                try
                {
                // byte str=(byte) myport.ReadByte();
                string str = myport.ReadLine();
                this.BeginInvoke((new myDelegate(strDebug)), str);
            }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
      

        private void button1_Click(object sender, EventArgs e)
        {
            myport.WriteLine("Arduino");
        }
    }
}

I found some problems in my Code, I will try your solution but I'm to stoopid right now to use Invoke functions in an WPF programm. Maybe I switch to an Windows Form App, but we will see.
I will look at it on the weekend.
Thanks for suggestion!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.