Hi,
I'm having trouble figuring out how to integrate a sensor into my state machine.
An ultrasonic distance sensor should signal and listen until something comes within range (this part works fine). Once something is in range of the sensor, a state machine turns on one series of nitiniol springs and piezo buzzers, lets them rest, then turns on a second series and lets them rest before listening to the sensor again.
My current code is here: Sonar-actuated-SMA-with-Sound-Effects/Placeholder_1_7.ino at master · silicontongue/Sonar-actuated-SMA-with-Sound-Effects · GitHub
Initially I made everything part of the state machine. State 0 was the sensor loop, State 1 was a conditional statement for when something was in range of the sensor...
switch (state)
{
case S_sensorRead:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(5);
digitalWrite(trigPin, LOW); //sends out ping
duration = pulseIn(echoPin, HIGH); //reads the echo
cm = microsecondsToCentimeters(duration); //time to distance
Serial.print(cm);
Serial.print("cm");
Serial.println();
ts = millis();
state = S_sensorTrigger;
break;
case S_sensorTrigger:
if ((cm <= 40) && (cm >= 2)) {
Serial.print("starting state machine");
state = S_seriesAOn;
}
else {
state = S_sensorRead;
}
break;
and the rest of the states continued from there, but I couldn't seem to get past the first state. If I omit the else statement, it gets hung up on the second state indefinitely. Any ideas?
In my current code, I've tried pulling the sensor activity out of the state machine and putting it at the beginning of the loop. I just can't figure out how to actually call the state machine when a condition is met. Am I on the right track with this?
A final issue, there's obviously an issue with my white noise generator. Either I'm not calling it properly, or what was working as stand alone code doesn't fit with this code.
What I'm trying to do is have the buzzers emit white noise whenever a spring is on. Calling generateNoise(frequency) has worked when I've tested that portion of the code on its own, but it isn't working here. Could the microdelay be causing an issue or is there just a better way to call it?
Any advice on this is greatly appreciated!