Tuer-Schild/Door/io/IR.hpp

108 lines
2.2 KiB
C++
Raw Normal View History

/*
* Interrupt.hpp
*
* Created: 18.11.2014 00:27:52
* Author: netz
*/
#ifndef INTERRUPT_H_
#define INTERRUPT_H_
#include <util/delay.h>
template <typename Port, int pin_int, typename Led>
class IR {
public:
IR() {
this->init();
}
int read() {
if(intpin::value()) { //Is High, Abbort
return 254;
}
_delay_ms(4); //Wait 4ms
if(intpin::value()) { //Is High, Abbort
return 254;
}
intpin::wait_is_set(); //Wait for the rest of the init.
intpin::wait_is_clear(); // Init Complete, wait for first Byte
//Read First Byte must be 0!
if(this->read8bit() != 0) { //Is first Byte not 0 Abbort;
return 255;
}
//Read Second Byte must be 239!
if(this->read8bit() != 239) {
return 255;
}
//Read Byte 3 and 4 (Data Byte and Checksum Byte!
uint8_t a = this->read8bit();
uint8_t b = this->read8bit();
//Make Checksum Byte 3 + 4 must be 255!
if(a+b != 255) {
return 255;
}
return a; //Return Byte 3
}
//The Interrupt Function
void interrupt() {
led.red(1);
uint8_t code = this->read();
if(code == 255) {
_delay_ms(500);
} else if(code == 254) {
_delay_ms(1);
} else {
this->_code = code;
}
led.red(0);
EIFR |= (1<<INTF0);
}
uint8_t getCode() {
uint8_t ret = this->_code;
this->_code = 255;
return ret;
}
private:
Led led;
uint8_t _code;
void init() {
intpin::make_input();
this->_code = 255;
this->init_int();
}
void init_int() {
// External Interrupt(s) initialization
// INT0: On
// INT0 Mode: Falling Edge
// INT1: Off
// Interrupt on any change on pins PCINT0-7: Off
// Interrupt on any change on pins PCINT8-14: Off
// Interrupt on any change on pins PCINT16-23: Off
EICRA=(0<<ISC11) | (0<<ISC10) | (1<<ISC01) | (0<<ISC00);
EIMSK=(0<<INT1) | (1<<INT0);
EIFR=(0<<INTF1) | (0<<INTF0);
}
uint8_t read8bit() {
uint8_t r = 0;
for (uint8_t i=0;i<8;i++) {
intpin::wait_is_set();
_delay_us(800);
if(intpin::read()) {
r |= (1<<i);
}
for(uint8_t j=0;j<50;j++) {
if(!intpin::value()) {
break;
}
_delay_us(20);
}
}
return r;
}
const typedef avrlib::pin<Port, pin_int> intpin;
};
#endif /* INTERRUPT_H_ */