Best way to read a serial stream on a Pic

Thread Starter


Joined Oct 9, 2009
I am a model railroader and the new locomotives have Pics in them that read serial data from the track for control rather than conventional DC power. I wanted to build one of my own because sound decoders are $100+. I built the board for a PIC 16F84a and now need help programing. The electrical specs for the serial timing can be found here.

Basically for a standard serial stream, 4 packets of 8 bits are sent. For an extended packet, 11 bits are sent. A 1 bit is represented by two halves of a rise and fall of the clock between 52 and 64 microseconds and 0 is between 99 and 10000 microseconds (not a typo. A 0 can be long to simulate DC voltage on the track). My decoder needs to be able to read these packets, update the PWM to motor, run the lights/accessories, and run the sound. I am having trouble deciding code order. Should I read all the data from the track, then update everything or should Iupdate between readings (worried about throwing timing off there). I need code design help.


Joined Sep 7, 2009
I'd recommend running your main code (motor control, sound, etc) in a loop and using an interrupt on the port to store and interpret the control signals. Looks like a pretty ambitious project. Because you also have to keep track of time for the serial stream you could also enable the timer interrupt and determine the source of interrupt in the interrupt routine. You would have to be careful that the interrupt does not change any variables in the middle of the main loop, maybe storing them in a temp variable and updating the ones used in the main loop at a safe point.


Joined Jan 11, 2009
Second what Markd77 said.
Any time there are time critical external events it is is sign to consider interrupts.
A rule is to do as little processing in the interrupt as possible, set flags, variables... then do the time consuming, non-time critical stuff in the main loop.
I have done something similare decoding IR signals. See: