SHOW:
|
|
- or go back to the newest paste.
| 1 | #include <NewPing.h> | |
| 2 | #include <NewTone.h> | |
| 3 | ||
| 4 | // Select which PWM-capable pins are to be used. | |
| 5 | #define RED_PIN 10 | |
| 6 | #define GREEN_PIN 11 | |
| 7 | #define BLUE_PIN 9 | |
| 8 | ||
| 9 | #define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor. | |
| 10 | #define ECHO_PIN 7 // Arduino pin tied to echo pin on the ultrasonic sensor. | |
| 11 | #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). | |
| 12 | ||
| 13 | NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. | |
| 14 | boolean triggered = false; | |
| 15 | ||
| 16 | ||
| 17 | #define ALARM 3 | |
| 18 | float sinVal; | |
| 19 | int toneVal; | |
| 20 | ||
| 21 | void setup(){
| |
| 22 | ||
| 23 | //set pinModes for RGB strip | |
| 24 | pinMode(RED_PIN,OUTPUT); | |
| 25 | pinMode(BLUE_PIN,OUTPUT); | |
| 26 | pinMode(GREEN_PIN,OUTPUT); | |
| 27 | ||
| 28 | pinMode(ALARM, OUTPUT); | |
| 29 | ||
| 30 | //reset lights | |
| 31 | analogWrite(RED_PIN,0); | |
| 32 | analogWrite(BLUE_PIN,0); | |
| 33 | analogWrite(RED_PIN,0); | |
| 34 | ||
| 35 | delay(5000); | |
| 36 | Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results. | |
| 37 | ||
| 38 | ||
| 39 | } | |
| 40 | ||
| 41 | void loop(){
| |
| 42 | if(triggered == true){
| |
| 43 | alarm(); | |
| 44 | } | |
| 45 | else{
| |
| 46 | delay(50);// Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. | |
| 47 | unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). | |
| 48 | unsigned int distance = uS / US_ROUNDTRIP_CM; | |
| 49 | Serial.println(distance); | |
| 50 | if(distance < 50){
| |
| 51 | triggered = true; | |
| 52 | } | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | void alarm(){
| |
| 57 | color(255,0,0); //red | |
| 58 | delay(100); | |
| 59 | color(255,255,0); //yelow | |
| 60 | delay(100); | |
| 61 | ||
| 62 | for (int x=0; x<180; x++) {
| |
| 63 | // convert degrees to radians then obtain sin value | |
| 64 | sinVal = (sin(x*(3.1412/180))); | |
| 65 | // generate a frequency from the sin value | |
| 66 | toneVal = 2000+(int(sinVal*1000)); | |
| 67 | NewTone(ALARM, toneVal); | |
| 68 | } | |
| 69 | } | |
| 70 | ||
| 71 | //helper function enabling us to send a colour in one command | |
| 72 | void color (unsigned char red, unsigned char green, unsigned char blue) // the color generating function | |
| 73 | {
| |
| 74 | analogWrite(RED_PIN, red); | |
| 75 | analogWrite(BLUE_PIN, blue); | |
| 76 | analogWrite(GREEN_PIN, green); | |
| 77 | } |