1 /*
2  * Copyright 2009-2012 Ettus Research LLC
3  */
4 
5 #include "io.h"
6 #include <avr/io.h>
7 
8 #define _GET_PIN(pin)           ((pin) & 0xf)
9 #define _GET_MASK(pin)          (_BV(_GET_PIN(pin)))
10 #define _GET_REG(pin, reg_x)    (*reg_x[pin >> 4])
11 
12 #ifndef IO_DEBUG
13 static volatile uint8_t *ddr_x[] = {&DDRA, &DDRB, &DDRC, &DDRD};		// 0: input, 1: output
14 static volatile uint8_t *port_x[] = {&PORTA, &PORTB, &PORTC, &PORTD};	// Port contents (will appear at output if direction is set to output. If input, '1' enables pull-ups, '0' set tri-state)
15 static volatile uint8_t *pin_x[] = {&PINA, &PINB, &PINC, &PIND};		// Port contents (input) If output, will return value on PORT
16 #endif
17 
io_output_pin(io_pin_t pin)18 void io_output_pin(io_pin_t pin){
19 #ifndef IO_DEBUG
20 	_GET_REG(pin, ddr_x) |= _GET_MASK(pin);
21 #endif
22 }
23 
io_input_pin(io_pin_t pin)24 void io_input_pin(io_pin_t pin){
25 #ifndef IO_DEBUG
26 	_GET_REG(pin, ddr_x) &= ~_GET_MASK(pin);
27 #endif
28 }
29 
io_is_output(io_pin_t pin)30 bool io_is_output(io_pin_t pin){
31 #ifndef IO_DEBUG
32 	return bit_is_set(_GET_REG(pin, ddr_x), _GET_PIN(pin));
33 #else
34 	return 0;
35 #endif
36 }
37 
io_is_input(io_pin_t pin)38 bool io_is_input(io_pin_t pin){
39 	return !io_is_output(pin);
40 }
41 
io_set_pin(io_pin_t pin)42 void io_set_pin(io_pin_t pin){	// In input mode, will enable pull-ups
43 #ifndef IO_DEBUG
44 	_GET_REG(pin, port_x) |= _GET_MASK(pin);
45 #endif
46 }
47 
io_clear_pin(io_pin_t pin)48 void io_clear_pin(io_pin_t pin){	// In input mode, will disable pull-ups
49 #ifndef IO_DEBUG
50 	_GET_REG(pin, port_x) &= ~_GET_MASK(pin);
51 #endif
52 }
53 
io_is_pin_set(io_pin_t pin)54 bool io_is_pin_set(io_pin_t pin){
55 #ifndef IO_DEBUG
56 	return bit_is_set(_GET_REG(pin, port_x), _GET_PIN(pin));
57 #else
58 	return 0;
59 #endif
60 }
61 
io_enable_pin(io_pin_t pin,bool enable)62 void io_enable_pin(io_pin_t pin, bool enable){
63     if (enable)
64         io_set_pin(pin);
65     else
66         io_clear_pin(pin);
67 }
68 
io_test_pin(io_pin_t pin)69 bool io_test_pin(io_pin_t pin){
70 #ifndef IO_DEBUG
71 	return bit_is_set(_GET_REG(pin, pin_x), _GET_PIN(pin));
72 #else
73 	return 0;
74 #endif
75 }
76