0

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?

ntgCleaner
  • 125
  • 6

1 Answers1

2

The maximum value you can pass to analogWrite() is 255. Anything higher than that will wrap around back to 0.

You should scale your value to fit into 0-255 instead of 0-1024.

Majenko
  • 105,095
  • 5
  • 79
  • 137