They're here! The much requested photos from our Texas Wedding & Maui Honeymoon. Just click the links to see the full online photo album. Here are two sneak preview pics.
 (Medium).JPG) |
| Just married! |
 (Small).JPG) |
| Enjoing Maui to the fullest! |
I'm giving this MSN Spaces thing a try since it was quick and easy to create the online photo album. When I get my new website up and running, I'll be able to add a lot more photos.
Previous wedding related blog posts:
Getting Married Today!, Countdown to My Wedding, 14 Days to I Do & Engaged to an Angel
For the last several years, I've dreamt of having a real leather couch! My living room at my Redmond (Seattle) apartment has been completely bare since I moved in (a year ago) with the occasional influx of moving boxes (from when I moved in then Dawn moved up). Occasionally I'd just sit on the floor in the middle of the completely bare living room dreaming of the day I'd be able to come home to a comfy couch, have guests over, and making it feel like a real home.
Now that I'm married (to the wonderful Dawn Coad) I'm out of the college / bachelor scene (Ikea like furniture) and have entered the realm of 'real' furniture.
Dawn and my first big purchase as a married couple, one month after getting married, was a couch, love seat, chair, ottoman, coffee table, and end table from Mor Furniture.
We've waited a long six weeks for delivery and as of last night, it all arrived! It is very exciting! What am I doing this weekend? Hanging out in my living room! 
.JPG) |
Before - Just an empty living room for the last year. Imagine me just sitting here on the floor Indian style, yup, sad. |
.JPG) |
After - A whole new experience! Now it actually looks like a home, a place to hang and invite friends over. |
For those of you that blog, have you noticed how much easier and faster it is to get a blog post out when you're excited about a new thing? That's what this is, I'm excited, here working at Microsoft on a Friday wishing I was hanging out on my couches, so what do I do? Blog about them! 
Introduction Here is my base collection of resources on C#. I'm putting this together so when I write articles or reply to e-mails, I have one central place to point people. This is a live post, which means I'll be updating it as needed. Feel free to make your own additions (in the feedback)!
Get C# - Visual Studio 2005 C# Express
Currently free for the first year (till 11/06), then it will be $50. While not quite free (in the long term), it is a very moderate and reasonable price for the power you get. - Visual Web Developer 2005 Express
If your primary target is the web (with C# or any other .NET language), use this SKU. You can install both this and C# Express side-by-side. C# Express is geared toward Windows Application and this is for web sites, both support C#. - Visual Studio 2005
Again, currently free while in beta, and will be about $800/$560 when released. - MSDN Subscription
Various levels of access to all of Microsoft's operating systems and development tools for a year. MSDN Premium costs $1100 to $3200 per year and includes one of the Visual Studio 2005 Team System editions.
Learning C# So you're starting out and would like my secret to success in C#? You've come to the right place! With you're passion, this is a sure-fire way to success in .NET:
- Get C#
You can start with the free C# Express (for Windows Applications) or Web Dev Express (for Web Sites, Web Services, etc). Both contain the C# language. These contain great resources when you start them up on learning the language. Go through the tutorials and resources they present on the start screen. - Study Books
Particularly the first two or three I list below. Dig into these. Everyone I know who has grasped this content has done well. They teach solid fundamentals, as well as practical application, from which all else stems. - Subscribe to Blogs
Start reading on a daily basis the blogs I list below and find others that tickle your fancy. Using an aggregate reader like RSS Bandit is practically a must. Consider starting your own blog where you can post tidbits you learn. Doesn't matter how newbie you may be, others will learn from you. Some of the simplest blog posts are the most useful. - Use Forums
Browse through issues other devs are encountering, ask you own questions, and look for questions that you may be able to answer. The more you do so, the better you'll be able to articulate what you're doing, understand it yourself, and learn to help other. This is how I obtained my MVP award. - Play Around
The #1 way to really learn is to get in there and do it. Try creating your own projects. Think of cool little things to make and just do it on your own time, a photo slide show, an MP3 tag editor, a way to track friend's birthdays, your own contact's list, a personal website, a database of scrapbooking supplies. Come up with an easy idea, make it, then make it better. A passion of getting in and doing it is the #1 anyone learns (myself included).
Armed with a passion to learn, just by following these 5 steps, you too will quickly become a C# developer.
Online Centers Sample Code & Tools - Shared Source CLI
This is the entire ECMA standard Common Language Infrastructure in C# source code. These are all the Base Class Libraries (BCL) that make up .NET in plain code. See how System, string, XmlDocument, etc is implemented. Extremely valuable educational resource! - C# Team Downloads
Many .NET code samples, tools, powertoys, etc from the C# team. - .NET Downloads
SDKs, Tools, Utilities, Sample Code all on .NET from MS
Books & Periodicals BlogsSubscribe to these blogs using
RSS Bandit (
download) (
open source in C#).
Forums, Newsgroups, and UsergroupsThese are some of the best places to go for help.
- C# Forums
Microsoft's official support outlet for C# developers. These forums will eventually replace the newsgroups all together. - C# Newsgroup
This is the old C# support newsgroup that will be replaced by the C# forum (above). - .NET Usersgroups
Find a local .NET support group in your area. They tyically consist of like minded developers, presentations, meetings, prizes, special events, and are a great way to meet other .NET developers face to face. - GotDotNet
A community run .NET site sponsored by Microsoft.
Support, Getting Help #1 place to go, the C# Forums.
Domain Specific ResourcesComing when I have the time to add them.
- Team System
- ASP.NET
- General Web Development
- ADO.NET
- XML
- SQL
- Windows Forms
- Serial & USB Communications
In just three hours I'll be waiting for my beautiful blushing bride at the alter!!
I'm in the hotel with my Best Man with half a tux on getting ready to head over to the church. Friends and family are pouring in from around Texas and even the nation for this special occasion. I can hardly wait!
At 3am my Best Man and I dropped off a "Happy 0th Anniversary" card and long stem rose in front of Dawn's parent's house for her to find this morning. That's it, I'm trademarking the "0th Anniversary" theme, very appropriate since the start of arrays is usually a 0 index (defiantly in C#), and this is the start of our new life together.
Other "Getting Married" Posts:
Countdown to My Wedding, 14 Days to I Do & Engaged to an Angel
My wedding is rapidly approaching! Here is how much time is left until my wedding on Saturday April 30th 2005 @ 1:30 PM CST. If it is after that date, the time is counting how long I've been married. 
Here are two other posts about my upcoming wedding.
14 Days to I Do & Engaged to an Angel
Note: RSS Bandit, other RSS feed viewers, and some browsers will not display the timer. Please view this blog post in IE for best results.
MSDN has moved to using cool new web forums to replace the old Whidbey newsgroups. The new forums have tons of features! There are RSS feeds, alerts, a nice UI, easier moderation, and much more.
One good feature is that we on the product team recieve daily e-mails of unanswered questions. This means a quick response to your posts.
Please give them a try. What do you think?
Whidbey Beta2 is Released! We all (you & MS) have been waiting long for this build! Wow, it is a substantial improvement over Beta1 and the client bits even have a Go Live License. I'm excited! How about you? 
If you have a MSDN Subscription, you can Get the Beta for the cost of S/H or download Visual Studio 2005 - Team System (aka VSTS). There is a Go-Live License which permits "production deployments of customer applications".
For the free (for now)
Express SKUs:
C#,
VB,
VC++,
J#,
Web Dev,
SQL Srv
In just two weeks from today, I'll be waiting at the alter for my fiance to walk down the isle to receive her hand in marriage. I'm very excited!
Dawn is aggresively packing up her appartment in Bryan, TX to be moved out by next week. Next week is also her last week teaching orchestra for two middle schools in Bryan ISD. We are both working fast & furious on finishing up wedding details.
The wedding is Saturday, April 30th in Houston, Texas @ Lakewood United Methodist Church, our reception is being hosted at Raveneaux Country Club, and we are headed to Maui, Hawaii for our honeymoon. We both have large families so it is going to be a big event!
We have a Wedding Site and here is my post about getting Engaged to an Angel.
 (2).jpg) |
| Our 'official' engagement photo (from a scanned proof). |
.jpg) |
| Dawn recieves her engagement ring at Chritopher's World Grill (August 2004). |
These are some of my core reference links that I consistently refer back to while working on the web (mostly from MSDN). I also use them with many other projects, but most frequently with web/html/scripting/xml apps. The main links have been listed on my IE Links toolbar for awhile and now I can replace them all with a single link here. 
I'll be updating this as I come across more. If you have any recommendations of reference links you use frequently, please leave a comment and I'll add them.
Main References
CSS, Color, DHTML, HTA, Regex, JScript, WSH, Filters, Script Runtime, SQL
eXtensible Markup Language
XML, XSLT, XPath, DOM, Node, DHTML, XmlNode, XNode
Secondary Links
.NET has a great class called SerialPort (MSDN reference) part of .NET 2.0 and is freely available in C# Express on MSDN. It is easy to use. Here’s how…
BTW, this article is about communicating through the PC's Serial COM RS-232 port using Microsoft .NET 2.0 or later by using the System.IO.Ports.SerialPort class. If you're looking for USB info, see here.
Example Application & Sample Code: SerialPort Terminal
Prerequisites: You will need Microsoft .NET 3.5 to run the app. It is installed as part of the regular Windows Updates (make sure your computer is fully up to date, see Microsoft Updates for more info) or if that doesn’t work for some reason, you can install .NET 3.5 from here.
To start off, here is sample code in a terminal application which you can try out to see how the SerialPort class is used. This requires Visual Studio 2010 to compile, which can be obtained free via C# Express. It is just a simple little application with basic support for text or binary (hex) modes to send and receive data. A nice feature or two is auto-detection of installed COM ports that update at runtime if you plugin or remove USB-to-Serial adapters, also you can change the DTR and RTS levels and monitor the CTS, DSR, and CD lines.
Build Note: You will receive an error that Visual Studio isn't able to find NoahCode.pfx. This is expected as it is the click-once certificate for publishing and is NOT NEEDED for normal code use. Just go to Project Properties > Signing > Click on Create Test Certificate. that’s it

Get Connected
You can obtain USB to Serial adapters and have just about as many ports on your PC as you like. I carry around two adapters with a null modem (wikipedia) between them so I can create a loopback to send & receive through to separate ports on most any computer. I'd recommend doing the same for when writing code for the serial port.
If you'd like to quickly and easily create your own external devices to communicate with the PC, I recommend starting with the Arduino, NetDuino (like an Arduino but programmed in C#), or Parallax BASIC Stamp modules. All three have many accessories and sensors available (such as LCDs, RF, Sounds, AD & DA, etc). sparkfun.com is a great place to look. After that you could migrate to an Atmel Microcontroller (recommended) or Microchip PIC.
Write Data Out
Here is an example of how easy it is to use the new SerialPort control. Very simply, here is how you can send a bit of data out the port.
// This is a new namespace in .NET 2.0 // that contains the SerialPort class
using System.IO.Ports;
private static void SendSampleData()
{
// Instantiate the communications // port with some basic settings
SerialPort port = new SerialPort( "COM1", 9600, Parity.None, 8, StopBits.One);
// Open the port for communications
port.Open();
// Write a string
port.Write("Hello World");
// Write a set of bytes
port.Write(new byte[] {0x0A, 0xE2, 0xFF}, 0, 3);
// Close the port
port.Close();
}
|
Read Data From Port
Now let's take a look at what it takes to read data in from the communications port. This demonstrates reading text.
- Create a new "Console Application" and replace all the default class code with this code
- Add a reference to "System.Windows.Forms" to the project
- Run w/ F5, to exit the app, press Ctrl-Break.
- Get Connected with two USB to Serial adapters and a null modem
- Use another app, the code above, or the SerialPortTerminal.zip example to send data and watch it come in with this code
#region Namespace Inclusions
using System;
using System.IO.Ports;
using System.Windows.Forms;
#endregion
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// 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();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
|
Listing Available Ports
One of the (several) new methods that is supported, and one I'm very glad is finally here, is the ability to obtain a list of the COM ports installed on the computer (ex: COM1, COM2, COM4). This is definately helpful when you want to present the list of ports avalible for the user to select from (as in the SerialPortTerminal.zip Win App example).
foreach (string s in SerialPort.GetPortNames())
Console.WriteLine(s);
|
Sending Files
Here are two helpful little methods for sending files through the serial port. Of course, these are the bare essentials and as always, you should check to make sure the port is open first (port.IsOpen) and use try/catch around trying to open a file, but you get the gist with this code. The binary sending routine is limited to about 2GB (the size of an int), but this should be okay for most uses. 
using System.IO;
private static void SendTextFile( SerialPort port, string FileName)
{ port.Write(File.OpenText(FileName).ReadToEnd()); }
private static void SendBinaryFile( SerialPort port, string FileName)
{
using (FileStream fs = File.OpenRead(FileName))
port.Write((new BinaryReader(fs)).ReadBytes( (int)fs.Length), 0, (int)fs.Length);
}
|
RS-232 Project Photos
Each of these involve RS-232 serial port communications.
|
Just what's needed to get started with microcontrollers,
a Basic Stamp, mini LCD display, power, and RS-232 port. |
|
Two USB to Serial adapters with a null modem
to loopback and test your serial software. |
|
The brains to a mini automated radio station that let me
control my PC & home using my HAM radio from around town. |
Port Wiring Notes
DB9 Male (Pin Side) DB9 Female (Pin Side)
DB9 Female (Solder Side) DB9 Male (Solder Side)
------------- -------------
\ 1 2 3 4 5 / \ 5 4 3 2 1 /
\ 6 7 8 9 / \ 9 8 7 6 /
--------- ---------
DB9 Female to DB9 Female Null-Modem Wiring
2 | 3 | 7 | 8 | 6&1| 5 | 4
---- ---- ---- ---- ---- ---- ----
3 | 2 | 8 | 7 | 4 | 5 | 6&1
9-pin 25-pin Assignment From PC
------ ------ ------------------------- ------------
Shield 1 Case Ground Gnd
1 8 DCD (Data Carrier Detect) Input
2 3 RX (Receive Data) Input
3 2 TX (Transmit Data) Output
4 20 DTR (Data Terminal Ready) Output
5 7 GND (Signal Ground) Gnd
6 6 DSR (Data Set Ready) Input
7 4 RTS (Request To Send) Output
8 5 CTS (Clear To Send) Input
9 22 RI (Ring Indicator) Input
- RTS & DTR are binary outputs that can be manually set and held
- DCD, DSR, CTS, and RI are binary inputs that can be read
- RX & TX can not be set manually and are controlled by the UART
- maximum voltages are between -15 volts and +15 volts
- binary outputs are between +5 to +15 volts and -5 to -15 volts
- binary inputs are between +3 to +15 volts and -3 to -15 volts
- input voltages between -3 to +3 are undefined while output voltages
between -5 and +5 are undefined
- positive voltages indicate ON or SPACE, negative voltages indicate
OFF or MARK
Protocol Development
If you are making your own serial interface/protocol, you really must have a good standard in place. Serial data flows into the com port byte by byte and must be buffered and parsed correctly. Think of it this way, if a terminal sent your computer "Hello World" it may come in as four OnComm triggers: "H", "ello", " Wo", and "rld"
The best protocols are usually a mix of these methods. Here are three simple protocol techniques:
- Beginning and Ending ("Start" & "Stop") Codes
This is good for sending text as it lets everybody know when text starts and ends. You simply tack on a non-normal byte at the beginning and end of the text. For example, you'd use '---' to signify the start of the string and '===' to signify the end. So you would use: com.Output = "---Hello World===";
- Fixed Length Codes
Used for specific commands. You can create your own codes to send and specify what they mean. Say I want to control the lighting in a house, I'd setup a protocol of commands like this:
1st byte = House Code, 2nd byte = Light Code, 3rd byte = On or Off (0 for off, 1 for on)
So to turn on the 11th light in my house (house code #3) I'd use:
com.Output = new byte[] {3, 11, 0};
- Prefixed Data Packet
This is probably the most common and flexible but requires the most coding. Just prefix your data packet with the length of the data. The prefix must be a fixed size, such as two bytes which would allow a data packet of up to 65,535 bytes. Then the receiver knows how much data is in the packet because it always takes the first two bytes and uses the rest as the data packet.
Example: com.Output = ((char) 00) + ((char) 11) + "Hello World";
Other Resources
Here are some additional sites, libraries, tutorials, etc. These are links that I just found around the net and am providing for convenience (they are not endorsed).
The Final Say
The new SerialPort class in .NET 2.0+ rocks! It is much easier to use than getting the old MSComm.ocx control going in a .NET app, contains new functionality, is a 'native' .NET control, has docs built into the MSDN Library, and is easy to use.
Frequently Asked Questions (FAQ)
I'm adding this section (as of 8/10/06) to address the common questions I get on this post and through e-mail. Chances are, if you ask a good question in the comments here, I'll post it here for others to see easily. Some of the most popular topics are usb, device, cable, lines, power, packets, bridge, permissions, help.
- Q: When updating a control (like a text box) while in the DataRecieved event, I get an error.
A: The SerialPort class raises events on a separate thread than the main form was create on. Windows Forms controls must be modified only on their original thread. Thankfully there is an easy way to do this. Each Windows control has a "Invoke" method which will run code on the control's original thread. So to put the recently received data into a text box (txtLog), this would do it: txtLog.Invoke(new EventHandler(delegate { txtLog.Text += comport.ReadExisting(); }); You can see this more in action in the "Log" event of "Terminal.cs" my sample code project, SerialPortTerminal.zip.
- Q: I can't find the System.IO.Ports namespace.
A: Using Visual Studio 2003? The new namespace, and SerialPort class, is part of .NET 2.0 and Visual Studio 2005. It is not included in .NET 1.x (and Visual Studio 2003). Even if you have .NET 2.0 or Visual Studio 2005 installed, you can not access the class from within Visual Studio 2003.
- Q: I only have .NET 1.1, what can I do?
A: Upgrade to .NET 2.0. Seriously, it's free. In fact, you can get the great C# and VB Visual Studio Interactive Development Environment (IDE) editors for FREE now with C# Express and VB Express. The .NET Framework Software Development Kit (SDK) for command-line development is also free. If you really must stay in .NET 1.1, you can use a 3rd party library.
- Q: I'm sending data to my device, but it is not responding.
A: First make sure the device will respond using a standard app like Hyperterminal. Check the settings (baud rate, data bits, stop bits, etc) and make sure they match with your code. Try sending binary data via binary arrays. Many devices expect a carriage return at the end of a command, so be sure to send 0x0D or \n. String data can be easily converted to a binary array using:
byte[] data = System.Text.ASCIIEncoding.Default.GetBytes("Hello World\n");
com.Write(data, 0, data.Length);
Many devices require several carriage returns first to sync baud rates, so send several, like: com.Output("".PadLeft(9, '\n')); It you're communicating with a modem, make sure Echo Back is turned on. Send "ATE1\n". Other than this, just keep trying and playing around with it. It can be hard because you don't see the response from the device as easily as you would with a terminal app.
- Q: When I put received data to a text box or rich text box, I get a strange symbols.
A: The default font of text boxes is designed only to show standard characters. Try using "CharMap" (a free tool in WinXP, click "Start", "Run", type "CharMap", enter). "Terminal" is a font designed to show classic ASCII characters and is what most terminal apps (like my sample code and Hyperterminal) use. There are also many ASCII codes that won't display correctly. This is why I choose to show the hex data instead of an ASCII string a lot of the time. System.Convert.ToString(mybyte, 16) will convert a byte to a string hex code, for example: byte b = 13; string s = Convert.ToStrong(b, 16).PadLeft(2, '0'), then s will contain "0D". See the "ByteArrayToHexString" and "HexStringToByteArray" methods in my sample app, SerialPortTerminal.zip.
- Q: What about USB communications? How can I do USB?
This blog post isn't about USB. Believe me, I wish the .NET framework supported USB natively, and I'm doing what I can here at Microsoft to see USB get into the framework in the future. For now, you can use a USB to Serial adapter. I use a lot of these. They plug into the USB port, then appear just as a SerialPort to the PC.
For native USB devices, microcontroller vendors such as Microchip, Atmel, and TI make chips that do this for projects as well as have chips that support USB natively (I'm using the PIC18F14K50). There is a lot of info and USB C# libraries readily available online with a quick search, try USB C#, which turns up resources like this great article or this USB HID C# open source project.
For simple USB-to-Serial bridges that allow your device to communicate via RS-232 but connect via USB to the PC, check out the section below on USB-to-Serial Bridge Chipsets
- Q: Can I use the sample code here in my own projects (commercial or not)?
Yes! All sample code on my blog is free public domain material. I'm not a legal guy so I don't know the exact words to use, but I'll try... I'm not responsible for any problems! Use at your own rick etc. However, have at it, if it helps you out, fantastic, that's what it's here for.
- Q: When using SerialPort.Open() (or SerialPort.PortOpen = true) I get the exception "UnauthorizedAccessException" or the error "An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in axinterop.mscommlib.dll"
It may be one of a few factors:
- It may require Administrative privileges to use the port.
- The port may already be open by another program, only one app can use a port at a time.
- The port may not exist on the computer (this happens a lot). Verify the port you're trying to open is listed in the Device Manager (FAQ #9).
- The name being provided is not exactly correct.
Use the full name of the port when opening, like "COM1" (not "1")
- Q: How do I know what COM ports are on my PC?
Use the Device Manager ("Start", "Run", "devmgmt.msc") and look for the "Ports" node (see below). If you don't see a Ports node, it's because there are no Serial or Parallel ports installed in the PC. You can also use System.IO.Ports.SerialPort.GetPortNames() to return the list of available ports. Many laptops these day's don't have a serial port. You can get more serial ports very easily today with USB to Serial adapters.
- Q: How do I communicate with my specific device? Modem, Mobile Phone, LED/LCD Display, Scanner, GPS, GSM/GPRS, CDMA, test equipment, etc
This post is specific to device independent serial port communications. RS-232 is a hardware standard and there are hundreds (if not thousands) of software protocols that are created for communicating over RS-232. An analogy would be that physical telephone hardware is used around the globe (like the RS-232 hardware standard), but there are hundreds of languages people can speak through the phone to each other to communicate (the software protocol). You will need to find information about the protocol used for your specific device elsewhere. I'd recommend looking on the manufacture's website, writing/calling the manufacture, or searching online for your specific device. Sometimes you can find fans or hackers of a device that congregate on a forum. Some protocols can be found through wikipedia, like the GPS NMEA 0183 serial protocol that GPS units use to send their data via a serial connection. Honestly the RS-232 communications is the easy part, I personally find the more interesting challenge is writing software for the particular protocol in use. Best of luck in finding specifications on the protocol you’re device uses!
- Q: What control lines can I manually manipulate?
Control lines on an RS-232 serial port were introduced to provide flow control of serial data. Even though a modem or PC may be rated for a particular baud rate, it doesn’t always mean that the device can process the data that fast. For example, bits may flow in through a modem at 2400 bps (bits per second) but in the early days a PC couldn’t process the data fast enough, so it would toggle control lines to tell the modem that it was read for more data or to ‘pause’ send it data. Now since PCs are quite fast these lines are mostly ignored. They can be used as a simple way to toggle an LED or send or receive high or low states. RTS/CTS control flow is one such technique which is supported natively by the control via the Handshake property.
Lines marked ‘Output’ in the table can be set by the serial port to a high or low state (True or False) and the ‘Input’ lines can be read as high or low. You can use the PinChanged event to be notified when one of the input pins changes. The Handshake property can be set to use RTS/CTS (uses hardware control lines) or XON/XOFF (uses software) or both.
| Control Line |
Name |
DB9 Pin |
SerialPort Property |
I/O |
| DTR |
Data Terminal Ready |
4 |
DtrEnable |
Output |
| RTS |
Request to Send |
7 |
RtsEnable |
Output |
| CTS |
Clear to Send |
8 |
CtsHolding |
Input |
| DSR |
Data Set Ready |
6 |
DsrHolding |
Input |
| CD (or DCD) |
Data Carrier Detect |
1 |
CDHolding |
Input |
For detecting a Ring Indication, see the next question.
- Q: How do you detect the Ring Indicator line?
There isn’t a property off of the SerialPort class to test the current state of the Ring Indicator (DB9 pin 9), but there is an event that gets triggered, PinChanged. You can attach an event listener to PinChanged and when the event is called, SerialPinChangedEventArgs is passed with a EventType property of type SerialPinChange which will indicate if a ring indication was detected. Here is an example:
comport.PinChanged += new SerialPinChangedEventHandler(comport_PinChanged);
void comport_PinChanged(object sender, SerialPinChangedEventArgs e)
{
if (e.EventType == SerialPinChange.Ring) RingDetected();
}
- Q: What pins can I use for powering devices, a high signal, or for boolean input & output?
The TX & RX pins carry the standard serial signal, but the other pins can be used as high/low input/output pins. The output pins (4 DTR or 8 CTS), supply 5 to 15 volts (15v is proper RS-232 standard, 5v is what you’ll usually get) when high and low is 0 to -15 volts. They only supply flea current (very little current) so they're not meant to be used for powering any devices (like USB is designed for). However, they can be used as a reference voltage or for switching to one of the input pins for a high or low signal. The input pins (1 DCD, 6 DSR, 8 CTS, and 9 RI) can be used to detect a high or low signal. Proper RS-232 signal levels are -15v for a low and +15v for a high (compared to ground, pin 5). A MAX232 or similar chip takes a TTL 0-5v input and produces the -15v to +15v levels. However, most PC RS-232 COM ports will accept a 0v for low and 5v for high, but it is not guaranteed and alters from PC to PC. If you want a simple "toggle high", just hold pin 4 DTR high, and switch it to pin 1 DCD. The .NET SerialPort class has easy to use properties for switching the output pins high or low and for detecting the current level of the input pins. I have been able to use pin 4 DTR for a very low current (20ma max) PIC processors, but not reliably. I prefer to always supply external power and use pin 4 as a signal to turn on or off my device. I'll attach pin 4 to a transistor that switches my power source to my PIC to turn it on or off.
- Q: What about ‘packets’? Does RS-232 support any commands or data segregation? OR Data comes in at seemingly random times?
Serial data flow through RS-232 has nothing to do with ‘packets’. It’s just a stream of bytes in and out. There is no guarantee that data arrives together.
Packet Protocols
Any notion of data compartmentalization (packets) would have to be coded by you for your unique use. Much of my time working with serial has been spent on defining useful packet like protocols, that usually include some type of header, command structure, and CRC check. For example, the first two bytes are the packet length, the next two bytes is the command, next two bytes are parameters, and the last byte is a CRC. Then my apps would buffer incoming data and look in the buffer for valid packets. Of course it differs depending on the device you’re working with and your specific needs. USB does have specific communications protocol defined, one of them being command based, like the little packet just mentioned. But with USB, you’re able to get the whole command and parameter together at once, with serial you have to create the protocol yourself, buffer, and parse the data.
Buffering Incoming Data
Since bytes may come in at any time, buffering incoming data is critical. For example, you may send a command out to your device, and the response back to the PC could trigger a single DataReceived event with all the 30 bytes of response data in the receive buffer. Or more likely, it could be any number of separate triggers of the DataReceived (up to the number of bytes received), like 4 triggers, first with 2 bytes, then 15 bytes, then 1 byte, then 12 bytes. Don’t look for a complete response in a single DataReceived call, instead:
1. buffer the incoming data
2. then scan your buffer to find complete data
3. remove the used data from the buffer
To buffer incoming data, use a coding pattern like this:
(download the code SerialComBuffering.zip)
using System;
using System.IO.Ports;
using System.Collections.Generic;
namespace SerialComBuffering
{
class Program
{
SerialPort com = new SerialPort(SerialPort.GetPortNames()[0],
9600, Parity.None, 8, StopBits.One);
List<byte> bBuffer = new List<byte>();
string sBuffer = String.Empty;
static void Main(string[] args)
{ new Program(); }
Program()
{
com.DataReceived +=
new SerialDataReceivedEventHandler(com_DataReceived);
com.Open();
Console.WriteLine("Waiting for incoming data...");
Console.ReadKey();
}
void com_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Use either the binary OR the string technique (but not both)
// Buffer and process binary data
while (com.BytesToRead > 0)
bBuffer.Add((byte)com.ReadByte());
ProcessBuffer(bBuffer);
// Buffer string data
sBuffer += com.ReadExisting();
ProcessBuffer(sBuffer);
}
private void ProcessBuffer(string sBuffer)
{
// Look in the string for useful information
// then remove the useful data from the buffer
}
private void ProcessBuffer(List<byte> bBuffer)
{
// Look in the byte array for useful information
// then remove the useful data from the buffer
}
}
}
- Q: How do you detect when a device is connected or disconnected?
Simply put, the device usually starts or stops sending data. There are no built in events when a device connects or disconnects. But there are a few tricks you can do, if you’re creating the serial device yourself, then you have more options. I’ve had my devices (and PC apps) send a constant “are you there” set of bytes, like 00 00 11 11 00 00 hex (I’d use a ‘are you there’ custom ‘packet’ as in Q13 above) till a device on the other end responds. You could also use hardware, that’s what some of the other signals lines are for (CDC, DSR, RTS, CTS, RI), you can tie one of these high and then catch an event when the line goes high so you know there’s a device there, when it goes low the device is gone.
- Q: How do I transfer files?
If you’re interested in sending entire files between computers or to a device, you have two primary choices. First choice is to write your own protocol for breaking a file into manageable packets, detecting errors, sending/receiving, etc. Second choice is to use a protocol already created, like XModem, YModem, ZModem, etc. These protocols were created long ago specifically to send files over a serial connection with features like error correction, being able to resume transfers, compression, etc. I’m only aware of commercial implementations for .NET right now, like Sax Software’s CommStudio. If anyone find an open source implementation, please let me know!
- Q: Where can I get USB-to-Serial cables?
USB-to-Serial adapter cables allow you to get a standard RS-232 DB9 cable by plugging in the adapter to your USB port. You can use several of these to get multiple DB9 ports. Many laptops, even desktops, don’t have serial ports these days which makes these particularly handy.
Every so often I source a good cable for a decent price, typically around $12. Here is the deal I’m currently using. http://amzn.to/JnZ7ag
Be forewarned, not all cables are created equally! There are two issues to contend with…
- There are a number of companies that create USB chipsets that emulates an RS-232 port. Some are much more compatible with PCs and Macs than others. For example, the Prolific and FTDI chipset are used in the most compatible adapters (unlike Ark Micro, or others). Those companies produce WHQL (Windows Hardware Quality Labs) certified drivers and the drivers are built into most Windows and Mac systems already. So when shopping for a cable, be sure to check the chipset manufacture. Here are some handy links to drivers in case you need them.
- Prolific Chipset Drivers
- FTDI Chipset Drivers
- Standard RS-232 signals range from 3 to 15 volts (plus or minus), 0 is not a valid signal. The USB-to-Serial interface chips used in these cables produce 0 to 5 volts, standard TTL level logic. While this works for some PCs, and certainly most microcontrollers, it is not 100% compatible. The ‘correct’ USB-to-Serial cables incorporate an additional line level driver, like the MAX232, that take the 0 to 5 volts and convert it to an appropriate +/- 12 volts for RS-232. The problem is that many low-quality cables exist out there without this line level driver chip.
- Q: How can I best interface with my microcontroller? USB-to-Serial Bridge Chipsets
If you are building your own devices, usually with some type of microcontroller, and want to interface with the PC, you can certainly use RS-232 either plugged straight into your PC or via a USB-to-Serial adapter cable, but another option is to use an USB-to-Serial bridge chipset directly in your project (what is inside of the USB-to-Serial adapter cables). This allows your device to use RS-232 internally, but connect to a computer via USB and you as a project designer never need worry about the USB interface or drivers (your device and PC software just see serial RS-232). You could use a native USB microcontroller (without an RS-232 bridge), such as the PIC18F14K50, but that requires writing your own USB drivers and a much deeper understanding of the USB infrastructure (both in hardware and software). That particular PIC also comes with a Serial emulator and drivers like below. This article is focused on serial RS-232, so I’m covering the USB-to-Serial bridges here.
These modern ICs don’t require external crystals, can power your device from USB Power, provide clock sources for your micro if you like, and come with Windows Certified (WHQL) drivers that are actually included in Windows Vista and beyond (also built in Mac drivers). Here are a few…
- FTDI FT232RL
The FTDI chips are most popular in electronics projects and used by companies like Parallax and the Arduino Duemilanove. They also have the best support in terms of evaluation modules, well written datasheet, and product availability. product info, evaluation modules, buy from Mouser, drivers
- Prolific PL-2303HX
These are the chips used in the most popular USB-to-Serial cables. They are slightly less costly than the FTDI chips in bulk, but are not quite as well supported in the US market. product info
- TI TUSB3410
Another option from Texas Instruments. I haven’t used this chip. Product Info
p.s. For trying it out and prototyping, I personally recommend this particular FTDI evaluation board, the UM232R since it plugs into typical solderless protoytpe breadboards and has most of the pins easily accessible. Last priced it was $20 from Mouser.
- Q: How do I automatically detect the baud rate of a device?
The PC doesn’t have built-in automatic baud detection, but there is an easy trick to implement basic baud detection for many devices. If there is a known call & response to the device you can set the baud rate of the port to one setting, open the port, send the call, see if you get the expected response, and if not close the port, set a different baud rate, and repeat. For my own devices I’ve had some of them send a known character string (could be anything, like 000ABCD) after they receive a high on the DTR line. This way my serial code can set DTR high, see if it gets the ABCD at one baud rate and if not, close the port, set another baud rate, open the port, turn DTR high, and try again. If the baud rates match the characters will be read correctly, if not then the characters will be jumbled. This can be done with many other devices as well if there's a known call and response, like sending a modem an AT command with an expected response code.
- Q: May I have permissions to use your code?
Yes! The code and samples here are released under the MIT License.
- Q: How can I get more support? What are my support options?
When explaining to a friend of mine some of the fundamentals of mathematics, I found myself giving definitions of these base terms. A quick search with Google returned this great excerpt that efficiently and eloquently defines the words and relations, and merits posting here.
The words axiom and postulate are synonymous in mathematics. They are statements that are accepted as true in order to study the consequences that follow from them. Suppose that you were studying a deductive system called Jabbermetry and the words toves and mome appeared in the statement For every two toves P and Q there is a unique mome PQ that contains both P and Q. Given no other information, you would be unable to prove that this statement is true. In fact, this statement defines an important relationship between toves and momes; it is an axiom or postulate of Jabbermetry. Notice that if you are informed that Jabbermetry actually means Geometry, toves means points, and mome means line, the statement becomes more familiar: axiom 1: For every two points P and Q there is a unique line PQ that contains both P and Q. Do not be misled by your familiarity with points and lines, however. It remains that this statement cannot be proven since you are given no other information and is thus an axiom or postulate.
Three other terms that occur in the hierarchy of deductive reasoning are theorem, corollary, and hypothesis. A theorem is a statement that is a logical consequence of axioms and other theorems. A theorem, unlike an axiom or postulate, exists only if a proof can be given for the statement. For example, if you allow the additional axioms axiom 2: There exist three points not all in one line, and axiom 3: Two lines L and M are parallel if they do not intersect or if L = M, then you can show that the statement Two distinct lines intersect in at most one point is a consequence of axioms 13; the proven statement is a theorem. A corollary is a trivial theorem, that is, a theorem that so closely follows another axiom or theorem that it practically does not require a proof. For example, a corollary of axiom 3 above is If L is a line, then L is parallel to itself. The proof of this corollary is the definition of equals: L = L. Finally, a hypothesis is a statement that has not been proven but is expected to be capable of proof. For example, you may hypothesize If point B is between points A and C, then point C is not between points A and B. This is equivalent to a conjecture. If this statement does not follow from your present system of axioms, you may wish to include an additional axiom or make the hypothesis an axiom itself and see where it leads you. For the hypothesis given above, you may want to introduce an axiom that establishes a coordinate system.
Thus, axioms and postulates form the roots of a particular deductive system; theorems and corollaries are the logical consequences that fill out the deductive system; hypotheses drive theoretical development forward.
From: The American Heritage Book of English Usage
At one of the developer conferences (late 90s, early 2000s?), Steve Ballmer, CEO of Microsoft, came out on stage saying 'Developers' over 15 times before his voice went out. Being a developer myself, I think this is cool. At the Microsoft company meeting that followed, I remember talk among us employees whether he was going to come out on stage saying another word repeatedly (he didn't that time). Here they are...
Steve Ballmer, CEO of Microsoft, can be seen here in an early days of Microsoft in this TV ad selling Windows v1.0. It is a facinating, and entertaining, video.
Get a load of the 286 computer w/ IBM EGA monitor! Wow, that brings back memories... The 'card filer' could use some sample data, it isn't clear what it does here. Looks like the control panel was a bit small in those days. Hehe, I actually remember trying out Reversi. :)
Congratulations to my friend Jeffrey Palermo on becoming a Microsoft Certified Application Developer (MCAD)!
Jeff's making great progress on his MS certifications and is headed towards a MCSD & MCT.
Between high school and college (at Texas A&M Univ.), I spent a year in Sandpoint, Idaho, working on a national biomedical smart card system. My Dad was working for a sister company at the same time on a portable home cholesterol monitor which interfaced with the smart card. The company, Lifestream, filed for a US Patent on the cholestoral monitor and medical tracking system and it was granted.
It was a great experience working with smart cards and creating a medical record tracking system. Smart cards at the time were desined for financial purposes, so it was a fun challange to create a flexible system on the cards for medical data. The smart card inserts into portable medical devices, like the cholesterol meter, glucose monitors, blood pressure cuffs, etc. Requiring the user's PIN, the medical device gets data from the smart card, saves its results to the card, then the user puts the card into a PC to save and analyse the data.
My Dad recently gave me this plaque to commemorate the patent being issued. Thanks Dad!
.jpg) |
| The plaque my Dad sent me to memorialize our accomplishment. |
My new favorite treat! Bubble tea is a tasty flavored drink with tapioca pearls in it. Also known as Pearl Tea, the drink comes in a flavored ice slush, milk shake, or tea form, but what really makes it is the squishy tapioca balls! At first glance, it may look strange since the tapioca is colored black (I think so you can see it since all my tapioca is opaque white to clear), and it looks funny going up the thick straw, but it is fun. :)
The best bubble tea in Seattle I've found is at Yunnie Bubble Tea (university district). The first good place I found was at Oasis Tea Zone (China Town), but Yunnie's tapioca is chewier. The only bubble tea in Redmond that I've found so far is at Jade Dragon, but they use nasty frozen tapioca and the flavors are very limited. If you know of any others in Redmond, please let me know! Even in my home town of College Station, Texas, a great new bubble tea shop just opened up, Cafe Biegnet Tea & Coffee (in the old Fuddrucker's building).
.jpg) |
| Enjoying my first Bubble Tea in Victoria BC Canada |
Brad Abrams posted Microsoft's Internal Coding Guidelines.
This is a good read! I'd agree with most everything there. I see a lot of Microsoft code and it sure is good to have consistancy. One thing I differ with, is that personally, I really like not using braces {} for single command blocks (ex: if (x == 2) return false;). When grouping simular members, instead of just // comments, I use #region directives (ex: #region Property Variables ... #endregion).
Thanks to Jeffrey Palermo for posting about this.
Update: 4NT is now called Take Command
Take Command by JPSoft is, in my humble opinion, one of the best apps ever created. It is a tool for the 'power user' who appreciates the power of the prompt (C:\>). :) It a console command prompt for Windows on steroids. I've used this app for over 14 years and it is still the one non-MS app I use more than any other.
The History
This page in history starts with MS-DOS. Though the history of the command prompt goes much further back, DOS made the prompt famous. DOS is made up of two parts, the first being a library of functions in two files that are loaded into memory at boot time which other apps used to do common tasks like access files, display text on the screen, and get keyboard input ... these were best known to software developers. The second part of DOS is a collection of separate utilities such as EDIT, HIMEM, XCOPY, SCANDISK, etc. But the most popular utility, which many considered to be 'DOS' is COMMAND.COM, the little app that gives the user the C:\> prompt, interprets what the user types, and starts other apps. It contains a small set of built-in commands such as COPY, DEL, RMDIR, CD, MKDIR, etc.
COMMAND.COM is what most everyone knew when it came to navigating the PC in the days of DOS. Other operating systems, such as Unix, had much more powerful prompts which supported coloring, better editing, and more commands. Until in 1989 JPSoft released the first, truly popular, COMMAND.COM replacement, called 4DOS, which was considerably more advanced than the simplistic COMMAND.COM. Where I entered the light was when Symantec licensed 4DOS 3.0 under Norton Utilities v6.0 in 1991 and called it NDOS with a few enhancements like a nice help system. I totally dug into the enhanced capabilities with the best example being my AUTOEXEC.BAT which had an animated ASCII art GUI powered by NDOS.
Now-a-days, the popular command interface for Windows is cmd.exe, which has come a long ways since COMMAND.COM, but is still a far cry from being a (relatively) powerful prompt. 4NT is JPSoft's Windows NT/XP command prompt replacement with considerable enhancements. This one little apps just keeps impressing me as I've discover new ways of using it continually for the last 14 years. It is the only app I've used for so long and is still the best.
.NET is my choice of programming environment, but some things (usually involving working with files) are just faster to code up in 4NT. I write a lot of console apps in C#, batch apps in 4NT, and use 4NT to bring all the magic together. Working here at Microsoft, I'm amazed at how much the console is used and how it seams that much of a dev's world is spent on the command prompt console.
What's So Cool
Commands & Environment
For starters, cmd.exe (the basic Windows Command prompt) supports about 50 built-in commands, 4NT has 130 built in commands. cmd has a very simplistic help system and 4NT has a full Compiled Help (.chm) cross-linked help system with examples, full descriptions, hints, tips, and more. 4NT supports copying & pasting on the prompt, popup ASCII windows, selection of files for commands, advanced inclusion/exclusion sets on files, full built-in FTP/FTPS/TFTP/HTTP/HTTPS support from any command, file/dir colorization, control of the Windows GUI, send e-mail, and the list goes on ... all of which cmd does not support (at all or without external help). All of the cmd commands are fully supported in 4NT, but with more command line options. But I've only begun!
Variable Functions
cmd supports a few (~7) functions with variables (try 'help set' at the cmd prompt). 4NT contains a library of 150 variable functions (in additional to the 130 commands) that do things such as determine file sizes, system memory availability, type of drives on the computer, file read/write/seek/etc, all common string operations, numeric processing, registry editing, and even regular expressions.
Internal Variables
4NT has over 100 additional internal variables that return information like the state of the alt, ctrl, shift keys, the day of the week, the current directory, the number of milliseconds since Windows started, how many pixels the screen is wide, the battery life remaining on a laptop, and of course, much more.
Batch
All put together, these enhancements make an amazingly flexible and powerful environment to script in. 4NT supports a "Batch to Memory" .btm file format which runs faster, can be compiled, and has a full debugging Interactive Development Environment (IDE). You can create subroutines that pass parameter, use if blocks (iff, elseiff, endiff), and pull all these commands, variable functions, and internal variables, into a substantial scripting experience.
Examples
del /s /r /w /x /y /z c:\temp
Move to the recycle bin all files and directories under c:\temp, removing empty subdirectories & system/hidden/readonly files, and without prompting the user.
dir /o:-s /k /m /2 c:\windows\*.bmp;*.gif;*.jpg
Show all .bmp, .gif, and .jpg files in c:\windows without the header or footer in two columns sorted from largest to smallest file size.
select /a:h-d del (.)
Brings up a selection dialog of the hidden files (no directories) in the current directory to select what to delete.
echo %@eval[%@filesize[c:\windows\explorer.exe]/(1024**2)]
Shows the file size of explorer.exe in megabytes.
drawbox 4 4 8 30 1 bri yellow on blue fill blue %+ scrput 6 9 bri white on blue Hello Fine People
Draws a blue box on the screen with a yellow border with the saying 'Hello Fine People' inside it in bright white.
Screen Shots
 |
| My splash screen when I startup the 4NT prompt. |
 |
| Pressing [PageDown] will show the history of commands from which you can choose to run again. Yes, it is mouse activated too. |
 |
| A directory listing with my colorizations. Green for docs, purple for text files, red for executables, light blue for zips, and yellow for anything else. |
Evaluation
You can download 4NT from JPSoft to try it out. Friends can e-mail me and I'll send them a trial version (covered under the EULA) that is pumped up with my favorite settings, includes the splash screen above, example batch files, WinKey, and a few more enhancements.
The price to purchase is a bit high, $70, but it is the best $70 I've ever spent on software.
I recommend using WinKey, a free hot key app, to assign [WindowsKey+C] or [WindowsKey+4] to run 4NT. This allows to you to rapidly pop up a 4NT prompt with one keyboard shortcut. (update, I now use AutoHotKey instead of WinKey)
Conclusion
When it's all said and done, 4NT is not for the faint of heart, but the user who enjoys feeling the power of command prompt. There is so much more that could be said, but I could go on for hours; so hopefully, if you're a prompt user, you'd see this is worth checking into. One of the reasons I've enjoyed this app so much is that even after 14 years, I'm still discovering commands, functions, and ways of using it all together.
This past weekend my friend Vito and I went out backpacking in the Mt Baker-Snoqualmie National Forest. We left Vitos birthday party Saturday night @ 2am, started hiking @ 3:30am, hiked over snow covered rocks in the dark (w/ headlamps) till 8am, pitched a tent and slept for a few hours, then went on a beautiful trail to some ice caves. It was an adventure!
.jpg) |
| Vito Sabella and I inside the ice cave. |
.JPG) |
| I'm standing by a beautiful, large, cold, mountain snow waterfall. |
.jpg) |
| A view from inside the ice cave to the world outside. |
One of the little gadgets I've wanted ever since getting a digital camera is an LCD Digital Photo Display. This is a unit that sits on the desk and cycles through photos. They typically cost a pretty penny, so using my PDA as the display unit, I built a little adjustable stand out of spare Legos to make my own! The gear on the back adjusts the display angle. The HP comes with photo viewing software that runs a slideshow of pics of my fiance. :)
.JPG) |
| The stand holds the PDA on its side at a good viewing angle. |
.JPG) |
| The gear knob adjusts the viewing angle. These are Technic Legos. |
Other Digital Photo FramesThere is a unit I have my eye on, a Ziga 5.6 LCD display. It has a remote control, accepts most medica cards, and can play movies & MP3s. I want this for my office to see 1,000s of my digial pics, save space, look elegant, watch video clips, and listen to music all in one unit.
A relative of mine recommended the Ceiva Digital Photo Reciever (5"x7" LCD) which you just plug power & a phone line into and it will automatically dial a toll-free number and download your pictures from a website each night. This is a great solution for family (his family uses several); just give the Parents/Grandparents the picture frame and when you post a new pic, they'll get it automatically. If several family members use the unit, everyone can see the same pics. The unit is $150 w/ $100/year subscription charge. We plan on trying it out and will post on how it turns out.
More Posts
« Previous page -
Next page »