Covering for margin of error in an input value
I am trying to create a program that can convert a duration to morse. And i cannot figure out why the if statements in durations2morse aren't printing the relevant snippet, I wanted to cover for a margin of error between input values. The add noise function was used to add variability for testing.
const int abcLength = 19;
int abcDurations[abcLength] = {420,-420,1260,-2940,1260,-420,420,-420,420,-420,420,-2940,1260,-420,420,-420,1260,-420,420};
void setup() {
Serial.begin(9600);
Serial.println("");
randomSeed(analogRead(0));
duration2morse(abcDurations,abcLength);
}
String duration2morse(int* durations, int length) {
const float Variability = 0.1;
int shortestDuration = 20000;
addNoise(durations, length, Variability);
for(int i=0; i < length; i++) {
if(abs(durations[i]) < shortestDuration) {
shortestDuration = durations[i];
}
}
for(int i=0; i < length; i++) {
Serial.print(durations[i] > shortestDuration * (1 - Variability));
if(durations[i] > shortestDuration * (1 - Variability) && durations[i] < shortestDuration * (1 + Variability)) {
Serial.print(".");
} else if(durations[i] > shortestDuration * (3 - Variability) && durations[i] < shortestDuration * (3 + Variability)) {
Serial.print("-");
} else if(abs(durations[i]) > shortestDuration * (3 - Variability) && abs(durations[i]) < shortestDuration * (3 + Variability)) {
Serial.print("/");
} else if(abs(durations[i]) > shortestDuration * (7 - Variability) && abs(durations[i]) < shortestDuration * (7 + Variability)) {
Serial.print(" ");
} else {
Serial.println("miss");
}
}
}
void addNoise(int* array, int length, float fraction) {
for(int i=0; i < length; i++) {
long variability = random(fraction * 100);
long plusMinus = random(0,1);
if(plusMinus == 0) {
array[i] = array[i] + variability ;
} else if(plusMinus == 1) {
array[i] = array[i] - variability;
}
}
}