I`m trying to make a LED dimmer using an ultrasonic sensor

Recently I bought an Arduino and entered the world of C++. I also ordered some sensor to got with it :smiley: . I tested my new HC-SR04 ultrasonic sensor and it works. Now, I`m trying to dim a LED like this: If the value read by the sensor is higher than 255 I want the LED -> 255 ( analog ), If the value read is lower than 255 I want the LED -> that value ( ex: Arduino gets 150 from sensor, analogWrite(13,150) ). I tried to do this alone ( a little help from the internet ) but the LED is not switching on :frowning: ( Serial Monitor gets the right values ). Here is the part where I am asking for your help. Code here:

#include <NewPing.h>


#define TRIGGER_PIN 12
#define ECHO_PIN 11 
#define MAX_DISTANCE 400 

int i;


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

void setup() {
Serial.begin(115200); 
pinMode(13,OUTPUT); 
}


void loop() {
delay(50);between pings.
unsigned int i = sonar.ping_cm(); 
Serial.print(F("Distanta: "));
Serial.print( i ); 
Serial.println(F("cm"));

 if(i>255)
  {analogWrite(13,255);
 analogWrite(13,i);}


}

Thank you in advance.I don`t want the full code, i just want some indications as I want to learn alone :smiley: .
PS: I attached the .ino file if it feels more comfortable :smiley: .

ultrasonic_led2.ino (977 Bytes)

You can use the map function to shorten or extend a variable.

Delta_G:
Note: If you call analogWrite with a value greater than 255 it doesn't break, it just turns the pin on fully.

I didnt know that if I call analog with greater than 255 it wont break. I thought that it wont turn on or the code wont work. Thank you!

Delta_G:
Why do you have two different variables named i in your sketch?

if(i>255)

{analogWrite(13,255);
analogWrite(13,i);}

Because I wanted to dim the led as the distance decreases.

Note: If you call analogWrite with a value greater than 255 it doesn't break, it just turns the pin on fully.

I disagree - only the lower 8 bits are used, so you end up with odd results.

For example, here is analogWrite() output with arduino pin to 10K+4.7uF cap to Gnd as a lowpass filter, looking at the RC junction.
The output was stepped from 0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 0.

Before this I had used 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 0
(because analogRead returns 0-1023, so I had used that for analogWrite)
and saw results that were oddly jumping up & down.
0 ok
100 ok
200 ok
300 - lower than 100 (300 = 0x12C, and 0x2C = 44 decimal)
400 - (144 decimal result)
500 - (244 decimal result)
600 - (88 decimal result)
700 - (188 decimal result)
800 - (32 decimal result)
900 - (132 decimal result)
1000 - (232 decimal result)

So I had 10 levels, they just didn't make sense on the scope until I realized that it was just using 8 bits of what I had sent.