I need to make and Arduino sketch , which samples an analog input, potentionmeter and is able to do these things:
- Filter high frequency noise, ussing running mean.
- Mapping the 10-bit filtered input to the 8-bit range of PWM output.
- Print serial message every 8sec with current PWM output, without delay function.
Serial print time is messed up for me, it does not work in my code. It just runs constantly without 8 sec delay.
It is a bit messed up code, probably I put too much information and code parts. But I tried to divide it in three parts by the exercise: running mean, mapping, serial print
I chose to add LED, that there would be something to control with pot.
Thank you for your help.
const int ledPin = 13; // LED connected to digital pin 13
const int analogInPin = A0; //analog input pin for potentiometer
const int numReadings = 10; //determing the size of the readings array
int inputpotValue = 0; //value read from the pot
int outputValue = 0; //value output to the PWM
int readings[numReadings];//the readings from the analog input
int index = 0;//the index of the current reading
int total = 0;//the running total
int average = 0; //the average
long previousMillis = 0;//will store the last time pot was updated
long interval = 8000;//interval at which to print mapping data
void setup() {
//initialize serial communication with computer:
Serial.begin(9600);
//initialize all the readings to 0(running mean part):
for(int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
//RUNNING MEAN PART
//subtract the last reading:
total = total - readings[index];
//read from sensor
readings[index] = analogRead(analogInPin);
//add the reading to the total:
total = total + readings[index];
//advance to the next position in the array:
index = index + 1;
//in the end of the array
if (index >= numReadings)
//wrap to the beginning:
index = 0;
//calculate the average:
average = total / numReadings;
//MAPPING PART
//read the analog in value:
inputpotValue = analogRead(analogInPin);
//map it to the run of the analog out
outputValue = map(inputpotValue, 0, 1023, 0, 255);
//change the analog out value
analogWrite(ledPin, outputValue);
//serial print will show data
Serial.print("pot = " );
Serial.print(inputpotValue);
Serial.print("\t led = ");
Serial.println(outputValue);
//DELAY PART IN MILLIS 8SEC
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > interval);
//save the last time message was printed
previousMillis = currentMillis;
}