



/**********************************************************************************************
 *                                                                                            *
 * Ex2.      :   Using Command Read Hex Distance (RH and Rh)                                  *
 *               By Not Use Interupt Recive Hex Distance                                      *
 *                                                                                            *
 *                                                                                            *
 **********************************************************************************************
 *                                                                                            *
 *                                                                                            *
 * Target MCU     : ATMEL AVR-MEGA128 (ET-BASE AVR ATMEGA128 r3 Board)                        *
 *                : X-TAL : 16 MHz                                                            *
 *                                                                                            *
 * Editor         : AVR Studio 4.15 Build 623                                                 *
 * Compiler       : WinAVR-20081205                                                           *
 * Create By      : Mr. Sittiphol Yooyod (WWW.ETT.CO.TH)                                      *
 * Last Update    : 08/October/2014                                                           *
 *                                                                                            *
 * Port Interface :  --- MCU-AVR Mega 128 ---           --- Module REMOTE DISTANCE ---        *
 *                                                                                            *
 *       Uart0    :  PE0 = RXDO (LineDrive)      Connect      Tx(RS232 Port)                  *  
 *                   PE1 = TXD0 (LineDrive)      Connect      Rx(RS232 Port)                  * 
 *                                                                                            *
 *                                                           Set JP-TTL/RS232 to RS232        *
 *       Baud Rate = 57600 at Clock 16 Mhz                   Set JP-BR (57600)                *
 *                                                           Disable Filter                   *
 *                                                                                            *
 * Port LED       : PB0..PB7(Out)  Connect   LED Common Anode for Show Value Hex Cmm RH       *
 *                  PC0..PC7(Out)  Connect   LED Common Anode for result of Cmm Rh            *
 *                                                                                            *
 *                                        5V                                5V                *
 *                                       -+-                               -+-                *
 *                              \\        |                      \\         |                 * 
 *                   PB0--------|<|-------+         PC0---------|<|---------+                 *  
 *                         .              |                  .              |                 *
 *                         .              |                  .              |                 *
 *                         .              |                  .              |                 *                                                                                           
 *                         .    \\        |                  .   \\         |                 *
 *                   PB7-------|<|--------+        PC7----------|<|---------+                 *
 *                                                                                            * 
 *                                                                                            * 
 *   Operation    : Read Distance (RH-Cmm) Value Integer Out to LED Port PB ,                 *
 *                  Read Distance (Rh-Cmm) Value Integer+Point if Distance                    *
 *                  5.0-5.4 cm  LED Port PC0-PC3 ON ,if Distance 5.5-5.9 LED                  *
 *                  Port PC4-PC7 ON, Distance Other LED PORTC OFF                             *                                                                     
 *                                                                                            *
 **********************************************************************************************/
 

#include <stdio.h>
#include <avr/io.h>                  //define port
#include <compat/deprecated.h>       //call function sbi(port,bit),cbi(port,bit) = Set,Clear bit
#include <avr/pgmspace.h>            //for progrm data to Area Flash
#include <avr/interrupt.h>           //Interrupt Service routine

#define F_CPU 16000000UL             //CPU Clock Frequency (Hz)
#include<util/delay.h>               //util_delay


 char distance[10] ;



 void Echo_Distance(char nm) ;

//-------------- Function Delay_ms ------------------

void delay_ms(unsigned int i)
 {
   for(;i>0;i--)
      _delay_ms(1);
 }




/***************************************************************
 **                 Function use For Printf(UART0)            **
 ***************************************************************/


//--------------------- Prototype function ---------------------

static int uart_putchar(char c,FILE *stream) ;
static FILE uart_str = FDEV_SETUP_STREAM(uart_putchar,NULL,_FDEV_SETUP_WRITE);
void Init_Serial(unsigned int baudrate);




//----------------------- UART0 Putchar -------------------------

static int uart_putchar(char c,FILE *stream)
 {
   if(c=='\a')
     {
     fputs("*ring*\n",stderr) ;
     return 0 ;
     }
   
   if(c=='\n')
     uart_putchar('\r',stream) ;

   loop_until_bit_is_set(UCSR0A,UDRE);
   UDR0 = c ;

   return 0 ;
 }



//------------------- Initial UART0 -----------------------

 static void UART0_Init(void)
 {

   UCSR0B = 0x00      ;     //disable while setting baud rate
   UBRR0H = 0         ;
   UBRR0L = 16        ;     //Set Baud Rate 57600(16) : BURR= [Fosc/[16x(9600)]]-1
  
   UCSR0C = 0x06      ;     //Set Frame format : 8data,NoneParity,1stop bit
   UCSR0B = 0x98      ;     //Uart0 Control Enable Reciver and transmitter,enable Rx INT.
       
   stdout = &uart_str ;     //Set address uart_str to stdout/stdin

   
 }


     

//-------------- Recive Echo Distance ----------------
//
//        nm : Number Data at Recive                 
//----------------------------------------------------

void Echo_Distance(char nm)
 {
 
   unsigned char m,ch ;  
   
     do
      {
       
        loop_until_bit_is_set(UCSR0A,RXC)        ; //Check data in Rx_buffer
        ch = UDR0                                ; //Read data Start Byte

      }while(ch != '#')                          ; //Check Byte Start of Echo cmm('#')
     
      distance[0] = ch                           ; //keep byte start'#'
      nm--                                       ; //Decrease counter Recive Data  
	  for(m=1;m<=nm;m++)                           //Loop keep Recive data all 
       {
         loop_until_bit_is_set(UCSR0A,RXC)       ; //Check data in Rx_buffer
         distance[m] = UDR0                       ; //Keep data to buffer distance[] 
      
       }
   
 }




/********************************************************
 **                                                    **
 **                        MAIN                        **   
 **                                                    **
 ********************************************************/


 int main (void) 
  {
     unsigned char enter = 0x0D ;
	 float ds                   ;
    

    //---------------Initial Port I/O ----------------

     DDRB  = 0xFF      ;        //Set PB0..PB7 = Output For LED      
     DDRC  = 0xFF      ;        //Set PC0..PC7 = Output For LED
   
     PORTB = 0xFF      ;        //Set Default data 0xFF  LED OFF       
     PORTC = 0xFF      ;        //Set Default data 0xFF  LED OFF
  
   
  
    delay_ms(500)      ;  //Wait Module ET-Remote Distance Ready when Power On
       

    UART0_Init()       ;  //Initial Uart0 and Enable Golbal Interrupt


//----------------- Start Sent Command Read Distance --------------

    while(1) 
    {   
      //################---- Sent Command RH ----#################

	  //---For CMM RH Recive Data to Buffer Distance[] by Byte0 keep '#' ,Byte1 Keep Hex Distance or 0xFE(Error), 
	  //                                                  Byte2 Keep  0x0D(Enter)
	  
	  
	  printf("*RH=%c",enter)                      ;  //Sent Command Read Distance Hex Integer  
	   
      Echo_Distance(3)                            ;  //Wait Recive data  3 Byte
	   
      if((distance[0]=='#')&&(distance[2]==0x0D))    //Check '#' Start Byte and 0x0D for end Byte
	   {  
	
	     if(distance[1]== 0xFE)                      //Check data byte1 if is 0xFE(error)  :Distance is not between 3-210 cm
          {
            
            PORTB = 0xFF                          ;  //LED PortB OFF

	      }
         else    //Distance is between 3-210 cm.
	      {
            
			PORTB = ~distance[1]                   ;  //Value Hex Distanc Display on LED PORTB
         
		  }          


         distance[0]=0;         //Clear Buffer keep Distance Byte Start and Byte end
         distance[2]=0;

       }
	
	
     //################---- Sent Command Rh ----#################

	  //---For CMM Rh Recive Data to Buffer Distance[] by Byte0 keep '#' , Byte1 Keep Hex Distance Integer or 0xFE(Error), 
	  //                                                  Byte2 keep Hex Distance point  , Byte3 Keep  0x0D(Enter)
	  
	  
	  printf("*Rh=%c",enter)                      ;  //Sent Command Read Distance Hex Integer+Point   
	   
      Echo_Distance(4)                            ;  //Wait Recive data  4 Byte
	   
      if((distance[0]=='#')&&(distance[3]==0x0D))    //Check '#' Start Byte and 0x0D for end Byte
	   {  
	
	     if(distance[1]== 0xFE)                      //Check data byte1 if is 0xFE(error)  :Distance is not between 3-210 cm
          {
            
            PORTC = 0xFF                          ;  //LED PortC OFF

	      }
         else    //Distance is between 3-210 cm.
	      {
             
            ds = distance[1]+(float)distance[2]/10  ;   //Total data integer+point keep in valiable float for use Calculate 

		    if((ds>=5.0)&&(ds<= 5.4))    //Check if Distance is 5.0-5.4 cm give LED PC0-PC3 ON
			{
              PORTC = 0xF0            ;  //LED PC0..PC3 =ON
 
			}
            if((ds>=5.5)&&(ds<= 5.9))    //Check if Distance is 5.5-5.9 cm. give LED PC4-PC7 ON
		    { 
              PORTC = 0x0F            ;  //LED PC4..PC7 =ON

			}
		   if((ds<5.0)||(ds > 5.9))      //Check if Distance less 5.0 cm. or more 5.9 cm. give LED PC0-PC7 OFF
		    {
              PORTC = 0xFF            ;  //LED PC0..PC7 =OFF

			}
 
		  
		  } //else          


         distance[0]=0;         //Clear Buffer keep Distance Byte Start and Byte end
         distance[2]=0;

       } //if

	}//while

  }



