Recently I purchased a "useless box". You turn on a switch and an arm immedietly pops out and turns the switch back off again. It was a bit boring so I bought an L298N DC motor controller and use an Arduino Nano. The motor controller is an H bridge which can switch the polarity going to the motor. I didn't bother with the protection diodes and so far it hasn't died.
It's built on strip board.
Here's how it behaves with a random delay.
The code has to read the main switch and a limit switch which is closed when the arm is "home" inside the box. I implemented the logic as a little state machine. To get a random number on an Arduino for the delay, an unterminated A/D pin is read to provide the random seed.
Here's the final form boxed up. I power it from a USB power bank. Amazingly the Arduino is able to power the motor just fine.
I tried to vary the speed of the motor by driving it with pulse width modulation but this motor doesn't seem to vary with PWM.
My head hurt writing the code for the required logic until I rememberd the state machine. This is the way.
// Switch connections
constint kMainSwitch = 2;
constint kLimitSwitch = 4;
// Motor A connections
constint kIn1 = 8;
constint kIn2 = 7;
// switches are pulled LOW when on
int gMainSwitchValue = HIGH;
int gLimitSwitchValue = HIGH;
// on the first go, don't delay
int gFirstGo = true;
enum State {
eStopped,
eForward,
eBackward
};
enum State state = eStopped;
voidsetup(){
pinMode(LED_BUILTIN, OUTPUT);
// Set switch inputs
pinMode(kMainSwitch, INPUT_PULLUP);
pinMode(kLimitSwitch, INPUT_PULLUP);
// Set the motor control pins to outputs
pinMode(kIn1, OUTPUT);
pinMode(kIn2, OUTPUT);
// Turn off motors - Initial state
digitalWrite(kIn1, LOW);
digitalWrite(kIn2, LOW);
// read an unterminated analog pin for the random seed
randomSeed(analogRead(0));
}
voidloop(){
gMainSwitchValue = digitalRead(kMainSwitch);
gLimitSwitchValue = digitalRead(kLimitSwitch);
switch(state){
case eStopped:
stop();
if(gMainSwitchValue == LOW){
state = eForward;
if(gFirstGo == true){
gFirstGo = false;
}else{
delayRandom();
}
}
break;
case eForward:
forward();
if(gMainSwitchValue == HIGH){
state = eBackward;
}
break;
case eBackward:
backward();
if(gLimitSwitchValue == LOW){
state = eStopped;
}
break;
}
}
voiddelayRandom(){
int seconds = random(5);
delay(seconds * 1000);
}
voidforward(){
digitalWrite(kIn1, HIGH);
// Tried slow motor with PWM but doesn't have much effect
No comments:
Post a Comment