Arduino 101 - Lesson 3

Discussion in 'Welcome to the DARK side' started by paul_l, Nov 17, 2017.

  1. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    And here is the result

    The turntable slowly auto homes on power outage or Arduino reset.

    Once the turntable makes the limit switch, it moves at normal speed to the entry position.

    [​IMG]

    Pressing the pushbutton the turntable rotates 180 degrees clockwise, pressing the button again and it rotates 180 counterclockwise, and just repeats this every time the buttons are pressed.

    https://youtu.be/pZEMmprce7w



    Code to follow

    Paul
     
  2. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    And so for the code

    =======================================================================

    /*
    Stepper Motor Control - Turntable 01 - turn 180 degrees with homing routine

    This program drives a unipolar 28BYJ-48 stepper motor with built in 64:1 gearbox.
    The motor is attached to digital pins 8 - 11 of the Arduino.
    Push button attached to digital pin 6 of the Arduino

    The when the button is pressed the motor should revolve 180 degrees.

    Created 19 Nov. 2017

    by Paul Lancaster

    */

    #include <Stepper.h>

    const int stepsPerRevolution = 2048; // change this to fit the number of steps per revolution
    // for your motor

    const int buttonPin = 6; // the number of the pushbutton pin
    int buttonState = 0; // variable for reading the pushbutton status
    const int home_switch = 5; // the number of the home limit switch pin
    int stepsFromHome = -1234; // Number of steps from Home position to Entry road - adjust value until correct
    int CurrentPosition = 0; // Current position of stepper motor
    int stepsToMove = 1000; // Number of steps to rotate between entry and exit position
    int steps; // Number steps including direction =ve clockwise, -ve counterclockwise
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    //=============================== SETUP ==============================================================================================

    void setup() {
    // initialize the serial port:
    Serial.begin(9600);
    // Homing Routine
    pinMode(home_switch, INPUT_PULLUP);
    Serial.println("Homing");
    while (digitalRead(home_switch)) { // Moves clockwise 1 step at a time with a delay 50ms between steps until the home_switch
    myStepper.step(1); // changes state
    delay(50);
    }
    Serial.println("Homing Complete - Moving to entry Road");
    // set the speed at 4 rpm:
    myStepper.setSpeed(4); // Sets stepper speed based on steps and rpm
    myStepper.step(stepsFromHome); // Moves the Turntable from the home position to the Entry Position - value dependant on entery position
    CurrentPosition = 0; // Sets current position to 0 once the move to Entry position is completed.
    pinMode(buttonPin, INPUT_PULLUP); // Initializes the pushbutton pin D6
    }

    //============================== Main Loop ============================================================================================

    void loop() {
    // Determine Direction
    if (CurrentPosition == 0) { //
    steps = stepsToMove;
    }
    else{
    steps = -stepsToMove;
    }

    // Press button to rotate 180 degrees:
    buttonState = digitalRead(buttonPin);
    if (buttonState == LOW) {
    Serial.println("Moving");
    myStepper.step(steps);
    delay(500);
    Serial.print("Stopped - Current Position = ");
    Serial.println(CurrentPosition);
    CurrentPosition = (stepsToMove - CurrentPosition); //
    Serial.print("New Current Position = ");
    Serial.println(CurrentPosition);

    }
    }

    =====================================================================

    Paul
     
  3. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    Before going through the code, I thought we'd go through the setup and testing.

    [​IMG]

    When running the sketch with the serial monitor open it prints useful information which can help pin point errors or issues.

    Above shows the output when it's working correctly, after the arduino boots, it starts the Homing routine, which depending on where the turntable was can take sometime.

    The second message "Homing Complete - Moving to entry Road", if this had appeared and there was no movement or the Turntable was driving against the limitswitch , I'd know that the limitswitch had changed state, but either there was no drive, or the direction was incorrect.

    If the direction is wrong change the stepsFromHome value from -ve to +ve or vice versa

    Check to see that the Turntable is aligned correctly - if not change the value of stepsFromHome
    If changes are required, upload the sketch and try again.

    The next message does'nt appear until the push button is pressed - so with one finger on the rest button of the arduino, the push button was pressed.

    "Moving", if it appears and there is no movement, then the push button press was detected, but the stepper is not driving. If there is movement but in the wrong direction, quickly press the reset button, before the turntable takes out the limit switch.

    Stopped - Current position = 0 The move has completed and the value for Current position is 0

    The sketch now calculates a new value for current position CurrentPosition = (stepsToMove - CurrentPosition); and then prints out the value, this was very helpful when I was trying to sort out the direction calculations and the result was the steps variable, as before I used that extra lines of code to check the correct values for the CurrentPosition.

    Again check if the turntable rotated to the correct position, if not change the value of stepsToMove, my original value was 1024, the final value ended up being 1000.
    As with before, make any changes and upload the sketch to the arduino.

    Again with finger poised on the reset button, press the push button, the turntable should rotate the opposite direction and return to the correct alignment.

    If all was ok, reset the Arduino and check again - you now have a working simple turntable.

    Paul
     
  4. Toto

    Toto I'm best ignored Staff Member Founder Administrator

    Messages:
    13,376
    Likes Received:
    1,926
    Joined:
    Dec 5, 2017
    And that's all there is too it. :tophat: no excuses now eh. :facepalm:
     
  5. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    Lets look at the code

    Libraries and definitions

    ======================================================================

    */

    #include <Stepper.h>

    const int stepsPerRevolution = 2048; // change this to fit the number of steps per revolution
    // for your motor

    const int buttonPin = 6; // the number of the pushbutton pin
    int buttonState = 0; // variable for reading the pushbutton status
    const int home_switch = 5; // the number of the home limit switch pin
    int stepsFromHome = -1234; // Number of steps from Home position to Entry road - adjust value until correct
    int CurrentPosition = 0; // Current position of stepper motor
    int stepsToMove = 1000; // Number of steps to rotate between entry and exit position
    int steps; // Number steps including direction =ve clockwise, -ve counterclockwise
    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    =====================================================================

    There are descriptions within the sketch to help

    Add the Stepper Library #include <Stepper.h>

    As with the previous sketch we have the stepsPerRevolution which as will be seen later this is irrelevant, but is used with the rpm value to determine the speed, essentially stepsPerRevolution x rpm = the number of steps per min that the stepper will be sent.

    buttonPin is the number of the input for the pushbutton in this case D6
    buttonState is the variable where we will store the value of the pushbutton

    Now we have some new variables

    home_switch is the number of the input for the limit switch in this case D5

    stepsFromHome this is the number of steps from the Home position to the entry track to the turntable. The value of this is determined by trial and error until the turntable stops at the correct position.

    CurrentPosition it says in the sketch it is the current position of the stepper, actually it is the current position of the 'A' end of the turmtable. In this sketch it is used to determine the direction of rotation, but in the next sketch, we will add additional exit roads and this variable will be more critical.

    stepsToMove this variable defines the number of steps the turntable will rotate to get to the exit road, and move back to the entry road. Again trial and error to determine the exact value.

    steps In this sketch is equal to stepsToMove but can be either a +ve or -ve version of the stepsToMove depending on the direction of travel, this is the value sent to the stepper motor.

    Finally initialize the stepper motor.


    //=============================== SETUP ==============================================================================================

    void setup() {
    // initialize the serial port:
    Serial.begin(9600);
    // Homing Routine
    pinMode(home_switch, INPUT_PULLUP);
    Serial.println("Homing");
    while (digitalRead(home_switch)) { // Moves clockwise 1 step at a time with a delay 50ms between steps until the home_switch
    myStepper.step(1); // changes state
    delay(50);
    }
    Serial.println("Homing Complete - Moving to entry Road");
    // set the speed at 4 rpm:
    myStepper.setSpeed(4); // Sets stepper speed based on steps and rpm
    myStepper.step(stepsFromHome); // Moves the Turntable from the home position to the Entry Position - value dependant on entery position
    CurrentPosition = 0; // Sets current position to 0 once the move to Entry position is completed.
    pinMode(buttonPin, INPUT_PULLUP); // Initializes the pushbutton pin D6
    }

    =====================================================================

    As with the other sketches we initialize the serialport so that we can get messages sent to the serial monitor to help with diagnostics.

    Now the Homing Routine

    We define the port for the limit switch as an input pinMode(home_switch, INPUT_PULLUP); which in our case is pin D5 and the PULLUP option mean the PIN is high until we connect it to ground. We use this in the next piece code.

    First we print a message to the serial monitor "Homing", this gives us a pointer to where the sketch is upto.

    while (digitalRead(home_switch)) { // Moves clockwise 1 step at a time with a delay 50ms between steps until the home_switch
    myStepper.step(1); // changes state
    delay(50);
    }


    On the limit switch we are connected to the Normally open contact, so until the switch is operated the home_switch value = High, once the switch is operated the pin is connected to ground and becomes LOW.

    The while command does the hard work for us, and does the following checks the value of the home_switch (Pin D5), if it is HIGH, then it tells the stepper motor to move clockwise 1 step myStepper.step(1); then waits for 50ms before repeating the while loop. This continues until the limit switch is operated, it then stops the while loop and moves to the next line of the sketch.

    Serial.println("Homing Complete - Moving to entry Road"); again another message to let us know what is happening.

    We now set the stepper motor speed myStepper.setSpeed(4);
    and move the turntable to the entry road position myStepper.step(stepsFromHome);

    The reason for using variable names instead just typing in the exact value is two fold, it makes the code easier to understand / read, and any tweaking that is needed is done in the Definitions & Libraries section, you don't have to check each line of code for the correct value.

    myStepper.step(stepsFromHome); is the same as myStepper.step(-1234);

    We set CurrentPosition to zero as the 'A' end is at the entry road
    And define the Push Button pin D6 as an input pinMode(buttonPin, INPUT_PULLUP);


    //============================== Main Loop ============================================================================================

    void loop() {
    // Determine Direction
    if (CurrentPosition == 0) { //
    steps = stepsToMove;
    }
    else{
    steps = -stepsToMove;
    }

    // Press button to rotate 180 degrees:
    buttonState = digitalRead(buttonPin);
    if (buttonState == LOW) {
    Serial.println("Moving");
    myStepper.step(steps);
    delay(500);
    Serial.print("Stopped - Current Position = ");
    Serial.println(CurrentPosition);
    CurrentPosition = (stepsToMove - CurrentPosition); //
    Serial.print("New Current Position = ");
    Serial.println(CurrentPosition);

    }
    }
    =====================================================================

    We start the Main Loop with an If statement to determine the direction of travel

    if (CurrentPosition == 0) {
    steps = stepsToMove;
    }
    else{
    steps = -stepsToMove;
    }


    The IF statement asks if CurrentPosition equals 0, if this statement is True then steps = stepsToMove
    However if this is NOT true then steps = -stepsToMove
    We know that stepsToMove is the number of steps needed to rotate from the entry position to the exit position and the same in the reverse direction. You will in a few lines time once the Turntable 'A' end reaches the exit road we set the current position to the same value as steps to move.
    We could have set it to any value other than 0 for the sketch to work, but we are putting the building blocks in place for the next sketch.
    The above If statement has determined the direction of travel and the number of steps to move.

    The next line checks the state of the push button.
    We read the state of the push button and store the value in the buttonState variable buttonState = digitalRead(buttonPin);
    We do it this way because the push button is a momentary contact, so by storing the value in the variable it will last for a whole loop.

    And another If loop - this one is doing the heavy lifting

    if (buttonState == LOW) {
    Serial.println("Moving");
    myStepper.step(steps);
    delay(500);
    Serial.print("Stopped - Current Position = ");
    Serial.println(CurrentPosition);
    CurrentPosition = (stepsToMove - CurrentPosition); //
    Serial.print("New Current Position = ");
    Serial.println(CurrentPosition);


    As with the limit switch the value of buttonPin is HIGH until the push button is pressed.
    So if the button isn't pressed the if (buttonState == LOW) question is NOT True as the value is HIGH, so the IF statement code is bypassed, and as there is no more code it jumps back to the start of the main loop.

    However when the Push Button is pressed the If statement is true, so the indented code is ran.

    First another message "Moving"

    Then the instruction to the stepper to move myStepper.step(steps);
    Once the move has completed we delay for 0.5 sec
    Another Message "Stopped - Current Position = " then prints the value of Current Position
    This last part was added as I was getting all sorts of inconsistencies in the direction of travel , and I couldn't figure out why. Printing out this value, and then ......
    We now update the value of CurrentPosition CurrentPosition = (stepsToMove - CurrentPosition);
    and print it to the monitor, between the two sets of values I located the fault in the code and created the steps variable which can change state depending on direction, where the calculation for CurrentPosition needed to give a result of 0 or 1000, I was getting 0, 1000, -1000 and -2000, the latter two results would cause the turntable to rotate the wrong way and I'd have to press the reset button.

    Hopefully that was understandable, and remember please forgive the rough and ready approach, I am not a programmer, just a bodger.

    Any questions ?

    Paul
     
  6. Ron

    Ron Staff Member Moderator

    Messages:
    3,193
    Likes Received:
    580
    Joined:
    Dec 5, 2015
    OK so far, although I'm not sure the switch works and I don't know how to get the readout??



     
  7. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    Ok Ron

    Good news the leds are flashing :avatar:

    With the arduino software running and the arduino connected to the PC

    Goto the Tools Menu and select Serial Monitor

    A window should pop up, the sketch will also restart.

    You should now see the messages appear in the window.

    Which example are you up to.

    Paul
     
  8. Ron

    Ron Staff Member Moderator

    Messages:
    3,193
    Likes Received:
    580
    Joined:
    Dec 5, 2015
    OK, the last one but not sure the switch is working as it should??
    Ron
     
  9. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    So you have the done motor slowly turning to allow you to determine the number of steps for 1 rev.

    Got the motor running in both directions

    Got the motor to rotate 180 degrees by pressing the push button

    The last example needs a limit switch and some form of actuator on the shaft to trigger the limit switch.

    [​IMG]

    Above is the limit switch, the actuator is on the side of the turntable piece I printed.

    [​IMG]

    You could use a cable tie tightly fitted to the shaft as an actuator.

    Paul
     
  10. Ron

    Ron Staff Member Moderator

    Messages:
    3,193
    Likes Received:
    580
    Joined:
    Dec 5, 2015
    Got done the activator or a limit switch but happy enough so far! :)
     
  11. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    Hi Ron - weldone grasshopper, the dark side welcomes yo0u with open arms ..... :thumbs:

    without the actuator, stay with the sketch version in post 14.

    But try changing the values of both the speed (rpm), number of steps per revolution to see what effect they have.

    Then as a bit of a challenge, how about adding an extra pushbutton to one rotate clockwise the other to rotate counterclockwise.

    Or even change the position it rotates to.

    Keith - Ron is throwing the glove down, he's got his one working :avatar:

    Paul
     
  12. Toto

    Toto I'm best ignored Staff Member Founder Administrator

    Messages:
    13,376
    Likes Received:
    1,926
    Joined:
    Dec 5, 2017
    Well done Ron. I think that nearly makes you a Jedi. :avatar:
     
  13. gormo

    gormo Staff Member Administrator

    Messages:
    3,416
    Likes Received:
    909
    Joined:
    Dec 5, 2015
    Use the FORCE Ron,

    :thumbup::thumbup::thumbup::thumbup::thumbup:

    http://www.click:tophat:Gormo
     
  14. Ron

    Ron Staff Member Moderator

    Messages:
    3,193
    Likes Received:
    580
    Joined:
    Dec 5, 2015
    By the Force, do you mean a hammer??:avatar:
     
  15. Toto

    Toto I'm best ignored Staff Member Founder Administrator

    Messages:
    13,376
    Likes Received:
    1,926
    Joined:
    Dec 5, 2017
    Works in 99.999% of cases.n:avatar:
     
  16. gormo

    gormo Staff Member Administrator

    Messages:
    3,416
    Likes Received:
    909
    Joined:
    Dec 5, 2015
    No not that force Ron,

    You know....THE FORCE....as in Star Wars.....Sheeesh.!!!!!:cool::cool:

    There is definitely a hammer culture on this forum......maybe we should call it a Thorum.????:scratchchin:

    Thor liked hammers didn`t he.????.....you know Thor.....the Norse God dude with a big one.!!!.....Hammer that is........:avatar::avatar::avatar::avatar:

    http://www.click:tophat:Gormo
     
    Andy_Sollis likes this.
  17. jakesdad13

    jakesdad13 Staff Member Moderator

    Messages:
    3,471
    Likes Received:
    1,109
    Joined:
    Dec 14, 2015
    Toto wrote:
    If you can understand any of that, it makes you a Gold card carrying Jedi Master :eek::confused::avatar:

    Pete.
     
    Andy_Sollis likes this.
  18. Ron

    Ron Staff Member Moderator

    Messages:
    3,193
    Likes Received:
    580
    Joined:
    Dec 5, 2015
    OOh, THE Force not Thor's force!! :avatar::avatar:

    (Just trying to humour the grand master as he's not well!!) :worship:
     
  19. paul_l

    paul_l Staff Member Administrator

    Messages:
    6,630
    Likes Received:
    1,812
    Joined:
    Dec 5, 2015
    :facepalm: James Bond never has to up with this :bleep6: :avatar:

    Paul
     
  20. ianvolvo46

    ianvolvo46 Staff Member Moderator

    Messages:
    4,426
    Likes Received:
    825
    Joined:
    Dec 8, 2015
    So I opened my 'hard dinna you know' box read Pauls instructions and ...

    Attached files [​IMG]
     
    Andy_Sollis likes this.

Share This Page