473,472 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problem with serial port in C# 2.0

Hi everybody,

I have a big problem. I am trying to use serial communication in C# 2. The
problem is that the event DataReceived is never fired. I have tried on two
computers and it does not work at all. I have tried also in C++ .NET 2005 and
also does not work.

I did not find any useful information on the net.

Do you have a small working C# program about how to setup and use the COM1
port and the DataReceived event?

Thank you.
Mar 1 '06 #1
9 14233
Sorry for this reply, but I forgot to mention that my problem is only with a
GUI program. The DataReceived works perfect in a console program.

What is wrong with a GUI program? Or I am missing something?

I would like to see a simple GUI program which works with DataReceived event
and to see what is wrong with my program.

Thank you.
Mar 1 '06 #2
Hi,

Try this code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SerialTest
{
public partial class Form1 : Form
{
SerialPort m_comPort;

public Form1()
{
InitializeComponent();

m_cmbPortName.Items.Clear();
foreach (string s in SerialPort.GetPortNames())
{
m_cmbPortName.Items.Add(s);
}

m_cmbStopbits.DataSource =
System.Enum.GetValues(typeof(StopBits));
m_cmbParity.DataSource =
System.Enum.GetValues(typeof(Parity));
}

private void button1_Click(object sender, EventArgs e)
{
Send();
}

private void Send()
{
try
{
if (m_comPort.IsOpen)
{
int delay = Int32.Parse(m_txtDelay.Text);
if (delay > 0)
{
string cmd = m_txtSend.Text;
for (int i = 0; i < cmd.Length; i++)
{
m_comPort.Write(cmd[i].ToString());
Thread.Sleep(delay);
}
}
else
{
m_comPort.Write(m_txtSend.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception while writing to COM: " +
ex.Message);
}
}

private void m_txtSend_TextChanged(object sender, EventArgs e)
{
//Send();
//m_txtSend.Clear();
}

private void m_btnOpen_Click(object sender, EventArgs e)
{
try
{
if (m_comPort != null)
{
if (m_comPort.IsOpen)
{
m_comPort.Close();
}
}
else
{
m_comPort = new SerialPort();
}

m_comPort.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);

/// Port Name
m_comPort.PortName = m_cmbPortName.Text;
/// Baud Rate
m_comPort.BaudRate = Int32.Parse(m_txtBaud.Text);
/// Stop Bits
m_comPort.StopBits =
(StopBits)Enum.Parse(typeof(StopBits), m_cmbStopbits.Text);
/// Parity
m_comPort.Parity = (Parity)Enum.Parse(typeof(Parity),
m_cmbParity.Text);
/// Data Bits
m_comPort.DataBits = Int32.Parse(m_txtDatabits.Text);
/// Flow Control
m_comPort.Handshake = Handshake.RequestToSend;
m_comPort.RtsEnable = true;

//m_comPort.Encoding = Encoding.UTF8;

m_comPort.Open();

Log("Port successfully opened");
}
catch (Exception ex)
{
Log("Error while opening " + m_cmbPortName.Text + ": "
+ ex.Message);
}
}

private void Log(string s)
{
m_txtLog.Invoke(new EventHandler(delegate
{
m_txtLog.Text += Environment.NewLine + s;
}));
}

private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string data = "";
while (m_comPort.BytesToRead > 0)
{
data += Convert.ToChar(m_comPort.ReadByte());
}

Log(data);
}

private void m_btnClose_Click(object sender, EventArgs e)
{
try
{
if (m_comPort.IsOpen)
{
m_comPort.Close();

Log("Port successfully closed");
}
}
catch (Exception ex)
{
Log("Could not close port: " + ex.Message);
}
}
}
}
Note: Send command supports sending chars with delay between them.

Janiek
On Wed, 1 Mar 2006 02:39:26 -0800, Mircea
<Mi****@discussions.microsoft.com> wrote:
Sorry for this reply, but I forgot to mention that my problem is only with a
GUI program. The DataReceived works perfect in a console program.

What is wrong with a GUI program? Or I am missing something?

I would like to see a simple GUI program which works with DataReceived event
and to see what is wrong with my program.

Thank you.


Mar 1 '06 #3
Mircea a écrit :
Sorry for this reply, but I forgot to mention that my problem is only with a
GUI program. The DataReceived works perfect in a console program.

What is wrong with a GUI program? Or I am missing something?


Hello,
just a idea :

Access to GUI stuff from an event has to be done via a BeginInvoke( someDelegate )

good luke
cyrille
Mar 1 '06 #4


"Janiek Buysrogge" wrote:
Hi,

Try this code:


Thank you, I figgured out how it works.

Mar 1 '06 #5
I face with another problem with serial port. I read string bytes of
different lenghts. If the incoming string has up to 8 bytes, everything is
fine. If the incoming string has more than 8 bytes, there is a problem. For
example, I read a byte string from the serial port which is 11 bytes long.
The function read returns only the first 8 bytes and I have to perform a
second read for the other 3. This behavoiur is exactly like a TCP port. This
time I know how many bytes I expect, but there are cases when I don't know
how many bytes I get.

Is tihs the behaviour of the serial port in C# 2, or I miss something?

I use the function Read(byte[], offset, length) and doesn't matter what I
use as lenght, either BytesToRead, or length of the byte array, which is
large enough. If the expected input is more than 8 bytes, BytesToRead is
always 8 and I need some more readings.

All this happens in DataAvailable function.

Thank you.
Mar 4 '06 #6
Bob
Hi Mircea,
Suggest you check your 'ReceivedBytesThreshold' property.
regards
Bob
"Mircea" <Mi****@discussions.microsoft.com> wrote in message
news:F9**********************************@microsof t.com...
I face with another problem with serial port. I read string bytes of
different lenghts. If the incoming string has up to 8 bytes, everything is
fine. If the incoming string has more than 8 bytes, there is a problem. For example, I read a byte string from the serial port which is 11 bytes long.
The function read returns only the first 8 bytes and I have to perform a
second read for the other 3. This behavoiur is exactly like a TCP port. This time I know how many bytes I expect, but there are cases when I don't know
how many bytes I get.

Is tihs the behaviour of the serial port in C# 2, or I miss something?

I use the function Read(byte[], offset, length) and doesn't matter what I
use as lenght, either BytesToRead, or length of the byte array, which is
large enough. If the expected input is more than 8 bytes, BytesToRead is
always 8 and I need some more readings.

All this happens in DataAvailable function.

Thank you.

Mar 5 '06 #7


"Bob" wrote:
Hi Mircea,
Suggest you check your 'ReceivedBytesThreshold' property.
regards
Bob

Hi Bob,

Thank you for your reply. The value of 'ReceivedBytesThreshold' property is
1. Is this the right value to be, or I miss something?

Mar 6 '06 #8


Mircea wrote:
I face with another problem with serial port. I read string bytes of
different lenghts. If the incoming string has up to 8 bytes, everything is
fine. If the incoming string has more than 8 bytes, there is a problem. For
example, I read a byte string from the serial port which is 11 bytes long.
The function read returns only the first 8 bytes and I have to perform a
second read for the other 3. This behavoiur is exactly like a TCP port. This
time I know how many bytes I expect, but there are cases when I don't know
how many bytes I get.
Yes, it is exactly a Stream, you are not guaranteed that the buffer you
pass is filled, only that at least one byte is written, or that the
stream is closed, in which case 0 bytes are returned.
Is tihs the behaviour of the serial port in C# 2, or I miss something?
How can the serial-port guess how many bytes you need to read? should it
always block untill your buffer is filled?

In the special-case of a serial-port stream, you can set a
timeout-value, s.t. Read will return if no data is not recieved within a
certain time-limit.
I use the function Read(byte[], offset, length) and doesn't matter what I
use as lenght, either BytesToRead, or length of the byte array, which is
large enough. If the expected input is more than 8 bytes, BytesToRead is
always 8 and I need some more readings.


if you wish to remain blocked while reading any amount of data, use a
helper function:

public static void FillBuffer(
Stream s, byte[] buffer, int offset, int count)
{
for ( int r = 0, i = 0; i < count; i += r )
{
r = s.Read(buffer, offset+i, count-i);
if ( r <= 0 )
throw new EndOfStreamException(
string.Format("EOS while reading {0} bytes, only got {1}",
count, i));
}
}
...
byte[] buf = ...;
FillBuffer(s, buf, 0, buf.Length);

If you have more complex requirements, you will need to encode the data
that you transmit in a protocol which you can parse chunk-by-chunk.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 6 '06 #9
Thank you Helge, I have figured out how to do it. The problem is now solved and
everything works fine.
Mar 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

38
by: jrlen balane | last post by:
basically what the code does is transmit data to a hardware and then receive data that the hardware will transmit. import serial import string import time from struct import * ser =...
13
by: Bob Greschke | last post by:
We have some equipment that communicates at 57600 baud RS232. The path from the PC is USB to a Phillips USB hub, then off of that a TUSB3410 USB/Serial converter. The driver for the 3410 chip...
3
by: collinm | last post by:
hi i send a command to a led display, the led display is suppose to return me some character i write a string on a serial port void ledDisplayExist() { char msg={'\0', '\0', '\0', '\0',...
7
by: Michael Chong | last post by:
I wrote a program that communicate with SerialComm. In every 300 milliseconds, my program continuously send & receive data via the serial port once the program starts. My program is once in a...
4
by: Lonifasiko | last post by:
Hi, I've been able to communicate using HyperTerminal with my device via serial port COM1. I just send a command and device switches on. I just need that to start playing with it. This way, I...
2
by: findyasir | last post by:
Hi all, I am having problem comunication with serial port in linux. I have tested the serial port with attaching a serial modem and dialing the numbers with wvdial. it works okie but when i...
3
by: Mugunth | last post by:
Hi, I've a strange problem with serial port class of .NET Framework 2.0 I use com0com (Null Modem COM Port emulator) to emulate a virtual port. This application creates virtual com port pairs...
3
by: psroga | last post by:
Can anyone look at this code and let me know why pthread_mutex_unlock and pthread_mutex_lock are giving me the "phtread_mutex_unlock" was not defined in this scope error. I am compiling the code...
1
by: lutherchp | last post by:
A baffling end to my week! I open my serial port on my Debian PC (Debian version 5.0.1) I have a decent Null Modem lead going to another PC (I'll call it PC#2), with its port open with the same...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.