Sarik_Kumpan

ult

Oct 24th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #define F_CPU 16000000UL
  2. #define BAUD 9600
  3. #define MYUBRR ((F_CPU/16/BAUD)-1)
  4.  
  5. #include <avr/io.h>
  6. #include <avr/interrupt.h>
  7. #include <util/delay.h>
  8.  
  9. volatile uint16_t time; // time before send
  10. volatile uint16_t time_cap; // start time capt
  11. volatile char buffer[3]; // store set of int value in char from time capture
  12.  
  13. void USART_Transmit(unsigned char data){
  14.     while( !(UCSR0A & (1<<UDRE0)));
  15.     UDR0 = data;
  16. }
  17. void USART_init(unsigned int ubrr){
  18.     //set baud rate
  19.     UBRR0H = (unsigned char)(ubrr>>8);
  20.     UBRR0L = (unsigned char)ubrr;
  21.     UCSR0A &= 0xFD;
  22.     //Enable transmitter
  23.     UCSR0B = (1<<TXEN0);
  24.     // set frame format 8data 2 stopbit
  25.     UCSR0C = (3<<UCSZ00);
  26. }
  27. void Send_trig(void){
  28.     UDR0 = 0x00;
  29.     PORTB |= 0xF0; //PB0 LOGIC '1'
  30.     _delay_us(10);
  31.     PORTB &= 0x00; //PB0 LOGIC '0'
  32. }
  33. int main(void) {
  34.     TCNT1 = 0;
  35.     USART_init(MYUBRR);
  36.     TCCR1A |= 0x00;// set up timer register TCCR1A - Normal Mode
  37.     TCCR1B |= 0x45;// set up timer register TCCR1B prescaler 1024 and Normal Mode
  38.     DDRB = 0xF0; // set port B pin 4 5 6 7 as output and 0 1 2 3 as input
  39.     TIMSK1 = 0x21; // set interrupt
  40.     TCNT1 = 57000; // start number
  41.     sei(); // open interrupt
  42.     Send_trig();
  43.     while(1){
  44.         // idle loop add after if want another function
  45.     }
  46. }
  47.  
  48.  
  49. ISR(TIMER1_OVF_vect){
  50.     TCCR1B = 0x45; // reset interrupt to rise edge
  51.     Send_trig();
  52.     TCNT1 = 57000;
  53. }
  54.  
  55. ISR(TIMER1_CAPT_vect){
  56.     if(TCCR1B == (0x45)){
  57.         time_cap = TCNT1;
  58.         TCCR1B = 0x05;
  59.     }else{
  60.         TIMSK1 &= ~((1<<ICIE1)|(1<<TOIE1));
  61.         time = TCNT1 - time_cap;
  62.         time = ((time*1024*34600)/F_CPU)/2; // cal time to distance
  63.         itoa(time, buffer, 10);
  64.         for (int i=0; i<sizeof(buffer); i++)
  65.             USART_Transmit(buffer[i]);
  66.         USART_Transmit('c');
  67.         USART_Transmit('m');
  68.         USART_Transmit(0x0a);
  69.         TCCR1B = 0x45;
  70.         TIMSK1|=(1<<ICIE1)|(1<<TOIE1);
  71.         sei();
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment