I'm trying to make an application in vb.net which can read the temperature from an arduino over a serial communication (USB).
I want that it is possible to only read the temperature when a user clicks on a button.
I have posted my code below. When I click on the button 'BtnManueel_Click' I first send a command to the arduino. When the arduino receives this command, it will read the temperature end send it to the PC. This works perfectly when I use a serial monitor. But when I run my application with the code below, I don't get the value in vb.net.
What am I doing wrong and/or why isn't it working?
I don't have much experience with vb.net and serial communication and I was hoping you could help me out with this.
Thanks in advance.
kind regards.
vb.net code:
Imports System
Imports System.IO.Ports
Imports System.Windows.Forms
Public Class Form1
Dim serielepoort As New SerialPort
Dim celsius As Double
Private Sub BtnVerbinden_Click(sender As Object, e As EventArgs) Handles BtnVerbinden.Click
Try
serielepoort.PortName = "COM8"
serielepoort.BaudRate = 9600
serielepoort.DataBits = 8
serielepoort.Parity = Parity.None
serielepoort.StopBits = StopBits.One
serielepoort.Handshake = Handshake.None
serielepoort.Encoding = System.Text.Encoding.Default
serielepoort.ReadTimeout = 10000
serielepoort.Open()
Catch ex As Exception
MessageBox.Show(ex.Message, "fout bij verbinden!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub BtnVerbindingVerbreken_Click(sender As Object, e As EventArgs) Handles BtnVerbindingVerbreken.Click
serielepoort.Close()
End Sub
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
BtnVerbindingVerbreken_Click(sender, e)
End Sub
Private Sub BtnManueel_Click(sender As Object, e As EventArgs) Handles BtnManueel.Click
If (serielepoort.IsOpen) Then
serielepoort.Write("t")
End If
End Sub
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
celsius = serielepoort.ReadLine()
LblTempWaarde.Text = celsius
End Sub
End Class
Code in arduino:
nt pinLM335 = 0;
void setup()
{
Serial.begin(9600);
}
void loop() {
if(Serial.available() >0)
{
String val = Serial.readStringUntil('\n');
if (val == "t")
{ int waarde = analogRead(pinLM335);
double spanning =(waarde / 1024.0)*5;
double Kelvin = (spanning) * 1000 / 10;
double celsius = Kelvin - 273.15;
Serial.println(celsius);
}
}
}