Read Water Level Sensor Data with c#

hi all .
i want to read analog data from the water level sensor in arduino and in C# application to get data from the analog reading and display to richtextbox in C#

here is the C# code :

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

namespace MenuUtama
{
    public partial class Form1 : Form
    {
        SerialPort ser = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] availablePorts;
            availablePorts = SerialPort.GetPortNames();
            for (int i = 0; i < availablePorts.Length; i++)
            {
                comboBox1.Items.Add(availablePorts[i]);
            }
            richTextBox1.Text = " WELCOME ";
        }

        private void button1_Click(object sender, EventArgs e)
        {
                    ser.PortName = comboBox1.Text;
                    ser.Open();
                    ser.Write("1");
                    ser.Close();
         }
          
        private void button2_Click(object sender, EventArgs e)
            {
                ser.PortName = comboBox1.Text;
                ser.Open();
                ser.Write("2");
                ser.Close();
            }
        
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        
    }
}

here is the Arduino code :

int Relay = 3;

void setup() 
{
  pinMode(Relay, OUTPUT);
}

void loop() 
{
  while (Serial.available() == 0);
  int nilai = Serial.read()-'0';
  
  if (nilai == 1)
  {
      Serial.println(analogRead(A10));
      delay(1000);
      digitalWrite(Relay, HIGH);
  }
  else if (nilai == 2)
  {
      digitalWrite(Relay, LOW);
  }
  
}

thanks before for your help :slight_smile:

Please use the #button when posting code to apply the right tags . The code is more readable and easier to debug etc
You can modify you post and select the code part (each separately) and press the # button ,

Thank you.

The problem is that the C# application does not read any serial data.

2 seconds of google

hehe . sorry . i am new in this forum :(

thank you very much for your help.

if i use serial.println in arduino code without input from c# app, i can read via serial monitor the value but if i use c# app to run the arduino code, when i look at serial monitor, there is no value, empty why is that ?

That is probably because when the data is read from the serial port by an application it is removed and therfore it is not available any more for a second application that also (tries to) read from that port.