Advertisement
Francoo

Ultrasonic Ruler

May 31st, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <main.h>
  2. #include <flex_lcd.c>
  3.  
  4. // Ad hoc programming, only for testing purpose (demo).
  5. // Needs to be revised before using.
  6.  
  7. #define trigger PIN_A1
  8. #define echo PIN_A0
  9. #define button PIN_B0
  10.  
  11. int32 overflow;
  12.  
  13. #INT_TIMER1
  14. void tm1_int(){
  15.    overflow++;
  16. }
  17.  
  18. long tr_strobe(){
  19.    set_timer1(0);
  20.    while( input(echo) );
  21.    output_high(trigger);
  22.    delay_ms(1);
  23.    output_low(trigger);
  24.    while( ! input(echo) );
  25.    setup_timer_1( T1_INTERNAL |  T1_DIV_BY_8 );
  26.    while( input(echo) );
  27.    setup_timer_1( T1_DISABLED |  T1_DIV_BY_8 );
  28.    return(get_timer1());
  29. }
  30.  
  31. void main()
  32. {
  33.    lcd_init();
  34.    port_b_pullups(true);
  35.    printf(lcd_putc, "Hello World!\nPress Button.");
  36.    while( input(button) );
  37.    lcd_init();
  38.    
  39.    int32 ctime;
  40.    int distance_m;
  41.    int32 distance_cm;
  42.    int32 time_ms;
  43.    int time_s;
  44.    
  45.    enable_interrupts(GLOBAL);
  46.    enable_interrupts(INT_TIMER1);
  47.    printf(lcd_putc, "Time:\nDist.:");
  48.    
  49.    
  50.    while(true){
  51.       set_timer1(0);
  52.       overflow=0;
  53.       ctime=tr_strobe();
  54.       ctime = (ctime | (overflow<<16));
  55.       ctime = (ctime << 3);
  56.       ctime = ctime / 10;
  57.       time_s = ctime / 100000;
  58.       time_ms = ctime - time_s * 100000;
  59.       lcd_gotoxy(6,1);
  60.       printf(lcd_putc, "%3.1u.%05lu s", time_s, time_ms);
  61.       lcd_gotoxy(7,0);
  62.       if(time_s==0 && time_ms < 40000){
  63.          distance_m = 17 * ( ( ctime + 5 ) / 10 ) / 1000;
  64.          distance_cm = ( ( 17 * ctime + 5 ) / 10 - 1000 * distance_m + 5 ) / 10;
  65.          printf(lcd_putc, "%5.1u.%02lu m", distance_m, distance_cm);
  66.       }
  67.       else {
  68.          lcd_putc("   --.-- m");
  69.       }
  70.       while(input(PIN_B0));
  71.      
  72.    }
  73.    
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement