/***
  UARTとDigital Inputを使ってボタンを押したら"y"、離したら"n"を送る。
  
  CPU: ATMEGA8 8MHz(内蔵)
  Compiler: WinAVR20050214(AVR-GCC3.4.3)
  Date: 2005/4/7
  Author: Yoshiro Sugano
  Special Thanks to: Sho Hashimoto
  WebSite:   
  ***/

#include <avr/io.h>

#define TRUE 1
#define FALSE 0

#define FOSC 8000000 // 8MHz
#define BAUD 9600 // 9600bps
#define MYUBRR FOSC/16/BAUD-1 // UART分周率

#define sbi(PORT,BIT) PORT|=_BV(BIT) // PORTの指定BITに1をセット
#define cbi(PORT,BIT) PORT&=~_BV(BIT) // PORTの指定BITをクリア


/* No Operation */
void nop(int count){
  int i;
  for(i = 0; i < count*100; i++){
  }
}

/* PORT設定 */
void port_init(void){
  //sbi(DDRB, PB0);
  DDRB = 0xfe;//PB0だけ入力
  sbi(PORTB, PB1); // PB1電源確認LED
}

/* USART設定 */
void usart_init(unsigned int baud){
  UBRRH = (unsigned char)(baud>>8); // ボーレート上位
  UBRRL = (unsigned char)baud; // ボーレート下位
  UCSRB = (1<<RXEN)|(1<<TXEN); // 送受信許可
  UCSRC = (1<<URSEL)|(3<<UCSZ0)|(1<<USBS)|(3<<UPM0);
  // フレーム設定 非同期通信 8ビット 2ストップビット 奇数パリティ
}

int main(void){
  port_init(); // PORT設定
  usart_init(MYUBRR); // USART設定
  
  for(;;){
    if(PINB&1){
      nop(30); // ちょっと停止
      UDR = 'y'; // 1文字送信
      sbi(PORTB, PB2); // PB2ボタン確認LEDをON
    }else{
      nop(30); // ちょっと停止
      UDR = 'n'; // 1文字送信
      cbi(PORTB, PB2); // PB2ボタン確認LEDをOFF
    }
  }
}
