ASK AN EDUCATOR! “How can I control a security gate with my Arduino?”

Freddie asks:

I have a question about Arduino DC Motor Control:

To make the motor run forward and backwards is not a problem.
Also I am not concerned about the speed of the motor.
The H Bridge configuration is also not a problem.

But, to time the motor on and off seems not to be a regular discussion on the net.

I need to open and close a security gate simply by using a push button (like those tiny square ones always used with arduino diagrams and tutorials).
If the button is pressed momentarily, the motor needs to run one direction for e.g. five seconds and stop in its tracks and must wait for my next button press.
If I press the button again, the motor must reverse direction to its default position (same timing span ) and stop in its tracks again. So, it is purely timed on and off in either direction.

On the net are lots of code available for the control of the H bridge including the button state. But with all of those codes the motor directions are not timed. They simply forward or reverse continuously.

With my limited knowledge of coding in C (Arduino), I some how feel the delay instruction is not the way to resolve the issue (or can it be possible?), but rather to make use of the timer of the Arduino. Either options put me in the dark.

Can you advise?


Rather then trying to time the Arduino to successfully open and close you gate, I would recommend using limit switches such as these. Use two, one to let the Arduino know that the gate is open, and the other to let it know the gate is closed. Then use a weatherproof pushbutton to tell the Arduino to “turn the motor CCW until the limit switch trips, indicating the gate is open” or “turn the motor CW until other limit switch trips, indicating the gate is closed.”

The other problem I see is that your security gate might run on AC rather then DC. In order for your Arduino to control the direction of an AC motor, you will need more complicated circuitry and it is considerably more dangerous. An option would be to use a AC Reversing Solid State Relay as it can be directly controlled by the microcontroller. Unless you are a trained electrician, I would NOT recommend interfacing your Arduino to an AC source.

Below is a rough schematic for your circuit and a bit of code that should get you started!


const int activate = 2; //set up our button constants
const int gateOpen = 3;
const int gateClosed = 4;
const int bridgeOneA = 5;
const int bridgeTwoA = 6;
const int enable = 7;
const int statLED = 13;
unsigned long currentTime = 0;
boolean gateState = false; //false = closed true = open
void setup() {
  pinMode(activate, INPUT); //set up I/O
  pinMode(gateOpen, INPUT);
  pinMode(gateClosed, INPUT);
  pinMode(bridgeOneA, OUTPUT);
  pinMode(bridgeTwoA, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, LOW); //make sure H-Bridge is off
  pinMode(statLED, OUTPUT); //setup our status LED
void loop() {
  if (digitalRead(activate) == HIGH && gateState == false) { //check to see if the button is pressed and the gate is closed
    digitalWrite(enable, HIGH); //enable h-bridge
    digitalWrite(bridgeOneA, HIGH); //configure for CW rotation
    digitalWrite(bridgeTwoA, LOW);
    while(1){ //run motor until switch is tripped
      if (digitalRead(gateOpen) == LOW) { //check switch state
        gateState = true;
        digitalWrite(statLED, LOW); //turn off LED
        digitalWrite(enable, LOW); //disable h-bridge
        digitalWrite(bridgeOneA, LOW); //reset h-bridge config
      if (millis() > currentTime + 500) { //flash status LED once
        digitalWrite(statLED, HIGH);
        currentTime = millis();
      else {
        digitalWrite(statLED, LOW);
  if (digitalRead(activate) == HIGH && gateState == true) { //check to see if the button is pressed and the gate is open
    digitalWrite(enable, HIGH);
    digitalWrite(bridgeOneA, LOW); //configure for CCW rotation
    digitalWrite(bridgeTwoA, HIGH);
      if (digitalRead(gateOpen) == LOW) {
        gateState = false;
        digitalWrite(statLED, LOW);
        digitalWrite(enable, LOW);
        digitalWrite(bridgeTwoA, LOW);
      if (millis() > currentTime + 500) { //flash status LED once
        digitalWrite(statLED, HIGH);
        currentTime = millis();
      else {
        digitalWrite(statLED, LOW);

I haven’t tried out the code, but it should get you started in the right direction. The idea is that when the button is pressed, the Arduino configures and activates the h-bridge, moving the gate until the “open” limit switch trips and stops the motor. Then when the button is pressed again, the Arduino configures and activates the h-bridge, moving the gate until the “closed” limit switch trips and stops the motor again. There is a also small bit of code that flashes the LED during the time the motor is in motion using the mills() counter.

I hope this has helped to steer you in the right direction and good luck with your project!

Don’t forget, everyone is invited to ask a question!

Click here!

“Ask an Educator” questions are answered by Adam Kemp, a high school teacher who has been teaching courses in Energy Systems, Systems Engineering, Robotics and Prototyping since 2005.

Adafruit publishes a wide range of writing and video content, including interviews and reporting on the maker market and the wider technology world. Our standards page is intended as a guide to best practices that Adafruit uses, as well as an outline of the ethical standards Adafruit aspires to. While Adafruit is not an independent journalistic institution, Adafruit strives to be a fair, informative, and positive voice within the community – check it out here:

Join Adafruit on Mastodon

Adafruit is on Mastodon, join in!

Stop breadboarding and soldering – start making immediately! Adafruit’s Circuit Playground is jam-packed with LEDs, sensors, buttons, alligator clip pads and more. Build projects with Circuit Playground in a few minutes with the drag-and-drop MakeCode programming site, learn computer science using the CS Discoveries class on, jump into CircuitPython to learn Python and hardware together, TinyGO, or even use the Arduino IDE. Circuit Playground Express is the newest and best Circuit Playground board, with support for CircuitPython, MakeCode, and Arduino. It has a powerful processor, 10 NeoPixels, mini speaker, InfraRed receive and transmit, two buttons, a switch, 14 alligator clip pads, and lots of sensors: capacitive touch, IR proximity, temperature, light, motion and sound. A whole wide world of electronics and coding is waiting for you, and it fits in the palm of your hand.

Have an amazing project to share? The Electronics Show and Tell is every Wednesday at 7pm ET! To join, head over to YouTube and check out the show’s live chat – we’ll post the link there.

Join us every Wednesday night at 8pm ET for Ask an Engineer!

Join over 36,000+ makers on Adafruit’s Discord channels and be part of the community!

CircuitPython – The easiest way to program microcontrollers –

Maker Business — “Packaging” chips in the US

Wearables — Enclosures help fight body humidity in costumes

Electronics — Transformers: More than meets the eye!

Python for Microcontrollers — Python on Microcontrollers Newsletter: Silicon Labs introduces CircuitPython support, and more! #CircuitPython #Python #micropython @ThePSF @Raspberry_Pi

Adafruit IoT Monthly — Guardian Robot, Weather-wise Umbrella Stand, and more!

Microsoft MakeCode — MakeCode Thank You!

EYE on NPI — Maxim’s Himalaya uSLIC Step-Down Power Module #EyeOnNPI @maximintegrated @digikey

New Products – Adafruit Industries – Makers, hackers, artists, designers and engineers! — #NewProds 7/19/23 Feat. Adafruit Matrix Portal S3 CircuitPython Powered Internet Display!

Get the only spam-free daily newsletter about wearables, running a "maker business", electronic tips and more! Subscribe at !

No Comments

No comments yet.

Sorry, the comment form is closed at this time.