I'm incredibly new to coding and it is not my forte at all but I'm trying! I want to set up a jig that runs four 3.3V motors at the same time for 2.5 mins when turned on by a toggle switch. I have managed to get them all running correctly with the switch and even them for 2.5 mins if I use a delay but I want to be able to press the toggle switch again during the 2.5 mins and turn the motor off (then when re pressed it starts the 2.5 mins running again).
int motorState1=0;
int motorPin1=13;
int motorState2=0;
int motorPin2=10;
int motorState3=0;
int motorPin3=8;
int motorState4=0;
int motorPin4=6;
int buttonPin=2;
int buttonNew;
int buttonOld=1;
int dt=100;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonNew=digitalRead (buttonPin);
if(buttonOld==0 && buttonNew== 1) {
if (motorState1== 0) {
digitalWrite (motorPin1, HIGH);
digitalWrite (motorPin2, HIGH);
digitalWrite (motorPin3, HIGH);
digitalWrite (motorPin4, HIGH);
motorState1=1;
motorState2=1;
motorState3=1;
motorState4=1;
}
else {
digitalWrite(motorPin1,LOW);
digitalWrite (motorPin2, LOW);
digitalWrite(motorPin3,LOW);
digitalWrite (motorPin4, LOW);
motorState1=0;
motorState2=0;
motorState3=0;
motorState4=0;
}
}
buttonOld=buttonNew;
delay (dt);
}
This is my code ^^^ I followed this guy's code and then just swapped the LEDs for motors.
I've searched around and it seems like millis is the answer but I just do not know how to incorporate it properly!
Any help would be much much much appreciated. Hope this is clear enough and makes sense!
I had read those but gave them a re read as the first time I didn't understand. I am still unsure how I would include millis into my needs but am having a go.
I tried your part 3 and 4 codes and all I was receiving on the monitor were the symbols shown in the screenshots. Any clue why?
Sorry I am very new to this so seems a little silly to make such a basic mistake!
Why do you choose a different baud rate than the standard one, I've only seen other codes with 9600, so am curious as to why?
As you use byte quite a lot in the codes, why that over int? I looked up the answer but couldn't really understand it haha so if you could explain it very simply that would be amazing!
115200 is my standard baud rate. Most/all of the Arduino examples were written a while ago and use 9600 as their standard. You can never have too may standards
If you ant you can use much faster baud rates, such as 2000000, yes, 2 million, if you want to and your connected hardware supports it.
As to int vs byte, as doug has illustrated it saves memory. Not so important with Mickey Mouse example sketches but a good habit to get into, as RAM is a precious resource on most microprocessors, is to use the smallest data type that will do the job in hand