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;


void setup() {
    pinMode(LED_PIN, OUTPUT);

void loop() {
    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(" ");
    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?

  • The maximum value you can pass to analogWrite() is 255, not 1024, unless you are using something that isn't an Arduino.
    – Majenko
    Jun 25, 2016 at 20:21
  • well that explains a lot! What am I think that takes 1024?
    – ntgCleaner
    Jun 25, 2016 at 20:43
  • The ADC can return a value between 0 and 1023 - that's analogRead(). That may be what you are thinking of.
    – Majenko
    Jun 25, 2016 at 20:44
  • Ah yes! You're correct. I just got back into doing Arduino stuff after a years absence. Thank you!
    – ntgCleaner
    Jun 25, 2016 at 20:45
  • To be fair, analogWrite() on a ESP8266 takes values up to 1023 by default, but then I suppose that falls under "isn't an Arduino". Jun 25, 2016 at 22:57

1 Answer 1


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.