用C语言写一段代码,串口中断接收
时间: 2024-05-07 13:16:44 浏览: 5
Sure, here is an example code for receiving data on a serial port using an interrupt in C language:
```
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#define BAUD 9600UL
#define BAUD_PRESCALE ((F_CPU/(BAUD*16UL))-1)
volatile char received_byte;
ISR(USART_RX_vect)
{
// read the received byte from serial port
received_byte = UDR0;
}
int main (void)
{
// configure UART
UBRR0H = (BAUD_PRESCALE >> 8);
UBRR0L = BAUD_PRESCALE;
UCSR0B |= (1 << RXCIE0) | (1 << RXEN0) | (1 << TXEN0); // enable RX interrupt, enable RX/TX
sei(); // enable interrupt globally
// main loop
while (1)
{
// do something with received_byte
}
return 0;
}
```
This code uses the AVR microcontroller's UART module to receive data on the serial port at a baud rate of 9600. The ISR (Interrupt Service Routine) is triggered whenever a byte is received on the serial port, and the received byte is stored in the `received_byte` variable. In the main loop, you can process the received byte accordingly.