The serial port is a serial communication interface through which information transfers in or out one bit at a time.
A quick search on Google reveals that there are a lot of free serial port monitor applications available for PC users. However, what these applications lack, is the possibility of controlling the serial port in a direct manner. They are generally good “sniffers” but they do not allow the user to actually write to the serial port or control any device attached to it. The applications with the write capability encapsulated are not for free, and the cheapest costs about 50 Euro – a great deal of money taking into account how easy it is to make a personalized application.
This article will show how it is possible to build such an application using the C# environment. It is not intended to be a C# tutorial, but to teach a user who has basic knowledge of C or C# to integrate serial port control in one of his applications.
For the example application, I have used the SharpDevelop development environment which includes a C# compiler. This is an open source IDE which takes up very little space on your hard drive and can be a good alternative to users who do not want to install the gigabytes of Visual Studio on their PCs for a simple serial port application.
Once you have downloaded and installed the SharpDevelop environment, create a Windows Application project (solution) called SerialPort:

Once you have created the application, display the windows form that was automatically created (by clicking on the “Design” button at the bottom of the screen) and unroll the menu available under “Components” available on the left-hand menu:


You will notice that one of the components available here is the one called “SerialPort”. Pick that component and drag&drop it over the surface of the form on the right. This will add the component to your project. The object that is created is called “serialPort1” and it will be used to access the serial port. To be able to use this component, however, you need to add at the beginning of your code the directive for using the System.IO.Ports namespace, as this is not added by default when you create the solution:
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO.Ports;
Once this is done, create a regular button on the surface of the form, call it “button1” and change its label to “Write”. Then double click on it in order to create the function that will be executed when the button is clicked. 
In this function we will perform several tasks. The first one is to configure the baud rate, COM port, number of data bits, parity and stop bits of the communication:
//configuring the serial port serialPort1.PortName="COM1"; serialPort1.BaudRate=9600; serialPort1.DataBits=8; serialPort1.Parity=Parity.None; serialPort1.StopBits= StopBits.One;
Next, before writing to the port, it needs to be opened:
//opening the serial port serialPort1.Open();
Please note that if the COM1 port is already used by an application, you will get an error message when this instruction is executed. Alternatively, if you open the COM1 port with your C# application and then fail to close it, any other application trying to use it will not be able to do that.
OK, it is now time to write to the serial port:
//write data to serial port
serialPort1.Write("ABC");
When this instruction is executed, three bytes are sent to the serial port: the ASCII code of “A”, the ASCII code of “B” and the ASCII code of “C”.
Once the write operation is performed, you must not forget to close the port:
//close the port serialPort1.Close();
So, as a summary, all the code that makes up the body of the function should be:
void Button1Click(object sender, EventArgs e)
{
//configuring the serial port
serialPort1.PortName="COM1";
serialPort1.BaudRate=9600;
serialPort1.DataBits=8;
serialPort1.Parity=Parity.None;
serialPort1.StopBits= StopBits.One;
//opening the serial port
serialPort1.Open();
//write data to serial port
serialPort1.Write("ABC");
//close the port
serialPort1.Close();
}
Now you have a broad path open in front of you, as you will be able to write your own customized applications that can send any data to any device attached to the serial port. The above code is also compatible with USB to Serial converters, provided that their drivers work by emulating COM ports.
Read the Italian version: Comunicazione Seriale in C#

C# and Serial Port.
Slinky, but what about receiving a string.....perhaps next blog ?
By the way, I'll give SharpDevelop a try, it seems worth it.
RE: C# and Serial Port
Hi Frabs,
What does "slinky" mean? I looked is up and found out it was a spring toy, but I do not really understand what you wanted to say...
Anyway, regarding the reading of bytes from the serial port: I didn't really detail this, because there are literally loads of freely available applications out there which perform the function of serial port sniffing and displaying, in any format you would need.
However, in case someone does want to do this in C#, the serialport class available, which is used in the above example provides several methods. To read bytes, you could use any of the following:
serialPort1.Read(byte_buffer,0,10); //this will read 10 bytes from the serial port and insert them starting with index 0 in a byte array called "byte_buffer", which has to be declared abovereceived_byte=serialPort1.Readbyte(); //this will read one byte from the serial port, and store it in a variable called received_byte
received_char=serialPort1.Readchar(); //same as above but reads a char
serialPort1.Readline(); //reads characters from the input buffer until the NewLine character is encountered; returns a string
Please pay attention though that the usage of all these functions is somewhat...tricky. In case you call any of these functions and no byte is available in the input buffer of the serial port, your application will appear to hang, and it will do so until either you kill it or the number of expected bytes (or at least one byte, depending on which of the above you use) is finally transmitted by the peripheral connected to the serial port of the PC.
There are ways of making the application work somewhat like in an "interrupt" manner, using the C# concept of "events" which trigger a function when bytes are available in the input buffer of the serial port, but although I am familiar enough to use them, I lack the theoretical notions of C# required to thoroughly explain these.
Regarding your thoughts of giving C# a try... I congratulate you! As you may have noticed, I am no C# expert myself, but for the hardware engineer who sometimes wants to format some text/binary files, to extract some data, to make a simple GUI...or to write some bytes to the serial port, it is a great tool. And this sharpdevelop compiler (not only free, but also open source, which is great!) only asks you to install a small amount on your PC (not hundreds of megabytes, like other IDEs)
Regards,
Cristian
C# and Serial Port.
Hi Cristian, nice to meet you here on YOUR ELECTRONIC OPEN SOURCE.
Slinky sounds like sexy (It has been even used on one of H.P.Books).
Thanks for the detailed explanation about receiving data from the serial port, though I think an event based module suits better my usual kind of program. (That's what I do with VB).
Well actually I was considering C# AND SharpDevelop that, quoting your own words is "not only free, but also open source, which is great!".
At the moment I'm still satisfied with VB for Visual Programming and VC++ for writing some dlls. Don't get me wrong, I'm not a Windows supporter and I'm not a kick ass high level programmer, I prefer stacks, ADC, I2C, Timers and watchdogs, but sometimes I must develop test benches or datalogger for my embedded projects, and that's where my "high level" programming comes handy. Perhaps getting a little acquainted with C# could let me drop VB and VC++, using one only language developed on an Open Source project.
Cheers
Frabs
asp.net connection with serial port
Thank you very much for code to transmit the data but if i want to receive data from this form please tell me what to do
RE: asp.net connection with serial port
Hi,
Regarding your question, please read the comments to this article as other have asked this before. In one of the comments above I actually detail a method for receiving data via the serial port. I hope it is what you are looking for and that it will work fine for you.
Best regards,
Cristian
How to access usb/ serial ports on the internet
Hi,
Thank you for good hint for ports. But my question is , how may i access usb/ serial ports over the internet. Can you tell me please?
Thank you.
RE: How to access usb/ serial ports on the internet
Hi GM,
It can be done but it is not trivial. And it is not very clear how you want to do it. Using a browser? Using a C# application? Or what? You should be more specific and somebody in this community might help you...
Regards,
Cristian
c++
please if you can help helpe me
RE: c++
Hi Abdale,
I would gladly help you if I could, but for that, I need to know... what is it exactly that you need. Is it code to access the serial port from C++? I think the latest .net framework maps the "outportb" instruction, in order to make things compatible to the old programs written in Borland C++, but I am not 100% sure.
Regards,
Cristian
Send AT command on GSM modem/Phone
Hi,
Dear i want to know that how i send the AT commands on GSM modem or mobile. Can i write the the AT commands in string that is send to port or u have any other method to send AT commands. plz guid me...
And also tell me that what mobile is best replacement of the GSM modem.
I am wait 4 ur answer.
umer_ufm@yahoo.com
RE: Send AT command on GSM modem/Phone
Hi UFM,
I would rather post the answer here for everybody to benefit from it, rather than writing you an e-mail.
So in short, it is perfectly possible to use the above code and write the AT commands as strings. I am not 100% familiar with these commands, and it might be that you need to append a termination character to each command (like 0x0A or 0x0D, depending on the phone).
I cannot tell you which the best mobile replacement is for the GSM modem. Guess it all depends on how much such a phone would allow you to do with AT commands.
Regards,
Cristian
Input for transmission
how wil i know which is the port that i can use or i must control the port that i wil be using fr communication?
RE: Input for transmission
Hi ST,
You will have noticed in the beginning of the article that there is a section dedicated to the configuration of the serial port. I want to draw your attention to a particular line of code in that section:
serialPort1.PortName="COM1";
This line is where you specify which COM port you want to use (in this case it is COM1). If your computer has more than one serial port, you can search for the available names in the Device Manager and see there which COM name these ports use.
Regards,
Cristian
Correction
Please consider this page first: http://www.codeproject.com/KB/system/rs232ThreadSafe.aspx
Your program would fail if you tried to access the serial port from a button, that's why people use thread safe calls...
Emrah
-----------------------------------------------------
Enslaving machines to free the mankind...
RE: Correction
Hi Emrah,
You are somewhat right. But only partially. Please note that the method described on the web page that you provided the link for, is actually the event driven method for reading the bytes from the serial port. Although this method is mentioned by myself and Frabs in the above comments, I have not described it, nor provided any source code for it. If it is used, the programmer does indeed need to take a little care about threading and other aspects of high level programming.
However, the methods for reading from the serial port that I have detailed will easily work without any complications, and you can directly assign the strings returned by the methods to textbox objects.
Regards,
Cristian
Then you taught me another
Then you taught me another way to access the serial port, thank you :)
Regards,
Emrah
Enslaving machines to free the mankind...
I lil help please
I have written a code in C# that helps me accept dome data from a test hardware which sends numbers in bytes when i press a button in the hardware.. But the code in my computer times out before I read the data. Also if i set the timeout to infinity. No data is recieved..
Please guide me. A source code to read such data will be highly appreciated. I've treid around 8 console and two variants of form codes but none of em are actually solving my problem.
Please help!
RE: I lil help please
Hello Sushi,
Can you confirm the correct functioning of your hardware by using the windows embedded hyperterminal? Can you see the bytes coming in?
Regards,
Cristian
Hi Cristian, I am using
Hi Cristian,
I am using Visual studio 8, i want to read the data from the serial port, i am actually interfacing pc and microcontroller.the data from the controller is commin to the serial port, from that i need to read and display it on the front end, the GUI is ready but data is to be read. does anyone knw as to how to do this? pls help
RE: Hi Cristian, I am using
Hello, whoever you are.
In cases like this, I always recommend using a proven and definitely fault-free method of checking for incoming data: the hyperterminal. Please use hyperterminal to confirm data is coming in to your PC (not only the scope).
Reading data from the serial pot using Visual Studio 8 applicatios is highly dependent upon the serial port access method you use. In case it is the method described n this article, please have a look at the second comment on this article, where I detail a way to do it.
Hope this helps!
Cristian
Thank you for the info
Thank you for the info cristian, yes i also agree that hyperterminal is the best way of checking the incoming data, actually that has already been implemented and tested. The data is coming till the serial port, since there is an option in visual studio where the data can be read from the serial port i wanted to implement the same, i am not finding any sort of tutorial regarding this. If u can suggest me a way to do it, it would be of great help.
Thanks in advance.
Microsoft C# System.IO.Ports.SerialPort
The way you do is the same I did for years, but I encountered some devices, that simply do not read anything at all when C# Serial Port class is used while you can perfectly read incoming data when using Microsoft HyperTerminal. I just encountered another case right now as I did 3 years ago. It seems that this did not change much over the last years.
I do not want to start complain about Microsoft, but I think that it is reasonable to be catious when you use their code and do not expect to work properly or at all. Try to manipulate some bitmaps. Microsoft classes are slow!!!!!!
In this case it is really necessary to unlock the pointer functionality. It is like returning into a pure C/C++, the conveniance if C# is definitely lost.
RE: Microsoft C# System.IO.Ports.SerialPort
Hi Stupido,
Can you give me some example of such devices? What you say is really news to me, although I realize that one of the previous posters in this thread might be experiencing the same.
If you told me what device this is, I might be looking if we have it here and I would investigate what does not work.
Regards,
Cristian
I can not read data from serial port
Hi guys
can any one help me to read from a serial port, i can send data from the pc to the pin pad but when i try to send data to the pc from the pin pad they are not comunicating and i dont know what to do . If anybody knew how to read data from the pin pad help out.
Hellen
"pin pad" serial port
Hi Helen,
I presume the "pin pad" is a device with RS-232 communication capabilities, right?
If this is the case, my recommendation is to always test your hardware with a known and proven software tool, like for instance the hyperterminal. Turn on and cofigure the hyperterminal, and you should see on the screen the hex values send by the device connected to the serial port. Make sure the correct COM port is selected and the correct communication protocol parameters are all in order (baud rate, data bits, stop bits etc.)
Regards,
Cristian
"pin pad" serial port
Hi Cristian,
Thank you, it works and i can read the hex from the pin pad and i converted to unicode.
Helen
Serial Port Communication in Excel (VBA)
Another great article about Serial Port communication.
"The purpose of this article is to demonstrate how you can perform serial port communication in the VBA (Visual Basic Applications - script editor included in any typical Microsoft Excel distribution) but without using the MSComm control or any other third party add-on or ActiveX."
Serial Port Communication in Excel (VBA)
Accessing Serial port Remotely
Hi guys,
I try to access my serial port device remotely, pls help.
Ronald
is it possible?
sir, is it possible to pass a value to a hardware using the serial port tool?
ahhmm i will appreciate your help..
im doing my thesis and i have to send signal to display the score of contestant into
the LED using the usb port, thnks in advance..
RE: is it possible?
Hi vigz,
To answer short: yes, it is possible. I am a little confuzed though, on your approach. Do you want to use the USB port or thephysical serial port of the PC? If you want to use the serial port, you can surely use the C# example in the article. If you want to use the USB port, you can also use thei c# example, provided that you use a USB-to-serial port converter that comes with Vicrtual Com Port (VCP) drivers. FTDI makes a few of these ICs and they work pretty neat from C#.
Regards,
Cristian
Is there any way
Hey guys,
I wrote an application which send and receive data from a pinpad and i start testing the application, when i finised testing the on my computer, I upload it to the server machine to do another test but when I run the application from client computers it does not recognize the pin pad, but when I run the application from my computer it works properly. My question is that is there any way I can access the pin pad remotely?
Thanks
Victor
Hi, It is Victor again, pin
Hi, It is Victor again, pin pad is a device with RS-232 which use serial port
Thanks again
Victor
RE: Hi, It is Victor again, pin
Hi Victor,
Can you let us know where do you connect the pin pad device when you run your application from the client computer? Is the pin pad connected to the server or to the client computer? I am not really sure which serial port is accessed this way, although I would firstly guess it should be the serial port on the client PC.
Regards,
Cristian
Pin pad
Hello Christian,
Sorry for not responding sooner,I connect the pin pad to the client computer, What i would like to do is ran the application from server and i have about 20 pin pads which will be connected to client computers, and i also want to locate the client computes in different places of the building.
Thanks
Victor
RE: Pin pad
Hi Victor,
Unfortunately I do not really have any idea why it would not work. I would say that given the circumstances you decribe, even if you call the application from the server it should be the serial port of the client computer that gets accessed. However, I am no guru in C# and I might be wrong here. Hopefuly it will be somebody with more knowledge in this area that will enlighten us.
Best regards,
Cristian
RE: Pin pad
Hello Cristian,
Thank you for your help, do you think if i use socket programming does it help? maybe by assigning IP Address and PortNo.
Thanks
Victor
RE: Pin pad
Hi Victor,
Unfortunately I am acquainted only marginally with socket programming. I remember doing something with "data socket" in LabView a few years ago, but that's about it. From what I remember, I would not think this would be a solution to the present problem, but I guess programming it yourself is for free...
Regards,
Cristian
Pinpad data communication
Hi Victor,
I am a software engineer who is currently working on POS device integration and I am currently working on the pinpad part.
It has come to my attention that you succeeded in implementing a pin pad communication program with pc. Is your program only using serial port library from .Net? How do you encrypt and decrypt the data from and to the pinpad? Do you have to install specific driver for the system to recognize the pinpad you plugged in?
I tried writing a program that sends data(in my case a string) to the pinpad, the pinpad shows that it is receiving data, but the response it give back is not suitable at all. Can you give me some guidance as to how do we ask the pinpad to perform specific operation such as accepting pin from users?
Thank you for your attention and your help will be very much appreciated because I've been stucked with this issue for days without any improvement.
Regards,
Andika
RE: Pinpad data communication
Hi Andika,
To answer your questions point by point (sinc victor des not seem to be around):
1. All you need to do serial comunication in C# is the serial port library from .NET. You also have to install the .NET framework on your PC, but that is transparent
2. You do not need to install any additional divers for any type of serial communication
As a general advice, I suggest that in order to see if you own code is wrong, you should take an existing application that does serial port communication (like hyperterminal, for instance, although it is rather not very flexible; or tera term would be another choice) and see if the commands you send do get the expected answer.
Regards,
Cristian
Pinpad data communication
Hi Adika,
Sorry for not replaying for your question. I know it is late but if it helps, yes I use a serial port library from .net. And the pin pad itself has an encryption and decryption algorithms ( just the user enters normal number like 1234 and the pin pad itself encrypt it to store to the database). Yes you have to install a driver for the system to recognize the pin pad after you install the driver go to device manager and you will find the com no for that specific pin pad.
If you have any question don’t hesitate to ask and I able to access the pin pad remotey.
Regards,
Victor
AT command
hi
i have a question about sending at command. if i want to send the following command :ATD 00000
which dial a a mobile number, i should send the hexdecimal of letters A,T and D. in other word the data send to the gsm modul by the fuction write should be 0x41,0x54,0x44 ?
if any one can post an example of an at command send using the c# lang i will be very thanks.
Reagards
RE: AT command
Hi man,
If you follow exactly the steps described in the article, you might want to replace the
//write data to serial port serialPort1.Write("ABC");instruction with:
//write data to serial port serialPort1.Write("ATD 00000");I believe this should do it. Of course, you can also use your approach, but the easiness of the AT commands resides exactly in giving the user the possibility to use ASCII strings, so you would do it more complicated than necessary.
Good luck,
Cristian
c#
but it not work for long time
i want that by pressing write button it write and when i press stop button it should display messege that port is closed............
RE: c#
I am afraid you will have to give me more details about what you are trying to do. Are you the same poster of the "AT Command" message? If you want to close the port upon pressing a button, you should simply create a button just like the "Write" button is exemplified in the article and then add the simple code:
//close the port
serialPort1.Close();
Hope this helps...
Cristian
Is there a library in C# which works for USB
Hi All,
I wrote a program for pin pad using serial port libraries and it work properly but when i changeed the cable to USB it does not send or receive data to the pin pad. Is there any USB library in c# which work the same as serial port? If there pls let me know and a sample code is very advantagous for me.
Thanks
Ruth
RE: Is there a library in C# which works for USB
Hi Ruth,
Are you talking about a USB-to-RS232 converter cable? Because if you are, then, the code above should work. I have specifically tried it with FTDI chips (FT232RL, specifically).
If you are talking about a plain USB cable betwen the PC and a potential USB interface of the pin pad, then you need special code to communicate via USB.
Let m know wht your situation is.
Regards,
Cristian
Hi Cristian, At first i
Hi Cristian,
At first i wrote the code for USB-to-RS232 converter cable, like you said the above code work perfectly but now i connect the plain USB cable to the PC and it is not working.
Thanks,
Ruth
RE: Hi Cristian, At first i
Hi Ruth,
As I wrote above this is totally expected. USB is a totally different protocol from UART, this is why USB-to-Rs232 converters do exist actually. Starting to write code for USB communication is not trivial, however the most basic pre-requisite in this case is for the pin pad to allow connection to an USB port of the PC (which I doubt it does, in case it is specified for RS232 communication only).
Regards,
Cristian
See if hardware's connected
Hi Guys
I have written an aplication that reads data from datalogger. Everything is working fine, but the customer wants to see if you click on the download button and the harware is disconnected a message that shows you that. I am testing it with a usb serial converter. I have write and read timeout set. On a normal comport it works but not virtual. If you click on the download button when the hardware is disconnected nothing happens. The application write the data to the virtual comport but noting happens, no exception or error, it just sits thre.
How can I test if the hardware is connected to the specific virtual port and switched on?
Thanks
Wilco
RE: See if hardware's connected
Hi Wilco,
I am not a professional programmer, but in case the driver fails in using the write and read timeout properties of the class, I would suggest to implement a timer approach (C# can access windows timers with 1ms resolution). I am afraid, however, that this approach would lengthen download time when the device is connected, so you might want to get a more "software oriented" advice.
Regards,
Cristian
help help
hej guys
can any body guide me how should i communicate with the com23 in visual studio????
actually i am doing something in hyper terminal with AT command... for gsm modem.... now i want to make a webpage in c# but can c# will communicate with the hyperterminal or with the com23 .......
any suggestion any idea please guidee meeee :)))))
thanks....
Draw shapes
Hi..
I have problem on sending data using serial port. in this case the data is an image type. My task is to transfer or send the image from sketching an object using the serial port. the idea of the image is similar to "draw scribble" that can be found in the internet.
I hope you can help me on this..
Thanks.
Regards,
Agnes
RE: Draw shapes
Hi Agnes,
I would suggest that you take the following approach. Read the image in some kind of a structure in C#. I have only used bitmaps before, and I would hope you do the same as the format is quite easy to read and interpret. Once ou do that, you can easily send the hole image, byte by byte, with the method described in the article. I do not know if this is the most efficient method, but it surely would work.
Regards,
Cristian
Re: Draw Shapes
Dear Christian,
Thanks for the advice. Hoewever, Im kinda confused here using bitmap. Actually, I have to draw the shapes out using mouse and from there I need to send it using serial port. The problem is how can I possibly save the drawing in bitmap?
Sorry to trouble you.
Thanks again.
Regards,
Agnes
RE: Re: Draw Shapes
Hi Agnezz,
Sorry for the late reply.
My suggestion, is as follows. You may draw the shapes in Paint, under Windows XP. Paint can save in BMP format and you may save your shapes as a known file (for instance "shapes.bmp").
After that you may read that BMP file using a C# program, extract the useful bytes from it, and then flush these bytes via serial port, as indicated in the article. For ease of use, I would suggest to use monochrome bitmap only, because it has the simplest format and you can easily interpret the file in C#, if you are familiar with this programming language.
Regards,
Cristian
test
this is a test comment
Half duplex communication using c#
Hi,
I want to implement half duplex communication protocol using C#.
Where do i find relative information
RE: Half duplex communication using c#
I am not really sure what you mean... the communication is half duplex by default, although the PC and the C# are capable of reading/writing bytes simultaneously.
If you are referring to serial protocols with hardware or software shaking then I would only suggest that you google for it in order to find out how exactly to assert/deassert the signals. Fortunately the class described in the article allows for asserting/deasserting the CTS/RTS signals.
Regards,
Cristian
Write in Hex
Hey all,
I am trying to write to a serial port but am wondering how I am to do this without using a string. Ideally, I would like to be able to send hex as the device that is connected to the port is not set up to read ASCII characters.
Any advice would be appreciated. Thanks.
RE: Write in Hex
Hi Kimmee,
You can easily write hex data. Try replacing the function for button1 in the above example with:
void Button1Click(object sender, EventArgs e) { byte [] byte_array=new byte[1]; serialPort1.PortName="COM1"; serialPort1.BaudRate=9600; serialPort1.DataBits=8; serialPort1.Parity=Parity.None; serialPort1.StopBits= StopBits.One; serialPort1.Open(); //define data to be written to serial port byte_array[0]=0x55; //write data to serial port serialPort1.Write(byte_array,0,1); //close the port serialPort1.Close(); }Basically, what this does is to define an array of bytes, with just one element. You then define that element to be 0x55 (hence, hex data), and then you instruct your application to send 1 element of byte_array, starting with element with index 0 (this is what serialPort1.Write(byte_array,0,1); does)
Regards,
Cristian
Inquiry
Hi Christian,
I am currently designing a GUI for a motor controller. The design comes from the idea that a 8051 class microcontroller is able to control the motor using PWM TECHNIQUE. I also adapt the modern idea that a control system best suit to modern application if it is in computer based. I designed the GUI using Visual C# with some hints coming from your article and finally is able to control the motor. But the problem is the GUI is not able to receive any data coming from the microcontroller. The microcontroller is able to send and I checked it using hyperterminal. I followed all the comments and all your replies in this article. You've mentioned that you have the idea on how to receive the data but you never publish it because of some technical and theoretical reasons. Can you please help me regarding this issue??? If you want, you can send me the code together the additional comments based on your own understanding. And I will further review the code if it is functional and send it back to you. Thanks for your time...
Erwynn Alcain Cepada
Electrical Engineering Student
MSU-SEES
RE: Inquiry
Hi Erwynn,
Have a look at the code below, I will try to explain what it does:
void Button1Click(object sender, EventArgs e) { byte[] read_buffer=new byte[3]; //configuring the serial port serialPort1.PortName="COM1"; serialPort1.BaudRate=9600; serialPort1.DataBits=8; serialPort1.Parity=Parity.None; serialPort1.StopBits= StopBits.One; //opening the serial port serialPort1.Open(); //write data to serial port serialPort1.Write("ABC"); serialPort1.Read(read_buffer,0,3); //close the port serialPort1.Close(); }After sending the "ABC" string to the serial port, this code will listen to the serial port and will write 3 incoming bytes to the read_buffer byte array. The catch with this code is that in case no data will arrive at the serial port from your microcontroller, the C# application will hang and you will have to kill it as a process. In addition, the same behavior will be noticed if your micro sends 2 bytes only, and you instruct your application to wait for 3 incoming bytes. Basically, the application will wait forever until the expected number of bytes will arrive. To be honest, this could be good enough for a school project where you will always know the number of bytes the micro will send back to the PC, so I wish you good luck.
Regards,
Cristian
C# serial comms
Hi,this question is probably far beneath everyone but I am stuck so I need to ask.
I have created the above example and everything works great.My question is how do you send just 1 or 2 bytes at a time to the serial port?
I am very new to this. My motor controller excepts 2 or 4 bytes of data to set the direction and speed.If I use the Polulu serial transmitter it sends the data correctly when I use this code it sends it as ASCii characters . Very confused but I have to start somwhere.
Any help would be appreciated Thanks
Jim
RE: C# serial comms
Hi Jim,
You can easily write hex data. Try replacing the function for button1 in the above example with:
void Button1Click(object sender, EventArgs e) { byte [] byte_array=new byte[1]; serialPort1.PortName="COM1"; serialPort1.BaudRate=9600; serialPort1.DataBits=8; serialPort1.Parity=Parity.None; serialPort1.StopBits= StopBits.One; serialPort1.Open(); //define data to be written to serial port byte_array[0]=0x55; //write data to serial port serialPort1.Write(byte_array,0,1); //close the port serialPort1.Close(); }Basically, what this does is to define an array of bytes, with just one element. You then define that element to be 0x55 (hence, hex data), and then you instruct your application to send 1 element of byte_array, starting with element with index 0 (this is what serialPort1.Write(byte_array,0,1); does)
Regards,
Cristian
C# serial comms
Thanks Cristian New it had to be a simple fix. Alot different than a plain ol serout command in basic or pbasic.But it is time to expand the robot brain and the only way to do that is learn a more powerful program language.
Works Great!!
Jim
How to receive data continuously
I really liked all the effort of you people in bring forward this valuable knowledge. My q is how to receive data continuously. how should i apply loop in this case.
RE: How to receive data continuously
Hi ghazanfar,
I would say that in case you know the number of bytes that periodically arrive, you can simply do a "while loop", in which you do the read as described in the article.
In case you do not, I would suggest that you use the BytesToRead property of the SerialPosrt class. This will always return you the number of bytes available in the input buffer. If in your case it returns a 0, then you do not have to do anything. In case it returns something different than 0, then you do know how many bytes you can read from the port, and you can consequently use the Read property of the class, as described in the article.
Regards,
Cristian
SerialPort Interface
I'd like to control a microcontroller to drive a dc morot using GUI C#, and i want to send binary data e.g(00001001) to microcontroller. Can you please tell me how to do this.
Hi Ali, I would like to
Hi Ali,
I would like to point you to an earlier comment on this article, which you may find above:
http://dev.emcelettronica.com/serial-port-communication-c#comment-2437
It describes how you can actually send hexadecimal data to the serial port. You can send your binary data coded in hexadecimal which is fairly easy using the method showed above.
Good luck, and keep us posted with your progress!
Regards,
Cristian
serial port communication
Hi,
can somebody help me out:
I am developing a project to communicate relay contact conditions to my pc using c#.when the contact is closed a variable value in my code should turn "true" and when the contact is openned the variable value should turn "False".
How do i do this using serial ports.
RE: serial port communication
Hi Larbi,
Sorry to get back so late to you with an answer. Fortunately you can do that without much additional hardware excpet for the relay. You should connect the output of the relay to one of the input lines of the serial port (CTS or DSR). The class described in the article provides also the possibility of reading the status of these lines, and returns the answer either as 0 or 1, or as true or false (don't exactly remember, though. t should be easy to map this value to a variable of your choice.
I would recommend you use a pull-down to GND to maks sure the CTS line is seen as a logic "low" when the relay is not active, and you can have the relay pull this line to some 5V.
Hex dump a satnav
Hi,
I am trying to write a piece of C# code to connect to a satnav via USB and take a hex dump of all the information on it.
However I am at a loss of how to access a usb device using c# coding as this is something i have never done.
If you could point me in the right direction, I would apreciate it :)
Thanks,
Ben
plz help me
hi I need power supply without traditional power transformer
serial port communication thr COM port
hai,
I have to communicate with the serial port COM1 in C#.im new to this so i want to know about.... how to communicate ?... i got some codes from above comments but that is not workin for me i have no device to connect but i have shorted the RXD and TXD pins in COM port by using a wire now i have to send data and recieve data in the hyper terminal ,so plz any one help me for this problem as soon as possible....
i think cristin has an idea about this can u plz plz help me out....or anyone
ill b more thankfull to u
by
krupagna
serial port communication thr COM port
kuprugna, Are you trying to read and write data on the same port COM1 with two programs (the one in C# and the hyperterminal) at the same time? I would not do that, I rather would use another one of the serial ports to have one port per program. Then, I would connect both ports with a "null modem", which is made of pure wires, crossed. Take into account the protocol you are using, X-on X-off, or the flow control signals RTS-CTS and DSR. Take into account if your ports have buffers. Remember, you first set both port parameters in agreement with each other, then you write and read bytes. Good luck.
reading data thr serail port
hai,
i have to communicate with serial port COM1 in C# and send data and recieve data in hyper terminal ,i have no device to connect to it so i have shorted the RXD and TXD pins in COM1 port .I tried the above code but it is not working for me ...so plz can anyone help me as soon as possible....i'll be very thankfull to you
I think cristine nos the solution for this so plz help me ....or anyone
But plz help me out as soon as possible
by,
krupagna
plz help me
hai,
i have to communicate with serial port COM1 in C# and send data and recieve data in hyper terminal ,i have no device to connect to it so i have shorted the RXD and TXD pins in COM1 port .I tried the above code but it is not working for me ...so plz can anyone help me as soon as possible....i'll be very thankfull to you
I think cristine nos the solution for this so plz help me ....or anyone
But plz help me out as soon as possible
by,
krupagna
loopback
krupagna, you should first be sure your loopback connection is the right one for the control signals you are using, X-on X-off, or CTS-DSR. You will find easily at internet how to connect a proper loopback.
Then, recall you first load the port parameters for the port work as you wish, I mean speed, parities, etc. ¿ Have you set a buffer size for the port? Ok. Once the port parameters are set, send your data. And test you can control the output with a LED.
For the input on the hyperterminal, it is not clear if Windows OS will allow to programs acceding to the same port at the same time, the OS could lock the port for use with one program only, I really do not know what it will do. However, to avoid this possibility, dont you have another port, like COM2, for the hyperterminal program? If so, connect both ports with "null modem", which is only made of wire crossings. Good luck.
Sending and Receiving data from Serial Port
Hello All,
I need support for send CAN(Control Area Network) Messages using RS232 to the CAN(Control Area Network) controller.
Also i am new in the programming environment i have little experience in programming.
Please also tell me how can i add buttons and input windows to make a GUI?
Best Regards
-OBAID
hep meeeeeeeee
i wanna write a program by C# t send file (txt files) to micro and i wanna send them without changing to ASCII codes , it means i want ti send INT and see it in Micro in INT form not AScII codes , ho can i do that?????
Receiving data from Serial Port
hello everyone,
can any one help to write c sharp code to receive data from serial port .
any example codes please..
Thank you.
Help needed to read and write to Maxim DS2431 chip
Hi,
I'm struggling to find a way to read and write to the Maxim DS2431 chip.
There are various ready made online solutions, but they cost a fortune.
Can anyone help please.
Eddie