ECE 4180 Lab 3 Part 1 Extra Credit

Dependencies:   HC_SR04_Ultrasonic_Library mbed

Fork of LPC1768_HCSR04_HelloWorld by jim hamblen

Committer:
abraha2d
Date:
Tue Oct 16 00:23:27 2018 +0000
Revision:
3:3ee23d961329
Parent:
2:3566c2d1e86b
Save point

Who changed what in which revision?

UserRevisionLine numberNew contents of line
abraha2d 3:3ee23d961329 1 //Theremin style demo using HC-SR04 Sonar and a speaker
abraha2d 3:3ee23d961329 2 // moving a hand away/towards sonar changes audio frequency
ejteb 0:1704ea055c4f 3 #include "mbed.h"
ejteb 0:1704ea055c4f 4 #include "ultrasonic.h"
abraha2d 3:3ee23d961329 5
abraha2d 3:3ee23d961329 6 DigitalOut audio(p26); //output to speaker amp or audio jack
abraha2d 3:3ee23d961329 7 DigitalOut led(LED1);
abraha2d 3:3ee23d961329 8 DigitalOut led2(LED2);
abraha2d 3:3ee23d961329 9
abraha2d 3:3ee23d961329 10 Timeout cycle;
abraha2d 3:3ee23d961329 11
abraha2d 3:3ee23d961329 12 volatile int half_cycle_time = 1;
abraha2d 3:3ee23d961329 13
abraha2d 3:3ee23d961329 14 //two calls to this interrupt routine generates a square wave
abraha2d 3:3ee23d961329 15 void toggle_interrupt()
ejteb 0:1704ea055c4f 16 {
abraha2d 3:3ee23d961329 17 if (half_cycle_time>22000) audio=0; //mute if nothing in range
abraha2d 3:3ee23d961329 18 else audio = !audio; //toggle to make half a square wave
abraha2d 3:3ee23d961329 19 led = !led;
abraha2d 3:3ee23d961329 20 cycle.detach();
abraha2d 3:3ee23d961329 21 //update time for interrupt activation -change frequency of square wave
abraha2d 3:3ee23d961329 22 cycle.attach_us(&toggle_interrupt, half_cycle_time);
ejteb 0:1704ea055c4f 23 }
abraha2d 3:3ee23d961329 24 void newdist(int distance)
abraha2d 3:3ee23d961329 25 {
abraha2d 3:3ee23d961329 26 //update frequency based on new sonar data
abraha2d 3:3ee23d961329 27 led2 = !led2;
abraha2d 3:3ee23d961329 28 half_cycle_time = distance<<3;
abraha2d 3:3ee23d961329 29 }
abraha2d 3:3ee23d961329 30 //HC-SR04 Sonar module
abraha2d 3:3ee23d961329 31 ultrasonic mu(p6, p7, .07, 1, &newdist);
abraha2d 3:3ee23d961329 32 //Set the trigger pin to p6 and the echo pin to p7
abraha2d 3:3ee23d961329 33 //have updates every .07 seconds and a timeout after 1
abraha2d 3:3ee23d961329 34 //second, and call newdist when the distance changes
abraha2d 3:3ee23d961329 35
ejteb 0:1704ea055c4f 36 int main()
ejteb 0:1704ea055c4f 37 {
abraha2d 3:3ee23d961329 38 audio = 0;
abraha2d 3:3ee23d961329 39 led = 0;
abraha2d 3:3ee23d961329 40 cycle.attach(&toggle_interrupt, half_cycle_time);
abraha2d 3:3ee23d961329 41 mu.startUpdates();//start measuring the distance with the sonar
abraha2d 3:3ee23d961329 42 while(1) {
ejteb 1:4a5586eb1765 43 //Do something else here
abraha2d 3:3ee23d961329 44 mu.checkDistance();
abraha2d 3:3ee23d961329 45 //call checkDistance() as much as possible, as this is where
abraha2d 3:3ee23d961329 46 //the class checks if dist needs to be called.
ejteb 0:1704ea055c4f 47 }
ejteb 0:1704ea055c4f 48 }