How do I access COM-Port with C#? - 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

Related

Capturing serial welcome message when connecting in c#

I am trying to write a program that communicates with a controller. The controller is supposed to send a "welcome" message when a connection is successfully established and, in fact, it does when I connect using a communications software. However, using the .NET code below, I never see the welcome message. Beyond that, it works. How can I capture this message. It seems to be sent the moment the connection is established.
Again, I am able to communicate fine with the controller after connection but I simply cannot seem to get the welcome message that is sent a the moment the connection is opened.
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
SerialPort sp;
public Form1()
{
InitializeComponent();
}
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort(comboBox1.SelectedItem.ToString(),Int32.Parse(comboBox2.SelectedItem.ToString()));
sp.DataReceived += SerialPort_OnDataReceived;
sp.Close();
sp.Open();
richTextBox1.AppendText("open\n");
button2.Enabled = true;
button3.Enabled = true;
}
catch (Exception ex)
{
richTextBox1.AppendText(ex.Message);
}
}
void SerialPort_OnDataReceived(object sender,SerialDataReceivedEventArgs args)
{
SerialPort sp = sender as SerialPort;
string s = sp.ReadExisting();
richTextBox1.Invoke(this.myDelegate, new Object[] { s });
}
private void button2_Click(object sender, EventArgs e)
{
sp.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
sp.Close();
richTextBox1.AppendText("\nclosed\n");
}
private void Form1_Load_1(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
string[] Ports = SerialPort.GetPortNames();
comboBox2.SelectedIndex = comboBox2.Items.Count - 1;
Array.Sort(Ports, (a, b) => string.Compare(a.Substring(3).PadLeft(3, '0'), b.Substring(3).PadLeft(3, '0')));
foreach (string port in Ports)
{
comboBox1.Items.Add(port);
}
comboBox1.SelectedIndex = 0;
}
}
}
I worked it out. Required a slight delay between connection and trying to pull data from the port.

C# SerialPort class receives incorrect data

I currently have a program made using VB6 code that uses the MSCOMM control to pull back data from the serial port. This manages to successfully receive the data from my serial port, in which a Denso BHT-904B device is connected.
I am now trying to move this code over to C# so it fits in with a new piece of software that i am developing. To do this i am using the SerialPort class. However, the issue is that when i open the port up the data received event only fires when the device fails to communicate (which im guessing is due to a timeout). The data then received in the event is '↑↑↑↑↑'.
My SerialPort control settings are the following:
DtrEnable = True
PortName = COM3
ReadBufferSize = 1024
WriteBufferSize = 512
The code that i am using behind my form control is:
namespace BHTTestingDotNet
{
public partial class Form1 : Form
{
private string rxString;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
serialPort.DtrEnable = true;
serialPort.Encoding = Encoding.Default;
serialPort.DataReceived += serialPort_DataReceived;
serialPort.ErrorReceived += serialPort_ErrorReceived;
serialPort.Open();
}
private void serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
MessageBox.Show(e.ToString());
}
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
var test = serialPort.BytesToRead;
SerialPort sr = (SerialPort)sender;
rxString = sr.ReadExisting();
this.BeginInvoke(new EventHandler(displayText));
}
private void displayText(object o, EventArgs e)
{
txtBHT.AppendText(rxString);
}
}
}
I have already tried to set both RtsEnable and DtrEnable to true but that didn't make any difference.
UPDATE - I have now changed to protocol settings on the device but i now only receive pipes and then a return symbol, for example like so:
|||||¬
I am using SerialPort class often and for my purposes I have made my own class
public class SerialPortDataSource : SerialPort
where SerialPort.DataReceived handler invoke this method:
private void SerialPortDataSource_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (BytesToRead > 0)
{
var buffor = new byte[BytesToRead];
Read(buffor, 0, buffor.Length);
_receivedBytes = buffor;
//wConsole.WriteLine(ArrayExtension.ToString(buffor));
var dataLogger = DataLogger;
if (dataLogger != null)
{
dataLogger.WriteLine("- DR - {0}", true, BitConverterExtension.ToHexString(buffor));
}
if (OnDataReceived != null)
{
OnDataReceived(this, buffor);
}
}
}
catch (InvalidOperationException)
{
// sometimes DataReceived event is invoked after port is closed which causes InvalidOperationException
}
}
This method is working for me in many applications with variety serial port settings.

Serial Port Programming Help in C#

Recently i want to connect and read data from Serial Port Using SerialPort Class in C#. I have a time attendance machine named RTA600 from Hundura. it is connected to my PC via serial-to-USB convertor. the code i have tested as follows
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.RtsEnable = true;
// Open the Serial Port
serialPort1.Open();
// Read Data from Serial port
string RXstring = serialPort1.ReadLine();
I use SerialPort Class of System.Io.Ports namespace. But it code hangs when serialPort1.ReadLine() executes. Can Some give me a idea how can i read the data from by time machine through serial-to-usb convertor
You can use ReadExisting() to read the whole data at a time.
You need to handle DataReceived Event of SerialPort
serialPort1.ReadExisting();
Sample:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
String myData=serialPort1.ReadExisting();
}
Example Code: Here i would like to show you the code to Read Data(RFID Tag Code which is basically of length 12)
String macid = "";
private void DoWork()
{
Invoke(
new SetTextDeleg(machineExe ),
new object[] { macid });
macid = "";
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string str1;
macid += serialPort1.ReadExisting();
if (macid.Length == 12)
{
macid = macid.Substring(0, 10);
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
}
public void machineExe(string text)
{
TextBox1.Text=text;
}

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

Semaphore timing out while accessing a serial port?

I'm experiencing this problem while opening a serial port in C# (which should be dirt simple; or so I thought).
When I try to open a serial port, I am getting the following exception:
The semaphore time-out period has expired.‎
Here is the method that is doing this.
public static void Open_TheActivePortWeWillUse(String Drone_StringNameFromUser)
{
var TempSerialPort = new SerialPort (
Drone_StringNameFromUser,
(int) SerialPortParameter.TheSerialPortSpeed);
// Now we have a name that anybody can see and use
OurSpecificPorts.TheActivePortWeAreUsing = TempSerialPort;
// We'll do 8-N-1 since almost the whole planet does that
OurSpecificPorts.TheActivePortWeAreUsing.DataBits = 8;
// We'll do 8-N-1
OurSpecificPorts.TheActivePortWeAreUsing.Parity = Parity.None;
// We'll do 8-N-1
OurSpecificPorts.TheActivePortWeAreUsing.StopBits = StopBits.One;
OurSpecificPorts.TheActivePortWeAreUsing.DataReceived +=
OurBackGroundSerialPortReceiver;
// We can now open our active port, which is what this line does
OurSpecificPorts.TheActivePortWeAreUsing.Open();
}
The strangest thing for me is that I get this error inconsistently. Half the time it works okay, and the other half, it does not.
Does anybody see anything obviously wrong with my code? Am I missing something?
Declaring your SerialPort object inside the method will not allow access to it after the method closes. Here is a method that works to open the port:
private void OpenSerialPort(String portName)
{
try
{
serialPort1.Close();
serialPort1.PortName = portName;
serialPort1.BaudRate = 115200;
serialPort1.DataBits = 8;
serialPort1.Handshake = Handshake.None;
serialPort1.Parity = Parity.None;
serialPort1.RtsEnable = false;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
}
catch (Exception ex)
{
MessageBox.Show("Could not open serial port " + portName, "Error");
}
}
The SerialPort object is declared in the class:
namespace Arcadia
{
public partial class Form1 : Form
{
private SerialPort serialPort1;
And the callback is added in the constructor:
public Form1()
{
InitializeComponent();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(this.SerialPortReadCallback);
Sending data is handled in a different method:
private void SerialPortWrite(String writeString)
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine(writeString);
}
}
And here is the received data callback:
private void SerialPortReadCallback(object sender, SerialDataReceivedEventArgs args)
{
try
{
while (serialPort1.BytesToRead > 0)
{
// Do something with the data
}
}
catch (Exception ex)
{
}
}

Categories

Resources