Serial port read includes what has been written in vb.net - vb.net

So I am trying to talk to a gsm modem using AT commands, I'm trying to do a basic test to make sure the modem is ok by sending the command AT and receiving OK. The issue is that I'm receiving "AT Blank Line OK", is there any way so when I send AT, I only read OK?
Imports System.IO.Ports
Public Class GUI
Dim Device As New System.IO.Ports.SerialPort()
Private Sub GUI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Port.Text = "Select Port"
For Each item As String In IO.Ports.SerialPort.GetPortNames
Port.Items.Add(item)
Next
Device.BaudRate = 9600
Device.Parity = Parity.None
Device.StopBits = StopBits.One
Device.DataBits = 8
Device.Handshake = Handshake.RequestToSend
Device.DtrEnable = True
Device.RtsEnable = True
Device.NewLine = vbCrLf
Device.WriteTimeout = 5000
End Sub
Private Sub Port_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Port.SelectedIndexChanged
Device.PortName = Port.SelectedItem.ToString
End Sub
Private Sub Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Send.Click
Try
Device.Open()
Dim msg As String
msg = Message.Text
Device.DiscardInBuffer()
Device.DiscardOutBuffer()
Device.Write("AT" & vbCrLf)
MsgBox(Device.ReadExisting())
Catch ex As Exception
MsgBox("Error!")
End Try
Device.Close()
End Sub
End Class

Sounds like the modem is set to Echo commands. To turn this off try sending E0 first.
More info here

Related

Serial Port strange data display and crash

I am trying to create vb.net program to get data from scales using serial port.
I don't know scales model, just Display model: IND231.
Problem is i get stupid data:
but if turn on Putty i get this:
As you see in putty there is only one line which refresh every sec, true weight is first two 00 (in middle), in my situation this line is not refreshing, but make a huge line and after 5-10 s, my program just crash.
My program code is:
Imports AxSerial
Public Class Form1
Dim Q As Queue(Of String) = New Queue(Of String)
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
For Each s In System.IO.Ports.SerialPort.GetPortNames()
lstPorts.Items.Add(s)
Next s
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnStart.Click
Try
If lstPorts.SelectedIndex = -1 Then
MsgBox("Please select a port")
Exit Sub
Else
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = 1
SerialPort1.RtsEnable = False
SerialPort1.PortName = lstPorts.SelectedItem.ToString
SerialPort1.Open()
Timer1.Start()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object,
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles SerialPort1.DataReceived
Q.Enqueue(SerialPort1.ReadExisting())
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Timer1.Tick
SyncLock Q
While Q.Count > 0
txtReceived.Text &= Q.Dequeue
End While
End SyncLock
End Sub
Private Sub btnStop_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnStop.Click
SerialPort1.Close()
Timer1.Stop()
End Sub
End Class
This is IND321 Serial Port Parameters
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = 1
SerialPort1.RtsEnable = False
Im not sure with RtsEnable, i think this is FlowControl.
What i need to correct to get data like putty?
It looks like your scale/serial port is returning data in another format.
Check your scale specs. It might be e72 or some other even/odd/bits/parity combination.

Serial data overwrite on visual basic

I am new to visual basic . I am sending data from arduino evey 1s say current. I wanted to print on text box. Here is my code on VB side . Problem i am facing here . I am getting data but Not ovwrwriting .it just print one after the other. I am using VB2010.
VB code
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class frmMain
Dim myPort As Array 'COM Ports detected on the system will be stored here
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available
cmbBaud.Items.Add(9600) 'Populate the cmbBaud Combo box to common baud rates used
cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)
cmbBaud.Items.Add(115200)
For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next
cmbPort.Text = cmbPort.Items.Item(0) 'Set cmbPort text to the first COM port detected
cmbBaud.Text = cmbBaud.Items.Item(0) 'Set cmbBaud text to the first Baud rate on the list
'SerialPort1.PortName = cmbPort.Text()
'SerialPort1.BaudRate = cmbBaud.Text()
btnDisconnect.Enabled = False 'Initially Disconnect Button is Disabled
End Sub
Private Sub btnConnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text()
'Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Text()
'Set Baud rate to the selected value on
'Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8 'Open our serial port
SerialPort1.Open()
btnConnect.Enabled = False 'Disable Connect button
btnDisconnect.Enabled = True 'and Enable Disconnect button
End Sub
Private Sub btnDisconnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close() 'Close our Serial Port
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Private Sub btnSend_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text & vbCr) 'The text contained in the txtText will be sent to the serial port as ascii
'plus the carriage return (Enter Key) the carriage return can be ommitted if the other end doe
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting()) 'Automatically called every time a data is received at the serialPort
End Sub
Private Sub ReceivedText(ByVal [text] As String)
'compares the ID of the creating Thread to the ID of the calling Thread
If Me.Current_Read.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.Current_Read.Text &= [text]
End If
End Sub
Private Sub cmbPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If SerialPort1.IsOpen = False Then
SerialPort1.PortName = cmbPort.Text 'pop a message box to user if he is changing ports
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
Private Sub cmbBaud_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If SerialPort1.IsOpen = False Then
SerialPort1.BaudRate = cmbBaud.Text 'pop a message box to user if he is changing baud rate
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
Private Sub RELAY_ON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RELAY_ON.Click
SerialPort1.Write("1")
End Sub
Private Sub RELAY_OFF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RELAY_OFF.Click
SerialPort1.Write("0")
End Sub
End Class
Arduino Code.
float Output_Current ;
void TakeReading()
{
newaverage = analogRead(A5);
Output_Current = 0.0336666666667*newaverage - 17.17;
}
void loop()
{
Serial.println( Output_Current );
delay(1000);
}

MultiThreading and Sockets/TCP [VB.NET]

I started learning about TCP/Sockets yesterday and decided to make a chatbox for a friend and I.
Unfortunately, i am having some difficulties with MultiThreading.
Whenever i am using it, i can no longer receive messages from my friend.
But, if i disable it then, everything works perfectly.
I don't know what's going on here, could somebody help?
Imports System.Net.Sockets
Imports System.Net
Public Class ServerClient
Dim _TCPServer As Socket
Dim _TCPListener As TcpListener
Dim _ListenerThread As System.Threading.Thread
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
'When Submit is pressed, send some text to the client
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(txtInput.Text)
txtBox.AppendText(vbCrLf & "Server: " & txtInput.Text)
txtInput.Clear()
_TCPServer.Send(bytes)
End Sub
Private Sub TCPListen()
'If somebody calls port 2424, accept it, unblock the socket and start the timer
_TCPListener = New TcpListener(IPAddress.Any, 2424)
_TCPListener.Start()
_TCPServer = _TCPListener.AcceptSocket()
btnSend.Enabled = True
txtBox.AppendText("Connection Established" & vbCrLf)
_TCPServer.Blocking = False
_Timer.Enabled = True
End Sub
Private Sub _Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick
'If data has been sent, receive it
Try
Dim rcvdbytes(_TCPServer.ReceiveBufferSize) As Byte
_TCPServer.Receive(rcvdbytes)
txtBox.AppendText(vbCrLf & "Client: " & System.Text.Encoding.ASCII.GetString(rcvdbytes) & vbCrLf)
Catch ex As Exception
End Try
End Sub
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Link the new thread to TCPListen(), allow access to all threads and wait for a call
_ListenerThread = New Threading.Thread(AddressOf TCPListen)
Control.CheckForIllegalCrossThreadCalls = False
txtBox.AppendText("Waiting for connection.." & vbCrLf)
btnSend.Enabled = False
_ListenerThread.Start()
End Sub
End Class
This example project contains four classes - TcpCommServer, TcpCommClient, clsAsyncUnbuffWriter and CpuMonitor. With these classes, you will not only be able to instantly add TCP/IP functionality to your VB.NET applications, but also has most of the bells and whistles we're all looking for. With these classes, you will be able to connect multiple clients to the server on the same port. You will be able to easily: throttle bandwidth to the clients, and send and receive files and data (text?) along 250 provided channels simultaneously on a single connection.
http://www.codeproject.com/Articles/307315/Reusable-multithreaded-tcp-client-and-server-class
Well, i learned BackgroundWorkers could do the exact same thing and now it all works.
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Wait for a call
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
TCPListen()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
_Timer.Enabled = True
End Sub

SQL Server connection related error

Below error is thrown in a already opened program which connects to different database
A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection
was forcibly closed by the remote host.)
Program details: code done using vb.net with SQL Server 2008 as back-end
Two instance of same exe where running simultaneously in same PC but error was thrown only by one instance
Program uses both SqlConnection (ADO.NET) and ADODB connection (upgraded from VB6) and the error is thrown by both types of connection
If the error is due to network problem with the server then why few programs work fine? I am not able to trace the reason for this behavior of the program
Can I know why this error occurs and why only in few programs of same instance
When each instance of your exe connects, it gets its own SQL Server process ID (SPID). You are getting the error because your instance's connection was either killed at the server level or disrupted at the network level, at some point before it tried to execute the SQL command where the error occurred.
In SSMS, check your SQL Server Log file. In this example I killed a SPID, and the killing of the SPID was logged:
If you don't see a logged event, you are probably dealing with a network issue. Further troubleshooting might involve setting one or more break points in your code somewhere after it opens the ADODB connection, but before the error, and then verifying through SSMS that a SPID for that instance is running at the break point. exec sp_who2 is a good command to list all currently active SPIDs on the server.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Function call_add()
Dim tam, eng, mat, sci, soc, tot As Decimal
tam = 0
eng = 0
mat = 0
sci = 0
soc = 0
tot = 0
If tamil.Text <> "" Then
tam = Convert.ToDecimal(tamil.Text)
End If
If english.Text <> "" Then
eng = Convert.ToDecimal(english.Text)
End If
If maths.Text <> "" Then
mat = Convert.ToDecimal(maths.Text)
End If
If science.Text <> "" Then
sci = Convert.ToDecimal(science.Text)
End If
If social.Text <> "" Then
soc = Convert.ToDecimal(social.Text)
End If
tot = tam + eng + mat + sci + soc
total.Text = tot.ToString
percentage.Text = total.Text / 500 * 100
Return False
End Function
Private Sub total_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles total.TextChanged
call_add()
End Sub
Private Sub percentage_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles percentage.TextChanged
call_add()
End Sub
Private Sub tamil_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tamil.TextChanged
call_add()
End Sub
Private Sub english_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles english.TextChanged
call_add()
End Sub
Private Sub maths_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles maths.TextChanged
call_add()
End Sub
Private Sub science_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles science.TextChanged
call_add()
End Sub
Private Sub social_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles social.TextChanged
call_add()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As SqlConnection
Dim cmd As SqlCommand
'Dim str As String
con = New SqlConnection("server=WHITE-PC\WHITEPC;initial catalog=markreg;Integrated Security=True")
cmd = New SqlCommand
con.Open()
Dim command As New SqlCommand
cmd.Connection = con
command = New SqlCommand("stdregno,stdname,tamil,english,maths,science,social,total,percentage", con)
command.ExecuteNonQuery()
con.Close()
MsgBox("Added Sucessfully", MsgBoxStyle.Information, "Succesfully")
call_clear()
End Sub
Private Function call_clear()
stdregno.Text = ""
stdname.Text = ""
tamil.Text = ""
english.Text = ""
maths.Text = ""
science.Text = ""
social.Text = ""
total.Text = ""
percentage.Text = ""
End Function
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Form1.Show()
Me.Hide()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
InputBox("Enter the Regno You want search")
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
InputBox("Enter the Regno You want Modify")
End Sub
End Class

Very basic VB.Net & Serial IO issue

After searching around I am still having issues with reading data from a serial port in VB.Net/VS2010. I know the Serial Port works, I can write to the port fine but when reading from it, nothing happens. I have only been programming for the last 3 weeks so am still trying to get my head around it all.
The program must run to capture data from a door logger, I will then be outputting the data to a database (not yet implemented - I want to get this part sorted first).
I have tried using several terminal programs as well as another device which outputs data onto the serial line, with nothing displaying in the textbox tbxIn.
Any help would be greatly appreciated.
Code is below:
Imports System.IO.Ports
Imports System.IO.Ports.SerialPort
Public Class Form1
Dim comPort As IO.Ports.SerialPort = Nothing
Dim sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
tbxIn.Text = e.ToString
End Sub
End Class
PRetty sure this will get you what you need. You DON't need the Serial1 component on the designer. Remove that and use this code:
Private comPort As IO.Ports.SerialPort = Nothing
Private sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
'must add handler
AddHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
'remove handler
RemoveHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
tbxIn.Text = e.ToString
End Sub