avr/lantern-controller/main.c

91 lines
2.5 KiB
C

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <dio.h>
#include <rfm.h>
#include <stdbool.h>
#include <string.h>
typedef enum {
lme_off,
lme_normal,
lme_spooky,
lme_eerie,
} lantern_msg_e;
dio_t buttons[4] = {
{ .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 5 },
{ .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 6 },
{ .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 7 },
{ .ddr = &DDRD, .port = &PORTD, .pin = &PIND, .addr = 6 },
};
typedef struct {
bool button_press[4];
} status_flags_t;
status_flags_t status_flags = {
.button_press = { false, false, false, false }
};
ISR(INT2_vect) {
for (int i = 0; i < 4; i++) {
status_flags.button_press[i] = dio_read(&buttons[i]);
}
}
int main(void) {
EIMSK = 1 << INT2;
EICRA |= 1 << ISC21 | 1 << ISC20;
dio_t int2 = { .ddr = &DDRD, .port = &PORTD, .pin = &PIND, .addr = 2 };
dio_set_direction(&int2, LINE_IN);
dio_set(&int2, false);
rfm_t radio = (rfm_t){
.spi = {
.clock = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 1 },
.data_out = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 2 },
.data_in = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 3 },
.chip_select = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 4 },
},
.irq = { .ddr = &DDRE, .port = &PORTE, .pin = &PINE, .addr = 6 },
.reset = { .ddr = &DDRD, .port = &PORTD, .pin = &PIND, .addr = 4 },
};
rfm_error_e error;
rfm_init(&radio, (uint8_t [4]){ 0xde, 0xca, 0xfb, 0xad }, 4, &error);
set_sleep_mode(SLEEP_MODE_IDLE);
while(1) {
sei();
sleep_mode();
cli();
uint8_t msg;
if (status_flags.button_press[0]) {
status_flags.button_press[0] = false;
msg = lme_normal;
} else if (status_flags.button_press[1]) {
status_flags.button_press[1] = false;
msg = lme_spooky;
} else if (status_flags.button_press[2]) {
status_flags.button_press[2] = false;
msg = lme_eerie;
} else if (status_flags.button_press[3]) {
status_flags.button_press[3] = false;
msg = lme_off;
} else {
continue;
}
rfm_transmit(&radio, &msg, 1);
interrupt_flags_t flags = rfm_interrupts(&radio);
while(!flags.packet_sent) {
_delay_ms(1);
flags = rfm_interrupts(&radio);
}
rfm_standby(&radio);
}
}