main.c


1
#include <avr/io.h>
2
#include <avr/interrupt.h>
3
#include <util/delay.h>
4
5
#define F_CPU  16000000
6
#define BUAD  9600
7
#define BRC    ((F_CPU/16/BUAD) - 1)
8
#define TX_BUFFER_SIZE  128
9
#define RX_BUFFER_SIZE  128
10
11
char serialBuffer[TX_BUFFER_SIZE];
12
uint8_t serialReadPos = 0;
13
uint8_t serialWritePos = 0;
14
15
char rxBuffer[RX_BUFFER_SIZE];
16
uint8_t rxReadPos = 0;
17
uint8_t rxWritePos = 0;
18
19
void appendSerial(char c);
20
void serialWrite(char  c[]);
21
22
char getChar(void);
23
char peekChar(void);
24
25
26
int main(void)
27
{  
28
  DDRB=(1<<PB0)|(1<<PB1)|(1<<PB2);
29
  DDRD=(1<<PD5)|(1<<PD6)|(1<<PD7);//OCR0A, OCR0B
30
  TCCR0A=(1<<WGM01)|(1<<WGM00)|(1<<COM0A1)|(1<<COM0B1)|(1<<COM0B0);
31
  TCCR0B=(1<<CS02);
32
33
  DDRB = ( 1 << PB5);
34
  UBRR0H = (BRC >> 8);
35
  UBRR0L =  BRC;
36
  
37
  UCSR0B = (1 << TXEN0)  | (1 << TXCIE0) | (1 << RXEN0)  | (1 << RXCIE0);
38
  UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
39
  
40
  sei();
41
42
  OCR0A=255;
43
  OCR0B=255;
44
  PORTD=(1<<PD7);
45
  PORTB=(1<<PB1);
46
  
47
    while(1)
48
    {
49
    }
50
}
51
52
void appendSerial(char c)
53
{
54
  serialBuffer[serialWritePos] = c;
55
  serialWritePos++;
56
  
57
  if(serialWritePos >= TX_BUFFER_SIZE)
58
  {
59
    serialWritePos = 0;
60
  }
61
}
62
63
void serialWrite(char c[])
64
{
65
  for(uint8_t i = 0; i < strlen(c); i++)
66
  {
67
    appendSerial(c[i]);
68
  }
69
  
70
  if(UCSR0A & (1 << UDRE0))
71
  {
72
    UDR0 = 0;
73
  }
74
}
75
76
ISR(USART_TX_vect)
77
{
78
  if(serialReadPos != serialWritePos)
79
  {
80
    UDR0 = serialBuffer[serialReadPos];
81
    serialReadPos++;
82
    
83
    if(serialReadPos >= TX_BUFFER_SIZE)
84
    {
85
      serialReadPos++;
86
    }
87
  }
88
}
89
char peekChar(void)
90
{
91
  char ret = '\0';
92
  
93
  if(rxReadPos != rxWritePos)
94
  {
95
    ret = rxBuffer[rxReadPos];
96
  }
97
  
98
  return ret;
99
}
100
101
char getChar(void)
102
{
103
  char ret = '\0';
104
  
105
  if(rxReadPos != rxWritePos)
106
  {
107
    ret = rxBuffer[rxReadPos];
108
    
109
    rxReadPos++;
110
    
111
    if(rxReadPos >= RX_BUFFER_SIZE)
112
    {
113
      rxReadPos = 0;
114
    }
115
  }
116
  
117
  return ret;
118
}
119
120
ISR(USART_RX_vect)
121
{
122
  rxBuffer[rxWritePos] = UDR0;
123
  
124
  rxWritePos++;
125
  
126
  if(rxWritePos >= RX_BUFFER_SIZE)
127
  {
128
    rxWritePos = 0;
129
  }
130
}