1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#define F_CPU        16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
 
 
#define STX        0x5F
#define ETX        0x2F
 
void UART_Init(void);
void UART_TX_CH(char c);
void UART_TX_STR(char *s);
 
char rx_buf[20], rx_cnt = 0;
char tx_buf[20], tx_cnt = 0;
volatile char rx_flag = 0;
 
 
/*
 * UART Initiallize
 */
void UART_Init(void) {
    UCSR0A = 0;
    UCSR0B = (1<<RXCIE0) | (1<<RXEN0) | (1<<TXEN0);        //RX INT enable, RX & TX Enable
    UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);                    //8bit no parity
    UBRR0H = 0;
    UBRR0L = 103;                                        //9600 baudrate
}
 
 
/*
 * UART 문자 출력
 */
void UART_TX_CH(char c) {
    while(!(UCSR0A & (1<<UDRE0)));
    UDR0 = c;
}
 
 
/*
 * UART 문자열 출력
 */
void UART_TX_STR(char *s) {
    while(*s) {
        UART_TX_CH(*s++);
    }
}
 
 
/*
 * UART Receive Interrupt
 */
ISR(USART_RX_vect) {
    int i;
    char rxdata;
    rxdata = UDR0;
    if(!rx_flag) {
        if(rxdata == STX) {
            rx_cnt = 0;
        }
        else if(rxdata == ETX) {
            for(i=0; (i<rx_cnt) && (i<10); i++) {
                tx_buf[i] = rx_buf[i];
                rx_buf[i] = ' ';
            }
            rx_cnt = 0;
            rx_flag = 1;
        }
        else {
            if(rx_cnt < 10) {
                rx_buf[rx_cnt] = rxdata;
                rx_cnt++;
            }
        }
    }
}
 
 
int main(void) {
    UART_Init();
    sei();
    while (1) {
        if(rx_flag) {
            UART_TX_STR(tx_buf);
            UART_TX_CH(0x0a);
            rx_flag = 0;
        }
    }
}
cs


반응형
로봇쟁이