I have a cell counter machine that sends data automatically after test end through a rs232 cable. I tried the following code to receive that data but I get nothing although I changed the BaudRate value many times. What is the problem?
My code:
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class ComReadWrite
Dim myPorts As Array
Dim txtline As String
Dim txtchar As String
Dim txtbyte As String
Dim txtexisting As String
Delegate Sub setTextCallBack(ByVal txt As String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myPorts = IO.Ports.SerialPort.GetPortNames()
portnamecombo.Items.AddRange(myPorts)
WriteButton.Enabled = False
CloseButton.Enabled = False
BaudRateBox.Items.Add(110)
BaudRateBox.Items.Add(300)
BaudRateBox.Items.Add(600)
BaudRateBox.Items.Add(1200)
BaudRateBox.Items.Add(2400)
BaudRateBox.Items.Add(4800)
BaudRateBox.Items.Add(9600) 'Populate the baudratebox Combo box to common baud rates used
BaudRateBox.Items.Add(14400)
BaudRateBox.Items.Add(19200)
BaudRateBox.Items.Add(38400)
BaudRateBox.Items.Add(57600)
BaudRateBox.Items.Add(115200)
BaudRateBox.Items.Add(128000)
BaudRateBox.Items.Add(256000)
BaudRateBox.Text = 38400
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
SerialPort1.PortName = portnamecombo.Text
SerialPort1.BaudRate = BaudRateBox.Text
SerialPort1.ReadTimeout = 500
SerialPort1.Parity = Parity.None
SerialPort1.DataBits = 8
SerialPort1.StopBits = StopBits.One
SerialPort1.Open()
Start.Enabled = False
WriteButton.Enabled = True
CloseButton.Enabled = True
End Sub
Private Sub WriteButton_Click(sender As Object, e As EventArgs) Handles WriteButton.Click
SerialPort1.Write(Chr(6))
End Sub
Private Sub CloseButton_Click(sender As Object, e As EventArgs) Handles CloseButton.Click
SerialPort1.Close()
Start.Enabled = True
WriteButton.Enabled = False
CloseButton.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Try
RecievedText(SerialPort1.ReadExisting())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub RecievedText(ByVal txt As String)
If Me.ReadBox.InvokeRequired Then
Dim x As New setTextCallBack(AddressOf RecievedText)
Me.Invoke(x, New Object() {(txt)})
Else
Me.ReadBox.Text &= txt
End If
End Sub
End Class
Related
I'm newbie to VB.net. my case is, i need to display data from serial port to text box. In continuous loop. How do i do that?
I have wrote simple program to display the data. i can display the data once in the textbox, but not continuously.
serialport1 is where i get data from port 1. serialport2 is data from port 2.
SerialPort2.Write("!12,F" & vbCr)
data "!11,F" and "!12,F" is a command to my 2 device.
TextBox2.Text and TextBox5.Text is where i want to continuously display my data.
here is the code;
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Form2
Dim myPort As Array
Dim myport1 As Array
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
'------------------------------------------------
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
myport1 = IO.Ports.SerialPort.GetPortNames()
ComboBox1.Items.AddRange(myPort)
ComboBox2.Items.AddRange(myport1)
btnwrite.Enabled = False
End Sub
'------------------------------------------------
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btninit.Click
SerialPort1.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort1.PortName = ComboBox1.Text
SerialPort1.BaudRate = TextBox3.Text
SerialPort1.Open()
SerialPort2.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort2.PortName = ComboBox2.Text
SerialPort2.BaudRate = TextBox3.Text
SerialPort2.Open()
btninit.Enabled = False
btnwrite.Enabled = True
btnwrite2.Enabled = True
btnclose.Enabled = True
End Sub
'------------------------------------------------
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnwrite.Click
SerialPort1.Write("!11,F" & vbCr) 'concatenate with \n
End Sub
Private Sub btnwrite2_Click(sender As Object, e As EventArgs) Handles btnwrite2.Click
SerialPort2.Write("!12,F" & vbCr) 'concatenate with \n
End Sub
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub SerialPort2_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
ReceivedText1(SerialPort2.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox2.Text &= [text] 'append text
End If
End Sub
Private Sub ReceivedText1(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox5.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText1)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox5.Text &= [text] 'append text
End If
End Sub
Private Sub btnclose_click(sender As System.Object, e As System.EventArgs) Handles btnclose.Click
SerialPort1.Close()
SerialPort2.Close()
btninit.Enabled = True
btnwrite.Enabled = False
btnwrite2.Enabled = False
btnclose.Enabled = False
End Sub
End Class
Is that possible? Checking if the port is open is okay but i don't know why i can't receive data/string after i sent a data.
In main Form:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connect_btn.Enabled = False
With com1
.PortName = "COM2"
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.RequestToSend
.RtsEnable = True
.DtrEnable = True
End With
com1.Open()
AddHandler RFID.DataReceived, SerialDataReceivedEventHandler1
End Sub
Sending Data:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim response As String = TextBox1.Text
If RFID.IsOpen Then
RFID.WriteLine(response)
End If
End Sub
Data Receive:
Private Sub com1_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs)
If com1.IsOpen = True Then
read()
End If
End Sub
Friend Sub DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
Dim newReceivedData As String
newReceivedData = RFID.ReadExisting
MessageBox.Show(newReceivedData)
End Sub
When i try to run it, There is no error.
EDITED
Using PuTTY and VSPE work to send a data.
I'm trying to make VB.net show the data "colors" from my Arduino,
My serial port working great but I have this massage every-time I press connect & weird data show's up
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string " = " to type 'Integer' is not valid.
Can someone help me in this?
this is my code
Public Class Form1
Private _msg As String
Dim R As String
Dim G As String
Dim B As String
Dim iR As String
Dim iG As String
Dim iB As String
Private indata As String
Dim IsConnected As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each str As String In IO.Ports.SerialPort.GetPortNames()
Ports.Items.Add(str)
Next
If (Ports.Items.Count > 0) Then
Ports.SelectedIndex = 0
End If
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (SerialPort1.IsOpen()) Then
Try
SerialPort1.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (SerialPort1.IsOpen = False) Then
SerialPort1.PortName = Ports.SelectedItem
SerialPort1.Open()
IsConnected = True
Status.Text = "Connected"
Status.BackColor = Color.LightGreen
Button1.Enabled = False
Button2.Enabled = True
End If
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'user chose string
'read data waiting in the buffer
Try
Dim msg As String = SerialPort1.ReadExisting()
indata = indata + msg
'Dim where As Integer = InStr(indata, ControlChars.Lf)
Dim where As Integer = InStr(indata, "R=")
If (indata.Length > where + 18) Then
R = indata.Substring(where + 1, 3)
G = indata.Substring(where + 7, 3)
B = indata.Substring(where + 13, 3)
indata = ""
End If
'display the data to the user
_msg = msg
_msg = _msg.Replace(ControlChars.Cr, "")
: DisplayData(msg)
Catch ex As Exception
End Try
End Sub
#Region "DisplayData"
''' <summary>
''' Method to display the data to and
''' from the port on the screen
''' </summary>
''' <remarks></remarks>
<STAThread()> _
Private Sub DisplayData(ByVal msg As String)
DisplayWindow.BeginInvoke(New EventHandler(AddressOf DoDisplay))
End Sub
#End Region
#Region "DoDisplay"
Private Sub DoDisplay(ByVal sender As Object, ByVal e As EventArgs)
'DisplayWindow.SelectedText = String.Empty
'DisplayWindow.SelectionFont = New Font(_DisplayWindow.SelectionFont, FontStyle.Bold)
'DisplayWindow.SelectionColor = MessageColor(CType(_type, Integer))
DisplayWindow.AppendText(_msg)
DisplayWindow.ScrollToCaret()
End Sub
#End Region
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
RL.Text = R
GL.Text = G
BL.Text = B
iR = CInt(R) * CInt(RM.Text)
iG = CInt(G) * CInt(GM.Text)
iB = CInt(B) * CInt(BM.Text)
RF.Text = iR
GF.Text = iG
BF.Text = iB
Try
Label6.BackColor = Color.FromArgb(CType(iR, Byte), CType(iG, Byte), CType(iB, Byte))
Catch ex As Exception
End Try
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)
System.Diagnostics.Process.Start("http://www.narzan.weebly.com/p-1049.html")
End Sub
Private Sub LinkLabel1_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
picOn.Visible = True
SerialPort1.Open()
SerialPort1.Write("^")
SerialPort1.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
picOn.Visible = False
SerialPort1.Open()
SerialPort1.Write("<")
SerialPort1.Close()
End Sub
Private Sub picOn_Click(sender As Object, e As EventArgs) Handles picOn.Click
End Sub
Private Sub RL_Click(sender As Object, e As EventArgs) Handles RL.Click
End Sub
Private Sub RM_TextChanged(sender As Object, e As EventArgs) Handles RM.TextChanged
End Sub
End Class
My problem was from my Arduino code not from VB.net
the solution is to remove "=" from R,G,B
void printColour(){
Serial.print("R = ");
Serial.println(int(colourArray[0]));
Serial.print("G = ");
Serial.println(int(colourArray[1]));
Serial.print("B = ");
Serial.println(int(colourArray[2]));
//delay(2000);
}
so the code will look like that
void printColour(){
Serial.print("");
Serial.println(int(colourArray[0]));
Serial.print("");
Serial.println(int(colourArray[1]));
Serial.print("");
Serial.println(int(colourArray[2]));
//delay(2000);
}
Thanks everyone, everything work great now
Basically I have this file creator program which is helping me to make a bunch of files and for some reason, it only does 2 instead of 100 files specified.
Code:
Imports System.IO
Public Class Main
Dim CURRENT_NUM As Integer
Dim CONTENT_STRING As String
Dim PATH_STRING As String
Dim FROM_NUM As Integer
Dim TO_NUM As Integer
Public Sub SetupVar()
Try
CONTENT_STRING = tbContent.Text
PATH_STRING = tbPath.Text
FROM_NUM = Integer.Parse(tbFrom.Text)
TO_NUM = Integer.Parse(tbTo.Text)
Catch ex As Exception
End Try
End Sub
Private Sub Make()
tmrMake.Enabled = True
End Sub
Private Sub btnMake_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMake.Click
SetupVar()
Make()
End Sub
Private Sub btnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
Private Sub tmrMake_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrMake.Tick
'disable quit
'and control box
Me.ControlBox = False
btnQuit.Enabled = False
CURRENT_NUM = FROM_NUM
CURRENT_NUM = CURRENT_NUM + 1
Using sw As New StreamWriter(PATH_STRING & CURRENT_NUM & ".txt")
sw.Write(CONTENT_STRING)
End Using
If CURRENT_NUM = TO_NUM Then
btnQuit.Enabled = True
Me.ControlBox = True
tmrMake.Enabled = False
End If
End Sub
End Class
The result is c1 and c2 in the folder. Instead of 1-100 As i specified in the two tb.
You need to move some of your code around and then you should be good. See the code below...
Imports System.IO
Public Class Main
Dim CURRENT_NUM As Integer
Dim CONTENT_STRING As String
Dim PATH_STRING As String
Dim FROM_NUM As Integer
Dim TO_NUM As Integer
Public Sub SetupVar()
Try
CONTENT_STRING = tbContent.Text
PATH_STRING = tbPath.Text
FROM_NUM = Integer.Parse(tbFrom.Text)
TO_NUM = Integer.Parse(tbTo.Text)
' Moved code from tmrMake_Tick to here
'disable quit
'and control box
Me.ControlBox = False
btnQuit.Enabled = False
CURRENT_NUM = FROM_NUM
Catch ex As Exception
End Try
End Sub
Private Sub Make()
tmrMake.Enabled = True
End Sub
Private Sub btnMake_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMake.Click
SetupVar()
Make()
End Sub
Private Sub btnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
Private Sub tmrMake_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrMake.Tick
Using sw As New StreamWriter(PATH_STRING & CURRENT_NUM & ".txt")
sw.Write(CONTENT_STRING)
End Using
' Increment your CURRENT_NUM after you've written the file
CURRENT_NUM = CURRENT_NUM + 1
If CURRENT_NUM = TO_NUM Then
btnQuit.Enabled = True
Me.ControlBox = True
tmrMake.Enabled = False
End If
End Sub
End Class
I am using AirCable Serial5 Bluetooth adapter for RS232 to Bluetooth transfer. I need to change Baudrate from lower 9600 to 115200. I talked with AirCable supplier and he said that, for that I have to send Baud changing Break command(0x85) to serial COM port. I don't know how to send break command with baud changing HEX code in VB.NET
Imports System
Imports System.IO.Ports
Imports System.Text
Imports System.Threading
Public Class Form1
Private Sp As New SerialPort
Private comBuffer As Byte()
Private Delegate Sub UpdateFormDelegate()
Private UpdateFormDelegate1 As UpdateFormDelegate
Dim m As Integer
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
With Sp
.PortName = "COM8"
.BaudRate = 9600
.DataBits = 8
.Parity = Parity.None
.StopBits = StopBits.One
.Handshake = Handshake.None
End With
Try
Sp.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
AddHandler Sp.DataReceived, AddressOf Sp_DataReceived
Sp.Write("s r0x90 115200" + vbCr)
Thread.Sleep(100)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Sp.Write("s r0x90 9600" + vbCr)
Thread.Sleep(100)
End Sub
Private Sub getBD_Click(sender As System.Object, e As System.EventArgs) Handles getBD.Click
Sp.Write("g r0x90" + vbCr)
Thread.Sleep(100)
End Sub
Private Sub Sp_DataReceived(ByVal Sender As Object, ByVal e As SerialDataReceivedEventArgs)
'Handles serial port data received events
UpdateFormDelegate1 = New UpdateFormDelegate(AddressOf UpdateDisplay)
Dim n As Integer = Sp.BytesToRead 'find number of bytes in buffer
m = n
comBuffer = New Byte(n - 1) {} 're dimension storage buffer
Sp.Read(comBuffer, 0, n) 'read data from the buffer
Me.Invoke(UpdateFormDelegate1) 'call the delegate
End Sub
Private Sub UpdateDisplay()
' updates label text
'Label1.Text = ""
Dim b As Integer = 0
Do Until b = m
Dim array() As Byte = {CStr(comBuffer(b))}
Dim value As String = System.Text.ASCIIEncoding.ASCII.GetString(array)
Label1.Text += value
b += 1
Loop
End Sub
Private Sub snd_Click(sender As System.Object, e As System.EventArgs) Handles snd.Click
Dim x As String
x = cmdBox.Text
Sp.Write(x + vbCr)
Thread.Sleep(100)
End Sub
End Class
Please let me know if you have any questions.