📬❄️📦Adafruit Holiday Shipping Deadlines 2019: Please place all UPS 3 Day orders by 11am ET Friday December 13 📬❄️📦
0

C# serial port question
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

C# serial port question

by MattieShoes on Mon Nov 17, 2008 12:43 am

So I've never tried to access a serial port in a program before today, so I gave it a shot. To my shock, it worked perfectly, the first time!
Something along the lines of:
Code: Select all | TOGGLE FULL SIZE
using System.IO.Ports;

void initialize()
{
  SerialPort sp = new SerialPort("COM4");
  sp.Open();
}
void poll()
{
  string data = sp.ReadExisting();
  //do magic things here
}


I made a simple windows forms application and used NPlot to graph values in realtime, and it all works. :-)

But now I'm wondering if there's things I SHOULD be doing when dealing with a serial port. Sort of a best practices thing. Obviously I shouldn't hard-code "COM4" and I should make sure I was able to open the port, but... other than that? I just feel like things will break in the future and people will say "What the hell were you doing? I don't even understand why this worked at all!"
MattieShoes
 
Posts: 8
Joined: Sat Nov 15, 2008 10:59 pm

Re: C# serial port question

by adafruit on Mon Nov 17, 2008 2:02 pm

dont forget to close it :)

adafruit
 
Posts: 12151
Joined: Thu Apr 06, 2006 4:21 pm
Location: nyc

Re: C# serial port question

by eil on Mon Nov 17, 2008 11:34 pm

Nope, the bare minimum that you really need to do is open the port, send/receive some data, and close it again. There are more pins on a serial port that you can manipulate (carrier detect, other stuff) but they were mostly used back when RS-232 was the "Ethernet" of the day.
eil
 
Posts: 440
Joined: Sun Aug 31, 2008 11:09 pm

Re: C# serial port question

by MattieShoes on Tue Nov 18, 2008 12:39 am

Haha, you know, my code doesn't currently close the serial port! That's exactly the sort of thing I'd run into two weeks from now and spend hours trying to figure out what went wrong. :-)
MattieShoes
 
Posts: 8
Joined: Sat Nov 15, 2008 10:59 pm

Please be positive and constructive with your questions and comments.