uart_forum.c


1
#include <avr/io.h>
2
#include <inttypes.h>
3
#include <avr/interrupt.h>
4
#include <avr/signal.h>
5
6
#include <delayms.c>
7
8
#ifndef F_CPU
9
#define F_CPU 16000000           /* Oszillator-Frequenz in Hz */
10
#endif
11
#define UART_BAUD_RATE 9600
12
#define UART_BAUD_CALC(UART_BAUD_RATE,F_OSC) ((F_CPU)/((UART_BAUD_RATE)*16L)-1)
13
14
//globals
15
volatile uint8_t command[3];
16
volatile uint8_t sreg_temp;
17
volatile uint8_t bytecountSen;
18
19
20
SIGNAL(SIG_UART_TRANS)  
21
//ISR for transmitting via serial Interface
22
{
23
  if (bytecountSen==3)  //bytes 0 bis 2 sind gesendet, also die 3 byte des Befehls
24
      bytecountSen==0;    
25
  else
26
    {
27
      while (!(UCSRA & (1<<UDRE)));    //warten bis Senden moeglich 
28
      UDR = command[bytecountSen];    //der hier erzeugte Interrupt zird getsartet nachdem
29
      bytecountSen++;            //dies ISR abgearbeitet ist.
30
    } 
31
}
32
33
SIGNAL(SIG_UART_RECV)
34
//ISR for receiving a sign via serial Interface
35
{
36
uint8_t data;
37
38
data = UDR;
39
 switch (data)
40
 {
41
   case 'a': {ToggleBit(PORTC,PC0); break;}
42
   case 'b': {ToggleBit(PORTC,PC1); break;}
43
   case 'c': {ToggleBit(PORTC,PC2); break;}
44
   case 'd': {ToggleBit(PORTC,PC3); break;}
45
 }
46
}
47
48
int main(void)
49
{
50
uint8_t i;
51
52
//Initialization UART
53
UBRRH=(uint8_t)(UART_BAUD_CALC(UART_BAUD_RATE,F_CPU)>>8);
54
UBRRL=(uint8_t)UART_BAUD_CALC(UART_BAUD_RATE,F_CPU);
55
56
UCSRB |= (1<<RXEN) | (1<<TXEN); //enable RxD & TxD
57
UCSRB |= (1<<RXCIE) | (1<<TXCIE);
58
59
//command generation
60
command[0] = 0xff;
61
command[1] = 0x00;
62
command[2] = 0x34;
63
64
sei();
65
DDRC = 0xFF;
66
PORTC = 0x00;
67
68
//main loop
69
for(;;)
70
 {
71
  while (!(UCSRA & (1<<UDRE)));
72
  
73
  bytecountSen = 1;
74
  UDR = command[0];
75
    
76
  delayms(500);
77
 } 
78
79
}