#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include "usb_keyboard.h"
#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
uint8_t usb_keys[8]= {KEY_1, KEY_5, KEY_2, KEY_6, KEY_3, KEY_7, KEY_4, KEY_8};
uint8_t led_ports[8] = {(1<<0), (1<<1), (1<<4), (1<< 5), (1<<0), (1<<1), (1<<2), (1<<3)};
int main(void) {
// f = flag: f = 1 means waiting for reset, f = 0 means waiting for contestant to press button
// b = port B input (bits 0 to 8 alternates between teams)
// m = mask (to access each bit in b)
// i = counter (to count through each bit in b)
uint8_t f, b, m, i;
// set for 16 MHz clock
CPU_PRESCALE(0);
// Configure all port B and port C pins as inputs with pullup resistors
DDRB = 0x00;
DDRC = 0x00;
PORTB = 0xFF;
PORTC = 0xFF;
// Configure all port D and port F as outputs (all OFF except LED on Teensy 2.0)
DDRD = 0xFF;
DDRF = 0xFF;
PORTD = (1<<6);
PORTF = 0;
// Initialize the USB, and then wait for the host to set configuration.
// If the Teensy is powered without a PC connected to the USB port,
// this will wait forever.
usb_init();
while (!usb_configured()) /* wait */ ;
// Wait an extra second for the PC's operating system to load drivers
// and do whatever it does to actually be ready for input
_delay_ms(1000);
// flag f = 0 means waiting for contestant to press button
f = 0;
while (1) {
// waiting for reset button
if (f == 1) {
// reset button has been pressed, so reset flag, send "R" to keyboard input
if ((PINC & (1<<7)) == 0) {
f = 0;
usb_keyboard_press(KEY_R, KEY_SHIFT);
// turn off all LEDs except LED on Teensy 2.0
PORTD = (1<<6);
PORTF = 0;
}
}
// waiting for contestant to press button
else {
// get input of all buttons
b = PINB;
m = 1;
// go through each bit of b to read individual buttons
for (i = 0; i < 8; i++) {
// button has been pressed, so set flag, send number to keyboard input
if (((b & m) == 0) && f == 0) {
f = 1;
usb_keyboard_press(usb_keys[i], 0);
// turn on LED on port F for first four buttons (and switch off LED on Teensy 2.0)
if (i < 4) {
PORTF = led_ports[i];
PORTD = 0;
}
// turn on LED on port D for second four buttons (and switch off LED on Teensy 2.0)
else {
PORTD = led_ports[i];
}
// have to split LED output as neither ports F or D have all 8 bits available
}
// increase mask to look at next bit
m = m << 1;
}
}
// wait a short delay so we're not highly sensitive to mechanical "bounce".
_delay_ms(2);
}
}
|