Understanding basics of programming arduino

When and where and why do you put void setup() and things like void loop()

Are you asking about the things you do inside the functions "setup" and "loop", or why they have no returned values?

Both

Hi, have you looked under the "Learning" tab at the top of this page?

Tom.... :slight_smile:

So I am 15, a total noob and I am really confused :P? Would you say the best way to learn is by designing and building projects? I know the basics and have all the basic parts (i.e resistors, sottering irons, capacitors and stuff like that). I am just really tied down on the programming portion. my dad is an electrical engineer so I guess he can help me on that part but I am also enrolled in electronics classes at my high school. I just am confused on the programming bit. I have been reading the reference and looked at the learning tab on this site but still don't understand. would someone mind explaining the basic parts of a program and what kind of stuff can be done in them. I really appreciate it!

I have been programming for over 30 years, and have taught many young programmers over that time. The one best learning tool is doing it, but there are some educational tools you should take advantage of as well. I think the two most powerful tools are books (or online books) and type-in programs, which you type in yourself and then modify. I do not think copying code from web pages achieves the same thing - you need to type the code.

It's important to play with the code too - don't just copy something and use it. In the programming community, we call that "copypasta" and it's a source of a lot of problems - don't be that guy. Do your best to understand the code, so you can modify it, combine it with other bits of code, make it 'generic' or implement it in a different way (Blink and Blink without Delay for example). Have fun with code and take things to the limit of your understanding, that's where the learning happens - don't back down until you're really stuck, then come here for help. When I was your age, I would type in programs from magazines, usually games, and then modify them to make them harder or easier, give me more ships or make the game run slower. I would take code from one game and put it into another one, and so on. Have fun with coding, don't let it get boring.

As far as that goes, I think Arduino is almost as good a platform as any other to practice coding, although I would suggest exploring other languages as well, such as object oriented languages like Java and C#, Ruby, Python, Javascript and also some declarative and functional languages which take a completely different approach to programming - such as HTML, SQL, and F# or MATLAB. However, the most important thing in choosing languages is motivation to practice, so if Arduino is what you're interested in, go hog wild.

As for books - I think there is one, possibly surprising title out there, which is really a great programming book, and I'm proud to say I own a copy and have lent it out on many occasions.

This is that book: http://www.amazon.com/Beginning-Programming-Dummies-Wallace-Wang/dp/0470088702/ref=sr_1_1?ie=UTF8&qid=1387748222&sr=8-1

Now, there's versions of that book for Java and C++ so one of those might be better, but I think the way he explains things is fun and makes sense, and he approaches the basics in a quick but thorough manner. Of course there's many programming tutorials for beginners that you can find on Google, but I think having a book in one hand and a keyboard in the other is a great way to learn. You might consider using a tablet or a Kindle to download programming books too.

You need a copy of my book, written to move along situation like yours. Paperback or Kindle. Paperback you can mark up with ideas, notes, questions.

A basic program using the IDE is 3 in sections:

  1. library callouts, IO pin name assignments, variable data type declarations.
  2. setup, where one-time stuff happens, like setting up pins as inputs or outputs, and starting functions like the serial port (very useful for debugging).
  3. loop, which runs continuously forever and ever.

So a simple program might be:

// test program, use double slash for a comment line
/* 
    or make
    a bunch
    of comments between these
*/
byte ledPin = 13;  // onboard LED is driven by this pin
int delayTime = 1000; // will use to hold a delay time

void setup(){
pinMode (ledPin, OUTPUT);  // pin is used as an output
Serial.begin(115200);  // Open the serial monitor and set it to this speed
} // end setup

void loop(){
digitalWrite (ledPin, HIGH); // LED pin on
Serial.print ("start on delay");
delay (delayTime);
Serial.println ("  end on delay");

digitalWrite (ledPin, LOW); // LED pin off
Serial.print ("start off delay");
delay (delayTime);
Serial.println ("  end off delay");

} // end loop

caleb121341:
When and where and why do you put void setup() and things like void loop()

Google C++ tutorial for an explanation of functions, how they're declared, defined and used. Setup() and loop() are just two functions that each sketch is required to implement.

Look at some of the very simple examples that come with the Arduino IDE and how they are structured.

Use the same structure for your own programs until you run into a problem where that is not sufficient. You will probably know a great deal about the Arduino system before you get to that stage (if you ever do).

The Arduino IDE hides some of the arcane features of C/C++ which is great, but it does mean that you may find a gap between standard textbooks and what you need in an Arduino sketch. (In a way it's the other way round - the sketch may appear to be missing stuff that is normally visible in textbook programs because, behind the scenes, the IDE adds in that stuff to save you the trouble.)

...R

I echo everything you see presented here, especially the part that tells you to type in the code and play around with it yourself. You will learn twice as fast if you do this versus simply downloading code and running it. Pick a really simply program, like lighting an LED and try to write the code yourself. If you get it running, great! If you don't, keep trying until you're just about ready to give it all up. Then look at the Blink code in the Examples distributed with the IDE.

There are tons of free tutorials available online, and some of them are really good. Read a few and see if one really resonates with you. Obviously, I think my Beginning C for Arduino would be a good choice, but every reader is different. Go to Amazon, type in C programming books, and read the reviews. Most have a "Look Inside" feature on the cover that lets you read a few pages. You should be able to make a selection if you think the tutorials don't fit the bill.

PeterH:

caleb121341:
When and where and why do you put void setup() and things like void loop()

Google C++ tutorial for an explanation of functions, how they're declared, defined and used. Setup() and loop() are just two functions that each sketch is required to implement.

Every Arduino program is just this... (pulled from the real main.cpp in my environment)

#include <Arduino.h>

int main(void)
{
	init();

#if defined(USBCON)
	USBDevice.attach();
#endif
	
	setup();
    
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
        
	return 0;
}

We just don't ever mess with that part, so the IDE doesn't show it to you. If you fail to "implement" (provide code for) those functions, the compiler will tell you that functions called in main.cpp are undefined....

C:\Program Files\Arduino\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'
C:\Program Files\Arduino\hardware\arduino\cores\arduino/main.cpp:14: undefined reference to `loop'

Let me know if you need any explanation of the main function. All Arduinos always run that function - all C/C++ programs must have a "main" function and it's the entry point that is called by the operating system to start the program.

In most programming environments, there is usually a bunch of stuff that happens "behind the scenes" that you are pretty-much asked to accept without understanding it, at least to start with. When you turn on your desktop computer, you don't worry about how it goes from having volatile memory full of random values to something where you can click on icons. "using the computer" starts long after the computer starts doing stuff.

In the Arduino environment, your "programming" starts with functions setup() and loop(), names carefully chosen to reflect some of the ways an Arduino is different from a desktop computer. You don't "run a program until it exits." Instead, you set some things up, and then it continues to run forever (looping.) You use setup() and loop() because that's the way it has been designed to work.

Sure, there's another level ("main()") that you can explore once you gain some expertise. And there's another level beyond that too. But it's not important to understand those before you start doing stuff.

westfw:
In the Arduino environment, your "programming" starts with functions setup() and loop(), names carefully chosen to reflect some of the ways an Arduino is different from a desktop computer. You don't "run a program until it exits." Instead, you set some things up, and then it continues to run forever (looping.) You use setup() and loop() because that's the way it has been designed to work.

Indeed, almost all computer programs have that structure, with the exception that most programs are capable of exiting. I believe the Arduino program could exit, but the Arduino would basically be dead at that point because there's no way to start another program other than resetting the whole thing. I could try that, I really wonder what would happen - there's very little chance it would brick the board or something, so I'll try that with my $9 Arduino.

So anyway I chose to reply to point out the fact that almost all software, at some point in the program, will run a loop that runs for the life of the program.

Here's a standard Windows App in .Net...

static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Main());
}

This code is rarely seen - we don't usually mess with it, the environment writes that code just like Arduino's "Main" program, and most developers never alter it. That's object-oriented code, but it's still the same basic structure, two lines that initialize things, then the last line starts a new "Main" window object, and lets that run forever. That object runs a loop waiting for mouse clicks and other events from the operating system, then it responds to those events until it is forced to quit by the "X" or the File->Exit or something like that. So, for things as different as Arduino sketches and Windows apps, we have the same basic structure - set some things up, then run a loop forever.

And yes, I agree - it's not important for most programmers to delve into things like how is the runtime environment initialized and how does the OS start the program. All you need to know is it does.

jasmine2501:
Indeed, almost all computer programs have that structure, with the exception that most programs are capable of exiting. I believe the Arduino program could exit, but the Arduino would basically be dead at that point

The concept of a program exiting only applies if there is another program running on the computer - usually the operating system. Once a computer is powered up it must be running a program - even if it's stuck in an infinite loop such as
1 goto 10
10 goto 1

How could an Arduino program exit? All you could do was make it run some useless code somewhere else so that it gives the impression of not working.

...R

Robin2:
How could an Arduino program exit? All you could do was make it run some useless code somewhere else so that it gives the impression of not working.

You could modify main.cpp to exit somehow. I know it's meaningless, but I wonder what would happen.

Could always go into power down sleep mode. Wait for an interrupt to do something.

That would still require the main program to be running though I think. I'm talking about exiting from "void main()" that function we never really look at. I would expect if you did that, the Arduino would just get stuck - or it may simply restart the program. I'll do a test later today and report what happened.

The AVR C runtime environment (the thing "above" main() in fact will call _exit() if main() returns.
_exit does a cli and infinite loop.

  f4:   0e 94 2f 02     call    0x45e   ; 0x45e <main>
  f8:   0c 94 3f 02     jmp     0x47e   ; 0x47e <_exit>
    :
0000047e <_exit>:
 47e:   f8 94           cli

00000480 <__stop_program>:
 480:   ff cf           rjmp    .-2             ; 0x480 <__stop_program>

You could modify main.cpp to exit somehow. I know it's meaningless, but I wonder what would happen.

This has been discussed before. IIRC, exit() just runs an infinite loop doing nothing. Or, rather, accomplishing nothing,

PaulS:

You could modify main.cpp to exit somehow. I know it's meaningless, but I wonder what would happen.

This has been discussed before. IIRC, exit() just runs an infinite loop doing nothing. Or, rather, accomplishing nothing,

I did try to find that - I also tried to find the code posted above, but my Google-fu failed me, and then I forgot to do my experiment because I discovered a new episode of Dr. Who on Amazon :slight_smile:

At least we have the code above, that shows at least, when main function exits, it does something reasonable, rather than executing data or something like that. It's "stuck" and won't do anything ever again at that point, but it's not doing something wrong. That's good to know because I can think of errors that might cause main to exit, and you wouldn't want your machine going nuts in that case.