임베디드/Atmega128
atmega128 시리얼통신
sj0020
2021. 2. 4. 16:34
아래 코드 main.c / uart.c / uart.h 로 분리
main.c
/*
* USART.c
*
* Created: 2018-11-09 오전 12:50:55
* Author : RRL
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <stdio.h>
#include "uart.h"
int main(void)
{
unsigned char data;
USART_Init();
while (1)
{
data=USART_Receive();
if(data=='1') {
float temp = 30.2;
float humi = 40;
char buf[40] = {0,};
sprintf(buf, "Temp:%f, humi:%f", temp, humi);
strTransmit(buf);
} // ON\n
if(data=='0') {
USART_Transmit('O');
USART_Transmit('F');
USART_Transmit('F');
USART_Transmit(10);
} // OFF\n
}
}
uart.c
/*
* uart.c
*
* Created: 2021-02-05 오전 10:33:46
* Author: User
*/
#include <avr/io.h>
#include "uart.h"
void USART_Init(void)
{
UCSR0A=0x00; // clear
UCSR0B=(1<<RXEN0) | (1<<TXEN0); // Rx, Tx Enable
UCSR0C=(0<<UCSZ02) | (1<<UCSZ01) | (1<<UCSZ00); // Tx data len : 8-bit
UBRR0H=0;
UBRR0L=103; // baudrate 9600bps
}
unsigned char USART_Receive(void)
{
while(!(UCSR0A & (1<<RXC0))); // Wait for data to be received
return UDR0; // Get and return received data form buffer
}
void USART_Transmit(unsigned char data)
{
while(!(UCSR0A & (1<<UDRE))); // Wait for empty transmit buffer
UDR0=data; // Put data into buffer, sends the data
}
void strTransmit(char *str) {
while (*str) {
USART_Transmit(*str);
str++;
}
USART_Transmit(10);
}
uart.h
/*
* uart.h
*
* Created: 2021-02-05 오전 10:23:17
* Author: User
*/
#ifndef UART_H_
#define UART_H_
void USART_Init(void);
unsigned char USART_Receive(void);
void USART_Transmit(unsigned char data);
void strTransmit(char *str);
#endif /* UART_H_ */
아래 코드 atmega128에 업로드 후 (cp2102 비연결 상태로)
#define F_CPU 16000000UL
#include <avr/io.h>
void USART_Init(void)
{
UCSR0A=0x00; // clear
UCSR0B=(1<<RXEN0) | (1<<TXEN0); // Rx, Tx Enable
UCSR0C=(0<<UCSZ02) | (1<<UCSZ01) | (1<<UCSZ00); // Tx data len : 8-bit
UBRR0H=0;
UBRR0L=51; // baudrate 19200
}
unsigned char USART_Receive(void)
{
while(!(UCSR0A & (1<<RXC0))) // Wait for data to be received
;
return UDR0; // Get and return received data form buffer
}
void USART_Transmit(unsigned char data)
{
while(!(UCSR0A & (1<<UDRE))) // Wait for empty transmit buffer
;
UDR0=data; // Put data into buffer, sends the data
}
int main(void)
{
unsigned char data;
USART_Init();
while (1)
{
data=USART_Receive();
if(data=='1') {
USART_Transmit('O');
USART_Transmit('N');
USART_Transmit(10); // 개행문자
} // ON\n
if(data=='0') {
USART_Transmit('O');
USART_Transmit('F');
USART_Transmit('F');
USART_Transmit(10);
} // OFF\n
}
}
사진과 같이 연결하여 아두이노 시리얼통신창을 열고(아두이노 코드는 상관없음. 장치관리자에서 cp2102 포트 확인하고 아두이노에서 포트 일치하는지 확인할 것) 보드레이트를 위의 코드와 같이 아두이노 시리얼 통신창에도 192000 으로 설정하면 됨
1을 입력하면 on 0을 입력하면 off가 뜸