How to start a loop with a manual switch

No, but I like to give clear advice. Some/all of my suggestions may not be the best/fastest/cleverest way to do what is wanted but I aim to push the reader in the right direction. Often it would be faster to post the actual code but IMHO that is not the way to learn.

Much better to take general ideas, such as 'set running false' and turn it into code to initialise a boolean variable called running with the value of false by entering the code yourself. The most important thing is to end up with working code that you understand. It can then be modified/improved to use other techniques if you want to. It seems to me that some people are here to show off rather than give constructive advice. Just think of what the response would be if someone suggested using Strings in response to a question....

I will continue to provide advice in the form of pseudo code where I think it appropriate.

Strings are bad practice on small environments. Using them instead of char array strings develops reliance on String.

Teaching people to over-code is a good thing now?

I guess you have a different idea of showing off too.

GoForSmoke:
Strings are bad practice on small environments. Using them instead of char array strings develops reliance on String.

I think you made my point for me and for what it is worth, I agree with you, but initial use of Strings fits well with the model of get it working, then improve it.

Teaching people to over-code is a good thing now?

Over-coding is not a good thing, but coding something that works is. Get it working, improve it, then use the improved techniques to deal with similar situations in the future.

I guess you have a different idea of showing off too.

I probably didn't explain what I meant too well, so let me expand on it. An experienced Arduino programmer will approach a problem in a different way to someone new to it. They will tend to suggest a solution that they themselves would use when a more stepwise (over-coded) solution would be more appropriate starting point, albeit not one that they would use themselves.

You asked if I like to type ?
What is your solution to do what the OP asked ?

With a switch through a pullup (which might have to be explained, but great to know),

while ( !digitalRead( switchPin ));

Without the pullup

while ( digitalRead( switchPin ));

And I do assume there would be questions.

I graduated HS in 75 but I haven't forgotten the better courses and teachers and how those went.

UKHeliBob:

set running false

start of loop
  while running is true  //infinite loop doing nothing
  end of while
[/quote]
How is he going to escape that loop?

Hey guys, I appreciate all the discussion. It gives me things to study and discover. Bob, I really appreciate the advice and welcome the longer, but more conducive to learning, code approach.
Side note:
This programming is for side projects, but my business is cnc machining of oilfield parts. I just started about 7 years ago at the age of 53 as a complete rookie, but it was something I'd always wanted to do, but had too many other careers going. I started part time at a casting plant with 5 cnc machines and they would flop you from one machine to another day to day, so I never had time to learn any of the machines in great detail. They start you out as a 'button pusher'. Load the part, hit the 'go' button, unload the part. Soon, I could set diameter offsets, etc and gradually learned the G code by watching it go by. After 8 months, I quit, built a small shop and bought a 15 yr old machine. I had a steep learning curve, but quickly got to where I could handle daily programming and get the job done. I hadn't learned about subroutines, and most of my 15 minute part cycles were around 10,000 lines of code. Improvements in production came from improved fixtures, higher cutting speeds, etc. Then, just about 6 months ago I finally got time to study subroutines. Now my programs are maybe 20% as many lines; are easier to modify, etc. The longhand approach got my machine paid for, then when I had time, the extra learning simplifies the process.

I expect this process to be similar and I love the learning process. The frustrating times are when I can't find what I am after in my C programming book and a couple hours online fails to yield any information. This thread gives me a few directions to go and I appreciate the time y'all spend giving pointers. I also enjoy the different views on how to approach the solutions.

This first project is for a partner in the film business with a Special FX company. He needs a sequencer for pyro with 48 channels that have a variable gap between firing as well as a variable duration that each is on. (Air mortars take a few seconds to unload, while squibs/bullet hits are instant) I plan to end up with a touch screen that sets up his variable library, as well as a sound library so that he can demonstrate the firing sequences to the director to make sure it is what they want.

Next project is an automated parts fixture for my cnc machine. I use 12 ft. flat bar to produce parts about 6" long. I have started a design that will feed in the full bar and cut one part at a time. Ultimate goal is a 'lights out' system that might run 16 hours per day with us there for 8 hours.
Thanks all, I appreciate your help!

I was writing NC and CNC code back in 79-83 before I went on to programming full time. I wrote shop programs to produce tapes for an NC Wiedemann turret press, a Spindle Wizard CNC mill and a CNC FANUC controlled lathe. Like you I had no degree at it, I learned by doing.

Yes Bob, I got the sense of those two cases backwards. We watch pullup switches for LOW and non-pullup switches for HIGH. But my loops when done right exit on switch change.

namenerb; we can connect a switch two different ways.

One way you connect the switch pin to the switch and a resistor then to 5V. If the switch is ON then the switch pin goes HIGH. The code to set the pin up in setup() is pinMode(switchPin, INPUT) and code to read the pin is X = digitalRead(switchPin).

The other way you connect the pin to the switch and the switch to ground. Or, for testing I just stick a jumper in the hole for that pin and tap the other end of the jumper to the grounded USB receptacle. If the "switch" is ON, the pin goes LOW. The code in setup() is pinMode(switchPin, INPUT_PULLUP) in IDE 1.0 and since (let me know if you run an older IDE) and the code to read the pin is the same.
Using the pullup to ground through switch saves you a resistor and guarantees low current use, the pullup resistor built into the chip is 20k or more.. it's safe.

Here's a working test. You can use it to test your switch for bounce.

// note that this code does no switch debouncing

byte  switchPin = 7; // I'm using pin 7 to connect my jumper wire "switch"
byte lastSwitchState;

void setup()
{
  Serial.begin( 9600 );
  Serial.println( "press the switch" );

  pinMode( switchPin, INPUT_PULLUP );
  while ( digitalRead( switchPin ) == HIGH ); // will loop until the switch grounds the pin 
  lastSwitchState = 1; // technical lie to trigger the inital print in loop()
}

// switch is pressed, the switch pin is LOW, go ahead and run
// IF your switch does bounce then you will see many lines printed for one ON or OFF
// my "ground the jumper wire switch" bounces no matter how careful I am.

void loop()
{
  if ( digitalRead( switchPin ) != lastSwitchState )
  {
    Serial.print( "Switch is " );
    if ( lastSwitchState == 0 ) // in shorthand we write if ( !lastSwitchState )
    {
      Serial.println( "ON" );
    }
    else
    {
      Serial.println( "OFF" );
    }
    lastSwitchState = !lastSwitchState; // ! means NOT, changes 0 to 1, 1 to 0
  }
}

Henry_Best:

UKHeliBob:

set running false

start of loop
  while running is true  //infinite loop doing nothing
  end of while
[/quote]
How is he going to escape that loop?

The way I read what he wants

The next step is to have the board powered on, then with a flip of a normally open spring loaded switch, start the loop and let it continue until finished (loop forever).

he doesn't want to escape the loop.

However, having read the original posting again what may be required is that the LED activity should repeat during the infinite loop. If so, then my suggested method needs to be changed to put the LED code in the infinite loop or to use the loop() function itself but still with the running flag set by the switch.

UKHeliBob:

My take on it would be:

set running false
start of loop
  If running is false, read switch
         (if switch closed, set running true)
  else, do rest of code  
 //don't reset running false
end of loop

Thanks guys! Looks like I have plenty to experiment with and study over the weekend. I really appreciate the great input and the encouragement.

OK all,
This is my button switch added to the top of my relay loop. It starts my millis() reference and turns on ch1 in prep for the main part of the loop. It seems to work fine.

Could it really have been this simple? I don't see how bounce would cause any problem other than very slightly delaying the sequence, correct?

Since this if for pyro used in filming Special FX, I will also need a 'kill' switch (e-stop button) in case the FX guy suspects any problems or the director 'cuts' and he needs to stop it quickly. I assume the safest and easiest method would be to simply put that e-stop on the power supply to the board?

Thanks for all the help!

void loop() {
  
    digitalRead(buttonPin);
   
    if(digitalRead(buttonPin) == HIGH && trip == 0)
    {
          startTime = millis();   
          digitalWrite(ch1,HIGH);
          trip = 1;
    }
    else {
         if(digitalRead(buttonPin) == HIGH && trip ==1)
         {
        
          // My relay loop
          // Do stuff with ch1, etc
        }
        }
    digitalRead(buttonPin);

Completely pointless line of code.

    if(digitalRead(buttonPin) == HIGH && trip == 0)
    {
          ...
    }
    else {
         if(digitalRead(buttonPin) == HIGH && trip ==1)
         {
          ...
        }
        }

Can be optimized:

if (digitalRead(buttonPin) == HIGH)
{
  if (trip == 0)
  {
    ...
  }
  else
  {
    ...
  }
}

Thanks Arrch,
I will simplify it as much as possible. I have to keep the if buttonPin = HIGH in the else statement so it doesn't take off in that sequence as soon as the loop starts. We will power up, then wait indefinitely for the button action (it will be a flip switch that stays on).

namenerb:
Thanks Arrch,
I will simplify it as much as possible. I have to keep the if buttonPin = HIGH in the else statement so it doesn't take off in that sequence as soon as the loop starts. We will power up, then wait indefinitely for the button action (it will be a flip switch that stays on).

Unless you plan on putting large delays in your code, then no, you don't have to. The code I posted was functionally equivalent to what you posted.

If you put the test in setup then you don't have to keep it on and can even use it for something else.

However these simple check the switch methods are all vulnerable to switch bouncing.

Where can I find info on what can be used in setup? GoForSmoke, are you saying I can put a complete button routine in setup?

Arrch; not sure that I understand what you are saying about not needing if(digitalRead(buttonPin) == HIGH && trip ==1) in my else statement. If buttonPin == LOW and I allow the program to continue into the loop, people will get blown up without knowing it's coming. (This is SFX pyro) Without that in the else statement, what keeps it from executing the rest of the loop?
The trip 1 is so that it sets millis(), etc and never re-enters that part of the if statement again. The else statement contains the entire remaining sequence.

Thanks!

namenerb:
If buttonPin == LOW and I allow the program to continue into the loop, people will get blown up without knowing it's coming.

What loop? You don't have any loops in your code, all you have are if statements.

Without that in the else statement, what keeps it from executing the rest of the loop?

Because the if is already nested inside the check for a HIGH input. Based on your previous wording about loops, I don't think you fully understand the flow of code execution.

namenerb:
Where can I find info on what can be used in setup? GoForSmoke, are you saying I can put a complete button routine in setup?

You can put a 1 time test in setup, and I would suggest 2 tests, one right after the other

while ( button not pressed ); // this test will happen until the button is pressed
// the next test will start before you can possibly let the button go
// next test waits for the button to be released for 1/10th of a second
// if the button 'bounces', the 1/10th second starts back up
// 1/10th second is a very long time to Arduino but a short time in button press & release
startTime = millis();
while (( button pressed ) || ( millis() - startTime < 100 ))
{
if ( button pressed )
{
startTime = millis();
}
}
// see what it takes to be reasonably sure? and still something may get around it!

Thanks, I'll give that a try!

GoForSmoke:

namenerb:
Where can I find info on what can be used in setup? GoForSmoke, are you saying I can put a complete button routine in setup?

You can put a 1 time test in setup, and I would suggest 2 tests, one right after the other
while ( button not pressed );

Once the button press has been detected by this line, what does it matter if there's bounce or the button is pressed for 5 milliseconds or 5 seconds? This is in setup() and will only run once, so there's no possibility of getting a false reading. Either the button has been pressed or it hasn't.
I can see the point of debounce where bouncing may cause a problem, but in this case it won't and can't.
I'd be more worried about who can activate this switch, seeing he's dealing with explosives, and suggest a keyswitch (hardware or software interlocked with the reset button, so that you can't reset when the switch is closed), with the only keyholder being the person in charge of the explosives.