Created
December 13, 2013 13:31
-
-
Save dagon666/7944242 to your computer and use it in GitHub Desktop.
gpio abstraction layer for atmega mcu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <avr/io.h> | |
| #include <stdint.h> | |
| #include <util/delay.h> | |
| typedef struct _gpio_pin { | |
| volatile uint8_t *port; | |
| uint8_t pin; | |
| } gpio_pin; | |
| /** | |
| * @brief get pointer to DDR register from PORT register | |
| * | |
| * @param __val pointer to PORT register | |
| * | |
| * @return pointer to DDR register | |
| */ | |
| #define GET_DDRX_FROM_PORTX(__portx) \ | |
| (__portx - 1) | |
| /** | |
| * @brief get pointer to PIN register from PORT register | |
| * | |
| * @param __val pointer to PORT register | |
| * | |
| * @return pointer to PIN register | |
| */ | |
| #define GET_PINX_FROM_PORTX(__portx) \ | |
| (__portx - 2) | |
| #define GPIO_CONFIGURE_AS_OUTPUT(__gpio) \ | |
| *(GET_DDRX_FROM_PORTX((__gpio)->port)) |= _BV((__gpio)->pin) | |
| #define GPIO_CONFIGURE_AS_INPUT(__gpio) \ | |
| *(GET_DDRX_FROM_PORTX((__gpio)->port)) &= ~_BV((__gpio)->pin) | |
| #define GPIO_GET(__gpio) \ | |
| (*(GET_PINX_FROM_PORTX((__gpio)->port)) & _BV((__gpio)->pin)) | |
| #define GPIO_SET_LOW(__gpio) \ | |
| (*(__gpio)->port) &= ~_BV((__gpio)->pin) | |
| #define GPIO_SET_HIGH(__gpio) \ | |
| (*(__gpio)->port) |= _BV((__gpio)->pin) | |
| #define GPIO_TOGGLE(__gpio) \ | |
| *(GET_PINX_FROM_PORTX((__gpio)->port)) = _BV((__gpio)->pin) | |
| int main(int argc, char const *argv[]) | |
| { | |
| gpio_pin x; | |
| uint8_t cnt = 0; | |
| x.port = &PORTB; | |
| x.pin = 4; | |
| GPIO_CONFIGURE_AS_OUTPUT(&x); | |
| GPIO_SET_LOW(&x); | |
| /* | |
| * if you want to test the second usage example | |
| * comment out the first loop | |
| */ | |
| // using toggle | |
| while (1) { | |
| GPIO_TOGGLE(&x); | |
| _delay_ms(500); | |
| } | |
| // using LOW/HIGH | |
| while (1) { | |
| if (cnt++ & 0x01) { | |
| GPIO_SET_HIGH(&x); | |
| } | |
| else { | |
| GPIO_SET_LOW(&x); | |
| } | |
| _delay_ms(500); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment