Serial Port listening in C# - c#

There are loads of questions about listening of devices on Serial Port using C#.
However I couldn't find something that will be useful for my application and working.
Now this is a code i finally decided to use however I cannot see why it will not output anything:
namespace SerialPorts
{
class Program
{
static void Main(string[] args)
{
SerialPort myPort = new SerialPort();
myPort.DataReceived += MyPortDataReceived;
myPort.PortName = "COM3";
myPort.BaudRate = 19200;
myPort.DataBits = 7;
myPort.Parity = Parity.Even;
myPort.StopBits = StopBits.One;
myPort.Open();
Console.ReadLine();
myPort.Close();
}
static void MyPortDataReceived(object sender,
SerialDataReceivedEventArgs e)
{
var myPort = sender as SerialPort;
Console.WriteLine(myPort.ReadLine());
}
}
}
My device is OCR PASSORT reader.
I expect a string when i swipe a passport. However I get nothing, no output at all.
Can you please help me what can i do to make it output a string at least?
BTW I know the OCR reader is working since there is an app coming with it that outputs its data and when I use apps that test the COM i get data but with this code I get nothing. Any help will be appreciated!
Regards!

Related

Communication between C# and Arduino

Code for C#
using System;
using System.Windows.Forms;
using System.IO.Ports;
SerialPort port;
private void btnStart_Click(object sender, EventArgs e)
{
port = new SerialPort("COM6", 9600);
port.Open();
port.Write("START");
port.Close();
}
Code for Arduino
"#"include "MOVIShield.h"
MOVI recognizer(true);
Code inside the loop
signed int res=recognizer.poll();
if(Serial.available() > 0){
String data = Serial.readString();
if(data = "START"){
recognizer.ask("Hello. My name is John");
}
}
I tried to click the btnStart to send "START" to my Arduino Program and the Arduino Program should run ask("Hello. My name is John") after received the data from C# program. But when I clicked the btnStart, there is nothing happened.
You can try different a couple of different things:
1- Make sure COM port parameters are the same on both sides
As explained at http://www.instructables.com/id/How-to-connect-Arduino-to-a-PC-through-the-serial-/
Add this to the Arduino C code outside the loop:
Serial.begin(9600);
And change your C# to a code similar to:
private void btnStart_Click(object sender, EventArgs e)
{
port = new SerialPort("COM6", 9600);
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.Parity = Parity.None;
port.Open();
port.Write("START");
port.Close();
}
2- Use a different tool than C# to test if you can communicate to the Arduino.
e.g. this tool has 15 days demo: https://www.eltima.com/rs232-testing-software/
I imagine the single equals in this line may have something to do with it.
if(data = "START")

Not able to read data from COM4 port C#

I'm trying to read data from COM port, but I'm stuck with this issue so long.
We're having some USB serial port device which is running on COM4 port, with that we have some predefined commands to execute and also there are some predefined outputs.
Our requirements is to send command to the COM4 port and read result.
Here what I have tried:
class Program
{
[STAThread]
static void Main(string[] args)
{
string cmd = "PING";
SerialPort mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.Open();
mySerialPort.Write(cmd);
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Console.WriteLine(mySerialPort.ReadChar());
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
Console.WriteLine(data);
}
But It's stuck with black console screen, even DataReceivedHandler is not called, and not able to get anything from COM4 port.
I've gone through many similar topics:
.NET SerialPort DataReceived event not firing
How to Read and Write from the Serial Port
And many mores, but no luck so far.
Am I missing something here?
P.S: It's working with RealTerm application, where we pass same command and are able to get output

Arduino and C# Serial Port "Crash"

I am trying to create a communication between an Arduino Leonardo and C#.
Just now, the Arduino's software sends a simple message (in loop) on the serial port:
void setup() {
Serial.begin(9600);
analogReference(INTERNAL);
}
void loop() {
Serial.println("test");
delay(500);
}
C# try only to read these messages and print them on the shell:
public class Program
{
private SerialPort mySerialPort;
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("PORTS: " + String.Join(" ", p.getSerialPortsList())+ ", enter to start.");
Console.Read();
p.SerialRead("COM6");
}
public String[] getSerialPortsList()
{
string[] ports = SerialPort.GetPortNames();
return ports;
}
public void SerialRead(String com)
{
mySerialPort = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
Console.Read();
Console.WriteLine("Incoming Data:");
SerialRead sr = new SerialRead();
Thread rs = new Thread(sr.StartRead);
sr.SetMySerialPort(mySerialPort);
rs.Start();
while (!rs.IsAlive);
Console.Read();
sr.SetSuspendThread(true);
rs.Join();
}
}
public class SerialRead
{
private Boolean suspendThread = false;
SerialPort mySerialPort;
public void StartRead()
{
mySerialPort.Open();
Thread.Sleep(500);
int i = 0;
while (!suspendThread)
{
i++;
Console.WriteLine(i + ": " + mySerialPort.ReadLine());
Thread.Sleep(500);
}
}
public void SetMySerialPort(SerialPort mysp){ mySerialPort = mysp; }
public void SetSuspendThread(Boolean a){ suspendThread = a; }
}
The output of this C# software depends. If I use the serial monitor on the Arduino IDE, then I receive the string's stream correctly (one each 500ms).
Otherwise, the C# software freezes. Sometimes, I receive a couple of strings as we can see this figure; but almost all time, the software does not give any string, as we can see here. After that the software freezes (thus, if I press enter the shell does not response).
Can you suggest a solution in order to get a fluent flow of string, and -as a consequence- read each message sent by Arduino on the serial port?
I am using Window 10 x64 as OS and the COM6 (it is an USB 2.0).
I found the solution and I share it in order to help people with the same problem.
C# does not activate as default the RTS and the DTR serial port.
Thus, adding
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
after the serial port declaration, everything works fine.
This is a really good example:
Serial Port Polling and Data handling
The Serial Port got an event called DataRecived, so you dont have to sleep your thread.
Something like this:
serialPort.DataReceived +=SerialPortDataReceived;
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine(serialPort.ReadLine());
}

C#: Not receiving from GSM device

I've coded a little program to read/send SMS messages using a GSM device. My code worked fine on one kind of device. Today I am using a different device and my program can't receive from it (although it can send to it just fine). The device works just fine with the same configs under puTTY.
private void Form1_Load(object sender, EventArgs e)
{
Variables.sp.PortName = "COM1";
Variables.sp.BaudRate = 9600;
Variables.sp.DataBits = 8;
Variables.sp.Parity = Parity.None;
Variables.sp.StopBits = StopBits.One;
Variables.sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
try
{
Variables.sp.Open();
Variables.sp.WriteLine("AT\r");
//Variables.sp.WriteLine("AT+CMGF=1\r");
}
catch
{
MessageBox.Show("Can't open COM1. Quit and try again.");
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
MessageBox.Show(indata);
}
Any idea why it would work fine on one device and not the other? While I'm typing the same commands under puTTY and they both work the same?

SerialPort First Command OK. Second Command Error

I'm writing a serialport app to talk to a Bluetooth module over serial port. The first At command I send to the device runs fine and I get a response of the module version. All subsequent commands fail with a response of ERROR.
Part of the code is here:
namespace PhoneApp
{
public partial class Form1 : Form
{
//SerialPort myport = OPenPort.OpenIt();
SerialPort myport = new SerialPort();
public Form1()
{
InitializeComponent();
myport.PortName = "COM3";
myport.BaudRate = 115200;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.NewLine = System.Environment.NewLine;
myport.ReadTimeout = 500;
myport.WriteTimeout = 500;
myport.DtrEnable = false;
myport.RtsEnable = false;
myport.WriteBufferSize = 4096;
myport.ReadBufferSize = 4096;
myport.Handshake = Handshake.None;
myport.Encoding = System.Text.Encoding.ASCII;
if (!myport.IsOpen)
{
myport.Open();
}
calling.Visible = false;
myport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
mycommand.Text = #"AT+BGVER";
the button which sends the command. The device requires a newline after each comand.
private void button2_Click(object sender, EventArgs e)
{
try
{
myport.WriteLine(mycommand.Text.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Not sure what I'm missing here.
Thanks for the replies. i found the problem. In fact I had to use myport.Write instead of myport.WriteLine. I deleted the line myport.NewLine and I appended "\r" to every command. Now the device responds as expected. As for DTR and RTS they are not required by the device according to the vendor
Not sure if this solves your problem, but I noticed that you don't have flow control enabled (e.g. myport.RtsEnable = false; myport.DtrEnable = false;).
Have you checked the documentation to make sure that the Bluetooth module doesn't require it? Typically devices with 115kbps and higher need flow control.
Another thing to check is the NewLine constant. You set it to the sys default which is likely Cr+Lf. Make sure that the module expects that.

Categories