I'm building a project that has 2 motors. What I want to do is: When button is pressed (hold down through RF controller) then:
- Run motor A on pwm at 50 for 1 second
- Run motor B on pwm at 255 for 1 second
After that first second
- Run motor A on pwm at 255 until button is released
- Stop motor B.
And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.
I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.
Here is my code:
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <elapsedMillis.h>
// Motor 1
int dir1PinA = 4;
int dir2PinA = 5;
int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed
// Motor 2
int dir1PinB = 7;
int dir2PinB = 8;
int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long previousMillis = 0;
long OnTime1 = 500;
long OnTime2 = 10000;
void setup(){
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();
pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);
}
void CandPush()
{
analogWrite(speedPinA, 50);//Sets speed variable via PWM
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 255);//Sets speed variable via PWM
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
void CandStop()
{
analogWrite(speedPinA, 255);//Sets speed variable via PWM
digitalWrite(dir1PinA, HIGH);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 0);//Sets speed variable via PWM
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, LOW);
}
void Home()
{
analogWrite(speedPinA, 0);//Sets speed variable via PWM
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, LOW);
analogWrite(speedPinB, 255);//Sets speed variable via PWM
digitalWrite(dir1PinB, HIGH);
digitalWrite(dir2PinB, LOW);
}
void loop(){
if (radio.available()){
bool done = false;
while (!done){
done = radio.read(msg, 1);
Serial.println(msg[0]);
if (msg[0] == 111)
{
unsigned long currentMillis = millis();
CandPush();
if(currentMillis - previousMillis >= OnTime1)
{
CandStop();
previousMillis = currentMillis;
}
}
}
}
else
{
Home();
Serial.println("Nothing");
}
}