Today I was trying to incorporate my HC-SR04 Ultrasonic Sensor to trigger various levels of brightness for an LED. This concept will become the basis for how much or how little to accelerate a motor given it's distance from an object. With that in mind I followed a tutorial on YT about this specific sensor to get some generic code then added my own tweaks to fit my needs. What I am having a problem with is that I cannot seem to adjust brightness levels for the LED via PWM. First I'll share my code and explain what I have tried.
#define trigPin 7
#define echoPin 8
void setup ()
{
Serial.begin (9600);
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
}
void loop()
{
int duration;
int distance;
digitalWrite(trigPin,HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) /29.1;
Serial.print(distance);
Serial.println(" cm");
if (distance>200){
Serial.println("Too Far");
}
if (distance<0){
Serial.println("Error");
}
delay(500);
}
As you can see it is set up to read values on the labeled "Echo" on the device. This converts to centimeters and returns a serial value. If the value is greater than or less than a particular value it will print either "Too Far" or "Error" or the given value in centimeters (up to 200cm). Using these values I tried to use PWM on one of the PWM pins (in my case Pin 9 for Nano v3.0). However the brightness would not change, it would either turn on or turn off if the values permitted so. If the value was >20cm it would put out a brightness of about 50, then I increased this for the distance; giving it an increasing brightness as the distance increases.
Given that this did not work I tried to do instead an analogRead on the Echo pin. This returned nothing. I am not sure why an analogRead would not work given that this is a sensor. My thinking is that it needs to digitally read/verify the incoming ultrasonic waves, and as such cannot give an analog value. Noting this though I tried next to digitally read the pin and analogRead the pin. This was a shot in the dark and as expected did nothing.
My question really is how can I get a value that I can use to change brightness in an LED, or speed in a motor, etc.? Also I may have incorrectly used the PWM output. What I used was...
...
if (distance > 20){
analogWrite(pwmpin, value);
{
...
if (distance <50)
{
analogWrite(pwmpin,value);
}
and so on and so forth to adjust brightness.
Any help would be greatly appreciated as overcoming this obstacle will really allow my project to take off. Thank you all again for any help/insight provided. =]
Out of Respect for the Community: Please be aware that I have also posted this thread on element14 in Jeremy Blum's "Ask me" thread.