Tuesday, September 30, 2025

Arduino controlled Useless box

Recently I purchased a "useless box". You turn on a switch and an arm immediatly 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.


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.

// Switch connections
int mainSwitch = 2;
int limitSwitch = 4;

// Motor A connections
int in1 = 8;
int in2 = 7;

// switches are pulled LOW when on
int mainSwitchValue = HIGH;
int limitSwitchValue = HIGH;

enum State {
eStopped,
eForward,
eBackward
};

enum State state = eStopped;

void setup() {
pinMode(LED_BUILTIN, OUTPUT);

// Set switch inputs
pinMode(mainSwitch, INPUT_PULLUP);
pinMode(limitSwitch, INPUT_PULLUP);

// Set the motor control pins to outputs
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);

// Turn off motors - Initial state
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);

// read an unterminated analog pin for the random seed
randomSeed(analogRead(0));
}

void loop() {
mainSwitchValue = digitalRead(mainSwitch);
limitSwitchValue = digitalRead(limitSwitch);

switch(state) {
case eStopped:
stop();
if(mainSwitchValue == LOW) {
state = eForward;
delayRandom();
}
break;
case eForward:
forward();
if(mainSwitchValue == HIGH) {
state = eBackward;
}
break;
case eBackward:
backward();
if(limitSwitchValue == LOW) {
state = eStopped;
}
break;
}
}

void delayRandom() {
int seconds = random(5);
delay(seconds * 1000);
}

void forward() {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}

void backward() {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
}

void stop() {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}

No comments: