I have set up an LED who's brightness is controlled by a sonar sensor. The sonar works well and I can see the values coming from it through the serial monitor. The LED fades until about 700 using analogWrite
#include <NewPing.h>
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 5000
int LED_PIN = 3;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(50);
int uS = sonar.ping();
long int max_uS = 8000;
float brightness = (1-(((float)uS/(float)max_uS)))*1024;
if(brightness < 0){
brightness = 0;
}
Serial.print("Distance: ");
Serial.print(uS / US_ROUNDTRIP_IN);
Serial.print("\" ");
Serial.print(uS);
Serial.print(" ");
Serial.println(brightness, 5);
analogWrite(LED_PIN, brightness);
}
When I view the serial monitor, I've made it output a line that looks like this:
Distance: 10" 1500 830.00000
830 is the number I'm using for my analogWrite. I can move my hand farther and closer to the distance sensor and when I do, the light fades, but after 13" (which is brightness = 774) the LED looks like it turns back on high.
Between 1"-13" it fades very smoothly, except at 13" the light is almost out, then at about 14" it turns on again almost at full brightness and is very hit or miss from there. Even though the numbers in the serial monitor are holding steady.
Any reason for this?
analogWrite()is 255, not 1024, unless you are using something that isn't an Arduino. – Majenko Jun 25 '16 at 20:21analogRead(). That may be what you are thinking of. – Majenko Jun 25 '16 at 20:44analogWrite()on a ESP8266 takes values up to 1023 by default, but then I suppose that falls under "isn't an Arduino". – Ignacio Vazquez-Abrams Jun 25 '16 at 22:57