728x90
제목 :
날짜 : 21.04.07
주제 : UART 연습
목표 : UART를 활용하여 LED 제어
<활동>
- main.c -
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
#include "uart0.h"
FILE OUTPUT = FDEV_SETUP_STREAM(UART0_Transmit, NULL, _FDEV_SETUP_WRITE);
char rxBuff[100] = {0,};
uint8_t rxFlag = 0;
ISR(USART0_RX_vect)
{
static uint8_t tail = 0;
uint8_t rxData = UDR0;
if(rxData == ';')
{
rxBuff[tail] = '\0';
tail = 0;
rxFlag = 1;
}
else
{
rxBuff[tail] = rxData;
tail++;
}
}
int main(void)
{
DDRF |= (1<<PF6) | (1<<PF7);
UART0_Init();
stdout =&OUTPUT;
sei();
while (1)
{
if(rxFlag == 1)
{
rxFlag = 0;
if(strncmp(&rxBuff[0],"LED0",4) == 0)
{
if(strncmp(&rxBuff[4],"ON",2) == 0)
{
PORTF |= (1<<PF6);
printf("LED0 ON\n");
}
else if(strncmp(&rxBuff[4],"OFF",3) == 0)
{
PORTF &= ~(1<<PF6);
printf("LED0 OFF\n");
}
}
else if(strncmp(&rxBuff[0],"LED1",4) == 0)
{
if(strncmp(&rxBuff[4],"ON",2) == 0)
{
PORTF |= (1<<PF7);
printf("LED1 ON\n");
}
else if(strncmp(&rxBuff[4],"OFF",3) == 0)
{
PORTF &= ~(1<<PF7);
printf("LED1 OFF\n");
}
}
}
}
}
- uart0.c
#include "uart0.h"
void UART0_Init(void)
{
UBRR0H=0x00; //대부분 0
UBRR0L=16; //데이터 통신 속도를 의미한다. 115200 baudrate
UCSR0A|=(1<<U2X0);
UCSR0B|=(1<<RXEN0)|(1<<TXEN0);//Rx enable/ Tx enable
UCSR0B|=(1<<RXCIE0);// 수신 Rx UART0 인터럽트 Enabale
}
void UART0_Transmit(unsigned int data)
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<<UDRE0)) )
;
/* Put data into buffer, sends the data */
UDR0 = data;
}
unsigned char UART0_Receive(void)
{
/* Wait for data to be received */
while ( !(UCSR0A & (1<<RXC0)) )
;
/* Get and return received data from buffer */
return UDR0;
}
void UART0_print_string(char *str)
{
for(int i=0;str[i];i++)
{
UART0_Transmit(str[i]);
}
}
- uart0.h -
#ifndef UART0_H_
#define UART0_H_
#include <avr/io.h>
void UART0_Init(void);
void UART0_Transmit(unsigned int data);
unsigned char UART0_Receive(void);
void UART0_print_string(char *str);
#endif /* UART0_H_ */
<파일>
'AVR' 카테고리의 다른 글
[AVR] I2C 연습 (0) | 2021.04.08 |
---|