Best way to read a serial stream on a Pic

Discussion in 'Embedded Systems and Microcontrollers' started by dpeterson3, Oct 9, 2009.

  1. dpeterson3

    Thread Starter New Member

    Oct 9, 2009
    19
    0
    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.
    http://www.nmra.org/standards/DCC/standards_rps/DCCStds.html.

    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.
     
  2. Markd77

    Senior Member

    Sep 7, 2009
    2,803
    594
    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.
     
  3. russ_hensel

    Well-Known Member

    Jan 11, 2009
    818
    47
    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:

    http://www.opencircuits.com/Experimenting_with_IR_Remotes_using_a_PIC_running_BoostC_Project

    http://www.opencircuits.com/A_Tutorial_on_PIC_interrupts_using_BoostC_including_Example_Programs
     
Loading...