/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define defMainDelay 5
#define defMaxDelay 16
long delayVal;
long lastDelayVal = -1;
long noisyDelayVal;
long threshold_up, threshold_down = 0;
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int hysteresis(long analog){
int accept = 11;
int reject = 0;
if(analog > threshold_up || analog < threshold_down){
threshold_up = (analog < 1024)? analog + 1 : 1024;
threshold_down = (analog > 0)? analog - 1 : 0;
return accept;
}
else return reject;
}
int main() {
// swipe all pot values
for (long analogRead = 2; analogRead < 1024; analogRead++){
// noiseless delayVal update
delayVal = round(map(analogRead, 0, 1023, defMainDelay, defMaxDelay));
if (delayVal > lastDelayVal){
printf("current delayVal is %ld\n", delayVal);
lastDelayVal = delayVal;
}
// subtract 1 bit of noise
long noisyAnalogRead = analogRead - 1;
if(hysteresis(noisyAnalogRead) == 1) {
noisyDelayVal = round(map(noisyAnalogRead, 0, 1023, defMainDelay, defMaxDelay));
// if there's flicker the mapped value will be less than the noiseless value.
if (noisyDelayVal < delayVal){
printf("%ld %ld %s\n", analogRead, noisyDelayVal, "<- flicker");
}
}
// add 1 bit of noise
noisyAnalogRead = analogRead + 1;
if(hysteresis(noisyAnalogRead) == 1) {
noisyDelayVal = round(map(noisyAnalogRead, 0, 1023, defMainDelay, defMaxDelay));
// if there's flicker the mapped value will be more than the noiseless value.
if (noisyDelayVal > delayVal){
printf("%ld %ld %s\n", analogRead, noisyDelayVal, "<- flicker");
}
}
}
return 0;
}