I am very new to the arduino programming... So i can't really write code yet....
I have a Arduino uno board, 1 press button, a 28byj-48 stepper motor, and a motor control board.
I would like it to: When i press the button, I would like it to start turning, TILL i release it at a slow speed And should not turn without being pressed. I only want it to turn 1 way.
I have programmed a code of what i know..... And it doesn't do what i want it.
This is my code and how my Motor is set up
#include <Stepper.h>
const float STEPS_PER_REVOLUTION = 32;
const float GEAR_REDUCTION = 64;
const float STEPS_PER_OUT_REV = STEPS_PER_REVOLUTION * GEAR_REDUCTION;
int StepsRequired;
int switchPin = 7;
//Extra Boolean variables to keep track of button and motor state
boolean current = LOW;
boolean last = LOW;
boolean isOpen = LOW;
Stepper steppermotor(STEPS_PER_REVOLUTION, 8, 10, 9, 11);
void setup()
{
pinMode(switchPin, INPUT);
}
boolean debounce(boolean inLast){
boolean inCurrent = digitalRead(switchPin);
if(inLast != current){
delay(5);
inCurrent = digitalRead(switchPin);
}
return inCurrent;
}
void garageAction(float factor){
StepsRequired = STEPS_PER_OUT_REV*factor;
steppermotor.setSpeed(1000);
steppermotor.step(StepsRequired);
if(isOpen == LOW){
delay(10000);
}else if(isOpen == HIGH){
delay(5);
}
}
void loop()
{
current = debounce(last);
if(current == HIGH && last == LOW && isOpen == LOW){
garageAction(2);
isOpen = !isOpen;
}
if(current == HIGH && last == LOW && isOpen == HIGH){
garageAction(-2);
isOpen = !isOpen;
}
}
No button in that poor presentation. How is it wired? Please use schematics (pen and paper). No power supply presented.
Good practise is to use INPUT_PULLUP and wire the button between GND and input pin.
So i am using a 5 volt usb cable connected to arduino. So what it does right now is
When i plug it in, it starts turning, and then it stops for a while. when i press the button it goes the other way for a while. if i wait for a while it will then start turning again the other way. When finished
it instantally starts turning the firsts move.
Welcome to Arduino programming! Let's tweak your code to achieve the desired behavior. We'll ensure the motor turns when the button is pressed and slows down when released. Here's a modified version of your code:
cppCopy code
#include <Stepper.h>
const int STEPS_PER_REVOLUTION = 32;
const int GEAR_REDUCTION = 64;
const int STEPS_PER_OUT_REV = STEPS_PER_REVOLUTION * GEAR_REDUCTION;
const int switchPin = 7;
Stepper steppermotor(STEPS_PER_REVOLUTION, 8, 10, 9, 11);
void setup() {
pinMode(switchPin, INPUT);
}
void loop() {
if (digitalRead(switchPin) == HIGH) {
steppermotor.setSpeed(300); // Adjust speed as needed
steppermotor.step(STEPS_PER_OUT_REV);
}
}
This code ensures that the motor turns only when the button is pressed and slows down when the button is released. Adjust the speed according to your preference by changing the value inside setSpeed(). Good luck with your project!