Hi guys, I'm programming the MaxSonar sonar sensor to sense objects within a range. When an object enters the range, a LED module that is wired up to the PWM pin 11 will light up accordingly with the distance to the sensor. I used the PWM as I have a MOSFET in between the module and the Uno as it needed 3.1V
This is my programm. Every time I try to delay the adapting of the brightness so it won't flicker, the cm measurements will not drop back to real values. Can anyone help me?
#include <math.h>
//Analog pin 1 for reading in the analog voltage from the MaxSonar device.
//PWM pin 11 is for lighting the LED module
//This variable is a constant because the pin will not change throughout execution of this code.
const int anPin = 1;
const int LEDs = 11;
//variables needed to store values
float anVolt, inches, cm;
int sum=0;//Create sum variable so it can be averaged
int avgrange=60;//Quantity of values to average (sample size)
float brightness, oldbrightness, goalbrightness;// for setting the brightness of the LED
float minbright=10.0;//the dimmed light
float maxbright=200.0;//the maximum light the LEDs will gave
float longrange=50.0;//set the outer range
void setup() {
//This opens up a serial connection to shoot the results back to the PC console
Serial.begin(9600);
}
void loop() {
pinMode(LEDs, OUTPUT);
pinMode(anPin, INPUT);
//MaxSonar Analog reads are known to be very sensitive.
//A simple fix is to average out a sample of n readings to get a more consistant reading.\\
//This loop gets 60 reads and averages them
for(int i = 0; i < avgrange ; i++)
{
//Used to read in the analog voltage output that is being sent by the MaxSonar device.
//Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
//Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
anVolt = analogRead(anPin)/2;
sum += anVolt;
delay(7);
}
inches = sum/avgrange;
cm = inches * 2.54;
if (cm < longrange)
{
goalbrightness = minbright + (maxbright - (maxbright * (cm / longrange)));
}
else
{
goalbrightness = minbright;
}
if (abs(goalbrightness - oldbrightness) > 5)
{
brightness += 0.3 * (goalbrightness - oldbrightness);
}
analogWrite(LEDs, brightness);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm, ");
Serial.print(brightness);
Serial.println();
//reset sample total
sum = 0;
oldbrightness = brightness;
//delay(10);
}