📄 uart1.c
字号:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <string.h>
#define UART_BAUD_RATE 19200
#define UART_BAUD_SELECT (((((F_CPU+(UART_BAUD_RATE/2))/UART_BAUD_RATE)+8)/16)-1)
#ifdef _AVR_IOTN2313_H_
#define UART_TX_vect USART_TX_vect
#define UART_RX_vect USART_RX_vect
#define UCR UCSRB
#define UBRR UBRRL
#endif //attiny2313
static volatile uint8_t *uart_data_ptr;
static volatile uint8_t uart_counter;
static volatile uint8_t led;
static volatile uint8_t flag;
static volatile uint8_t txReady;
ISR(UART_TX_vect)
{
uart_data_ptr++;
if(--uart_counter && txReady) {
UDR = *uart_data_ptr;
txReady = 0;
}
}
ISR(UART_RX_vect)
{
led = UDR;
PORTB = ~led;
flag = 1;
}
ISR(USART_UDRE_vect)
{
txReady = 1;
}
void uart_send(uint8_t* buff, uint8_t size)
{
if(!uart_counter) {
uart_data_ptr = buff;
uart_counter = size;
UDR = *buff;
}
}
void uart_init(void)
{
UCR = _BV(RXCIE) | _BV(TXCIE) | _BV(RXEN) | _BV(TXEN);
#ifdef _AVR_IOTN2313_H_
UBRRH = (uint8_t)(UART_BAUD_SELECT >> 8);
UCSRC = _BV(USBS) | _BV(UCSZ0);
#endif //attiny2313
UBRR = (uint8_t)UART_BAUD_SELECT;
}
char* int2str(uint8_t num, char* str_val)
{
uint8_t i;
uint8_t hi = num >> 4;
str_val[0] = '0';
str_val[1] = 'x';
str_val[4] = 0;
for(i=2; i<4; i++) {
if(hi > 9) str_val[i] = hi + 55;
else str_val[i] = hi + 48;
hi = num & 0x0f;
}
return str_val;
}
int main(void)
{
cli();
char str_val[5];
char message[21] = "Recive value:";
uart_init();
DDRB = 0xff;
PORTB = 0x00;
flag = 0;
txReady = 1;
uart_counter = 0;
sei();
while(1) {
if(flag == 1) {
strcpy(message, "Recive value:");
int2str(led, str_val);
strcat(message, str_val);
strcat(message, "###");
uart_send(message, sizeof(message)-1);
flag = 0;
}
sleep_enable();
sleep_cpu();
sleep_disable();
}
return(0);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -