Recently I bought an Arduino and entered the world of C++. I also ordered some sensor to got with it . 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 ( 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 .
PS: I attached the .ino file if it feels more comfortable .
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.