4

I have an Arduino UNO with 3 switches attached (2 limit switches, 1 activation switch). I'm trying to make the activation switch turn the motor forwards once hit, then wait for any of the limit switches to be hit and stop the motor. The next step is to wait for the activation switch to be hit again and turn the motor in the opposite direction and wait for the limit switch to be hit and stop the motor.

But the issue I'm facing right now is when i press the activation switch the arduino board and H bridge board restart. The LED's turn on and off and the code restarts. And nothing happens. I know all the switches and motor is working because i have tested them by simplifying the code with just the functions.

(edit) Here is a picture of the schematic: Schematic View

Can someone please review my code below to see if my logic is correct.

const byte  frontButtonPin = 2;     
const byte  backButtonPin = 4;     
const byte  onOffButtonPin = 11;     
const int   motorPin =  8;      
const int   motorPin2 =  7;      

boolean  frontButtonState = 0;      
boolean  backButtonState = 0;        
boolean  onOffButtonState = 0;   



/**
    setup inputs for switches and outs for motor pins
    serial begin to read the switches to test for errors
*/
void setup() {
  // initialize the pin as an inputs:
  pinMode(motorPin, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(frontButtonPin, INPUT);
  pinMode(backButtonPin, INPUT);
  pinMode(onOffButtonPin, INPUT);
  Serial.begin(9600);
}

/**
   this function turns motor foward
*/
void drawMovesForward() {
  // turn motor foward:
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}

/**
   this function turns motor backwards
*/
void drawMovesBackward() {
  // turn motor in other direction:
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}

/**
   Stop the motor form moving
*/
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}


/**

*/
void loop() {

  frontButtonState = digitalRead(frontButtonPin);
  backButtonState  = digitalRead(backButtonPin);
  onOffButtonState = digitalRead(onOffButtonPin);



  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();

    }

    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }

  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }

    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }
}
7
  • Welcome to StackExchange. I'm pleased to say you have made an excellent start by formatting your code and giving details in your description of your problem. Your logic looks good to me. To start troubleshooting, I would put println() statements in each of the functions, and try to work out where the program is hanging. When you say the "LEDs turn on and off", what LEDs are you referring to? This is where a schematic might help us troubleshoot, but you have mentioned that the parts are working by themselves. May 5 '18 at 11:06
  • Presumably you are currently testing with the parts disconnected (not installed in the drawer?). This makes it a lot easier to identify what is going wrong. May 5 '18 at 11:14
  • Thanks, I had a professional programmer help me program the Arduino but he has never used Arduino stuff before so he recommended using this website to look for other peoples advice. The LED's are the LED's on the arduino board. they turn on and off again and the arduino boards reset (they turn off and off again) when the back limit switch is hit and i hit the on/off switch at the same time.
    – ldprice
    May 7 '18 at 2:45
  • Can you edit your question to mention whether the circuit is using a "toggle" or push-button activation switch? I presume it is a "toggle" switch as otherwise your code would only work by holding down a pushbutton switch. May 8 '18 at 6:55
  • Yeah there just momentary push buttons, push the button and let go. Also i actually fixed the code and now it works fine. Should i update the original post to say "problem solved" and then insert the code and how i fixed it? or do i do that somewhere else?
    – ldprice
    May 8 '18 at 9:58
3

Check your switches have pull-up resistors

It would be helpful if your question included a schematic. Do you have pullup resistors in line with your activation and limit switches? If not, you might find the input is "floating" - that is, it will randomly return either HIGH or LOW. This would possibly cause the motor to go forwards and backwards, but because the loop is possibly occurring hundreds of times per second, you might not see anything moving. You need pull-up or pull-down resistors in the circuit so the Arduino can see a definite LOW or HIGH. See https://www.arduino.cc/en/Tutorial/Button for a tutorial with a resistor, or even better, use https://www.arduino.cc/en/Tutorial/InputPullupSerial and use the existing onboard pullup resistors on the Arduino, as suggested by Juraj below.

Potential Logic Error

There might be a logic error in this part of the code:

  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();
    }
    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }
  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }
    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }

Loop #1: Let's say the onOffButtonState is HIGH (someone has pressed the switch to ON). The drawer is closed, so the front limit switch is depressed, so frontButtonState is HIGH. So the program will execute stopDrawFromMoving, and do nothing. Currently you are saying nothing is happening, so this might be your issue.

What you will probably need to do is use flags and while loops. For example:

At the start of the loop() declare this

drawerMovingOutFlag = 1;

Then change the loop to contain:

if (onOffButtonState == HIGH) {
    if ( frontButtonState == HIGH ) {
        while(drawerMovingOutFlag == 1)
            drawMovesForward();
            if ( backButtonState == HIGH ) {
                drawerMovingOutFlag = 0;
                stopDrawFromMoving()
            }
        }
    }
    else ...

I'll let you do the rest!

4
  • 1
    not that button tutorial, please. use the the input_pullup tutorial arduino.cc/en/Tutorial/InputPullupSerial
    – Juraj
    May 5 '18 at 11:46
  • 1
    Hey thanks for the fast reply. Yes i have resistors going down to GND on all 3 switches. And I've used the serial monitors to check all the switches and they work and are read correctly.
    – ldprice
    May 7 '18 at 2:51
  • I'm working on the schematic now (:
    – ldprice
    May 7 '18 at 2:51
  • 1
    Schematic is uploaded (: Thanks for your help
    – ldprice
    May 8 '18 at 4:43
3

I actually had the right code all along but I just had to add delays when reading the limit switches and detecting the activation switches. Here is one of the original programs i wrote that i threw out thinking it doesnt work, but once the delays were added it works fine.

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin3 = 11;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  8;      // the number of the LED pin
const int motorPin2 =  7;      // the number of the LED pin

// variables will change:
boolean buttonState = 0;         // variable for reading the pushbutton status
boolean buttonState2 = 0;         // variable for reading the pushbutton status
boolean buttonState3 = 0;   // variable for reading the pushbutton status


int drawPosition = 2;  // Tells progam what position the draw is in


/**
 *  setup inputs for switches and outs for motor pins
 *  serial begin to read the switches to test for errors
 */
void setup() {
    // initialize the pin as an inputs:
    pinMode(motorPin, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    Serial.begin(9600);
}

/**
 * this function turns motor foward 
 */
void drawForward() {
     // turn motor foward:
     digitalWrite(motorPin, LOW);
     digitalWrite(motorPin2, HIGH);
}

/**
 * this function turns motor backwards
 */
void drawBackward() {
     // turn motor in other direction:
     digitalWrite(motorPin, HIGH);
     digitalWrite(motorPin2, LOW);  
}

/**
 * Stop the motor form moving
 */
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}


/**
 * 
 */
void loop() {
   // read the state of the pushbutton value:
   buttonState = digitalRead(buttonPin);
   buttonState2 = digitalRead(buttonPin2);
   buttonState3 = digitalRead(buttonPin3);



   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      drawPosition = 2; 
      Serial.println(F("Front button state is high draw is open")); 
      stopDrawFromMoving();
   }else if (buttonState2 == HIGH) {
      drawPosition = 1;        
      stopDrawFromMoving();
  } 

  if (buttonState3 == HIGH) {
    if( drawPosition  == 1 ){
      drawBackward(); 
      delay(100);      
      drawPosition = 2;
      delay(100);  
    }else if (drawPosition == 2 ) {
      delay(100); 
      drawForward();
      delay(100); 
      drawPosition = 1;       
    }

  }
}
1
  • 1
    Please "Mark this as Answer", because this is the real answer to your problem. May 14 '18 at 6:47
3

I know this was opened years ago now but I just wanted to add some clarification. When I started this project and created this question I had 0 understanding of software development and didn't understand the code I was writing at the time. Now 3 years later I have revised this project multiple times.

The logic for a project like this is pretty simple, but if you're new to programming and trying to get into the STEM field with Arduino school projects and such, here is what my code now looks like for this same project: https://github.com/LeehamElectronics/Automated-Cabinet

I have tried to comment it as best I could to help other students understand it. The project is simply a timber cabinet that has an electrically automated draw inside that can be opened and closed at will.

If you are stuck with a similar problem with your own project, I would suggest that you watch a free YouTube video course for C++ programing or even a Arduino programming video course. Even just a few hours of doing that will be enough to get started. That's the one thing I wish someone told me to do when I was starting off 3 years ago, I was wasting hours and hours debugging code that I didn't understand because I just jumped straight into Arduino with little understanding of coding.

I hope this comment helps someone else out there in a similar situation to mine 3 years ago.

Cheers

2

That is an excellent project. Great work.

Some suggestions for improvement. You could use a enum class byte instead of a String for the drawer position and the drawer moving direction:

/* Allows the program to keep track of the last known position of the drawer */
enum class DrawerPositions : byte
{
  Closed,
  Open
} drawerPosition = DrawerPositions::Closed;

/* Keep track of what direction the drawer is moving, can one of the following:  Null | Closing | Opening */
enum class DrawerMovingDirections : byte
{
  Null,
  Closing,
  Opening
} drawerMovingDirection = DrawerMovingDirections::Null;
...
if (drawerPosition == DrawerPositions::Closed)
...
else if (drawerPosition == DrawerPositions::Open)
...
if (drawerMovingDirection == DrawerMovingDirections::Opening)
...

It would also be a good idea to add debouncing for all the switch inputs. There are many debouncing algorithms on the internet, but here is a very simple debouncer I put on GitHub which could be implemented something like this:

#include "Debouncer.h"
...
void loop()
{
  static Debouncer limitSwitch0(limitSwitchPin0);
  static Debouncer limitSwitch1(limitSwitchPin1);
  static Debouncer manualToggleButton(manualToggleButtonPin);
  
  limitSwitch0.Update();
  limitSwitch1.Update();
  manualToggleButton.Update();
  
  if (drawerIsMoving == true)
  {
    if (drawerMovingDirection == DrawerMovingDirections::Opening)
    {
      if (limitSwitch0.Output() == LOW)  // Get the debounced output of the switch.
      {
        drawerPosition = DrawerPositions::Open;
  ...
  if(manualToggleButton.Rise())   // For rising edge trigger.
  //if(manualToggleButton.Fall())  // For falling edge trigger.
  {
    ...
  }
  ...
}

Here is a debounce demo I put on Wokwi.

1
  • Thanks for your advice. I guess some of my laziness from Python crept into my c++ work doing silly things like using reference types to store, effectively 1s and 0s. I definitely should be using a primitive type such as a byte like you mentioned, I will most likely make those changes soon. As for debouncing, I haven't really had the need to use it much but I know I should, I'll add that to the to-do list. Thanks!!
    – ldprice
    Aug 24 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.