| 1 | ## Time of flight measurement |
| 2 | |
| 3 | * A 5V relay is opened, and the electromagnet is exposed. Its driver pin is connected to B0. |
| 4 | * The program makes B0 HIGH, and therefore the electromagnet is energized. |
| 5 | * The user now fixes this relay at a fixed height from the floor/table, and attaches |
| 6 | * a small steel ball to it. |
| 7 | * When the user sends binary number 1 via UART, the relay is turned off and the ball will automatically fall down. It should hit a contact switch made with 2 metal |
| 8 | * plates connected between PA0 and GND. |
| 9 | * The microcontroller starts a timer when the relay is turned off, and stops it when the contact switch |
| 10 | * is triggered, thereby measuring the time taken for the ball to travel the known distance. |
| 11 | * Results are returned via the serial port |
| 12 | |
| 13 |  |
| 14 | |
| 15 | |
| 16 | The code |
| 17 | |
| 18 | !!! tip "examples/C/time_of_flight_uart.c" |
| 19 | ```c |
| 20 | #include <avr/kp.h> |
| 21 | #include <avr/interrupt.h> |
| 22 | #include <string.h> |
| 23 | #include <stdlib.h> |
| 24 | |
| 25 | #define PIN_RELAY 0 |
| 26 | #define RELAY_OFF PORTB |= (1<<PIN_RELAY) |
| 27 | #define RELAY_ON PORTB &= ~(1<<PIN_RELAY) |
| 28 | |
| 29 | #define INPUT_HIGH PINA&(1<<0) |
| 30 | |
| 31 | #define PIN_GREEN 5 |
| 32 | #define GREEN_ON PORTD |= (1<<PIN_GREEN) |
| 33 | #define GREEN_OFF PORTD &= ~(1<<PIN_GREEN) |
| 34 | |
| 35 | |
| 36 | int main(void) |
| 37 | { |
| 38 | char buffer[50],cnt; |
| 39 | uint32_t x; |
| 40 | double distance=0; |
| 41 | |
| 42 | uart_init(38400); |
| 43 | DDRA=0; PORTA=1; //input. switch for detecting ball |
| 44 | DDRB=1; // output. for controlling the relay |
| 45 | |
| 46 | DDRD=(1<<PIN_GREEN); |
| 47 | |
| 48 | while(1){ |
| 49 | RELAY_ON; |
| 50 | while(!(UCSRA & (1 <<RXC)) )//wait for serial input |
| 51 | {GREEN_ON;delay_ms(20);GREEN_OFF;delay_ms(20);} ; // Wait for UART and flicker |
| 52 | |
| 53 | if(UDR==1) |
| 54 | RELAY_OFF; |
| 55 | else |
| 56 | continue; |
| 57 | start_timer(); // start the timer using Timer/Counter1 |
| 58 | while(INPUT_HIGH) ; // Wait for the ball to hit the switch between PA0 and GND |
| 59 | x = read_timer(); |
| 60 | |
| 61 | distance = (float)(x)/1000.; //this is actually the time in mS |
| 62 | uart_send_string("Time(ms): "); |
| 63 | ltoa(distance,buffer,10); //10 means decimal. |
| 64 | for(cnt = 0;buffer[cnt]!='\0';cnt++){ |
| 65 | uart_send_byte(buffer[cnt]); |
| 66 | if(cnt>12)break; |
| 67 | } |
| 68 | uart_send_byte('\n'); |
| 69 | |
| 70 | |
| 71 | distance = 0.5*981*distance*distance/1000./1000.; // S = 0.5 * g * t^2 |
| 72 | |
| 73 | uart_send_string("Distance(mm): "); |
| 74 | ltoa(distance*10,buffer,10); // |
| 75 | for(cnt = 0;buffer[cnt]!='\0';cnt++){ |
| 76 | uart_send_byte(buffer[cnt]); |
| 77 | if(cnt>12)break; |
| 78 | } |
| 79 | uart_send_byte('\n'); |
| 80 | } |
| 81 | } |
| 82 | ``` |
| 83 | |
| 84 | ## Serial Monitor Output |
| 85 | |
| 86 |  |