arduino goto


Loop is have it perform a task once have some tasks written inside the void. Loop brackets perform that task once and then in a sense, get out a void loop so that it doesn’t endlessly repeat that task over and over and over again anybody who’s watching this videos probably experienced something like this say. I want the sentence to print once so. I’Ve put the serial print line command inside the void loop I’ve. Given it a delay, I’ve only entered one line of code. I’Ve want it to do this one time so I’ve entered it once well. When I upload this code, what happens? Well, let’s open the serial marker I’ll be printed 100 ups, oh no! I wanted it to print once what is it doing, it’s printing it over and over and over again and that’s, exactly what I didn’t want to happen. So how do we stop that? How can we control if I want something to print once or I want a countdown to go through from ten down nine eight, seven all the way to zero, and I want that to happen one time in the program. Well, the first option is, we can just take whatever commands. We won’t execute it one time and just place them inside void, set up and leave void, loop completely empty there’s, no problem, leaving it empty just empty, and then we can upload this code and check the serial monitor, see what happens. I want this sinister probe once and it dia, so all that we’ve done is basically place the code that we want to execute one time inside the very function that’s made to execute code just one time at startup, namely the void setup.

But what happens after is perform this task and void setup. Well, the Arduino keeps going, it goes, the void, loop and since void loop is empty. It just infinite it’s in an infinite loop of doing nothing. That’S what’s happening right here, so you’ve basically had the Arduino perform some tasks and then kicked it off into an endless loop, which is perfectly fine, there’s, nothing wrong. With that microcontrollers don’t mind being in an infinite loop. There is no operating system, so there is nothing to return back to so it has to do something so it’ll spin itself in an endless loop. But what if we wanted to give it actually control would loop itself like say if I want to have this sentence printed once let’s cut it and then paste it inside the loop again say I want some tasks to be performed. One time this sentence is just a stand in for whatever group single task for multiple tasks, one would like perform two one time. What is this tighten that up and what, if I do, need to be accomplished inside void, loop, well think about what happened when we placed it up in void setup, we place the sentence inside void setup. If printed once, then it moves to void loop and it spins in an infinite loop. Well, couldn’t we just construct an infinite loop at the bottom of void, loop and then have the Senate print once and then pitch it off into that infinite loop.

Absolutely you can do it using this sort of idiom in the C language known as an empty for loop, that it has no initiation point no test and no increment or decrement, and then it’s brackets are empty. Just to note that you could say empty using the multi line, comment, structure and then well does this work. Are we uploaded same check the serial monitor, yeah? I wanted it to prevalence and it did, but is this the only way to keep the Arduino in an infinite loop? No way there isn’t there’s at least two others? You can go wild and then say one and then have it empty. You can use in what’s known as an empty while loop and what happens with this while control structure is as long as its condition is true. It’Ll do whatever’s inside its brackets endlessly, and this is the trouble while loops most of the time as you’ve got. To remember to update some counter variable in the back end and the bottom end of a while loop or either you’ll be pitched off into an infinite look, especially when you’re doing programming in the C language or C or Python, etc, etc. You have to be sensitive when you use while loops, because they can be kind of dangerous where you have to hard stop the program if you pitch it into an infinite loop. Well, in this case, we can use it in microcontroller scenario to our advantage and actually have the Arduino do some tasks.

I mean this can be multiple tasks, I mean we could have serial count. One I don’t know. Cats are great whether one agrees with that or not and etc, etc. We could basically have blah, however much blah we want to occur before that wild one will only occur one time so just to test that and upload and Joe Mauro yeah. I want the center sprint once cats are great now at this point, what’s happening with the Arduino it’s spinning itself in an endless loop. So exactly what it’s doing, which is perfectly fine, because, as far as all outward behavior goes, what we really care about. It’S did what we wanted it to do and then it stopped it stopped and scare quotes it. Didn’T stop doing everything it’s still spinning right here, but it stopped every it stopped at the point we wanted it to so we have ultimately total control over wind void. Loop stops that empty for loop. We just discussed in this while one of it, while true, will also do the exact same thing. We can change this around. Just a verifier puppies are great upload the code and then verify through the serial monitor. Well. Listeners friend wants puppies are great, so this sort of casting void loop into an infinite loop at the very bottom like there’s the closed bracket. The void loop will give us the ability to do whatever task. We want it to run through one time and then it throws it into an infinite loop, that’s three different styles of infinite loops, just show them one more time have an empty four.

We can have while one of empty braces or you can have wild true eat. Any of those three will work and there’s, probably tons more. The C language is known for being able to do really neat things, these sort of idioms of the same language so that’s. All one has to do to be able to stop the void loop at the bottom and caste are doing them into an infinite loop. But if we want to be able to have in a sense a little more technical control over that, what if we want to vary, whether it goes into an empty or an infinite loop or not, based on something that occurs prior to that? Well, can definitely do that too, and this is the option that I tend to prefer. I tend to like to write games with where the Arduino is, where there’s a single player and their request Arduino is requesting moves in the game. The player enters. Those moves. Person plays the game, they either win or lose, and then it asks do you want to replay the game and based on their answer to that question. It either restarts with loop or it halts it or if well it puts it in another form of infinite loop. At least so, how would we do something like that? Well, we can do the global variable of the boolean time. Let’S use it so that we’re thinking more in terms of a game, we’ll say the replay variable and let’s set this variable initially to true and note what a global variable this is going to sculpt over everything that comes up a lot so in inside would look What we can do is test.

We can use an if control structure. We can say if we play double equivalence. It’S true, then do something like in here play the game, and then, after the person finishes playing the game, we can do a request. Like do you want to play again? Have that have a sentence to that effect, sent to the serial, monitor and then have the other sorts of serial available functions, catching the users and the players answer and then, depending on whether they answer whether he or she answers? Yes or no, we can toggle or keep the replay value the same let’s say we toggle it the faults so replay it using as false and then close down void, loop or that bracket, and so just so, we can see this say serial arm I’m totally with It this should just print once I’ll see if it does upload enjoy the game if printed just once. Why? Well, because what happened is initially we have. The replay value set to true it goes through set up hits void, bloom says, is it test is what is the value of replay? Well, if it happens to be true, then print that sentence and then after it exits the if the replay, which is a global variable, keep in mind, the value has been total defaults. So as soon as we talk about here to false it’s changed to false up. Here on this on this bottom pass, and so when it loops back around when void loop comes back around replay is no longer equal to true, so it stops, but it doesn’t, really your Arduino doesn’t stop doing anything.

No it keeps checking basically polling is replay. True, is it true, is it true, is it true and given that it’s been toggle defaults, no it’s, not true anymore, so it’ll never kick back into the loop, it will never repeat, but you can control back. I mean in I’ll have a more videos, video tutorials about the code involved and actually toggling this value based on user or player input, but that’s the simple structure. This is my preferred structure. This is the preferred way Miette for me at least, prefer this method or technique just set up a global variable, a blend type have it set to true or false, depending on how you want it to play out in the hand, have void loop begin and immediately Drop into a if test and then have something occur inside that if tests whatever I want to happen, one time through and then at the bottom toggle the value defaults and that will basically it forces void loop to act like setup, except the beauty of this structure Is that you could add more control code in here and actually have a person control, whether this value toggles, false or true? And if you you know in case you want it to run again, you could have it toggle true and then, when it comes around it’ll play it again, just to see that all that would have to happen. Let’S just set it to true this sentence: will print let’s put a delay in here, so we’re not wiped out with it on the serial order, so every half second enjoy the game should play on the serial, monitor cerium our enjoy the game.

Every half second see so all you need is code to control the value of replay which that’s pretty simple, that’s, just more ifs and more testing. Now there is another option: there’s actually more than any more options but say someone wants to create a kind of fancy. Stop the void loop function, that’s totally possible to you just to be consistent with something like that. Let’S rename our global variable say we want to have a bull in a stop it variable and set it to false. So this is saying: do we want to stop it? No, and all we would need, is to create just a function that returns updates to the stop it variable, so we can have given that we want it to return a boolean type value so stop. This will be, we can refer to this as the fancy stop main loop function. This isn’t really the with the method that I would pick, but it does work. So what just one do well you’re, basically going to do that same sort of if structure inside this let’s take let’s clean out, void loop just so this isn’t too confusing. So we have empty void, loop and we’re. Just building a special purpose. Stop main loop function. What we’d want it to do is every time it’s called we’d want to test that stop it variable. If stop it equals false, namely the users we don’t want it to stop the main loop to stop, then do something so let’s say serial one.

Just so, we know we’re inside the stop function, and then we can at the bottom of that condition, do something very similar. Just like we did before. We can say, stop it equals true. So after we do whatever happens inside the, if we toggle the stop it value and then just to cover all bases, because sometimes modifications inside a function that you’ll create variables that you think they’re global but they’re really not, and to avoid all that you can just Return, whatever the updated value of stop, it is so return stop it, and this will effectively shove the updated value outside of the bottom bracket to the stop and main loop function. And then all we have to do is inside a loop. Have the same. Stop at variable stop. It is going to be equal to well, whatever the value the updated value was ejected by the stop main loop function, so whatever this return value happens to be so, in this case, stop it’s going to equal, true, so it’s going to return that value, namely true, So this is going to in the sense, be replaced with true, so stop it’s going to equal true and then it will hit the bottom of void loop. But this is going to force that value to toggle at the global level and then, when all of this rolls back around stop it won’t be equal to faults anymore, and this sentence won’t run again, so we can test it just to make sure this is the More complicated way to do it, but for a person coming from using other sorts of programming languages that likes building little functions, see inside the stop main loop function, and it only executed one time and at this point what is the Arduino doing? Well, it’s come it’s continuously rolling around checking that condition, and it just so happens that that condition is true, so it never executes this line of code again and that’s.

Just to sort of fancy stop main loop function, that’s one way a person could go about stopping the main loop using a specially created function to do it, like I said earlier, this isn’t my preferred method, but it does work it just it tends to use a Little more bytes to because every function call takes a little more bias than just using a overarching if structure inside a void, loop itself and doing away with this. But no memory is always a concern and the Arduino contacts Ram is at least so. But this is an option now one could also as a final sort of humorous option. Let’S, take this out, take this out of main loop and take this away and say that you want they are doing able to do something just one time and then say: stop everything like cut its power off. Well, all you would need to do is have code so put whatever code. You want performed once there and then under here have say a servo lip power to our switch and have a switch built into the power cable for the arduino between the arduino and the battery and then at your very last command and void. Loop is have that server pull that switch open, that’s, why you could do that, but then you kind of are in a bind you’re going to manually flip the switch by but that’s. One way to do it. Another way would be have some sort of latching relay set up.

I’Ve done this myself, where you have say a security system that you’ve built for your home or your workshop or whatever just playing around with the arduino and you have it consistently checking a whole bunch of sensors, the whole bunch of proximity, sensors, etc, etc. And then, once a person pushes a button on the outside or their fingerprints, recognized or whatever you have, the very final command on void. Loop it’s, like it’s, continuously checking their sensors checking their sensors, and it ignores this value until some other external event occurs, at which time it flips a latching relay that cuts the power off the arduino and then turn the whole security systems. Disabled that’s also an option. Just something to think about there’s an interesting, really humorous discussion about all these various ways of even in a really humorous one. So you could have it have a servo and drop a hammer on top of the Arduino or whatever that’s the beauty of the Arduino. Is you can control the external world and all you have to do is control the power to the Arduino as it’s very last command inside point loop, that’s always an option. Well, I just soon as you power back up it’s going to start that loop all over it down until whatever value is toggled to trigger these other Vance. But Oh discussion of these various ways of stopping that pesky endlessly repeating main loop.


arduino goto Video







arduino goto news








arduino goto Social






👋 Want to bring Tony Stark-like gesture control to your projects? Learn how with the BLE-enabled MKR WiFi 1010 and Nano 33 BLE Sense boards using the ArduinoBLE library.
safe image.php?d=AQDyi1ELcW4VGzhx&w=720&h=720& dChOhNMmeF - arduino goto

Arduin-yo ho ho! A fairground favorite, the pirate ship is a fun way to explore the oscillation of a pendulum. How much fun, you ask? Access our Science Kit Physics Lab preview and see for yourself:

🔬 Now that you’ve gotten your feet wet, dive into the kit and enjoy all nine experiments. Order yours today:

70537898 550174072395145 8798850142103928832 n.jpg? nc cat=102& nc oc=AQmCfMPwMf1oPpYqFhzbxfnGdbrmsjZXrEEBy1ox5Z8EJtiYMADoFNZ5mnSNRgCCY74& nc ht=scontent - arduino goto
krNpw2k6 normal - arduino goto
Fri Jul 03 13:50:49 +0000 2009

@sergiocm Yo aprendí con un Colour Genie y descubrí que esto no era bueno:
10 rele on
20 rele off
30 goto 10

Con el spectrum programé en asm y me fabriqué una placa que manejaba 8 relés y un DAC y ahora algunos se creen muy listos porque hacen algo con un Arduino, Já!

M16 2nd edit

Arduino Pro Mini, my goto platform for anything



Originally posted 2019-02-17 06:23:40.

(Visited 339 times, 1 visits today)

About The Author

You might be interested in

Comment (47)

  1. I used aurduino analog to sense an anemometer’s input, and was struggling to get the microprocessor to ‘trip’ a circuit only a single time after a certain analog input level was reached. This was extremely helpful. I now have a wind sensor that protects my electrical awning from high speed winds by forcing it to roll up during inclement weather. Thank you.

    1. @SALTYstunt That’s a great way to use an Arduino and some stop void loop code to save an awning.  

      Is the code logic something like:  Read current wind speed, if speed exceeds a certain threshold, trigger awning ‘roll-up’ motor, and then “stop” (at least until the reset button is pressed)?  Just curious.  

      I always enjoy hearing about the creative ways people use microcontrollers to accomplish specific tasks.  The limits to what one can come up with are almost endless.        

      Greatly appreciate the comment and I’m glad the video was helpful.  Definitely let me know if there are any coding questions, etc., in the future and I will always do my best to help.    

    2. @philo mech You got it spot on! Thats exactly what I have coded.  I was really struggling to find a “stop”  after triggering roll up, since I am new to aurduino and my only experience is varying a blinking led with a potentiometer! ha.   This video saved me though! Thank you again! 

  2. Every time you referred to “void loop” I cringed.  Surely it is simply “the loop function” This is why people wrongly refer to functions as voids

    I notice that when you referred to your stop_main_loop function you did not call it “boolean stop_main_loop”

    1. Appreciate the comment.  I can understand the concern,  All the void qualifier really means is that the ‘main loop function’ required in every Arduino program returns nothing (at least at the level it’s operative on).  Which makes sense given that there’s no operating system for it to return anything to.  Is it a less than ideal habit to refer to it as ‘void loop’?  Perhaps.  It is as you mention, not necessary and potentially technically misleading.  But, I tend to refer to it as such because that’s what beginners see in most of the tutorials and reference materials, not to mention that they have to type in “void loop” rather than “main loop” in every Arduino program they’ll ever write.  Essentially, they will constantly see references to “void loop”, not the “the loop” or “main loop” function.  The assumption is that once they move past the beginner stage and begin creating their own special purpose functions they’ll soon discover that the ‘void’ in front of ‘void loop’ is nothing more nor less that an indicator that the ‘main loop’ function provides no usable return value. (at least at the level it’s operative on).  Hope that seeing my reasoning is somewhat helpful.   Definitely appreciate the feedback.  

    1. @philo mech well played 🙂 I tried something like that once at 2:11  watch?v=UwvpjSPCBJ0&list=UUNWQzHrAxPdBlxjiNTx-obQ  🙂

    1. @Ruben Munoz   Thanks for the question, I gladly do my best to help.

      First, let’s make sure I have the logic of what you want the Ard to do right.  

      You want it to run a loop (loop A) for a specific amount of time,
      then enter another loop (loop B) and run it for a specific amount of time,
      and then repeat loop A?

      Correct?  or Incorrect?

    2. @philo mech  well im working on arduino car and i want the car to go forward for a short period than stop and go backwards. do i do a if statement or a while statement 

    3. @Ruben Munoz Thanks for the reply.
      Are you using plain (i.e., brushed) DC motors, continuous rotation servos, or perhaps steppers?   Each can require different code.  In most cases you won’t need the if or while control structures to achieve the behavior you seem to be after.  

      Second (assuming you’re using DC motors) are you powering the motors via discrete components (e.g., an H bridge or some other configuration made from mosfets, etc.)?  Or might you be using a specific motor shield?  Such will sometimes make a difference in the code.   

      Either way, I can definitely provide you with a generic while loop example that would handle all cases (and much more).  I built such an example today and will be uploading a video about it tomorrow.  

      Just let me know and I will continue to do my best to help.

    4. @Ruben Munoz My video software is currently misbehaving but I’ll have a video about constructing time-sensitive while loops uploaded by tomorrow afternoon at the latest.  My apologies for the delay.

  3. Hi. I´m trying to make a loop with “while” to move servo between 40 e 140 degrees. Could you help me? Thanks.

    1. @Rubens Mendonca Thanks for the question. I’ll need a little more information in order to help. Is the goal to move a servo from 40 to 140 and then back again from 140 to 40, then repeat over and over? Sort of like the sweep example discussed on the Arduino website? Google keywords: “servo sweep Arduino” Or might you have something else in mind?

    2. @philo mech Hi,Philo!

      Firstable, tanks for your quick answer!
      I`m using two servos, one (servo 1) goes from left to right and another (servo 2) from up to down.
      My idea is: when servo 1 goes from 40 to 90, servo 2 also goes from 40 to 90; and when servo 1 goes from 90 to 140, servo 2 goes from 90 to 40. It´s kind of “V” moviment, got it?
      I already know do with “for”, but I want to do with “while”.
      Could you help me?

      Thanks a lot.

    3. @Rubens Mendonca Thanks for the reply and additional information. I’ll do my best to help.

      Most anything one can do with a for loop can also be done a while loop. While loops just have the addition benefit of being able to loop when the precise “count” isn’t necessarily known from the start. For example, for loops are great for cases where one wants something to repeat for a known amount of times (trigger a relay 5 times, blink an led 10 times, etc. While loops can do that too, but they can also perform tasks like, ‘perform a specific task until some external event occurs, the precise number of times to actually perform the task isn’t known or perhaps even cared about ‘, ‘keep stepping a stepper motor until a button is pressed, when one doesn’t really care how many steps are actually taken’, etc. It’s accomplishing the latter sort of tasks where while loops often become especially useful.  

      As to using a while to perform a sort of 40 to 90, 90 to 40 sweep of a servo, all one should structurally need is something like the following:

      //global variable, or could have been previous written to servo, etc.
      int current_servo_position = 40; //initial value used by 1st while loop
      //this is what normally appears in the
      //first slot of a for loop i.e.,for (i = 0; …){…}

      //inside void loop
      //(1st while loop) advance servo from 40 degrees to 90
      while(current_servo_position < 90){ //test value, this is what normally appears //in the center slot of a for loop // i.e., for( ...; i < 100; ...){ ...} servo.write(current_servo_position); delay(15); current_servo_position = current_servo_position + 1; //increment pos by 1 //each time through loop //this is what normally   //appears in the last slot  //of a for loop i.e., for(..;.. ; i++){...} } //(2nd while loop) reverse servo from 90 degrees back to 40 while(current_servo_position > 40){ //it’ll be 90 after exiting the 1st while loop
      current_servo_position = current_servo_position – 1; //decrements by 1

      Hope these lines and comments are helpful. Hopefully, they’ll at least get us started in the direction of securing the target behavior. If you have already figured out how to interleave (drive two servos ‘simultaneously’) and simply need to convert for loops to while loops, then you’re already well ahead in the game and the above code structure should be all that you’d need. The above lines of code are just the Arduino servo sweep example that utilizes for loops converted into while loops. If you need something more than simply a conversion from one to the other, then please and let me know and I will continue to do my best to help.

    4. @philo mech Thanks a lot, my friend. I have to sleep now, but tomorrow I´ll make this test and you´ll know the results! ; – ) … Thanks again, best regards. Rubens

  4. I have been watching your videos looking for clues to solve my problem.  I really like your videos and your teaching technique and have learned a lot – Thanks!
    I want to start a step motor with a momentary on push button, have it run a loop one time then stop and wait for the next button push to run the same loop or a different loop depending on which button is pushed.
    I am building an X- Y table for my drill press to increment my work piece along in the X direction then stop to be drilled manually, and moved again to next location.  The Y direction is used rarely and will be hand cranked to position for now.
    The hardware I am using is: 
    Laptop (for downloading only)
    Arduino uno
    Spark fun Easy Driver 4.4
    4 momentary on push buttons
    NEMA 17 (maybe 23) Bipolar Stepper Motor (1.8 deg. / 200 steps per revolution)
    Jumper Wires and connectors
    Bread Board (Until final setup)
    Power from computer tower transformer (3.3V, 5V, 12V, 24V)
    The desired steps to start and use the X—Y table would be:
    ·         Power up
    o   LED comes on to show (Power On)
    ·         Nothing happens
    ·         Operator presses and releases any one of 4 momentary on buttons
    o   Stepper motor rotates 2, 3 , 4, or 6 revolutions as per button pushed
    o   Then stops to wait for next button push
    ·         Direction is controlled by external toggle switch connected to DIR pin of Easy Driver

    1. @Bill Guthridge Thanks for watching! Appreciate the feedback and question. I’ll certainly do my best to help.

      For ease of discussion let’s assume one uses a 200 step per revolution motor.

      I tend to always start with the target input to output behaviors

      (1) press button 1 –stepper advances by 400 steps (2 revolutions)
      (2) press button 2 –stepper advances by 600 steps (3 revolutions)
      (3) press button 3 –stepper advances by 800 steps (4 revolutions)
      (4) press button 4 –stepper advances by 1200 steps (6 revolutions)

      I haven’t yet had the chance to use the easy driver board so I followed the link from the sparkfun website to the easy driver website. Assuming that DIR,etc., is accounted for, it seems that advancing a motor one step at a time essentially involves sending a pulsing high/low signal to the driver’s STEP pin. The rising edge of each low to high transition will advance the motor by a step. Definitely let me know if there’s more to it. 
      If not, then the core lines of code could be something like:  

      const int step_pin = 6; //connected to STEP pin of driver board

      digitalWrite(step_pin, LOW); delay(2); digitalWrite(step_pin, HIGH); // 1 step  
      The rising edge of the transition from LOW to HIGH on step_pin should advance the motor a single step in the direction dictated by setting the DIR pin HIGH or LOW. (I’d test to see if such works as expected)  

      If that’s all that needed to ‘manually’ advance the motor a single step, then one could obtain the desired revolutions (2, 3, 4, 6, etc.) with something like the following function (other, perhaps more elegant, functions could be constructed but this should work):

      void steps(int num_of_steps){
      for(int i = 0; i < num_of_steps; i++){ digitalWrite(step_pin, LOW); delay(2); digitalWrite(step_pin, HIGH); delay(2); //I added the 2ms delay between the transitions but it might not be needed or a   //slightly longer delay might be needed depending on how quickly the driver's STEP   //pin can process LOW to HIGH transitions } digitalWrite(step_pin, LOW); //don't know if this would be needed, but it shouldn't hurt //anything to include it } One could call this function using, e.g., steps(400); and the motor should advance 2 revolutions. steps(600); for 3 revolutions, steps(800); for four revolutions, etc. That would take care of securing a significant number of revolutions (though one would need to change the num_of_steps argument from int to long/unsigned long to obtain an excess of around 160 complete revolutions --160 revolutions = 32000 steps/200steps per revolution... the int type is about used up at a little over 32000 so one would have to switch to long if more than that number is needed--- Assuming that the above step function would work, then the next step would be to secure the execution of the desired number of revolutions based on which momentary button is pressed.   Make sure to debounce the momentary buttons (I'd do so externally with a schmitt trigger setup--see, e.g., Jeremy Blum's channel or Derek Molloy's channel for schematics of the typical s trigger debounce circuitry ... such is often a little more convenient (at least to me) than dealing with millis() debounce code. Either will work, but using the external s trigger tends to simply the code one has to write). After debouncing the buttons one could then use something like the following to have four buttons select between the desired revolutions: void loop(){ if(button_one == HIGH){ //or LOW, depending on how one wires the s-trigger circuitry step(400); //2 revol } else if (button_two == HIGH){ step(600); // 3 revol } else if (button_three == HIGH){ step(800); //4 revol } else if(button_four == HIGH){ step(1200); //6 revol } } //end of main loop The if/else if control structure means that the Arduino would be constantly polling the button pins each time through the main loop. That shouldn't be a concern unless one plans to alsohave the Ard perform other, e.g., time sensitive or math intensive, lines of code. Please let me know if I missed the mark with the code or understanding of easy driver board's control pins. As mentioned, I haven't used it before and based the step() function described above off of a quick glance as the easy driver website. If I did miss the mark or more is needed to get you started definitely let me know and I will continue to do my best to help. I want to start a step motor with a momentary on push button, have it run a loop one time then stop and wait for the next button push to run the same loop or a different loop depending on which button is pushed. I am building an X- Y table for my drill press to increment my work piece along in the X direction then stop to be drilled manually, and moved again to next location. Bread Board (Until final setup)The desired steps to start and use the X—Y table would be: ·         Power up o   LED comes on to show (Power On) ·         Nothing happens ·         Operator presses and releases any one of 4 momentary on buttons o   Stepper motor rotates 2, 3 , 4, or 6 revolutions as per button pushed o   Then stops to wait for next button push ·         Direction is controlled by external toggle switch connected to DIR pin of Easy Driver

    2. @philo mech Thank you for the quick reply. I will be gone today, but I have read your reply and cant wait to try it out. your code for running the step motors is much cleaner than mine and will be easy to fine tune the revolutions if needed. When I get all done and running i will let you know. THANKS!!

    3. @Bill Guthridge Hope the code is helpful and that it at least gets us started in the direction of securing the behavior you’re after. If you try it and find that more is needed, just let me know and we can go from there. I look forward to hearing about how the project turns out.

  5. Hi… I would like to thank you for your instructional videos you’ve placed on Youtube
    I am a neophyte to Arduino and programing so I ask your indulgence in my question to you. I would like to know if you can use the commands you describe in this video on a For Loop? I have a sketch I would like to pause after it runs the for loop 5 times pause for 10 seconds than continue. Thanking in advance for any help or direction you can provide and for your time.

    1. @Sal C Thanks for the question and for watching!

      If I haven’t misunderstood the target behavior, then the following should work.

      void loop(){

      for(int i = 0; i < 5; i++){ //task you want performed five times goes here }   delay(10000); //delay for 10,000 milliseconds = 10 seconds } //<-- end of void loop (1) enter void loop(), (2) for loop performs task five times, (3) delay for 10 seconds, and then (4) start all over again.   Did you have more in mind? Just let me know if more is needed and I will continue to do my best to help.

  6. hi,

    I am building a knee orthese, and i want to count how many cycles my orhtese makes.
    there for i need to count how many times my flexsensor reaches a specific value.

    the problem is that my counter always count to much , when i reach the range

    my counter needs to go +1 each time my flexensesnor reaches a value.
    I think it is with a pulse? , but i don’t know how to program it.

    or are there other possibilities, like counting the void loop? 

    this is the code where i switch my motor in direction. by the range of the flexsensor of 90° 

    case 90 :  

            flexvalue = constrain(flex90to0, 0, 90); digitalWrite(richtingmaxon, HIGH );
            if (flexvalue == 0) {
              digitalWrite (directionmotor , LOW);

    so, how can i count these loops?

    1. @Pieterjan De Meulenaere Thanks for the question.

      Is the goal to increment the count by 1 each time the flex sensor surpasses a specific threshold?

      Something like:

      If (flex_sensor_value > threshold_value){
      count = count + 1;


      Just let me know and I will do my best to help.

    2. @philo mech  hi , thanks for the quick reaction. yes that’s the goal.

      so if it reaches 90 the motor goes Clock Wise , if it reaches 0 its goes CCW.

      the problem is that the flexsensor is not that acuarate, so the threshold value of 90 is exceeded more than once every time. so the normal if structure doesn’t work. Got it?

      so we need to count +1 every time the direction of the motor changes…

      thanks fo your help

    3. @Pieterjan De Meulenaere Thanks for the details, they’re helpful.

      Triggering an event based on a consistent threshold can be a challenge with flex sensors.  

      The behavior of the ones I’ve worked with: 

      When not bent they tend to ‘hover/float’ around a small range of values and when bent to the left or right (forward/backward) the values tend to decrease…something like 600 when not bent, 300 to 400 when bent all the way left or right.  

      Their low values appear twice (once when bent left, once when bent right). For example: bent_left_value = 300, unbent_value = 600, bent_right_ value 300.

      Since you’re limiting the range of movement (like a knee) to the 0 to 90 degree window, it should be possible to map and constrain the values.

      Let’s see…

      Suppose the unbent_value = 600;
      and the 90 degree bent value = 300;

      int flex_sensor_pin = A1;
      int flex_sensor_value = 0;

      int unbent_value = 600;
      int bent_value = 300;

      int count = 0; //type could be changed to unsigned long if needed

      void setup(){
      Serial.begin(9600); delay(100);
      pinMode(flex_sensor_pin, INPUT); //not strictly necessary

      void loop(){

      //collect reading from sensor
      flex_sensor_value = analogRead(flex_sensor_pin);

      //map incoming values to a 0 to 90 degree scale
      flex_sensor_value = map(flex_sensor_value, bent_value, unbent_value, 0 , 90);

      //constrain flex_sensor_value to 0 to 90 (anything above 90 is changed to 90)
      flex_sensor_value = constrain(flex_sensor_value, 0, 90);

      //the above lines should deal with the case of the value exceeding 90
      // I’d test it to make sure…bend the sensor and see if flex_sensor_value ever  
      //exceeds 90 now…
      Serial.print(“flex_sensor_value = “); Serial.println(flex_sensor_value);

      //assuming we’ve successfully confined the range to 0 – 90, then the if control  
      //structure should work 

      if(flex_sensor_value == 0){
      // motor CCW code

      count = count + 1;

      else if(flex_sensor_value == 90){
      //motor CW

      count = count + 1;


      } //<-- end of main loop Hope these lines are helpful.   Please let me know if the above code is starting to approach what you're after (or not) and we can go from there.

    1. @Bogdan Morecz Appreciate the question.

      Something like the following would work

      void loop(){

      int i;

      for(i = 0; i < 10; i++){ //command to repeat 10 times here } for(i = 0; i < 50; i++){ //command to repeat 50 times here } while(1){ } //stops void loop from repeating } //<--end of void loop This would execute the first command 10 times, execute the second 50 times, and then "stop" the main loop. Hope the code snippet helps. Please continue to let me know if/when there are any questions and I will always do my best to help.   Thanks for watching!

    2. @philo mech it helped me a lot with that for “thing” thanks a lot. I am using arduino for a 3×3 led matrix and i am trying to do my best in understanding how this small thing works befor going further this is my code:
      void setup() {
      pinMode (2, OUTPUT);
      pinMode (3, OUTPUT);
      pinMode (4, OUTPUT);
      pinMode (5, OUTPUT);
      pinMode (6, OUTPUT);
      pinMode (7, OUTPUT);

      void loop() {
      for(int a= 0; a <70; a++){
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(7, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(7, LOW);
      digitalWrite(3, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(7, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(5, LOW);
      digitalWrite(7, LOW);
      digitalWrite(2, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(7, HIGH);
      digitalWrite(2, LOW);
      digitalWrite(5, LOW);
      digitalWrite(7, LOW);
      for(int b= 0; b <70; b++){
      digitalWrite(2, HIGH);
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      digitalWrite(2, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      digitalWrite(3, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(7, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(5, LOW);
      digitalWrite(7, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);

      at the moment is just a 2 step animation but it seams kinda long, have i done something wrong ? i mean what if i want 20 steps ? this thing would be verry long.

    3. @Bogdan Morecz Glad the “for” code helped. Working with led matrix animations is always a lot of fun. One can learn a lot about coding during the process. There’s nothing ‘wrong’ with your code. It’s possible to manually control large (e.g., 10x10x10, etc.) led cubes using little more than hundreds/thousands of digitalWrite commands. The code soon becomes very very long, but it can be done and will work.  

      But, there are alternatives. One option is to use one or more shift registers (595s, etc.). Using shift registers allows one to simply shift out the binary equivalent numbers of the pattern one wants. Another option is to use a multidimensional array, e.g., int array[3][3] = {…} to store the HIGH/LOWs patterns you want and then step through each row in the array using for loops. The third and very common option is to store the binary equivalent numbers of the various patterns you want in one or more arrays, step through the rows in the arrays with for loops and send the numbers out to one or more shift registers. As these comments are likely starting to indicate, coding matrix patterns and animations can quickly become quite the task.  

      But, at base, matrix patterns/animations are just many many sequences of ON/OFF signals to leds like your current digitalWrite code indicates.  

      The challenge is often in learning about the various ways to condense all of those writes into more compact code structures. That’s where multidimensional arrays, loops, and shift registers come in. Given that you’re currently working with a 3×3 matrix (nine led total) using a shift register would be overkill and likely add unnecessary confusion to the mix. If/when you decide to go to an 8×8 (or larger) matrix, then shift registers are definitely the way to go.  

      But for a 3×3, learning about how to use multidimensional arrays to store the sequence of ON/OFF patterns you want and how to step through those patterns would likely be more than enough. I would definitely encourage you do a search for “coding multidimensional arrays in C”. Once you learn how to construct and successfully step through those sorts of arrays, then you will have the core coding structure and techniques needed to control patterns across small to huge led matrices, led cubes, etc.  

      Arrays –and especially multidimensional arrays— may initially appear complex, painful, and not a lot of fun. But, they are the “secret” to coding simple to sophisticated matrix animations in a manner that doesn’t require manually typing thousands of digitalWrites. Most or the matrix animations that one sees on a daily basis are grounded in code that utilizes multidimensional arrays.  

      If you think it might be helpful, I can compose a few videos on the coding structures, etc., associated with creating led matrix patterns/animations. It will be a few months before I will have the time to do so (I have quite a few viewer requests and project videos to make it through first), but I certainly don’t mind making the videos. Just let me know if a series of videos about this topic might be helpful.

    4. that would be verry helpfull indeed. And my 74hc595 shift register are on their way. This 3×3 was just the begining. I made it this small so i can understand the coding much better. If you are willing to do a simple video for arrays that would be great. Meanwhile i will look on other sites for examples of arrays. thanks again for your kindnes. Oh and i condensed the code into something like this

      void setup() {
        pinMode (2, OUTPUT);
        pinMode (3, OUTPUT);
        pinMode (4, OUTPUT);
        pinMode (8, OUTPUT);
        pinMode (9, OUTPUT);
        pinMode (10, OUTPUT);
      void toggleLed(int led1, int led2, int led3, bool state)
        digitalWrite(led1, state);
        digitalWrite(led2, state);
        digitalWrite(led3, state);
      void loop() {
        for (int a = 0; a < 100; a++) {     toggleLed(4, 8, 10, 1);     delay(1);     toggleLed(4, 8, 10, 0);     toggleLed(3, 8, 10, 1);     delay(1);     toggleLed(3, 8, 10, 0);     toggleLed(2, 8, 10, 1);     delay(1);     toggleLed(2, 8, 10, 0);   }   for (int b = 0; b < 100; b++) {     toggleLed(2, 9, 10, 1);     delay(1);     toggleLed(2, 9, 10, 0);     toggleLed(3, 8, 10, 1);     delay(1);     toggleLed(3, 8, 10, 0);     toggleLed(4, 8, 9, 1);     delay(1);     toggleLed(4, 8, 9, 0);   } } it helped me reduce the code to almost half the lines.

  7. I have a question see if you can help,, I am inside of a while loop and when the button of pin2, is not being used I wanted to exit   while loop

  8. I have a problem with my code.

    if (buttonState == HIGH) {

    if (buttonState == LOW) {

    I’ve tried doing all your steps however, I put it inside an if statement but it doesn’t work.

    My problem is when I still haven’t pushed the button, I keeps printing B. same thing happen when I keep the button HIGH.

    I need it to perform the task like when I pushed the button it will print A once and when I release the button it will also print B once.

    1. +Adrian Joseph Almoro Thanks for the question. 

      It sounds like you want the code to respond to single state changes (state “toggles”). That is, you want it to note (print A or B) when the button state changes from HIGH to LOW or from LOW to HIGH but you don’t want it to do anything (besides continuing to read the button) when the button state remains unchanged. Please let me know if I misunderstood what you’re trying to accomplish.  

      Assuming I didn’t misunderstand, the following should help.

      //global variables

      int button_pin = 4; //set to whatever digital pin you’re using

      boolean button_state = 0; //for storing current button state  

      boolean previous_button_state = 0;

      void setup(){

      pinMode(button_pin, INPUT);
      Serial.begin(9600); delay(100);

      } //end of setup

      void loop(){
      //read and store current button_state
      button_state = digitalRead(button_pin);

      //if current_button_state doesn’t equal previous_button_state
      if (button_state != previous_button_state){

      //then print a letter corresponding to new current state: A for LOW to HIGH transition,
      //B for a HIGH to LOW transition

      if(button_state == 1){
      else if(button_state == 0){

      //update previous_button_state variable, set it to current_button_state value
      //this is the crucial bit. previous_button_state provides you with a way to test for
      //state changes each time through the loop

      previous_button_state = button_state;

      delay (200);

      //if there wasn’t a mismatch between button_state and previous_button_state,
      //then the code should just loop back to the top, read the button, check for a state change, if not, //then loop again, and again, etc.
      //Should only see A or B appear for changes of button_state, otherwise the serial monitor will be //blank

      } //end of main loop

      If you see multiple As or Bs (3 to 10+ of them) and then nothing, then the button you’re using will need to be debounced in the software or via some hardware.

      Hope the code helps. Please let me know if you had something else in mind and I will continue to do my best to help.

  9. Good tutorial, really clear and exhaustive.
    But I have a question. What do you think about making a request at the beginning of the loop, waiting for the answer whitout performing the first loop? If the request will be satisfied the first loop will be executed, if not, the loop is stopped.
    In my case:


    void loop()
    // Wait for the user to press button A.

    // function to be performed


    It works, but my question is, which of these methods requires less memory and power?


  10. I’m building a green house where the user can control or set the desired levels of various parameters.
    the user interacts with the program via a 4×4 keypad.the program should display the status of the current values but when a key is pressed the user should be able to edit the values desired.
    i know how the sensors works but the main problem is that the program is not detecting my keypresses.


    #include // include the library code
    # include #include

    const int numRows = 2;//constants for the number of rows and columns in the LCD
    const int numCols = 16;
    int count = 0;
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);// initialize the library with the numbers of the interface pins

    const byte ROWS = 4; //four rows
    const byte COLS = 4; //three columns
    char keys[ROWS][COLS] = { {‘1’, ‘2’, ‘3’, ‘A’},
      {‘4’, ‘5’, ‘6’, ‘B’},
      {‘7’, ‘8’, ‘9’, ‘C’},
      {‘*’, ‘0’, ‘#’, ‘D’}
    float humidity, temprature, moisture; // variables globally declared
    boolean light;

    byte rowPins[ROWS] = {22, 23, 24, 25}; //connect to the row pinouts of the kpd
    byte colPins[COLS] = {26, 27, 28, 29}; //connect to the column pinouts of the kpd

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    void setup()
      lcd.begin(numCols, numRows);
      lcd.setCursor(0, 0);
      for (int i = 0; i < 16; i++) {     lcd.setCursor(i, 1);     lcd.write(255);     delay(170);   }   lcd.clear(); } void loop() { // THE PROGRAM SHOULD DISPLAY THE STATUS OF SENSORS UNTILL A KEY IS PRESSED   keypad.getKey();   while (NO_KEY)//THIS DOES NOT WORK   {     lcd.print("hello");// EXAMPLE STATUS   } } void keypadEvent(KeypadEvent eKey) { switch (keypad.getState()) {     case PRESSED:       Serial.println(eKey);       delay(10);       switch (eKey)       {  // though i am able to get in this part         case 'A': lcd.clear(); // WANT USER TO ENTER A 4 DIGIT NUMBER WHICH CAN BE MADE AS SETPOINT OR UPDATES THE CURRENT VALUE           lcd.setCursor(0, 0);           lcd.print("Enter Desired");           lcd.setCursor(0, 1);           lcd.print("HUMIDITY:");// THE USER SHOLD BE ABLE TO ENTER THE VALUE HERE WHICH WOULD BE UPDATED           break;         case 'B': lcd.clear();           lcd.setCursor(0, 0);           lcd.print("Enter Desired");           lcd.setCursor(0, 1);           lcd.print("TEMPRATURE:");           break;         case 'C': lcd.clear();           lcd.setCursor(0, 0);           lcd.print("Enter Desired");           lcd.setCursor(0, 1);           lcd.print("MOISTURE:");           break;         case 'D': lcd.clear();           lcd.setCursor(0, 0);           lcd.print("LIGHT");           lcd.setCursor(0, 1);           lcd.print("ON/OFF"); //BOOLEAN TRUE/FALSE           break;       }   } } pease help

  11. I want to ask a question.

    but before that i want to give you my problem:

    I was making a program with 1 switch button and 3 led,

    if i press the switch button it will produce a running light:

    and if i press the switch button again it will stop the running light.

    I tried using debounce but it became redundancy due to using of delay to run the light(LED)

    so pressing again the switch wont work tried using several syntax as container to avoid redundancy but still failed. hope you can help me.

    heres my CODE:

    const int sw1 = 2; //control for switch1 < >
    const int sw2 = 3; // control for swtich2 < >
    int oldbutton = 0;
    int bstate;
    int bstate1;
    int last;
    const int ledstate= LOW;
    const int ledstate1= LOW;
    int reading;

    void setup() {
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(sw1, INPUT);
    pinMode(sw2, INPUT);

    digitalWrite(7, ledstate);
    digitalWrite(6, ledstate);
    digitalWrite(5, ledstate);


    void loop() {

    bstate = digitalRead(sw1);
    reading =digitalRead(sw1);
    if (bstate == HIGH){

    while ((bstate ==HIGH) &&(ledstate == LOW)){

    digitalWrite(7, HIGH);
    digitalWrite(7, LOW);

    digitalWrite(6, HIGH);
    digitalWrite(6, LOW);

    digitalWrite(5, HIGH);
    digitalWrite(5, LOW);


    if ((bstate == HIGH) && (ledstate == HIGH))
    bstate == !bstate;


  12. hi great tutorial, is it possible for you to explain how can i save position of a 3 servo motors moved by potentiometer and repeat the saved movement by pressing a button?
    thanks very much


Your email address will not be published. Required fields are marked *