PetrovIgor

USART test. Atmega8. WITH interrupts.

Aug 12th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <avr/io.h>
  2. #include <util/delay.h>
  3. #include <avr/interrupt.h>
  4.  
  5. #define XTAL 8000000L
  6. #define BAUDRATE 9600L
  7. #define BAUDDIVIDER (XTAL/(16*BAUDRATE)-1)
  8.  
  9. #define BUFFER_SIZE 16
  10.  
  11. void init(void);
  12. void initTransmition(void);
  13.  
  14. char buffer[BUFFER_SIZE] = "0123456789ABCDEF";
  15. unsigned char bufferIndex = 0;
  16.  
  17. int main(void) {
  18.     init();
  19.     sei();
  20.  
  21.     while(1) {
  22.         if(PINB & (1 << PINB0)) {
  23.             initTransmition();
  24.         }
  25.         PORTB = 0b00000000;
  26.         _delay_ms(1000);
  27.         PORTB = 0b10000000;
  28.         _delay_ms(1000);
  29.     }
  30.  
  31.     return 0;
  32.  
  33. }
  34.  
  35. void init(void) {
  36.     DDRB = 0b11111110;
  37.     PORTB = 0x00;
  38.     UBRRH = BAUDDIVIDER >> 8;
  39.     UBRRL = BAUDDIVIDER & 0xFF;
  40.  
  41.     UCSRA = 0;
  42.     UCSRB = (1 << RXEN) | (1 << TXEN) | (0 << RXCIE) | (0 << TXCIE) | (0 << UDRIE);
  43.     UCSRC = (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1);
  44. }
  45.  
  46. void initTransmition(void) {
  47.     bufferIndex = 0;
  48.     UDR = buffer[0];
  49.     UCSRB |= (1 << UDRIE);
  50. }
  51.  
  52. ISR(USART_UDRE_vect) {
  53.     bufferIndex++;
  54.     if(bufferIndex == BUFFER_SIZE) {
  55.         UCSRB &= ~(1 << UDRIE);
  56.     } else {
  57.         UDR = buffer[bufferIndex];
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment