I'm doing a keypad project for 10-digit ID input. For each key press, it will send '1' or '2' or '3' and so on to the serial port. However, after trying to display the content of my id buffer with Console.WriteLine(id[i]), it only display the first keypad value from serial port. I need to display all 10-digit input from the buffer. I cant find where is the error in the code. I'm using System.IO.Ports
static void Main(string[] args)
{
char[] id = new char[10] ;
SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
port.Open();
if (port.IsOpen)
{
Console.WriteLine("port is now open");
}
else
{
Console.WriteLine("port not opened correctly");
}
port.Read(id, 0, 10);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(id[i]);
}
Console.ReadLine();
}
First check whether your device is sending any data.
You can use a RS232 terminal for this.
Termite is a free terminal software.
If your hardware is sending data correctly,
Add DataReceive event,
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Then use ReadExisting() method for capture received data.
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine(port.ReadExisting());
}
Related
I have a small window form application (C#): Read data from barcode by COM UART RS232 and display to textbox
If I connect barcode with COM extension ( PCI express serial), after scan barcode => data only have /0/0/0/0/0/0/0/0
If I connect barcode with default COM ( communication COM) of computer => It's OK.
How can I fix that with extension COM ?
the below is my Code :
string path = ".\\Setting\\Config.ini";
IniFile inisys = new IniFile(path);
string PortName = inisys.GetString("FORMULA", "BarcodeCOM", "COM5");
int BaudRate = inisys.GetInt32("FORMULA", "baudrate", 9600);
port = new SerialPort(PortName, BaudRate, Parity.None, 8, StopBits.One);
port.Open();
if (port.IsOpen)
{
// set the 'invoke' delegate and attach the 'receive-data' function
// to the serial port 'receive' event.
accessControlFromCentralThread = displayTextReadIn;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs rcvdData)
{
while (port.BytesToRead > 0)
{
lineReadIn += port.ReadExisting();
Thread.Sleep(100);
}
// display what we've acquired.
displayTextReadIn(lineReadIn);
}
private void displayTextReadIn(string ToBeDisplayed)
{
if (Txt_itemNo.InvokeRequired)
Txt_itemNo.Invoke(accessControlFromCentralThread, ToBeDisplayed);
else
Txt_itemNo.Text = ToBeDisplayed;
}
I'm trying to read messages sent form my Arduino over a Serial port using baud rate 9600.
My Arduino code is programmed to send a "1" whenever I press a button and a "0" when I release my finger off the button.
So it's not constantly sending data.
My C# Program is to read that message and add it to a ListBox. But whenever I start it, the program hangs.
private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;
port.Open();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
ee = port.ReadLine();
listBox1.Items.Add(ee);
}
catch (Exception)
{
timer1.Stop();
}
}
I guess, maybe the reason is that my program should check if there's data available to be received before receiving?
Try something like this instead. It will at least not hang, and then you can sort out what sort of data your are getting via DataReceived
From there you can determine how to better write your app
private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer in the output window
Debug.WriteLine("data : " + port.ReadExisting());
}
SerialPort.DataReceived Event
Indicates that data has been received through a port represented by
the SerialPort object.
SerialPort.ReadExisting Method ()
Reads all immediately available bytes, based on the encoding, in both
the stream and the input buffer of the SerialPort object.
To avoid this problem, you need to add "\n" to your data in your arduino because
port.ReadLine(); search for ending line ("\n")
For example, let's say that the data which arduino sends is "1", to read this data with port.ReadLine(); it should be "1\n"
Also, do not worry, port.ReadLine(); doesn't read "\n". Just stops there when it sees "\n".
I hope it helps.
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());
}
I am trying to communicate with ECUsim 2000 which is OBD-ll ECU simulator (link). Yet, responses I always receive from device are something like "??" or "?" (when I run programs like TouchScan or OBD Auto Doctor, they successfully reads data so device is working properly). I am sending comand in C# via
serialPort1.Write("010D\r")
and I am receiving signal in SerialPort's DataReceived event as
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
I do not now what I am missing. Here is the full source code
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 115200;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.DataBits = 8;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("010D\r");
}
}
private void displayText(object sender, EventArgs e)
{
textBox1.AppendText(message + "\n");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
}
Default communication settings of ECUsim 2000 are
Baud Rate: 115200
Data bits: 8
Parity: none
Stop bits:1
protocol is ISO 15765-4 and there are two switches on the device which are protocol attribute CAN ID 29/11 bit and CAN Baud Rate 500 kbps/250kbps. Maybe, the problem are related with these such that there is no proper communication set.
Another question -> Is there a way to set protocol (like ISO 15765-4) in serial communication?
There are two problems related with the code given.
1) There are two connector on the ECUsim 2000. One of them is type B USB port, other one is Diagnostic Link Connector (DLC). If one wants to get connected to device via type B USB port, baud rate is: 115200. If DLC is used, Baud Rate is most probably either 9600 or 38400. Here, connection is made through scan tool, therefore (for my case) baud rate 38400 worked for me.
2) As mentioned in the comment, In order to get data, Read() method of SerialPort must be used. It can be used as the following code:
int buffSize = 1024;
bool cont = true;
int count = 0;
byte[] bff = new byte[buffSize];
string returnVal = string.Empty;
count = serialPort1.Read(bff, 0, buffSize);
returnVal += System.Text.Encoding.Default.GetString(bff, 0, count);
I have application with several windows (actually its two almost same windows with some functions). One of that function is reading data from COM port (read weight from weighting machine). Problem is that, it works perfect on first window, but when im closing it and opening another window, then clicking same function (lets call it calculate weight), im getting this error message:
Access to the port 'COM1' is denied.
Code:
private void calculateWeight_Click(object sender, RoutedEventArgs e)
{
sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
tekst = string.Empty;
sp.Open();
sp.WriteLine(((char)5).ToString());
sp.WriteLine(((char)17).ToString());
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private delegate void UpdateUi(string s);
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
tekst += sp.ReadExisting();
if (tekst.Contains('S') && tekst.Length > 14)
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUi(czytajWage), tekst);
}
string tekst = string.Empty;
void czytajWage(string s)
{
string w = "";
for (int i = 5; i < 14; i++)
{
w += s[i];
}
MessageBox.Show(w);
w = "";
tekst = "";
sp.DataReceived -= sp_DataReceived;
}
Anyone can help? ;)
Method calculateWeight_Click opens serial port. So I assume that you get your exception on Open call as documentation states UnauthorizedAccessException can be thrown when:
The current process, or another process on the system, already has the specified COM port open either by a SerialPort instance or in unmanaged code.
So solution for you is to Close and Dispose sp after you are done or use IsOpen if you want to reuse existing instance.