Hey! I am a newbie to arduino, but am currently creating a project where once an ir sensor is triggered, a dc motor goes on for 4 seconds, and an mp3 decoder goes on for 20. i also need it so that once a microswitch is not pressed, a motor turns on, and vice versa. here is my circuit diagram (fritzing doesnt have the option for a microswitch or mp3 decoder so the button would actually be a microswitch, and the 2 wires going to nowhere on the left would be going to my mp3 decoder.
This code i mostly got from someone else as i am not an expert at millis, so if you could try and read through it and tell me if something looks off that would be great. currently my first motor is just staying on. `#define SENSOR_PIN 6
#define MOTOR_PIN 11
#define MP3 4
#define Switch 8
#define Motortwo 13
int SwitchValue = 0;
void setup() {
pinMode(SENSOR_PIN, INPUT);
pinMode(MOTOR_PIN, OUTPUT);
pinMode(MP3, OUTPUT);
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(MP3, LOW);
}
struct event_t {
int pin;
int on;
int duration;
unsigned long timer;
event_t(int pin, int duration) :
pin(pin),
duration(duration)
{ on = false; timer = 0; }
} schedule[2] = {
{ MOTOR_PIN, 4000 },
{ MP3, 20000 }
};
void item_state(int which, bool bOn) {
schedule[which].on = bOn;
if (bOn) {
digitalWrite(schedule[which].pin, HIGH);
schedule[which].timer = millis() + schedule[which].duration;
} else {
digitalWrite(schedule[which].pin, LOW);
schedule[which].timer = 0;
}
}
void sequence(int &which, bool &active) {
if (!schedule[which].on) { // if not started
active = true;
item_state(which, active);
} else {
if (millis() >= schedule[which].timer) {
item_state(which, false);
if (++which != sizeof(schedule)) {
item_state(which, true);
} else {
which = 0;
active = false;
}
}
}
}
void loop() {
SwitchValue = digitalRead(Switch);
if(SwitchValue !=0){
digitalWrite(Motortwo, LOW);
}
else{(Motortwo, HIGH); }
static bool bActive = false;
static int activeEvent = 0;
if (digitalRead(SENSOR_PIN) == HIGH) {
// don't start if already active
if (!bActive) {
bActive = true;
sequence(activeEvent, bActive);
}
}
// The sequence(...) function does not block.
// Continue to do other stuff here asynchronously.
// bActive will be set to false when sequence has completed.
}` Thank you all so much!