//[소스] getch()함수 만들기 : 인터럽트방식으로 시리얼 통신에서 데이터 수신하기
//ICC-AVR application builder : 2011-01-19 오전 11:44:58
// Target : M128
// Crystal: 16.000Mhz
#include <iom128v.h>
#include <stdio.h>
#include <macros.h>
#define UART0 0
#define UART1 1
#define ON 1
#define OFF 0
volatile int which=UART0;
volatile unsigned char RXdata0, RXdata1;
volatile int RXon0=OFF, RXon1=OFF;
// printf 함수 사용시 추가할 것.
int putchar(char c)
{
if(which==UART0){
while (((UCSR0A>>UDRE0)&0x01) == 0) ; // UDRE, data register empty
UDR0 = c;
}
if(which==UART1){
while (((UCSR1A>>UDRE0)&0x01) == 0) ; // UDRE, data register empty
UDR1 = c;
}
return c;
}
// scanf 함수 사용시 추가할 것.
int getchar(void)
{
if(which==UART0){
while ((UCSR0A & 0x80) == 0);
return UDR0;
}
if(which==UART1){
while ((UCSR1A & 0x80) == 0);
return UDR1;
}
}
// getch 함수 사용시 추가할 것.
int getch(void)
{
unsigned char ch0, ch1;
if(which==UART0){
if(RXon0==ON){
ch0=RXdata0;
RXon0=OFF;
}else ch0=0x00;
return ch0;
}
if(which==UART1){
if(RXon1==ON){
ch1=RXdata1;
RXon1=OFF;
}else ch1=0x00;
return ch1;
}
}
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
PORTE = 0x00;
DDRE = 0x00;
PORTF = 0x00;
DDRF = 0x00;
PORTG = 0x00;
DDRG = 0x00;
}
//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart0_init(void)
{
UCSR0B = 0x00; //disable while setting baud rate
UCSR0A = 0x00;
UCSR0C = 0x06;
UBRR0L = 0x67; //set baud rate lo
UBRR0H = 0x00; //set baud rate hi
UCSR0B = 0x98;
}
#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
//uart has received a character in UDR
RXdata0=UDR0;
RXon0=ON;
}
//UART1 initialize
// desired baud rate:9600
// actual baud rate:9615 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart1_init(void)
{
UCSR1B = 0x00; //disable while setting baud rate
UCSR1A = 0x00;
UCSR1C = 0x06;
UBRR1L = 0x67; //set baud rate lo
UBRR1H = 0x00; //set baud rate hi
UCSR1B = 0x98;
}
#pragma interrupt_handler uart1_rx_isr:iv_USART1_RXC
void uart1_rx_isr(void)
{
//uart has received a character in UDR
RXdata1=UDR1;
RXon1=ON;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
XDIV = 0x00; //xtal divider
XMCRA = 0x00; //external memory
port_init();
uart0_init();
uart1_init();
MCUCR = 0x00;
EICRA = 0x00; //extended ext ints
EICRB = 0x00; //extended ext ints
EIMSK = 0x00;
TIMSK = 0x00; //timer interrupt sources
ETIMSK = 0x00; //extended timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
//
void main(void)
{
init_devices();
//insert your functional code here...
while(1){
if(getch()=='a'){
printf("a pressed");
}
if(getch()=='b'){
printf("b pressed");
}
}
}
