So I am trying to write a very basic program in Arduino(which pretty much uses C++), but I am brand new to programming and have no idea what I'm doing. I'm trying to write an Arduino sketch that prints the integers in increasing order from 1 to n and then in decreasing order from n-1 to 1 in the serial COM window, when n=7. The result should be displayed in a row, as opposed to a column, with at least two spaces in between each number.
This is what the program should spit out:
1 2 3 4 5 6 7 6 5 4 3 2 1
....I have no idea where to even start. I tried to make some basic logic statements, but I know there must be an easier way, and I'm not sure how I would print the result in a row. This is what I have right now, but the right numbers aren't even being printed :/....can someone please give me a nudge in the right direction?
void setup() {
Serial.begin(9600);
int n = 7;
int x = n-6;
int y = x++;
int z = y++;
int a = z++;
int b = a++;
int c = b++;
A good place to start would be with the tutorials at arduinos site and the sample programs which come with the IDE.
I'm not sure exactly what you want to do. Is it:
a) Write the entire line 1 2 3 4 5 6 7 6 5 4 3 2 1 at once to the serial monitor?
b) Write 1 number at a time with a timed delay between writing each number?
Since b is more interesting, I'll go with that.
This code compiles and gives the expected output on my Uno:
int x = 1;
bool up = true;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
x = 1;
up = true;
}
void loop() {
Serial.print( x );// print number
Serial.print(" ");// 2 blank spaces
if( up )// counting up
{
if( ++x > 7 )
{
x = 6;
up = false;// time to start counting down
}
}
elseif( --x < 1 )// counting down
{
x = 1;
up = true;// time to start counting up
Serial.println("");// new line
}
delay(500);// half second delay. Adjust to suit.
}
Thanks for the input! I decided to write my own version using two for loops, but I think I messed up on the logic somehow, because the monitor is spitting out 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 instead of the intended 1 2 3 4 5 6 7 6 5 4 3 2 1......thoughts?
I like your solution. It's much simpler than mine.
Some misplaced braces, an extra semicolon and not counting down far enough are the problems in the 2nd for loop.
void setup() {
Serial.begin(9600);
}
void loop() {
int n;
for ( n=1; n<=7; ++n) {
Serial.print(n);
Serial.print(" ");
delay(500);
}
for (n=6; n>=1;--n)//; no semicolon here. >=1 so it loops for n=1
{
Serial.print(n);
Serial.print(" ");
delay(500);// delay here too
}
Serial.println("");// don't forget a new line
}