Advertisement
xerpi

AVR Arduino serial C

Jun 26th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #define F_CPU 16000000UL
  2. #define BAUD 9600
  3.  
  4.  
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <avr/io.h>
  8. #include <util/delay.h>
  9. #include <util/setbaud.h>
  10.  
  11.  
  12. void uart_init(void) {
  13.     UBRR0H = UBRRH_VALUE;
  14.     UBRR0L = UBRRL_VALUE;
  15.  
  16. #if USE_2X
  17.     UCSR0A |= _BV(U2X0);
  18. #else
  19.     UCSR0A &= ~(_BV(U2X0));
  20. #endif
  21.  
  22.     UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); /* 8-bit data */
  23.     UCSR0B = _BV(RXEN0) | _BV(TXEN0);   /* Enable RX and TX */
  24. }
  25.  
  26. void uart_putchar(char c) {
  27.     //loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
  28.     while(!(UCSR0A & (1<<UDRE0)));
  29.     UDR0 = c;
  30. }
  31.  
  32. char uart_getchar(void) {
  33.     //loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
  34.     while(!(UCSR0A & (1<<RXC0)));
  35.     return UDR0;
  36. }
  37.  
  38. void uart_putstring(char* string)
  39. {
  40.     char *p = string;
  41.     while(*(p++))
  42.     {
  43.         uart_putchar(*p);
  44.     }
  45. }
  46.  
  47. char String[] = "Hello world!!\n";
  48.  
  49. static FILE uart_output = FDEV_SETUP_STREAM((int (*)(char, struct __file *)) uart_putchar, NULL, _FDEV_SETUP_WRITE);
  50. static FILE uart_input  = FDEV_SETUP_STREAM(NULL, (int (*)(struct __file *)) uart_getchar, _FDEV_SETUP_READ);
  51.  
  52. int main(int main, char *argv[])
  53. {
  54.     uart_init();
  55.     stdout = &uart_output;
  56.     stdin  = &uart_input;
  57.  
  58.     char input;
  59.     while (1)
  60.     {
  61.         puts("Hello world!");
  62.         input = getchar();
  63.         printf("You wrote %c\n", input);
  64.  
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement