Activities
This project requires the PIC chip, two LEDS (plus limiting resistors), one button.
To be able to program the chip you need to connect the serial board as below.
This will allow us to use the Bootloader software on the PC.
Now connect the items we will use for this project:
We need to select the clock speed that the CPU will run at, and tell the compiler what we have chosen so that it can correctly compute delay loops later.
This is where you start to need the Datasheet for the cpu (see references page), Section 5.0 Oscillator Mode is the part we need, looking at 5.9 Register definitions on Page 75 we can see the values we might need to set in the OSCCON register.
At the top of the main() function add code to select a 4MHz clock.
This can either be done by setting all of the bits at once, e.g. OSCCON = 0b00110100;
or we can set only the part of the register we care about, OSCCONbits.IRCF = 0b1101;
Tell the compiler that speed
#define _XTAL_FREQ 4000000
Chapter 12.0 I/O Ports - We need to choose some pins to connect our LEDs and button. Let us use pins RC0, RC1 (pin 10 & 9) for the LEDs, RA5 (pin 2) for the button.
Enable weak pull-ups WPUEN bit of OPTION_REG (Chapter 19.2 page 185)
For the input pin, set to input mode (TRISA), turn the Weak Pull-up on (WPUA), page 132 on.
For the output pins, turn analog off (ANSELC), set to output mode (TRISC), page 140 on.
Now loop waiting for the button to be pressed (PORTAbits.RA5 == 0) when it does, fetch the next random number, if the lowest bit is 0 turn on RC0 and off RC1. of bit is 1 set the opposite. repeat.
The following routine returns a 16bit pseudo-random number.
uint16_t dorand(void) { static uint16_t lfsr = 0xACE1u; lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xB400u); return lfsr; }
Now you need to write your program into your chip, when you Build Project in MPLAB one of the many things it will output in its dist/ directory is a .hex file. this is the finished code, and what the bootloader requires.
With your board all wired up and plugged in, run: boot.exe -v myproject.hex it should prompt you to hit reset on your dev board, and if all is correct it will identify the chip and write your program. A few seconds after writing the chip will reset and start running your program.
To make button presses more reliable, check that it has reached a stable state before and after being pressed, like this...
#define CHECK_MSEC 5 // sample key every 5 mS #define PRESS_MSEC 10 // stable before presses #define RELEASE_MSEC 100 // stable before released void KeyPress(void) { uint8_t count = PRESS_MSEC / CHECK_MSEC; while (count > 0) { if (PORTAbits.RA5 == 0) count--; else count = PRESS_MSEC / CHECK_MSEC; __delay_ms(CHECK_MSEC); } count = RELEASE_MSEC / CHECK_MSEC; while (count > 0) { if (PORTAbits.RA5 == 1) count--; else count = RELEASE_MSEC / CHECK_MSEC; __delay_ms(CHECK_MSEC); } }