Arduino Uno + C# | Function doesnt work

Dear community,
why the functions doesnt work?

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        string serialDataIn;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button_open.Enabled = true;
            button_close.Enabled = false;
            button_send.Enabled = false;
            progressBar_status.Value = 0;
            label_status.Text = "DISCONNECTED";
            label_status.ForeColor = Color.Red;

            comboBox_BAUD.Text = "9600";
            string[] portLists = SerialPort.GetPortNames();
            comboBox_COM.Items.AddRange(portLists);

        }

      

        private void button_open_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox_COM.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox_BAUD.Text);
                serialPort1.Open();

                button_open.Enabled = false;
                button_close.Enabled = true;
                button_send.Enabled = true;
                progressBar_status.Value = 100;
                label_status.Text = "CONNECTED";
                label_status.ForeColor = Color.Green;

                DateTime localDate = DateTime.Now;
                DateTime utcDate = DateTime.UtcNow;
                String[] cultureNames = { "de-DE" };

                foreach (var cultureName in cultureNames)
                {
                    var culture = new CultureInfo(cultureName);
                   
                    richTextBox_text.AppendText(Environment.NewLine + "   Local date and time: " +
                                      localDate.ToString(culture) + "  " + localDate.Kind + " --|| Nemesis started... ||");
                   
                    richTextBox_text.AppendText(Environment.NewLine + "   Enter h to display menu...");
                    

                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        private void button_close_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Close();

                    button_open.Enabled = true;
                    button_close.Enabled = false;
                    button_send.Enabled = false;
                    progressBar_status.Value = 0;
                    label_status.Text = "DISCONNECTED";
                    label_status.ForeColor = Color.Red;
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Close();
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);
                }
            }
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Write(textBox_input.Text + "#");

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            serialDataIn = serialPort1.ReadExisting();
            _ = this.Invoke(new EventHandler(ShowData));


        }

        private void ShowData(object sender, EventArgs e)
        {
            richTextBox_text.Text += serialDataIn;
            if (serialDataIn == "1")    // This function dosent work , but worked a few minutes before... 
            {
                DateTime localDate = DateTime.Now;
                DateTime utcDate = DateTime.UtcNow;
                String[] cultureNames = { "de-DE" };

                foreach (var cultureName in cultureNames)
                {
                    var culture = new CultureInfo(cultureName);

                    richTextBox_text.AppendText("   Local date and time: " + localDate.ToString(culture) + "  <-->" + localDate.Kind + " --|| TIME ||");
                    //serialPort1.Write(localDate.ToString(culture) + localDate.Kind);
                }
            }
            else if (serialDataIn == "2")     // This function dosent work too
            {
                DateTime localDate = DateTime.Now;
                DateTime utcDate = DateTime.UtcNow;
                String[] cultureNames = { "de-DE" };
                foreach (var cultureName in cultureNames)
                {
                    var culture = new CultureInfo(cultureName);
                    richTextBox_text.AppendText(Environment.NewLine + localDate.ToString(culture) + " Ping");
                }
                try
                {
                    Ping myPing = new Ping();
                    PingReply reply = myPing.Send("www.google.de", 1000);
                    if (reply != null)
                    {
                        richTextBox_text.AppendText(Environment.NewLine + "Status :  " + reply.Status + Environment.NewLine + " \n Time : " + reply.RoundtripTime.ToString() + Environment.NewLine + " \n Address : " + reply.Address);
                        richTextBox_text.AppendText(reply.ToString());
                        serialPort1.Write(reply.ToString());
                        serialPort1.Write("Status :  " + reply.Status + " \n Time : " + reply.RoundtripTime.ToString() + " \n Address : " + reply.Address);

                    }
                }
                catch
                {
                    richTextBox_text.AppendText(Environment.NewLine + "ERROR: You have Some TIMEOUT issue");
                }
            }






        }


        private void richTextBox_text_TextChanged(object sender, EventArgs e)
        {
            richTextBox_text.SelectionStart = richTextBox_text.Text.Length;
            richTextBox_text.ScrollToCaret();

        }

        private void start_1_Click(object sender, EventArgs e)
        {
            Process.Start("C:\\Program Files (x86)\\Arduino\\arduino.exe");
        }

        private void start_2_Click(object sender, EventArgs e)
        {
            Process.Start("D:\\Programme (x86)\\arduino-nightly-windows\\arduino-nightly\\arduino.exe");

        }

        private void start_3_Click(object sender, EventArgs e)
        {
            Process.Start("C:\\Users\\cl0ud\\AppData\\Local\\Programs\\Arduino IDE\\Arduino IDE.exe");
        }

        private void openfolder_btn_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"C:\Users\cl0ud\.Nemesis");
        }


    }
}

// Author: BlackLeakz
// Date: 18.05.2022
// Time: 0732
// Website: https://blackzspace.org
// Version: 1
// 3x 16x2 LCD , 1xExternal LED, //-+ potentiometer

// Libarys
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <TimerOne.h>





// LCD DISPLAYS
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);
LiquidCrystal_I2C lcd2 = LiquidCrystal_I2C(0x26, 16, 2);
LiquidCrystal_I2C lcd3 = LiquidCrystal_I2C(0x25, 16, 2);



// SETUP
void setup() {
  //LED + Serialmenu
 pinMode(LED_BUILTIN, OUTPUT);
 Serial.begin(9600);





 delay(300);


 delay(1000);
//init display1
 lcd.init();
 lcd.backlight();
 lcd.setCursor(0,0);
 lcd.blink();
 lcd.print("Version: v.0.1");


// init display2
 lcd2.init();
 lcd2.backlight();
 lcd2.setCursor(0,0);
 lcd2.blink();
 lcd2.print("Lcd2 ready...");


//init display3
 lcd3.init();
 lcd3.backlight();
 lcd.setCursor(0,0);
 lcd3.blink();lcd3.blink();
 lcd3.print("Welcome...");


 delay(4000);

 lcd.clear();
 lcd.home();
 lcd.blink();
 lcd2.clear();
 lcd2.home();
 lcd2.blink();
 lcd3.clear();
 lcd3.home();
 lcd3.blink();

 digitalWrite(LED_BUILTIN, HIGH);
 delay(30);
 digitalWrite(LED_BUILTIN, LOW);
 delay(30);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(30);
 digitalWrite(LED_BUILTIN, LOW);
 delay(300);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(100);
 digitalWrite(LED_BUILTIN, LOW);

}


// LOOP

void loop() {

 //int sensorValue = analogRead(A0);
 if(Serial.available() > 0)  {
 int incomingData= Serial.read(); // can be -1 if read error
    switch(incomingData) {
        case '-1':
            Serial.println("Error");
            break;

        case '1':
            Serial.println();
            Serial.print("Get current time");
            Serial.write("1");
            Serial.println();
            break;

        case '2':
            Serial.println();
            Serial.print("Get PING");
            Serial.write("2");
            Serial.println();
            break;

        case '3':
            Serial.println("Starting Tracert-Test...");
            Serial.write("3");
            break;

        case '4':
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.blink();
            lcd.print("Start PIPE...");

            break;

        case '!':
            Serial.println("!-: Write to LCD");
            Serial.println();
            if (Serial.available()) {
            delay(200);
            lcd.clear();
            while (Serial.available() > 0) {
            lcd.write(Serial.read());
            }
            }
            break;



       case 'v':
           Serial.println("Version: v0.1");
           lcd.clear();
           lcd.home();
           lcd.print("Version: v0.1");
           delay(1000);
           break;

    //   case 'p':
    //      Serial.println("Potentiometer");
          //Serial.println(sensorValue);
    //      lcd2.clear();
    //      lcd2.setCursor(0, 0);
    //      lcd2.blink();
          //lcd2.print(sensorValue);
    //      delay(500);
    //      break;


       case 'c':
          Serial.println("Clearing LCD's...");
          lcd.print("CLEAR");
          lcd.clear();
          lcd.home();
          lcd.blink();
          lcd2.print("CLEAR");
          lcd2.clear();
          lcd2.home();
          lcd2.blink();
          lcd3.print("CLEAR");
          lcd3.clear();
          lcd3.home();
          lcd3.blink();

       case 'h':
          Serial.println("___________________________________________________________________________________________________");
          Serial.println("== nemesis_montor |    || (c)by BlackLeakz                                                       ==");
          Serial.println("---------------------------------------------------------------------------------------------------");
          Serial.println("== !: Write to display  || v: version  || i: Led off || o: Led on || x: Led blink || h: Help     ==");
          Serial.println("== (1): Time ||  (2): ping  || (3): tracert  || (4): PIPE || p: Potentiometer1(?)  || c: clear   ==");
          Serial.println("===================================================================================================");
          break;

        case 'i':
          digitalWrite(LED_BUILTIN, HIGH);
          break;

        case 'o':
          digitalWrite(LED_BUILTIN, LOW);
          break;

        case 'x':
          while(true) {
          digitalWrite(LED_BUILTIN, HIGH);
          delay(30);
          digitalWrite(LED_BUILTIN, LOW);
          delay(30);
          digitalWrite(LED_BUILTIN, HIGH);
          delay(30);
          digitalWrite(LED_BUILTIN, LOW);
          delay(300);
          digitalWrite(LED_BUILTIN, HIGH);
          delay(100);
          digitalWrite(LED_BUILTIN, LOW);
          if (Serial.read() == 'm')
          {
            return loop();
          }
          }
          break;


       default:
          // handle unwanted input here
          break;
  }

}
}

1 Like

What does "Function doesnt work" mean?

Not troubleshooting C# code, not the proper forum.

1 Like

in

case '1':
            Serial.println();
            Serial.print("Get current time");
            Serial.write("1");
            Serial.println();
            break;

I write to c# Serial
and the c# function:

private void ShowData(object sender, EventArgs e)
        {
            richTextBox_text.Text += serialDataIn;
            if (serialDataIn == "1")    // This function dosent work , but worked a few minutes before... 
            {
                DateTime localDate = DateTime.Now;
                DateTime utcDate = DateTime.UtcNow;
                String[] cultureNames = { "de-DE" };

                foreach (var cultureName in cultureNames)
                {
                    var culture = new CultureInfo(cultureName);

                    richTextBox_text.AppendText("   Local date and time: " + localDate.ToString(culture) + "  <-->" + localDate.Kind + " --|| TIME ||");
                    //serialPort1.Write(localDate.ToString(culture) + localDate.Kind);
                }
            }```

Should  print the local date and time to richTextBox

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise) your project.

1 Like

thnx

try sending a command using a line of text terminated by a newline, e.g.

Serial.println("Get current time");

then rather than using

serialDataIn = serialPort1.ReadExisting();

where you could read fragments of a line of text try

serialDataIn = serialPort1.ReadLine();

which retruns a complete line of text, e.g. Get current time

then use the Contains method to look for a command within the line of text
public bool Contains(string value)
Returns a value indicating whether the specified String object occurs within this string.
e.g.

            if (serialDataIn.contains("Get current time") )   
                
1 Like

Not solving the problem

  1. Text between single ticks is a character; '-1' is not a character. You should check the numeric value -1 (so case -1:).
  2. The above case will never be encountered if Serial.available() indicates that there is something to read
1 Like

have a look at this simple test program
an Arduino UNO sends a command every 10 seconds to a C# program running on a PC to print the local datatime or the UTC datatime

void setup() {
   Serial.begin(115200);
 }

void loop() {
  delay(10000);
  Serial.println("Get current time");
  delay(10000);
  Serial.println("Get UTC time");
}

and the C# console program

using System;
using System.IO.Ports;

namespace ConsoleTerminal
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort serialPort = new SerialPort() ;
            serialPort.PortName = "COM10";
            serialPort.BaudRate = 115200;
            serialPort.Open();
            while (true)
            {
                string s = serialPort.ReadLine();
                Console.WriteLine("data received " + s);
                // check command received
                if (s.Contains("Get current time"))
                {
                    DateTime localDate = DateTime.Now;
                    Console.WriteLine("   Local date and time: " + localDate.ToString());
                 }
                if (s.Contains("Get UTC time"))
                {
                   DateTime utcDate = DateTime.UtcNow;
                    Console.WriteLine("   UTC date and time: " + utcDate.ToString());
                }
            }
        }
    }
}

a run gives

data received Get current time
   Local date and time: 19/05/2022 09:01:34
data received Get UTC time
   UTC date and time: 19/05/2022 08:01:44
data received Get current time
   Local date and time: 19/05/2022 09:01:54
data received Get UTC time
   UTC date and time: 19/05/2022 08:02:04
data received Get current time
   Local date and time: 19/05/2022 09:02:14
data received Get UTC time
   UTC date and time: 19/05/2022 08:02:24
1 Like

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