Here is the code that works fairly well now. I need to work on the delays to better refine it for further distances.
/*
HC-S04 on a DigiSpark with and RGB Shield
Author: Chris Crumpacker
Date: January 2013
Copyright (c) 2013 Chris Crumpacker. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
Sketch Notes: The HC-S04 Ultrasonic detector is attached to Pins 3 and 5.
The RGB shield is set to use pins 0, 1, and 4 for PWM.
As something comes closer to the detector the RGB goes from green to red.
*/
#define trigPin 3
#define echoPin 5
byte RED = 0;
byte GREEN = 1;
byte BLUE = 4;
int greenValue = 0;
int redValue = 0;
long distanceMax = 40;
long distanceMin = 0;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
//sonicCalibrate();
}
//Function to check the distance in centimeters, This explains the theory here: http://trollmaker.com/article3/arduino-and-hc-sr04-ultrasonic-sensor
long sonicDistance(){
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //Ping
delayMicroseconds(1000); //Need to futs with this value now to make it work better on digispark
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); //Boop
distance = (duration/2) / 29.1;
return distance;
}
//Function for setting the color of the RGB LED depending on the distance
void setColor(long distance){
digitalWrite(BLUE, LOW); //Make sure the Blue LED is off
greenValue = map(distance, distanceMin, distanceMax, 0, 255); //Map the distance range to a range of 0 to 255 to the pwm value for the Green LED
redValue = 255 - greenValue; //Make the pwm value for the Red LED the oppisite of the Green LED so it fades
analogWrite(GREEN, greenValue);
analogWrite(RED, redValue);
}
void loop() {
long distance = sonicDistance();
if (distance >= distanceMax || distance <= distanceMin){
//Out of range, turn the LED blue
digitalWrite(GREEN, LOW);
digitalWrite(RED, LOW);
analogWrite(BLUE, 100);
}
else {
setColor(distance);
}
delay(2000);
}