Not able to read barcode with c# or getting unknown characters - c#

I am getting error
System.TimeoutException was unhandled The operation has timed out... etc
while I am trying to read a barcode I tried a lot to solve it with but nothing worked out.
I checked parameters of SerialPort that matching Windows Device Manager many times.
I tried to replace
String data = _serialPort.ReadLine();
with
String data = _serialPort.ReadByte().ToString();
as you can see, but that show me unknown number it shows for example 12 then removed then 26 etc.
I tried to change the Encoding but when I change the encoding I am getting unknown characters, like empty squares black triangle or Playing card symbol etc.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static SerialPort _serialPort;
private delegate void SetTextDeleg(string text);
private void Form1_Load(Object sender, EventArgs e)
{
_serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
// Encoding
//_serialPort.Encoding = Encoding.ASCII;
_serialPort.Encoding = Encoding.Default;
_serialPort.Open();
}
private void btnStart_Click(Object sender, EventArgs e)
{
try
{
if (!_serialPort.IsOpen)
_serialPort.Open();
_serialPort.Write("SI\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(2000);
String data = _serialPort.ReadLine();
//String data = _serialPort.ReadByte().ToString();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new Object[] { data });
}
private void si_DataReceived(String data)
{
textBox1.Text = data.Trim().ToString();
//textBox1.Text = data;
//label1.Text = data;
}
}

How about this?
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
spL.Read(buf, 0, buf.Length);
string data = System.Text.Encoding.Default.GetString(buf);
}

Related

How do I access COM-Port with C#?

Here the serial communication port shows error it cannot be accessed .....But the serial communication port works perfect in arduino, so it cant be the port problem, its not the driver problem either, the driver is updated and works well, so the problem can be in the code .....i am a newbie to C#.
public partial class Form1 : Form
{
private SerialPort myport;
private string in_data;
public Form1()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 19200;
myport.PortName = pn.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!!");
}
}
void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
*in_data = myport.ReadLine();***
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
string[] newData = in_data.Split(',');
bv.Text = newData[0];
bi.Text = newData[1];
pv.Text = newData[2];
pi.Text = newData[3];
t.Text = newData[4];
}
}
it cannot be accessed
This may indicates that the port doesnt exists or is already in use.
Maybe another application is already listening on this port. (arduino?)
Comport.Open() Exceptions are descibed here:
MSDN SerialPort.Open Method

Serial port Write and read event not subscribing/ not reading serial port

I have been trying to send and read commands using the serial port COM4 which is already configured using this code, it is connected to a bill acceptor device
im using an event to suscribe whenever the device sends an answer however when debbuging i found out that it never actually reaches the event nor subscribes to it , i have been reading the whole week how to solve this with no luck,
Even if i happen to put the "read port" lines right after the "write port lines" and the program gets to the
ptSerial.Read(RxMensaje, 0, 5);
line the program just frezzes and i have to stop it hopefully someone here can help me oput
public partial class Form1 : Form
{
public SerialDataReceivedEventHandler DataReceivedDelegate;
public Form1()
{
InitializeComponent();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
DataReceivedDelegate = new SerialDataReceivedEventHandler(DataReceivedHandler);
//SerialPort sp = (SerialPort)sender;
//string indata = sp.ReadExisting();
byte[] RxMensaje = new byte[5];
ptSerial.Read(RxMensaje, 0, 5);
rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);
// rtbDevice.Text = indata;
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
Open(sender, e);
}
catch (Exception ex)
{
lblSalida.Text = ex.Message;
}
}
private void Open(object sender, EventArgs e)
{
ptSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
ptSerial.Open();
lblSalida.Text = "Puerto COM4 Abierto";
}
private void btnSend_Click(object sender, EventArgs e)
{
if (ptSerial.IsOpen)
{
byte[] TxMensaje = new byte[5] { 0x02, 0x00, 0x01, 0xFE, 0xFF }; //CCtalk
ptSerial.Write(TxMensaje, 0, 5);
rtbHost.Text = "2 0 1 254 255 Enviado";
//byte[] RxMensaje = new byte[5];
//ptSerial.Read(RxMensaje, 0, 5);
//rtbDevice.Text = Encoding.ASCII.GetString(RxMensaje, 0, 5);
ptSerial.Close();
lblSalida.Text = "Bytes Enviados Pto Cerrado";
}
else
{
lblSalida.Text = "Puerto Cerrado";
}
}
private void btnCerrar_Click(object sender, EventArgs e)
{
if (ptSerial.IsOpen)
{
ptSerial.Close();
lblSalida.Text = "Puerto COM4 Cerrado";
}
else
{
lblSalida.Text = "No ocurrio nada :(";
}
}
}
I don't see the full definition of the serial port (e.g. where do you bind to "COM4"). Very important the baud rate is set properly else the device won't synchronize correctly with your application and no event will generate.
See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx
_serialPort = new SerialPort(); // Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

Multiple Serial Ports in C# / Trouble using List <>

I have a system that sends an "at" command to a serial port and displays the return on a MessageBox.
But I needed to do this in all available serial ports. So I created a List and I'm adding all the ports on it.
I managed to send the command, but could not continue the rest of the code to catch the return because I am having trouble handling the lists. I am a beginner in C #.
Below is my current code.
The part that is commented out is what I'm struggling to continue.
This part belongs to the old code (when it was just one serial port).
public partial class Form1 : Form
{
List<SerialPort> serialPort = new List<SerialPort>();
// delegate is used to write to a UI control from a non-UI thread
private delegate void SetTextDeleg(string text);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var portNames = SerialPort.GetPortNames();
foreach (var port in portNames) {
SerialPort sp;
sp = new SerialPort(port, 19200, Parity.None, 8, StopBits.One);
sp.Handshake = Handshake.None;
//sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.ReadTimeout = 500;
sp.WriteTimeout = 500;
serialPort.Add(sp);
listPorts.Items.Add(port);
}
}
private void listPorts_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
foreach (var sp in serialPort) {
// Open port
try
{
if (!sp.IsOpen)
sp.Open();
MessageBox.Show(sp.PortName + " aberto!");
sp.Write("at\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
}
/* HELP START
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
string data = sp.ReadLine();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
private void si_DataReceived(string data)
{
String retorno = data.Trim();
MessageBox.Show(retorno);
// Fecha a porta após pegar o retorno
sp.Close();
}
HELP END */
}
What to put in place 'sp.ReadLine ();' and 'sp.Close ();'?
I don't know do this because of the List <>
The simplest approach would be to use a lambda expression which would capture the port you're using. A lambda expression is a way of building a delegate "inline" - and one which is able to use the local variables from the method you declare it in.
For example:
foreach (var port in portNames)
{
// Object initializer to simplify setting properties
SerialPort sp = new SerialPort(port, 19200, Parity.None, 8, StopBits.One)
{
Handshake = Hanshake.None,
ReadTimeout = 500,
WriteTimeout = 500
};
sp.DataReceived += (sender, args) =>
{
Thread.Sleep(500); // Not sure you need this...
string data = sp.ReadLine();
Action action = () => {
MessageBox.Show(data.Trim());
sp.Close();
};
BeginInvoke(action);
};
serialPort.Add(sp);
listPorts.Items.Add(port);
}
A few notes about this:
Just because some data has been received doesn't mean that a whole line has, so ReadLine may still block
If you only need to show a message box, you may not need Control.BeginInvoke. (If you need to do more here, you might want to extract most of that code into a separate method which just takes a string, then create an action which would call that method.)
Are you sure you want to close the serial port as soon as the first line has been received?
You can chage your sp_DataReceived method as,
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
SerialPort sp = (SerialPort)sender;
string data = sp.ReadLine();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
sp.Close();
}
and remove the sp.Close(); from si_DataReceived method.
If you want to have a Serial port value in your si_DataReceived method,
you should pass it there:
// First, add port into your delegate
private delegate void SetTextDeleg(SerialPort port, string text);
...
/* HELP START */
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
SerialPort sp = (SerialPort) sender; // <- Obtain the serial port
string data = sp.ReadLine();
// Pass the serial port into si_DataReceived: SetTextDeleg(sp, ...
this.BeginInvoke(new SetTextDeleg(sp, si_DataReceived), new object[] { data });
}
// "SerialPort sp" is added
private void si_DataReceived(SerialPort sp, string data) {
String retorno = data.Trim();
MessageBox.Show(retorno);
// Fecha a porta após pegar o retorno
sp.Close();
}
/* HELP END */
See also:
http://msdn.microsoft.com/library/system.io.ports.serialport.datareceived.aspx

C# Telephone Number Receiver

I am trying to build a simply app that returns the number calling via a modem, however I only seem to be getting the first line of the data received from the modem.
When I run HyperTerminal and pass through the AT#CID=1 command, ring the number, I get a full output of :
OK
DATE=0314
TIME=1111
NMBR=4936
NAME=Stuart E
RING
In my app i only seem to receive the first section containing the "OK" part. Any help on what i am doing wrong or am missing?
Code:
public partial class Form1 : Form
{
public SerialPort port = new SerialPort("COM3", 115200,Parity.None,8,StopBits.One);
public String sReadData = "";
public String sNumberRead = "";
public String sData = "AT#CID=1";
public Form1()
{
InitializeComponent();
}
private void btnRun_Click(object sender, EventArgs e)
{
SetModem();
ReadModem();
MessageBox.Show(sReadData);
}
public void SetModem()
{
if (port.IsOpen == false)
{
port.Open();
}
port.WriteLine(sData + System.Environment.NewLine);
port.BaudRate = iBaudRate;
port.DtrEnable = true;
port.RtsEnable = true;
}
public string ReadModem()
{
try
{
sReadData = port.ReadExisting().ToString();
return (sReadData);
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error in Reading: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
MessageBox.Show(errorMessage, "Error");
return "";
}
}
private void btnExit_Click(object sender, EventArgs e)
{
port.Close();
Close();
}
}
}
In ReadModem() try to use port.ReadLine() in a loop instead and loop until you get a line saying RING (if that is the final line you are expecting).
You are just reading the Modem once after setting it. You need to subscribe the DataReceivedEvent on serialPort to continuously get data from the port.
public void SetModem()
{
if (port.IsOpen == false)
{
port.Open();
}
port.WriteLine(sData + System.Environment.NewLine);
port.BaudRate = iBaudRate;
port.DtrEnable = true;
port.RtsEnable = true;
port.DataReceived += port_DataReceived;
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//For e.g. display your incoming data in RichTextBox
richTextBox1.Text += this.serialPort1.ReadLine();
//OR
ReadModem();
}

Serial communication in c#

I have made a simple windows form with a ComboBox, TextBox and two Buttons to setup a serial protocol with my hardware.
However, whenever I send something I do get reply from hardware but C# doesn't display it. Instead it gives an exception saying that the operation has timed out. I even used an oscilloscope to check if I received something and it was positive. But C# doesn't display the code as stated before.
I am attaching my code below. Anyhelp would be welcome. Thanks in advance.
public partial class Form3 : Form
{
string buffer;
public SerialPort myComPort = new SerialPort();
delegate void setTextCallback(string text);
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Caption"].ToString().Contains("(COM"))
{
comboBox1.Items.Add(queryObj["Caption"]);
}
}
comboBox1.Text = comboBox1.Items[0].ToString();
}
catch (ManagementException ex)
{
MessageBox.Show(ex.Message);
}
}
private void setText(string text)
{
if (textBox1.InvokeRequired)
{
setTextCallback tcb = new setTextCallback(setText);
this.Invoke(tcb, new object[] { text });
}
else
{
textBox1.Text = text;
}
}
void myComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string myString = myComPort.ReadLine();
setText(myString);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void button1_Click(object sender, EventArgs e)
{
myComPort.Close();
// button1.Enabled = false;
string name = comboBox1.Text;
string[] words = name.Split('(', ')');
myComPort.PortName = words[1];
myComPort.ReadTimeout = 5000;
// myComPort.WriteTimeout = 500;
myComPort.BaudRate = 9600;
myComPort.DataBits = 8;
myComPort.StopBits = StopBits.One;
myComPort.Parity = Parity.None;
myComPort.DataReceived += new SerialDataReceivedEventHandler(myComPort_DataReceived);
myComPort.Open();
}
private void button2_Click(object sender, EventArgs e)
{
myComPort.WriteLine("?GV1\r");
}
}
It say
...The DataReceived event is not guaranteed to be raised for every byte received...
Try something like:
private static void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// prevent error with closed port to appears
if (!_port.IsOpen)
return;
// read data
if (_port.BytesToRead >= 1)
{
// ...
// read data into a buffer _port.ReadByte()
DataReceived(sender, e);
}
// ...
// if buffer contains data, process them
}
Have a look at this url:
http://csharp.simpleserial.com/
And this url for WMI:
http://www.codeproject.com/Articles/32330/A-Useful-WMI-Tool-How-To-Find-USB-to-Serial-Adapto

Categories

Resources