The code is here:
/*************************************************
* Description: switch on LEDs with switches
*
* File: switches.c
* Author: Chris Hill
* Created: August 2012
*
************************************************/
#include
#include
__CONFIG(FOSC_XT & WDTE_OFF & PWRTE_ON & CP_OFF & BOREN_OFF & LVP_OFF & CPD_OFF & WRT_ON);
/***** GLOBAL VARIABLES *****/
union {
uint8_t port;
struct {
unsigned RB0 : 1;
unsigned RB1 : 1;
unsigned RB2 : 1;
unsigned RB3 : 1;
unsigned RB4 : 1;
unsigned RB5 : 1;
unsigned RB6 : 1;
unsigned RB7 : 1;
};
} sPORTB;
#define SW1 PORTBbits.RB7
#define SW2 PORTBbits.RB6
#define SW3 PORTBbits.RB5
#define sLED1 sPORTB.RB2
#define sLED2 sPORTB.RB1
#define sLED3 sPORTB.RB0
void main() {
// initialisation
TRISB = 0b11111000;
for (;;) {
sLED1 = SW1 ? 1 : 0;
sLED2 = SW2 ? 1 : 0;
sLED3 = SW3 ? 1 : 0;
PORTB=sPORTB.port;
}
}
It looks quite long at first sight, but it is simple enough, most of the complexity coming from a union to create a shadow for PORTB. This allows the shadow PORTB to be addressed as an eight bit integer or as individual bits. I like to use the shadow for ports because it helps with the read-modify-write problem of I/O ports. There no need to debounce the switches, the LEDs would just flash so fast that no one would notice.
The compiler makes accessing registers in various banks much easier, such as TRISB, makes everything a bit more readable and so less prone to errors - though perhaps professional assembler programmers might not agree. The resulting code is 47 words long out of 4096 available in the PIC16F873, so room to grow.
The hardware layout to test this was set up on bread board, rather randomly set up as a temporary test. I used an external crystal - I usually do - so I needed to connect two 33pF capacitors between GND and the crystal and pins 8 & 9, hook up +5v to pin 20, two GND pins 8 & 19 and connect the MCLR (pin 1) to +5v. You need this for every circuit so it it easy enough to leave it on a bread board ready for the next circuit. This is not quite as plug and go as an Arduino, but not too hard either. If I build something I want to make more permanent then something on Veroboard is easy to make too.
Overall I think the PicKit 3 and the XC8 C compiler from Microchip has encouraged me to dabble again micro controller electronics. So what next?
No comments:
Post a Comment