Menu

Practical Sub Routine Example

2015-06-24
2015-08-07
  • William Roth

    William Roth - 2015-06-24

    Here is what I think is a good and useful example of a sub routine. When called, this sub will blink an LED for the number of times and duration as determined by the input parameters.

    This is intended to demonstrate how to create and use a SUB with a useful example.

    The syntax is:

    Flash_LED (numtimes, OnTime, (optional) OffTime)

    Where numtimes is from 1 - 255 and OnTime/OffTime is from 0 - 65535 ms. If OffTime is not entered, then OffTime = OnTime.

    Below is the actual sub routine:

    Sub Flash_LED (in numtimes, in OnTime as WORD, Optional OffTime as WORD = OnTime)
    repeat numtimes
        set LED on
        wait OnTime ms
        set LED OFF
        wait OffTime ms 
    end repeat
    End Sub
    

    Below is a working example program using a PIC 18F25K22. Change Settings/PORTS as needed for other Chips. Connect an LED to the LED pin through a 1K series resistor:

    #chip 18F25K22, 16
    #config OSC = INTIO67, MCLRE = OFF, XINST = OFF
    
    #define LED PORTC.1       'Led on PIN 14 via 1K resistor
    DIR LED OUT
    
    wait 1 sec
    
    ;======== MAIN PROGRAM LOOP ================
    Do
       Flash_LED 3,250        '3 Flashes 250 ms equal on/off time
       Wait 2 Sec
       Flash_LED 5,250,500    '5 flashes On 250 ms / off 500 ms
       Wait 2 Sec
       Flash_LED 10,100       '10 rapid flashes
       Wait 2 Sec
    Loop
    ;==========================================
    
    Sub Flash_LED (in numtimes, in OnTime as WORD, optional OffTime as word = OnTime)
    
        repeat numtimes
            set LED on
            wait OnTime ms
            set LED OFF
            wait OffTime ms
        end repeat
     End Sub
    

    Enjoy

     
  • viscomjim

    viscomjim - 2015-08-06

    GREAT EXAMPLE thanks!!!

     
  • Anobium

    Anobium - 2015-08-07

    Agree. I have moved to the Help File. We always need good example code.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.