Help With Code for Simple Door Lock

Hey Guys -

Although versed in PowerShell and the like, I'm new to Arduino and need some assistance with my first code - which I'd think should be a simple project, please. Below is the project goal, hardware used, the issue, & current code I've been working on with schematic attached. Any help would be appreciated...

Project Goal
Lock / Unlock a door using this model via a single button. An RGB LED beside button should turn red if door is locked and green if unlocked.
I don't mind using individual red & green LEDs instead of a single RGB one if easier...

Hardware

  • Arduino Nano
  • RGB LED (or red & green LEDs)
  • Generic Servo
  • 3D Printed Parts
  • x4 220 ohm resistors

The Issue(s)
Once powered on, the servo starts and continuously spins. Pressing the button reverses it & changes the LED color, but only for as long as I hold it down. Once released, it goes back to initial state. The colors displayed by the LED seem incorrect, but it's not highest priority.

Current Code
I tried the Servo Sweep example in Arduino and it word, so tried to combine it with example code for a Button & LEDs, but cant get it to work. I've found code examples online which were to simply switch servo back and forth using single button, but cant get anything to work.

#include <Servo.h>
Servo myservo; 
int pos = 0; 
const int buttonPin = 3;
const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
int counter = 0;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
myservo.attach(8);
}
void loop()
{
int buttonState;
buttonState = digitalRead(buttonPin);
if (buttonState == LOW)
{
counter++;
delay(150);
}
// Lock & change LED to Red
if (counter == 0)
{
myservo.write(180);
delay(15);
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
}
// Unlock & change LED to Green
else if (counter == 1)
{
myservo.write(0);
delay(15);
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
}
{
counter = 0;
}
}

Any suggestions would be appreciated.

Thank You!

Once powered on, the servo starts and continuously spins.

"This model requires the use of a standard sized 180 degree servo motor"

Give us a link to the servo, "continuously" implies you have the wrong servo!

You're not allowing the servo long enough to move to its position.

Also, use the iDE's auto-format tool, and get rid of excess braces.

Once powered on, the servo starts and continuously spins.

You don't have a servo. You have a continuous rotation (not really a) servo

Such a "servo" will rotate continuously in one direction or another based on what is written to it. It cannot be commanded to move to a particular angle as there is no positional feedback from it unlike a real servo

Another consideration is that the "servo" is quite possibly taking too much current from the Arduino and should really be powered by a separate power supply

//Version 1.01

#include <Servo.h>
Servo myservo;

#define LOCKED        true
#define notLOCKED     false

#define LEDon         HIGH
#define LEDoff        LOW

const byte servoPin = 8;

//const byte buttonPin = 2;
//const byte redPin    = 3;
//const byte greenPin  = 4;
//const byte bluePin   = 5;

const byte buttonPin = 3;
const byte redPin    = 11;
const byte greenPin  = 10;
const byte bluePin   = 9;

byte buttonState;
byte lastButtonState;
byte counter = 0;
byte pos;

bool LOCKEDflag;

//timing stuff
unsigned long lastMillis;

//****************************************************************************
void setup()
{
  Serial.begin(9600);

  pinMode(buttonPin, INPUT);
  lastButtonState = digitalRead(buttonPin);

  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

  myservo.attach(servoPin);

  //***********************************
  //unlock at power up
  myservo.write(0);
  delay(15);
  digitalWrite(redPin, LEDoff);
  digitalWrite(greenPin, LEDon);
  digitalWrite(bluePin, LEDoff);
  Serial.println("Not Locked");

  LOCKEDflag = notLOCKED;


} //END of setup

//****************************************************************************
void loop()
{
  //***********************************
  //is it time to check the switches?
  if (millis() - lastMillis >= 50)
  {
    //restart the timing
    lastMillis = millis();

    checkSwitches();
  }

  //***********************************
  //when we are not locked, lock & change LED to Red
  if (LOCKEDflag == notLOCKED && counter == 1)
  {
    myservo.write(180);

    Serial.println("Locked");

    delay(15);
    digitalWrite(redPin, LEDon);
    digitalWrite(greenPin, LEDoff);
    digitalWrite(bluePin, LEDoff);

    LOCKEDflag = LOCKED;
  }

  //***********************************
  //when we are locked, unlock & change LED to Green
  else if (LOCKEDflag == LOCKED && counter == 2)
  {
    myservo.write(0);

    Serial.println("Not Locked");

    delay(15);
    digitalWrite(redPin, LEDoff);
    digitalWrite(greenPin, LEDon);
    digitalWrite(bluePin, LEDoff);

    LOCKEDflag = notLOCKED;
  }

  //***********************************
  //oter non blocking code goes here
  //***********************************

} //END of loop()


//****************************************************************************
void checkSwitches()
{
  //***********************************
  buttonState = digitalRead(buttonPin);

  if (lastButtonState != buttonState)
  {
    //update to this new state
    lastButtonState = buttonState;

    //was the button pushed?
    if (buttonState == LOW)
    {
      counter++;

      if (counter > 2)
      {
        counter = 1;
      }
    }
  }

} //END of checkSwitches()

//****************************************************************************

Thanks, guys -

OK, ok - you're right and I didn't notice. The servo is a Parallax continuous. Whoops!

larryd: I tried the code (1.01) you posted above - Thanks. The servo still rotates continuously, however; pressing (and releasing) the button reverses it & changes the LED as before this only occurred when holding down the button.

So... is it possible to modify code to use this (continuous) servo for this project? I only need it to go about 180 degrees each way. I do have some MG90S servos that I just got in. Considered using them, but they are much smaller yet have metal gears. Again, it's only needed to move the bar back and forth in below post.

Note: I hooked up one of the MG90S servos instead and it seemed to work as desired...

Thanks!

Buy the correct servo :wink:

A continuous motor might work if you add limit switches.

Get the servo the author told you to use.

Thanks again, Guys -

I ended up finding a remix of the same design which was designed for a MG90S (after a bit of modification).

One final question if I may...

When testing, I've powered everything below via USB on the Arduino Nano...

  • Arduino Nano
  • Servo (MG90S)
  • LED

I'm considering powering the project via 9V battery, but if so; have the below questions...

  1. Could I connect the 9V directly to Arduino Nano's VIN/GND or would it require voltage regulators? I've seen posts saying wither will work

  2. If voltage regulators are required and got it down to 5V, would there be any difference powering the servo directly vs having Arduino Nano power it?

  3. With the Arduino Nano & LED being on 24/7 & servo used about 5 times a day, approximately what kind of battery life could I expect? Know there are many variables, but didn't know if it would be hours, days, weeks, etc...

Thanks Again!

If the 9V battery is what I know as a PP3, small, rectangular with press stud contacts at the top then don't bother as it cannot supply the required current for very long. Use 6 AA's instead

You can connect 9V to the Arduino VIN and GND pins quite safely, No voltage regulator required, but powering the servo from the Arduino 5V pin is not to be recommended due to the current drawn, so a voltage regulator will be required to power it from the 9V battery

Thanks for the reply...

I really appreciate you guys answering my many questions. Worked extensively with RasPis up until now and Arduino is a different beast! I have just a couple more then promise to not bug you anymore (for now :))...

  1. Would it be correct to assume that a properly tuned LM2596 buck converter could be used to bring the 9V down to 5V with the 6 AA batteries? (I have a spare handy)

  2. I'd like to add support in the future to remotely lock/unlock - ideally with SmartThings integration. I did a bit of research and it seems that with this script, it may not be that big of an ask. Regardless, even if I wanted to add WiFi with control using a simple web server, would an ESP8266 be the only hardware I'd need to add this support?

Thanks again!

4xAA NiMH rechargeables will give you a suitable voltage to run the servo and Nano (via its 5V pin) and no regulators/buck converters needed.

The buck converter would allow 6xAA rechargeables or non-rechargeables to be used and extend the batter life. Set for 5V, this could run the servo and power Nano via 5V pin.

For remote use, replace the Nano with a Wemos D1 mini. Adding an ESP-01 to a Nano is difficult because of the power requirements of the ESP-01 being more than the Nano can provide and the need to level-shift the TX & RX signals between the 3.3V ESP-01 and 5V Nano.

Hey Guys -

So I finally got a few ESP8266 NodeMCU boards which I've been playing around with and been able to successfully set up a web server and such on them. The last step of my project is adding code to the above script which will allow the following:

  • All of the above continues to work (button, LED, servo)
  • Host a webpage displaying single web button where clicking it emulates pressing the physical button.
  • The web button will change to reflect if the door is locked / unlocked

This seemed simple enough by doing the below...

  • Adding necessary coding for ESP8266
  • Using different digital pins for ones that do not exist on the ESP8266
  • Plugging pins into ESP8266 as they were on the Nano

Unfortunately, it did not work. When the ESP8266 boots, the RGB LED doesn't light and the serial console actually shows it boot looping with the below echo:

Connecting to XXXXX
...........
WiFi connected.
IP address:
192.168.0.130

ets Jan 8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1392, room 16
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld
Connecting to XXXXX
...

I plugged everything up 1-1 except that the ESP doesn't have a 5V so tried plugging it into VIN, 3.3, & not plugging in at all (5V goes directly to servo) but still a nogo.

Attached is the code I'm using (too large to post). Any suggestions would be greatly appreciated - Thank You!

DoorLock-Share.ino (7.76 KB)

Please post shortest code you can which demonstrates the error. Do you see the same error if you upload the blink sketch, for example? Also post a schematic (hand drawn ok if neat) and perhaps some bright clear pics of the circuit so that all wires can be traced. You may have connected the gpio pins in a way which prevents your code from running, for example gpoi0 and/or gpio2.

OK - Thanks for the reply...

My initial project was to set up a Nano with button, RGB LED, & Servo connected as shown in the first screenshot. Pressing the button would unlock the door (servo) and turn LED green. Pressing the button again would lock the door and turn the LED red. The code for this posted by larryd on Jan 19, 2020, 08:26 pm works flawlessly.

My overall goal is to port this over to an ESP8266 NodeMCU so that it acts the exact same as above, but also includes a web server hosting page with single web button. The desire is that clicking the web button emulates pressing the physical button.

As you'll see in the 2nd screenshot, I connected everything similarly to how it was connected to the Nano except that I had to change a couple of pin assignments which the NodeMCU didn't have. Unfortunately, once I upload the code, it goes into a boot loop - even if I unplug everything. I read that certain pins shouldn't be used (and was using one) so changed it physically + in code to no avail.

Note: I also attempted the initial setup and connect the NodeMCU via serial, but didn't get that far.

I've also attached the latest code (attempt) that goes with the 2nd schematic...

Hope that's the information requested. I've spent hours working on this. Thanks a ton for your help!

DoorLock-Share.ino (7.76 KB)

I can't open your .ino attachment on my phone. Is it short enough to post between code tags?

Why do you think Nano and NodeMCU are the shape they are, and not the same shape as an Uno?

Why do you think they have pins instead of sockets?

Why do you think the pins point down below the board instead of up?

Can you think of any reason why this might make them easier to use with breadboards?

Can you really push a wire and the pin of a button into the same hole in a breadboard?

Do these images truly represent how you wired your circuit?