You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
1.9 KiB
92 lines
1.9 KiB
#define F_CPU 8000000UL
|
|
|
|
#include "../avr-i2c-slave/I2CSlave.h"
|
|
#include <util/delay.h>
|
|
#include <avr/io.h>
|
|
|
|
#include <avr/interrupt.h>
|
|
|
|
#define BAUDRATE 9600
|
|
#define BAUD_PRESCALLER (((F_CPU / (BAUDRATE * 16UL))) - 1)
|
|
|
|
#define I2C_ADDR 0x20
|
|
|
|
void USART_init(void){
|
|
UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
|
|
UBRR0L = (uint8_t)(BAUD_PRESCALLER);
|
|
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
|
|
UCSR0C = (3<<UCSZ00);
|
|
}
|
|
|
|
void USART_send( unsigned char data){
|
|
while(!(UCSR0A & (1<<UDRE0)));
|
|
UDR0 = data;
|
|
}
|
|
|
|
void USART_putstring(char* StringPtr){
|
|
while(*StringPtr != 0x00){
|
|
USART_send(*StringPtr);
|
|
StringPtr++;
|
|
}
|
|
}
|
|
|
|
volatile uint8_t challenge = 0; // Use 0 as 'challenge not sent' condition
|
|
uint16_t time_open = 0;
|
|
|
|
uint8_t check_challenge(uint8_t arg) {
|
|
return (arg >> 3);
|
|
}
|
|
|
|
void I2C_received(uint8_t received_data) {
|
|
uint8_t solution;
|
|
char message[100] = {0};
|
|
|
|
solution = check_challenge(challenge);
|
|
sprintf(message, "Response: %d. Expected: %d\n", received_data, solution);
|
|
USART_putstring(message);
|
|
if (received_data == solution) { // Check validity of response
|
|
// Open lock
|
|
time_open = 5000;
|
|
}
|
|
}
|
|
|
|
void I2C_requested() {
|
|
challenge = (uint8_t)(TCNT1 & 0xff);
|
|
I2C_transmitByte(challenge);
|
|
char message[100] = {0};
|
|
sprintf(message, "Request received. Sending %d\n", challenge);
|
|
USART_putstring(message);
|
|
}
|
|
|
|
void setup() {
|
|
// set received/requested callbacks
|
|
I2C_setCallbacks(I2C_received, I2C_requested);
|
|
// init I2C
|
|
I2C_init(I2C_ADDR);
|
|
// init output gpio
|
|
DDRC = 0b00000100; // PC2
|
|
TCNT1 = 0;
|
|
TCCR1B |= (1 << CS10) | (1 << CS11); // No prescaling
|
|
}
|
|
|
|
int main() {
|
|
int i = 0;
|
|
setup();
|
|
USART_init();
|
|
while (1) {
|
|
i++;
|
|
if (time_open > 0) {
|
|
PORTC |= 2 << 1;
|
|
time_open -= 1;
|
|
} else {
|
|
PORTC = 0;
|
|
}
|
|
_delay_ms(1);
|
|
if (i > 1000) {
|
|
char message[] = "Alive\n";
|
|
USART_putstring(message);
|
|
i = 0;
|
|
}
|
|
}
|
|
}
|