单片机串口接受数据的代码
时间: 2023-11-27 21:04:31 浏览: 26
以下是一段基于C语言的单片机串口接收数据的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#define BAUD 9600
#define BAUD_PRESCALE (((F_CPU / (BAUD * 16UL))) - 1)
volatile char received_data;
void USART_Init(void)
{
UBRR0H = (BAUD_PRESCALE >> 8);
UBRR0L = BAUD_PRESCALE;
UCSR0B |= (1 << RXEN0) | (1 << RXCIE0);
UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01);
}
ISR(USART_RX_vect)
{
received_data = UDR0;
}
int main(void)
{
USART_Init();
sei();
while (1)
{
if (received_data == 'A')
{
// do something when 'A' is received
}
}
return 0;
}
```
该代码使用AVR单片机的USART模块,通过9600波特率进行串口通信。在中断服务程序中,将接收到的数据存储到变量received_data中。在主函数中,通过轮询该变量的值,实现对接收数据的处理。需要注意的是,该代码中使用了中断服务程序,需在程序中开启中断。