/* * File: cointoss.c * Author: justin * * Created on 17 June 2013, 11:19 */ #include #include #include #include #pragma config CP = OFF // Flash Program Memory Code Protection (Program memory code protection is disabled) #pragma config CPD = OFF // Data Memory Code Protection (Data memory code protection is disabled) #pragma config BOREN = ON // Brown-out Reset Enable (Brown-out Reset enabled) #pragma config CLKOUTEN = OFF // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin) #pragma config IESO = ON // Internal/External Switchover (Internal/External Switchover mode is enabled) #pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled) // CONFIG2 #pragma config WRT = OFF // Flash Memory Self-Write Protection (Write protection off) #pragma config PLLEN = ON // PLL Enable (4x PLL enabled) #pragma config STVREN = ON // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset) #pragma config BORV = LO // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.) #pragma config LVP = ON // Low-Voltage Programming Enable (Low-voltage programming enabled) /* default clock is 500kHz */ #define _INT_OSC 500000L #define _XTAL_FREQ _INT_OSC uint8_t random_byte = 0xB4; void dorand(void) { asm("BCF STATUS,0"); asm("RRF _random_byte,W"); asm("BTFSC STATUS,0"); asm("XORLW 0xB4"); asm("MOVWF _random_byte"); } #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.RA2 == 0) count--; else count = PRESS_MSEC / CHECK_MSEC; __delay_ms(CHECK_MSEC); } count = RELEASE_MSEC / CHECK_MSEC; while (count > 0) { if (PORTAbits.RA2 == 1) count--; else count = RELEASE_MSEC / CHECK_MSEC; __delay_ms(CHECK_MSEC); } } /* * main function */ int main(int argc, char** argv) { /* 12.0 page 101 setup the ports */ TRISAbits.TRISA0 = 0; TRISAbits.TRISA1 = 0; TRISAbits.TRISA2 = 1; /* disable analog features */ ANSELAbits.ANSA0 = 0; ANSELAbits.ANSA1 = 0; ANSELAbits.ANSA2 = 0; /* page 107 enable weak pullup on A2 */ WPUAbits.WPUA2 = 1; OPTION_REGbits.nWPUEN = 0; while (1) { // Wait for the button to press (go low) KeyPress(); // toss the coin dorand(); // set the lights if (random_byte & 0x01) { PORTAbits.RA0 = 1; PORTAbits.RA1 = 0; } else { PORTAbits.RA0 = 0; PORTAbits.RA1 = 1; } } return (EXIT_SUCCESS); }