Interface from Arduino to VB.net, need help as a beginner

Hi!

I have learned alot the last days, but want to expand more.

I'm setting up a soil-moisture program, will post pictures and codes of what i got so far.

First, my arduino code:

#define soilSensor1 A0
#define soilSensor2 A1

#define pump1 2
#define pump2 3


const int dry = 534;
const int wet = 297;

const int dry1 = 534;
const int wet1 = 297;

//
const unsigned long Seconds = 1000;
const unsigned long Minutes = 60 * Seconds;
unsigned long PreviousMillis = 0;
//



    
void setup() {
  pinMode(pump1, OUTPUT);
  pinMode(pump2, OUTPUT);

  
  Serial.begin(9600);

  
}

void loop()
{
  int sensorVal1 = analogRead(soilSensor1);
  int percentageHumididy = map(sensorVal1, wet, dry, 100, 0)
  ;Serial.print(" Sensor 1 = ");
  Serial.print(percentageHumididy);
  Serial.println("%");

  int sensorVal2 = analogRead(soilSensor2);
  int percentageHumididy2 = map(sensorVal2, wet1, dry1, 100, 0)
  ;Serial.print(" Sensor 2 = ");
  Serial.print(percentageHumididy2);
  Serial.println("%");


  {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal1 > 380 )
    {
      digitalWrite(pump1, HIGH);
      delay(10000);
      digitalWrite(pump1, LOW);
    }
  }
}

   {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal2 > 380 )
    {
      digitalWrite(pump2, HIGH);
      delay(10000);
      digitalWrite(pump2, LOW);
    }
  }
}
  
  delay(1000);
}

This is my VB. net code:

Public Class Form1
    ' set up delegate to display data received from serial port
    Private Delegate Sub SerialDelegate(ByVal Buffer As String)
    Private adre As New SerialDelegate(AddressOf DisplayData)
    ' key pressed on terminal textbox
    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        SerialPort1.Write(e.KeyChar)
    End Sub
    ' character received from serial port
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim ReceivedData As String = SerialPort1.ReadExisting()
        Me.Invoke(adre, ReceivedData)
    End Sub
    ' delegate to display string received
    Private Sub DisplayData(ByVal sdata As String)
        TextBox1.AppendText(sdata)
    End Sub
    ' on form load open serial port
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
    End Sub

    Private Sub Form1_FormClosed(sender As System.Object, e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        SerialPort1.Close()
    End Sub
End Class

As you can see in this picture, I managed to get the readings into a textbox:

As said, I want to take this further, but I'm a beginner end need some help with the basics.
As I undersatnd, VB now reads what my COM-port recieves from the Arduino.
First question; how to i split the values from A0 and A1 so i can show them in diferent text-boxes?
Question 2; Can i get this into a progressbar/diagram or anything else to make it more pro-looking?

You can use standard VB string handling functions to split the string, for example instr and look for the first % character.

Alternatively, make it easier and just send the two readings from the arduino separated by a comma.

Hate to be in the basic learning process, but have to start somewhere :wink:

I sort of understand what you say, but still got some questions to your answer:

VB string to split the string; does that mean that VB will split the string after a specific "letter"?

Alternatively make it easier .. .. (can i program the arduino to send 2 seperate reading?

If you don't mind, please copy my codes and put in the examples :slight_smile:

Something like this?


' String to search in.
Dim searchString As String = "XXpXXpXXPXXP"
' Search for "P".
Dim searchChar As String = "P"

Dim testPos As Integer
' A textual comparison starting at position 4. Returns 6.
testPos = InStr(4, searchString, searchChar, CompareMethod.Text)

' A binary comparison starting at position 1. Returns 9.
testPos = InStr(1, SearchString, SearchChar, CompareMethod.Binary)

' If Option Compare is not set, or set to Binary, return 9.
' If Option Compare is set to Text, returns 3.
testPos = InStr(searchString, searchChar)

' Returns 0.
testPos = InStr(1, searchString, "W")

And where do I put the string code, what other changes do i hve to do with the code to define the different strings? (If that's the case) ...

Or something like this with the arduino?

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

Hi, if you are sending two strings give each string a header followed by a comma like this for example

int percentageHumididy1;
int percentageHumididy2; 

void setup()
{
 

  Serial.begin(9600);  
 
}

void loop()
{
 percentageHumididy1=55;
 percentageHumididy2=72; 
delay(1000);
  Serial.print("Sensor1,");
  Serial.println(percentageHumididy1);
  Serial.print("Sensor2,");
  Serial.println(percentageHumididy2);
}

The commas at the end of Sensor1 and at the end of Sensor2 separate the headers from the data and by using println you would be appending a carriage return to your data. The VB serial port has a method called "ReadLine" that will read the serial buffer until it reaches a line terminator, which will be carriage return. Here is your code modified slightly to include "ReadLine" and also the split function that wildbill mentioned.

The VB form has 2 textboxes and 1 serial port

 Private Delegate Sub myDelegate(ByVal Buffer As String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        SerialPort1.Open()
    End Sub

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        SerialPort1.ReadTimeout = 100

        Dim sData As String = Nothing
        Try
            sData = SerialPort1.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)

    End Sub

    Private Sub DisplayData(ByVal sdata As String)

        Dim txtarray As String() = Split(sdata, ",")

        If txtarray.Count = 2 Then
            If txtarray(0) = "Sensor1" Then
                TextBox1.Text = "Sensor 1 value=" & txtarray(1) & " %"
            End If

            If txtarray(0) = "Sensor2" Then
                TextBox2.Text = "Sensor 2 value=" & txtarray(1) & " %"
            End If

        End If

    End Sub

The above is very basic but provides a good foundation to build on, once you capture the readings in the textboxes you can move on to add a graphical dial (a user control) that displays percentage.

Thanks alot for the reply!

As said, I'm in the process of learning, and tried to understand the code you posted..

Loads of errors, and don't know where to start..

If it's not a big problem for you, would you mind copy my exsisting code and put in what you wrote?

Anyways, thanks alot for answering my post :slight_smile:

"Loads of errors, and don't know where to start" does not really tell me anything so it is hard for me to point you in the right direction.

The objective is to create a simple protocol where we place data in a bracket of a header and a terminator and VB is set up to recognise the data in it's brackets. The header is a simple word, either "Sensor1," or "Sensor2," (no spaces) this is followed by the data, either "percentageHumididy" or "percentageHumididy2" and finally the terminator which is CR and produced by using the "Serial.println" instruction. Notice the difference between print and println.

So the first sensor would transmit a string like this "Sensor1,the actual data value here"CR. The comma that follows the header is used as the marker to split the string into header and data which is then placed in an array that I call txtarray. We now end up with two strings from one txtarray(0)="Sensor1" (comma has been removed) and txtarray(1)=the value of percentageHumididy.

The visual basic code I posted is set up to capture this protocol, your Arduino code needs the following modification.

void loop()
{
  int sensorVal1 = analogRead(soilSensor1);
  int percentageHumididy = map(sensorVal1, wet, dry, 100, 0);
  Serial.print("Sensor1,");                                   //header
  Serial.println(percentageHumididy);                         //data transmitted with CR
  
  int sensorVal2 = analogRead(soilSensor2);
  int percentageHumididy2 = map(sensorVal2, wet1, dry1, 100, 0);
  Serial.print("Sensor2,");                                  //header
  Serial.println(percentageHumididy2);                       //data transmitted with CR

Thanks for taking the time to answer me :slight_smile:

Think I'm nearly there now, just have to re-read your posts and do some more research.

No errors now, but it still wont read values to the text boxes.. Probably some easy fix..

I'll just post my codes as they are atm. Dont want to be the guy that comes with stupid questions, soon I'll be the one answering other people in trouble :rofl:

Arduino code:

#define soilSensor1 A0
#define soilSensor2 A1

#define pump1 2
#define pump2 3


const int dry = 534;
const int wet = 297;
const int dry1 = 534;
const int wet1 = 297;

int percentageHumididy;
int percentageHumididy2;

const unsigned long Seconds = 1000;
const unsigned long Minutes = 60 * Seconds;
unsigned long PreviousMillis = 0;



    
void setup() {
  pinMode(pump1, OUTPUT);
  pinMode(pump2, OUTPUT);

  
  Serial.begin(9600);

  
}

void loop()
{

  int sensorVal1 = analogRead(soilSensor1);
  int percentageHumididy = map(sensorVal1, wet, dry, 100, 0)
  ;Serial.print("Sensor1,");
  Serial.println(percentageHumididy);


  int sensorVal2 = analogRead(soilSensor2);
  int percentageHumididy2 = map(sensorVal2, wet1, dry1, 100, 0)
  ;Serial.print("Sensor2,");
  Serial.println(percentageHumididy2);



  {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal1 > 380 )
    {
      digitalWrite(pump1, HIGH);
      delay(10000);
      digitalWrite(pump1, LOW);
    }
  }
}

   {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal2 > 380 )
    {
      digitalWrite(pump2, HIGH);
      delay(10000);
      digitalWrite(pump2, LOW);
    }
  }
}
  
  delay(1000);
}

VB code:

Public Class Form1
    ' set up delegate to display data received from serial port
    Private Delegate Sub myDelegate(ByVal Buffer As String)


    ' character received from serial port
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        SerialPort1.ReadTimeout = 1000

        Dim sData As String = Nothing
        Try
            sData = SerialPort1.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)
    End Sub
    ' delegate to display string received
    Private Sub DisplayData(ByVal sdata As String)

        Dim txtarray As String() = Split(sdata, ",")

        If txtarray.Count = 2 Then
            If txtarray(0) = "Sensor1," Then
                TextBox1.Text = "Sensor 1 value=" & txtarray(1) & " %"
            End If

            If txtarray(0) = "Sensor2," Then
                TextBox2.Text = "Sensor 2 value=" & txtarray(1) & " %"
            End If

        End If
    End Sub
    ' on form load open serial port
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
    End Sub

    Private Sub Form1_FormClosed(sender As System.Object, e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        SerialPort1.Close()
    End Sub
End Class


Thanks again!

Got it working! :smiley:

Thanks alot for the help @sumguy ,really appriciate it :slight_smile:

Can you tell us what the problem was and how you fixed it.

The time out value is too high drop it down to 50 or 100

SerialPort1.ReadTimeout = 1000

Your next steps would be to research a few things to make a better inteface, buttons to open and close the serial port, combo boxes to display baud rates and available com ports.

If you need some help on how to design a dial as a visual percentage indicator then say so and we can give you a start with that.

Not shure exactly what i did to get it working, but think the problem was that i forgot to add
Imports System.IO.Ports

This is my working VB code:

Imports System.IO.Ports

Public Class Form1
    Private Delegate Sub myDelegate(ByVal Buffer As String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        SerialPort1.Open()
    End Sub

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        SerialPort1.ReadTimeout = 50

        Dim sData As String = Nothing
        Try
            sData = SerialPort1.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)

    End Sub

    Private Sub DisplayData(ByVal sdata As String)

        Dim txtarray As String() = Split(sdata, ",")

        If txtarray.Count = 2 Then
            If txtarray(0) = "Sensor1" Then
                TextBox1.Text = "Sensor 1 value=" & txtarray(1) & " %"
            End If

            If txtarray(0) = "Sensor2" Then
                TextBox2.Text = "Sensor 2 value=" & txtarray(1) & " %"
            End If

        End If

    End Sub
End Class

And this is my working Arduino code:

#define soilSensor1 A0
#define soilSensor2 A1

#define pump1 2
#define pump2 3


const int dry = 558;
const int wet = 290;
const int dry1 = 562;
const int wet1 = 310;

int percentageHumididy;
int percentageHumididy2;

const unsigned long Seconds = 1000;
const unsigned long Minutes = 60 * Seconds;
unsigned long PreviousMillis = 0;



    
void setup() {
  pinMode(pump1, OUTPUT);
  pinMode(pump2, OUTPUT);

  
  Serial.begin(9600);

  
}

void loop()
{

  int sensorVal1 = analogRead(soilSensor1);
  int percentageHumididy = map(sensorVal1, wet, dry, 100, 0)
  ;Serial.print("Sensor1,");
  Serial.println(percentageHumididy);


  int sensorVal2 = analogRead(soilSensor2);
  int percentageHumididy2 = map(sensorVal2, wet1, dry1, 100, 0)
  ;Serial.print("Sensor2,");
  Serial.println(percentageHumididy2);



  {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal1 > 380 )
    {
      digitalWrite(pump1, HIGH);
      delay(10000);
      digitalWrite(pump1, LOW);
    }
  }
}

   {
  if (millis() - PreviousMillis >= 1 * Minutes)
  {
    PreviousMillis += 1 * Minutes;
    if (sensorVal2 > 380 )
    {
      digitalWrite(pump2, HIGH);
      delay(10000);
      digitalWrite(pump2, LOW);
    }
  }
}
  
  delay(1000);
}

I allready got some projects with "buttons to open and close" "baud-rates" and "available COM ports", so I'll take a look at that..

I would like to get it to work with "circular_progress_bar" and maybe a chart of some kind, so if you could tell me where to start, please do :slight_smile:
Fonts and other stuff i will manage myself :slight_smile:

So, this is my code now, with working scan port and baud rate :smiley:

Imports System.IO.Ports

Public Class Form1
    Private Delegate Sub myDelegate(ByVal Buffer As String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.CenterToScreen()
        ConnectionPanel.Focus()
        ComboBoxBaudRate.SelectedIndex = 0
    End Sub

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort.DataReceived

        SerialPort.ReadTimeout = 50

        Dim sData As String = Nothing
        Try
            sData = SerialPort.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)

    End Sub

    Private Sub DisplayData(ByVal sdata As String)

        Dim txtarray As String() = Split(sdata, ",")

        If txtarray.Count = 2 Then
            If txtarray(0) = "Sensor1" Then
                TextBox1.Text = "Sensor 1 value = " & txtarray(1) & " %"
            End If

            If txtarray(0) = "Sensor2" Then
                TextBox2.Text = "Sensor 2 value = " & txtarray(1) & " %"
            End If

        End If

    End Sub

    Private Sub ButtonScanPort_Click(sender As Object, e As EventArgs) Handles ButtonScanPort.Click
        ConnectionPanel.Focus()
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to scan the new port.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
        ComboBoxPort.Items.Clear()
        Dim myPort As Array
        Dim i As Integer
        myPort = IO.Ports.SerialPort.GetPortNames()
        ComboBoxPort.Items.AddRange(myPort)
        i = ComboBoxPort.Items.Count
        i = i - i
        Try
            ComboBoxPort.SelectedIndex = i
            ButtonConnect.Enabled = True
        Catch ex As Exception
            MsgBox("Com port not detected", MsgBoxStyle.Critical, "Warning !!!")
            ComboBoxPort.Text = ""
            ComboBoxPort.Items.Clear()
            Return
        End Try
        ComboBoxPort.DroppedDown = True
    End Sub

    Private Sub ComboBoxPort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPort.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub

    Private Sub ComboBoxPort_DropDown(sender As Object, e As EventArgs) Handles ComboBoxPort.DropDown
        ConnectionPanel.Focus()
    End Sub

    Private Sub LinkLabel_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)

    End Sub

    Private Sub ComboBoxPort_Click(sender As Object, e As EventArgs) Handles ComboBoxPort.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Connection in progress, please Disconnect to change COM.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ComboBoxBaudRate_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub



    Private Sub ComboBoxBaudRate_DropDown(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.DropDown
        ConnectionPanel.Focus()
    End Sub


    Private Sub ComboBoxBaudRate_Click(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to change Baud Rate.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
        ConnectionPanel.Focus()
        Try
            SerialPort.BaudRate = ComboBoxBaudRate.SelectedItem
            SerialPort.PortName = ComboBoxPort.SelectedItem
            SerialPort.Open()
            TimerSerial.Start()

            LabelStatus.Text = "Status : Connected"
            ButtonConnect.SendToBack()
            ButtonDisconnect.BringToFront()
        Catch ex As Exception
            MsgBox("Please check the Hardware, COM, Baud Rate and try again.", MsgBoxStyle.Critical, "Connection failed !!!")
        End Try
    End Sub
    Private Sub ButtonDisconnect_Click(sender As Object, e As EventArgs) Handles ButtonDisconnect.Click
        ConnectionPanel.Focus()
        TimerSerial.Stop()
        SerialPort.Close()
        ButtonDisconnect.SendToBack()
        ButtonConnect.BringToFront()
        LabelStatus.Text = "Status : Disconnect"
    End Sub

    '====================================== Connection Panel End ================================================'



End Class

Anyone wanna try to explain how I get these values to a chart?

I don't know a great deal about MSChart but I believe it's a subject you are going to have to research on more appropriate forums, there is a great deal of info out there. To get you started I can help with something simple that allows you to alter values and play around with a template that assumes the values come from the Arduino once every second for a duration of five minutes.

Snippet 1 is code that resets the Arduino and clears the PC serial buffer giving you a clean start.

SerialPort1.DtrEnable = True
        SerialPort1.Open()
        SerialPort1.ReadExisting()

Snippet 2 is an addition to your existing DisplayData sub routine and passes the data to the chart.

Dim chartvalue As Integer

If txtarray(0) = "Sensor1" Then
                TextBox1.Text = "Sensor 1 value=" & txtarray(1) & " %"
                Integer.TryParse(txtarray(1), chartvalue)
                Chart1.Series("Series1").Points.Add(chartvalue)
            End If

            If txtarray(0) = "Sensor2" Then
                TextBox2.Text = "Sensor 2 value=" & txtarray(1) & " %"
                Integer.TryParse(txtarray(1), chartvalue)
                Chart1.Series("Series2").Points.Add(chartvalue)
            End If

Snippet 3 is a sub routine with various chart settings that you can play around with to learn and modify the charts properties. Call this sub from the Form1 Load event handler.

Private Sub ChartSettings()

        Chart1.BackColor = Color.Bisque

        Chart1.Series("Series1").ChartType = SeriesChartType.Spline
        Chart1.Series("Series2").ChartType = SeriesChartType.Spline

        Chart1.Series("Series1").BorderWidth = 2
        Chart1.Series("Series2").BorderWidth = 2

        Chart1.Series("Series1").Color = Color.Red
        Chart1.Series("Series2").Color = Color.DarkBlue

        With Chart1.ChartAreas(0).AxisX

            .Maximum = 300
            .Minimum = 0

            .LabelStyle.Format = "0S"
            .Title = "Humidity"
            .TitleFont = New Font(New FontFamily("Arial"), 9, FontStyle.Bold)

            .MajorGrid.Interval = 1
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 1
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10

        End With

        With Chart1.ChartAreas(0).AxisY

            .Maximum = 100
            .Minimum = 0

            .MajorGrid.Interval = 10
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 10
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10

        End With

        Chart1.ChartAreas(0).AxisX.ScrollBar.IsPositionedInside = False
        Chart1.ChartAreas(0).AxisX.ScaleView.Zoom(1, 59)

    End Sub

Snippet 4 is the Imports instruction required to use the chart properties.

Imports System.Windows.Forms.DataVisualization.Charting

Great, exactly what i was looking for :slight_smile:

Imports System.IO.Ports
Imports System.Windows.Forms.DataVisualization.Charting

Public Class Form1
    Private Delegate Sub myDelegate(ByVal Buffer As String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.CenterToScreen()
        ConnectionPanel.Focus()
        ComboBoxBaudRate.SelectedIndex = 0
    End Sub

    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        SerialPort1.ReadTimeout = 50

        Dim sData As String = Nothing
        Try
            sData = SerialPort1.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)

    End Sub

    Private Sub DisplayData(ByVal sdata As String)
        Dim chartvalue As Integer
        Dim txtarray As String() = Split(sdata, ",")


        If txtarray(0) = "Sensor1" Then
            TextBox1.Text = txtarray(1) & " %"
            Integer.TryParse(txtarray(1), chartvalue)
                Chart1.Series("Series1").Points.Add(chartvalue)
            End If

            If txtarray(0) = "Sensor2" Then
            TextBox2.Text = txtarray(1) & " %"
            Integer.TryParse(txtarray(1), chartvalue)
                Chart1.Series("Series2").Points.Add(chartvalue)


        End If

    End Sub

    Private Sub ButtonScanPort_Click(sender As Object, e As EventArgs) Handles ButtonScanPort.Click
        ConnectionPanel.Focus()
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to scan the new port.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
        ComboBoxPort.Items.Clear()
        Dim myPort As Array
        Dim i As Integer
        myPort = IO.Ports.SerialPort.GetPortNames()
        ComboBoxPort.Items.AddRange(myPort)
        i = ComboBoxPort.Items.Count
        i = i - i
        Try
            ComboBoxPort.SelectedIndex = i
            ButtonConnect.Enabled = True
        Catch ex As Exception
            MsgBox("Com port not detected", MsgBoxStyle.Critical, "Warning !!!")
            ComboBoxPort.Text = ""
            ComboBoxPort.Items.Clear()
            Return
        End Try
        ComboBoxPort.DroppedDown = True
    End Sub

    Private Sub ComboBoxPort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPort.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub

    Private Sub ComboBoxPort_DropDown(sender As Object, e As EventArgs) Handles ComboBoxPort.DropDown
        ConnectionPanel.Focus()
    End Sub

    Private Sub LinkLabel_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)

    End Sub

    Private Sub ComboBoxPort_Click(sender As Object, e As EventArgs) Handles ComboBoxPort.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Connection in progress, please Disconnect to change COM.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ComboBoxBaudRate_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub



    Private Sub ComboBoxBaudRate_DropDown(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.DropDown
        ConnectionPanel.Focus()
    End Sub


    Private Sub ComboBoxBaudRate_Click(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to change Baud Rate.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
        ConnectionPanel.Focus()
        Try
            SerialPort1.BaudRate = ComboBoxBaudRate.SelectedItem
            SerialPort1.PortName = ComboBoxPort.SelectedItem
            SerialPort1.Open()
            TimerSerial.Start()

            LabelStatus.Text = "Status : Connected"
            ButtonConnect.SendToBack()
            ButtonDisconnect.BringToFront()
            PictureBoxConnectionStatus.BackColor = Color.Green
        Catch ex As Exception
            MsgBox("Please check the Hardware, COM, Baud Rate and try again.", MsgBoxStyle.Critical, "Connection failed !!!")
        End Try
    End Sub
    Private Sub ButtonDisconnect_Click(sender As Object, e As EventArgs) Handles ButtonDisconnect.Click
        ConnectionPanel.Focus()
        TimerSerial.Stop()
        SerialPort1.Close()
        ButtonDisconnect.SendToBack()
        ButtonConnect.BringToFront()
        LabelStatus.Text = "Status : Disconnect"
        PictureBoxConnectionStatus.Visible = True
        PictureBoxConnectionStatus.BackColor = Color.Red

    End Sub

    Private Sub ChartSettings()

        Chart1.BackColor = Color.Bisque

        Chart1.Series("Series1").ChartType = SeriesChartType.Spline
        Chart1.Series("Series2").ChartType = SeriesChartType.Spline

        Chart1.Series("Series1").BorderWidth = 2
        Chart1.Series("Series2").BorderWidth = 2

        Chart1.Series("Series1").Color = Color.Red
        Chart1.Series("Series2").Color = Color.DarkBlue

        With Chart1.ChartAreas(0).AxisX

            .Maximum = 300
            .Minimum = 0

            .LabelStyle.Format = "0S"
            .Title = "Humidity"
            .TitleFont = New Font(New FontFamily("Arial"), 9, FontStyle.Bold)

            .MajorGrid.Interval = 1
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 1
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10

        End With

        With Chart1.ChartAreas(0).AxisY

            .Maximum = 100
            .Minimum = 0

            .MajorGrid.Interval = 10
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 10
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10

        End With

        Chart1.ChartAreas(0).AxisX.ScrollBar.IsPositionedInside = False
        Chart1.ChartAreas(0).AxisX.ScaleView.Zoom(1, 59)

    End Sub

    '====================================== Connection Panel End ================================================'



End Class

Thanks for all the help @sumguy , really appriciate it!
It took a couple of posts, but you tought me everything I needed for this project..

I also understands the basics now, here's my late-night design:

I will set this post as solved now :slight_smile:

Thanks

VB CODE:

Imports System.IO.Ports
Imports System.Windows.Forms.DataVisualization.Charting

Public Class Form1
    Private Delegate Sub myDelegate(ByVal Buffer As String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        Me.WindowState = FormWindowState.Maximized
        ConnectionPanel.Focus()
        ComboBoxBaudRate.SelectedIndex = 0
        KeyPreview = True
    End Sub

    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Escape Then Me.Close()
    End Sub


    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        SerialPort1.ReadTimeout = 50

        Dim sData As String = Nothing
        Try
            sData = SerialPort1.ReadLine
        Catch ex As Exception

        End Try

        Me.BeginInvoke((New myDelegate(AddressOf DisplayData)), sData)

    End Sub

    Private Sub DisplayData(ByVal sdata As String)
        Dim chartvalue As Integer
        Dim txtarray As String() = Split(sdata, ",")


        If txtarray(0) = "Sensor1" Then
            TextBox1.Text = txtarray(1) & " %"
            Integer.TryParse(txtarray(1), chartvalue)
            Chart1.Series("Sensor1").Points.Add(chartvalue)
        End If

        If txtarray(0) = "Sensor2" Then
            TextBox2.Text = txtarray(1) & " %"
            Integer.TryParse(txtarray(1), chartvalue)
            Chart1.Series("Sensor2").Points.Add(chartvalue)
        End If

        If txtarray(0) = "Sensor3" Then
            TextBox3.Text = txtarray(1) & " %"
            Integer.TryParse(txtarray(1), chartvalue)
            Chart1.Series("Sensor3").Points.Add(chartvalue)
        End If

    End Sub

    Private Sub ButtonScanPort_Click(sender As Object, e As EventArgs) Handles ButtonScanPort.Click
        ConnectionPanel.Focus()
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to scan the new port.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
        ComboBoxPort.Items.Clear()
        Dim myPort As Array
        Dim i As Integer
        myPort = IO.Ports.SerialPort.GetPortNames()
        ComboBoxPort.Items.AddRange(myPort)
        i = ComboBoxPort.Items.Count
        i = i - i
        Try
            ComboBoxPort.SelectedIndex = i
            ButtonConnect.Enabled = True
        Catch ex As Exception
            MsgBox("Com port not detected", MsgBoxStyle.Critical, "Warning !!!")
            ComboBoxPort.Text = ""
            ComboBoxPort.Items.Clear()
            Return
        End Try
        ComboBoxPort.DroppedDown = True
    End Sub

    Private Sub ComboBoxPort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPort.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub

    Private Sub ComboBoxPort_DropDown(sender As Object, e As EventArgs) Handles ComboBoxPort.DropDown
        ConnectionPanel.Focus()
    End Sub

    Private Sub LinkLabel_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)

    End Sub

    Private Sub ComboBoxPort_Click(sender As Object, e As EventArgs) Handles ComboBoxPort.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Connection in progress, please Disconnect to change COM.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ComboBoxBaudRate_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.SelectedIndexChanged
        ConnectionPanel.Focus()
    End Sub



    Private Sub ComboBoxBaudRate_DropDown(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.DropDown
        ConnectionPanel.Focus()
    End Sub


    Private Sub ComboBoxBaudRate_Click(sender As Object, e As EventArgs) Handles ComboBoxBaudRate.Click
        If LabelStatus.Text = "Status : Connected" Then
            MsgBox("Conncetion in progress, please Disconnect to change Baud Rate.", MsgBoxStyle.Critical, "Warning !!!")
            Return
        End If
    End Sub

    Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click
        ConnectionPanel.Focus()
        Try
            SerialPort1.BaudRate = ComboBoxBaudRate.SelectedItem
            SerialPort1.PortName = ComboBoxPort.SelectedItem
            SerialPort1.Open()
            TimerSerial.Start()

            LabelStatus.Text = "Status : Connected"
            ButtonConnect.SendToBack()
            ButtonDisconnect.BringToFront()
            PictureBoxConnectionStatus.BackColor = Color.Green
        Catch ex As Exception
            MsgBox("Please check the Hardware, COM, Baud Rate and try again.", MsgBoxStyle.Critical, "Connection failed !!!")
        End Try
    End Sub
    Private Sub ButtonDisconnect_Click(sender As Object, e As EventArgs) Handles ButtonDisconnect.Click
        ConnectionPanel.Focus()
        TimerSerial.Stop()
        SerialPort1.Close()
        ButtonDisconnect.SendToBack()
        ButtonConnect.BringToFront()
        LabelStatus.Text = "Status : Disconnect"
        PictureBoxConnectionStatus.Visible = True
        PictureBoxConnectionStatus.BackColor = Color.Red

    End Sub

    Private Sub ChartSettings()

        Chart1.BackColor = Color.Bisque

        Chart1.Series("Series1").ChartType = SeriesChartType.Spline
        Chart1.Series("Series2").ChartType = SeriesChartType.Spline
        Chart1.Series("Series3").ChartType = SeriesChartType.Spline

        Chart1.Series("Series1").BorderWidth = 2
        Chart1.Series("Series2").BorderWidth = 2
        Chart1.Series("Series3").BorderWidth = 2

        Chart1.Series("Series1").Color = Color.Red
        Chart1.Series("Series2").Color = Color.DarkBlue
        Chart1.Series("Series3").Color = Color.Yellow

        With Chart1.ChartAreas(0).AxisX



            .Maximum = 300
            .Minimum = 0

            .LabelStyle.Format = "0S"
            .Title = "Humidity"
            .TitleFont = New Font(New FontFamily("Arial"), 9, FontStyle.Bold)

            .MajorGrid.Interval = 1
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 1
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10


        End With

        With Chart1.ChartAreas(0).AxisY

            .Maximum = 100
            .Minimum = 0

            .MajorGrid.Interval = 10
            .MajorGrid.Enabled = True

            .MajorTickMark.Enabled = True
            .MajorTickMark.Interval = 10
            .MajorTickMark.Size = 2

            .LabelStyle.Enabled = True
            .LabelStyle.Interval = 10

        End With



        Chart1.ChartAreas(0).AxisX.ScrollBar.IsPositionedInside = False
        Chart1.ChartAreas(0).AxisX.ScaleView.Zoom(1, 59)


    End Sub

    Private Sub ButtonClose_Click(sender As Object, e As EventArgs) Handles ButtonClose.Click
        Dim frm As New Form1
        frm.Show()

        Me.Close()
    End Sub



    '====================================== Connection Panel End ================================================'



End Class

ARDUINO CODE:


#define soilSensor1 A0
#define soilSensor2 A1
#define soilSensor3 A2

#define pump1 2
#define pump2 3
#define pump3 4


const int dry = 541;
const int wet = 290;
const int dry1 = 546;
const int wet1 = 310;
const int dry2 = 541;
const int wet2 = 290;

int percentageHumididy;
int percentageHumididy2;
int percentageHumididy3;

const unsigned long Seconds = 1000;
const unsigned long Minutes = 60 * Seconds;
unsigned long PreviousMillis = 0;



    
void setup() {
  pinMode(pump1, OUTPUT);
  pinMode(pump2, OUTPUT);
  pinMode(pump3, OUTPUT);

  
  Serial.begin(9600);

  
}

void loop()
{

  int sensorVal1 = analogRead(soilSensor1);
  int percentageHumididy = map(sensorVal1, wet, dry, 100, 0)
  ;Serial.print("Sensor1,");
  Serial.println(percentageHumididy);


  int sensorVal2 = analogRead(soilSensor2);
  int percentageHumididy2 = map(sensorVal2, wet1, dry1, 100, 0)
  ;Serial.print("Sensor2,");
  Serial.println(percentageHumididy2);


  int sensorVal3 = analogRead(soilSensor3);
  int percentageHumididy3 = map(sensorVal3, wet2, dry2, 100, 0)
  ;Serial.print("Sensor3,");
  Serial.println(percentageHumididy3);



  {
  if (millis() - PreviousMillis >= 10 * Minutes)
  {
    PreviousMillis += 10 * Minutes;
    if (sensorVal1 > 380 )
    {
      digitalWrite(pump1, HIGH);
      delay(10000);
      digitalWrite(pump1, LOW);
    }
  }
}

   {
  if (millis() - PreviousMillis >= 10 * Minutes)
  {
    PreviousMillis += 10 * Minutes;
    if (sensorVal2 > 380 )
    {
      digitalWrite(pump2, HIGH);
      delay(10000);
      digitalWrite(pump2, LOW);
    }
  }
}

   {
  if (millis() - PreviousMillis >= 10 * Minutes)
  {
    PreviousMillis += 10 * Minutes;
    if (sensorVal3 > 380 )
    {
      digitalWrite(pump3, HIGH);
      delay(10000);
      digitalWrite(pump3, LOW);
    }
  }
}
  
  delay(1000);
}

@sumguy

Is there a easy way to get the X-axis to show realtime (DateTimeNow) (dd-mm-yy hh:mm:ss)?
You were really helpfull to get the project working, and now I'm stuck with this issue.

Think maybe this is where I have to make some changes?

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