Arduino Endless Loop of Array - loops

I need help to create endless loop for items in array, I want loop restart automaticly ;
My code is below ;
const int myArray [] = {3,5,6,7,1,2};
void loop() {
for (int element : myArray) {
Serial.println(element);
}
}
Thanks in advance

Wrap it in an infinite loop
while (true) {
for (int element : myArray) {
Serial.println(element);
}
}
As pointed out by hcheung in their comments, your loop() function should already be called as part of an infinite loop. Since that does not seem to be the case, then it is highly likely you have an error somewhere in your code. Have a look at the link posted by hcheung, which is a very basic Arduino application, and make sure you have something similar on your end, at least as far as the endless for loop calling loop() goes.

Related

Problem with Arduino using arrays in Structure

With an Arduino Uno I'm having a problem that is probably simple to solve for somebody who knows what they're doing. I'm trying to get this code to print out "-30" but all I get is "0" no matter what value I put in "setpt[x]" in the serial.print line in loop().
Thanks in advance, Don
typedef struct
{
byte seg_num[12];
byte ramp_hrs[12];
int setpt[12];
byte ramp_mins[12];
}record_type;
record_type profile[8];
void setup()
{
Serial.begin(9600);
Serial.println("*** START ***");
}
void loop()
{
profile[0] = (record_type) {(1,2,3),(5,7,9),(-40,-30,-25),(2,4,6)};
Serial.println(profile[0].setpt[2]); // fails with setpt[from 0 to 3]
}
Comma operators are used in your expressions like (1,2,3).
(1,2,3) is equivalent to 3 here.
You should use {} instead of () to initialize each arrays.
profile[0] = (record_type) {{1,2,3},{5,7,9},{-40,-30,-25},{2,4,6}};
Then, correct the index to get -30 instead of -25.
Serial.println(profile[0].setpt[1]);

Recursive Main function

I have to make the code of a coffee dispenser in C.
I already have everything done and I just need to know how I can keep on running my "main" function until a certain condition is met (for example: util the machine can give no more change).
How can I achieve this?
I don't think you need a recursive main or for that matter any recursive function call at all for this. All you need is an infinite loop.
int main()
{
while (1) /* Infinite Loop */
{
... do stuff
if (condition is met)
break;
}
}

how to stop a loop arduino

I have this loop, how would I end the loop?
void loop() {
// read the pushbutton input pin:
a ++;
Serial.println(a);
analogWrite(speakerOut, NULL);
if(a > 50 && a < 300){
analogWrite(speakerOut, 200);
}
if(a <= 49){
analogWrite(speakerOut, NULL);
}
if(a >= 300 && a <= 2499){
analogWrite(speakerOut, NULL);
}
This isn't published on Arduino.cc but you can in fact exit from the loop routine with a simple exit(0);
This will compile on pretty much any board you have in your board list. I'm using IDE 1.0.6. I've tested it with Uno, Mega, Micro Pro and even the Adafruit Trinket
void loop() {
// All of your code here
/* Note you should clean up any of your I/O here as on exit,
all 'ON'outputs remain HIGH */
// Exit the loop
exit(0); //The 0 is required to prevent compile error.
}
I use this in projects where I wire in a button to the reset pin. Basically your loop runs until exit(0); and then just persists in the last state. I've made some robots for my kids, and each time the press a button (reset) the code starts from the start of the loop() function.
Arduino specifically provides absolutely no way to exit their loop function, as exhibited by the code that actually runs it:
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
Besides, on a microcontroller there isn't anything to exit to in the first place.
The closest you can do is to just halt the processor. That will stop processing until it's reset.
Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.
If that's the case, there are several solutions:
If you want to generate the signal with the input of a button you could do the following
int speakerOut = A0;
int buttonPin = 13;
void setup() {
pinMode(speakerOut, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
int a = 0;
void loop() {
if(digitalRead(buttonPin) == LOW) {
a ++;
Serial.println(a);
analogWrite(speakerOut, NULL);
if(a > 50 && a < 300) {
analogWrite(speakerOut, 200);
}
if(a <= 49) {
analogWrite(speakerOut, NULL);
}
if(a >= 300 && a <= 2499) {
analogWrite(speakerOut, NULL);
}
}
}
In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors.
Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.
The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.
The three options that come to mind:
1st) End void loop() with while(1)... or equally as good... while(true)
void loop(){
//the code you want to run once here,
//e.g., If (blah == blah)...etc.
while(1) //last line of main loop
}
This option runs your code once and then kicks the Ard into
an endless "invisible" loop. Perhaps not the nicest way to
go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in
an endless circle... perhaps one could set up a sort of timer
function that puts the Ard to sleep after so many seconds,
minutes, etc., of looping... just a thought... there are certainly
various sleep libraries out there... see
e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100
for further discussion of such.
2nd) Create a "stop main loop" function with a conditional control
structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the
"stop main loop" function toggle the value of the variable
upon termination. E.g.,
boolean stop_it = false; //global variable
void setup(){
Serial.begin(9600);
//blah...
}
boolean stop_main_loop(){ //fancy stop main loop function
if(stop_it == false){ //which it will be the first time through
Serial.println("This should print once.");
//then do some more blah....you can locate all the
// code you want to run once here....eventually end by
//toggling the "stop_it" variable ...
}
stop_it = true; //...like this
return stop_it; //then send this newly updated "stop_it" value
// outside the function
}
void loop{
stop_it = stop_main_loop(); //and finally catch that updated
//value and store it in the global stop_it
//variable, effectively
//halting the loop ...
}
Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this
time it's a case of repeatedly checking the if(stop_it == false) condition in stop_main_loop()
which of course fails to pass every time after the first time through.
3rd) One could once again use a global variable but use a simple if (test == blah){} structure instead of a fancy "stop main loop" function.
boolean start = true; //global variable
void setup(){
Serial.begin(9600);
}
void loop(){
if(start == true){ //which it will be the first time through
Serial.println("This should print once.");
//the code you want to run once here,
//e.g., more If (blah == blah)...etc.
}
start = false; //toggle value of global "start" variable
//Next time around, the if test is sure to fail.
}
There are certainly other ways to "stop" that pesky endless main loop
but these three as well as those already mentioned should get you started.
This will turn off interrupts and put the CPU into (permanent until reset/power toggled) sleep:
cli();
sleep_enable();
sleep_cpu();
See also http://arduino.land/FAQ/content/7/47/en/how-to-stop-an-arduino-sketch.html, for more details.
just use this line to exit function:
return;

"Saving" current state in foor loop to continue later

currently I'm thinking about the following problem and maybe someone can help me:
For minecraft I want to change a lot of blocks and to prevent lags I want to change only a couple of blocks at the same time. To change a cuboid I usually use a loop like this:
for(int x=t.x; x<t.X; x++)
for(int y=t.y; y<t.Y; y++)
for(int z=t.z; z<t.Z; z++) {
// ..
}
where t saves the from and to coords.
Now I want to save the current progress to continue later.
Please help me im tired of thinking about it..
Your code looks like C. In C, a process cannot return to a given stack state after leaving the calling functions. So leaving a loop and later returning to it are not possible at the language level. In other languages, things are different. E.g. in the Pypy implementation of the Python language, continuelets can be used to achieve what you describe.
However, you can achieve similar ways by using your own objects to store the last counters.
struct counters { int x, y, z; };
bool continueLoops(struct counters *ctrs) {
for (; ctrs->x < t.X; ctrs->x++) {
for (; ctrs->y < t.Y; ctrs->y++) {
for (; ctrs->z < t.Z; ctrs->z++) {
// ..
if (weWantToInterruptTheLoop)
return true;
}
ctrs->z = t.z;
}
ctrs->y = t.y;
}
return false;
}
void startLoops() {
struct counters ctrs;
ctrs.x = t.x;
ctrs.y = t.y;
ctrs.z = t.z;
while (continueLoops(&ctrs)) {
// do whatever you want to do between loops
}
}
However, I don't see much benefit in the above approach, as opposed to perform the relevant operation directly within the inner loop. So I'm not sure whether this is useful for you.

What does for(;;) mean?

I am confused by the for(;;) construct. I think it is a form of shorthand for an unlimited for loop but I can't be sure.
Here is the code:
for(;;)
{
//whatever statements
}
Your guess is correct; it's an infinite loop.* This is a common C idiom, although many people (including me) believe the following to be less cryptic:
while (1) { whatever statements; }
* It's infinite assuming there are no break/return/etc. statements inside the loop body.
It's an un-terminated loop. It is sometimes written with a while:
while (1)
or even better:
while (true)
I would expect to see a break or return inside any such loop, no matter whether it is written with for or while. There has to be some abnormal control flow or it really will be an infinite loop.
Yes, that's the for C syntax with blank fields for initialization expression, loop condition and increment expression.
The for statement can also use more than one value, like this sample :
for (i=0, j=100, k=1000; j < 500 || i<50 || k==5000; i++, j+=2, k*=6) {};
Maybe one step beyond in for understanding ? =)
Yes, the expressions in the for loop are just optional. if you omit them, you will get an infinite loop. The way to get out is break or exit or so.
This statement is basically equal to:
while(1) {}
There is no start, no condition and no step statement.
As I understand it, for(;;) creates a deliberate non-exiting loop. Your code is expected to exit the loop based on one or more conditions. It was once provided to me as a purer way to have a do while false loop, which was not considered good syntax. Based on the exit condition, it is easier to dispatch to a function to handle the result, failure, warning, or success, for example.
My explanation may not be the reason someone used that construct, but I'll explain in greater detail what it means to me. This construct may be someone's "Pure C" way of having a loop in which you can serially perform multiple steps, whose completion mean something like your application has performed all steps of initialization.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
for(;;)
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
break;
}
If part of the initialization fails, the loop bails out with a specific error code.
I arrived at using C having done a lot of firmware work, writing in assembly language. Good assembly language programmers taught me to have a single entry point and single exit. I took their advice to heart, because their creed helped them and me immensely when debugging.
Personally, I never liked the for(;;) construct, because you can have an infinite loop if you forget to break; out at the end.
Someone I worked with came up with do..until(FALSE), but the amount of proper C furvor this caused was not to be believed.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
do
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
}
until (FALSE);
This runs once, no matter what.

Resources