Here is a quick and dirty tutorial on how to make a single LED flash on and off on PORTB pin 0.
The Circuit
First of all you will need a microcontroller. My favourite at the moment is the pic 18f4685, so I will be using that. You will also need a programmer, an LED and a resistor (pretty much anything from 120 ohm to 1kohm will do)
Connect the cathode of the LED to one end of the resistor and the other end of the resistor to ground. Then connect the other end of the LED (the anode) to PORTB pin 0. And that's the circuit!
The code
Even if you haven't ever programmed in Basic, the code here will be quite easy to recognise.
Code: Select all
Device = 18F4685 // Tell the compiler what chip we are using
Clock = 8 // Tell the compiler what we will be setting the clock to (Mhz)
Config OSC = IRCIO67 // This tells the microcontroller to use the internal clock
include "utils.bas" // we are including an extra file here which allows us to use shortcuts
// like "SetAllDigital" Which will take care of making all ports digital ports.
// Start Of Program...
OSCCON = %01111111 // Sets the internal oscillator for 8Mhz
SetAllDigital // Make all Pins digital I/O's
TrisB = %00000000 // Make all PORTB pins outputs (even though we only need PORTB, 0)
// Main Loop
While True() // This creates an infinite loop
PORTB.0 = 1 // Turn the LED on
DelayMS(500) // Hold that for half a second
PORTB.0 = 0 // Turn the LED off
DelayMS(500) // Hold that for half a second
Wend // Loop back to the while loop as long as we havent finished.
the % symbol before digits means that we are using binary.
The While Wend loop is very handy indeed! Basically we will remain in the loop the whole time our While statement is true (in the example above it will never be false because I have set it to true.
Here's a better example. Lets say I only wanted the LED to flash on then off 10 times and then stop. Here's the While Wend code:
Code: Select all
dim counter as byte
counter = 10
While counter > 0 // This will loop as long as counter is greater than 0
PORTB.0 = 1 // Turn the LED on
DelayMS(500) // Hold that for half a second
PORTB.0 = 0 // Turn the LED off
DelayMS(500) // Hold that for half a second
Dec(counter) // take one away from the counter variable
Wend // Loop back to the while loop as long as we havent finished.
The code will turn the led on, hold then turn it off and hold. it will then take one away from our counter (which now leaves 9) and will go back to the while statment. It checks if the statement is true (which it is, 9 is greater than 0)
It will keep doing this until our counter variable is not greater than 0.