Main Site Documentation

Changing the Baud rate on a SerialPort


#1

I have run into a problem with the SerialPort class. I have an application that requires a UART interface to an OBD protocol chip. The chip starts at 9600 and I need to change the baud rate to 500000 and then back to 9600 again so initialization does not require a power reset. When I include a write and this write times out I can end up in a state where the port close locks the EMX tighter than a drum. I am assuming that a close and an open is all that is required to change the baud rate (it throws an exception when it is open). It turns out that the write is required and the bit rate must change for this lockup to occur. It can take some number of iterations. You must debug this code and then set the boolean to true. Otherwise rebooting leads to an immediate lockup. The serial port does not have to be connected.


using System;
using System.Threading;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Media;

using GHIElectronics.NETMF.Hardware;
using GHIElectronics.NETMF.Native;
//using GHIElectronics.NETMF.Hardware;
using System.Text;

namespace NetMF
{
	public class Program
	{
		public static void Main()
		{
			SerialPort prot;
			prot = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
			prot.WriteTimeout = 1000;
			prot.ReadTimeout = 1000;

			prot.Open();
			string message = "junk";
			bool b = false;
			int rate = 500000;

			while (b)
			{
				prot.Write(Encoding.UTF8.GetBytes(message),	0, message.Length);
				prot.Close();
				prot.BaudRate = rate;
				if (rate == 500000)
					rate = 9600;
				else
					rate = 500000;
				prot.Open();
			}
		}
	}
}



#2

I previously noticed that the debugger has a hard time when there is no Thread.Sleep in a while loop.

When I created while loops without delays, I always ended op reflashing my firmware.

My suggestion is to add some Thread.Sleep(100) after say Closing and Opening the port. Give your CPU some time :wink:


#3

This works like a champ as long as the baud rate is not changed or the write is removed. It cannot get trapped in here on a normal reboot because of the boolean. As it is written, once the boolean is set to true, the entire EMX will lock so that breakpoints cannot not even be set. The debugger fails - comm is gone. A thread sleep does not change this.


#4

We will fix in next release. For now please do this:

Add at the begining of your program:


// for COM2
GHIElectronics.NETMF.Hardware.LowLevel.Register U1FDR = new GHIElectronics.NETMF.Hardware.LowLevel.Register(0xE0010028);

Then right after you open the COM port, do this:


prot.Open();
if ((U1FDR.Read() & 0xF0) == 0)
  U1FDR.SetBits(0x10);


#5

Works great. Thanks!