while loops

Arduino – While Loop

While there are a few choices for loops to do while coding in Arduino(Puns intended), you will find a lot of different situations to use each of these loops. We took a look at the for loop in this post, and discovered some of the uses for that. Now we’re going to take a look at the while loop, which is a little different, and I’ll explain to you why and when to use this loop.

while loops

What is it?

The while loop is a block of code that is run while the condition between the parenthesis is true. This is useful when you’re waiting for something, or you have to send a serial command somewhere repeatedly until the desired outcome is returned. It will stay in this loop until the pre-determined requirements are met. This is different from the for loop, because the for loop loops through and increments a variable until it hits a certain number. The while loop can also be written to do this, but that’s not what it’s designed to do.

Uses

One of our examples is going to be a listener, we’ll have the while loop wait until it sees that there is serial data available to read, then it will take action on the serial data that is received.

Another example is a temperature monitor. You can have it sit in the while loop and only do a temperature reading until it changes, then when it changes you can have it send a text message, write to a database, or do any other task imaginable(except split atoms, Arduino is not designed to perform that).

Usage

The following is they syntax from Arduino.cc:

while(condition){
  // statement(s)
}

Let’s break that down, it’s a very simple piece of code, right? In the first line we tell the compiler that we’re using a while statement, by stating “while”. Immediately after that we have a set of parenthesis, inside these parenthesis will be the condition that you are testing. If the condition immediately returns false, your code will never be run, otherwise it runs continuously until it returns false.

You can also use “break” to break out of the loop. This would effectively add a second condition to the while loop, if you use it inside an if statement. For example your while loop tests for sensor a to change, and your if statement tests for sensor b to change. When sensor a changes you have it return false to break out of the loop, when sensor b changes you have it return true to break out of the loop(because an if statement only reads the code inside the curly braces if the condition is true).

 

You can run forever loops by doing while(true). This is not recommended, but it can be done. An example of a forever loop is the “loop()” function that Arduino uses to loop the code you write. This is a loop that is always run, unless you use a break somewhere to remove it from the loop. You can get stuck in this loop indefinitely, so it’s not recommended to use forever loops. Just mentioning it today, so you do know that it’s possible, and that it’s also a risk.

Examples

A great example for this loop, is the post I did about serial communication via the serial monitor. The following is the code from that post:

String data;//initialize string variable

void setup() {
 Serial.begin(9600);//initialize serial
}

void loop() {
 while (Serial.available()){//loop while data is available
 Serial.print("You typed: ");
 data = Serial.readString();//read the data
 Serial.println(data);//print the data to serial monitor
 }
}

If you look through this code, you’ll see in the first line we set up a string named data. In the setup function we instantiate serial at 9600 baud rate. In this case the loop will not run until serial data is available, which would mean that something was sent from the serial monitor to the Arduino. To trigger this, you just have to type something in the serial monitor. Then it does the loop until no more serial data is available, and waits until next time it is available. You can learn more about this process in this post.

Hello World Tutorial

Arduino Serial Hello World

Hey guys, this time I’m going to introduce a hello world example outputting to the serial monitor on your Arduino IDE. You’ll learn how to write a very simple code that sets your first variable, and output that variable on to your computer screen.

What you need:

Pre-Setup:

This is where we create our variable. Our variable is a character array, more commonly known as a string. Arduino sends data via serial byte by byte, meaning 8 bits at a time. Later, you’ll find that you need to define the length of what you’re sending, when communicating with other devices some times.

The following code is our simple initialization of our character array. The key here is starting with “char”, this tells the IDE what type of variable we’re trying to set up. Next we name the variable “myString”, this is the second part of setting your variable. Then we set the char type to array by adding “[]” to the end of the name. Finally we set the value of our variable to “Hello World!”, and close the line out with a semi-colon. You’ll notice that every line has to be closed out with a semi-colon, this tells the compiler that you’re done with the current statement.

Setup:

Next we’re going to start the setup function. Setup is only run once, right when the program is started on your device. This is a good place to start initializing things that need to be started prior to reading or writing. Here we will initialize the serial port, the first serial port is always linked to USB. It can be used for other things than USB, but I prefer to leave it that way.

You’ll see our complete code below, this is a very simple one-liner setup. We start by calling “void setup()”, this tells the compiler that we’re defining the setup function. You can define custom functions as well, but we’ll get to that later. To create a box for your setup to reside in, you need to enclose your code in curly braces, “{” and “}”. These curly braces tell the compiler what code belongs to the function you’ve created, which in this case is setup.

Now that Our setup function is defined we can call “Serial.begin”, capital letters do matter here – Serial needs to be capitalized. If we take this call apart, “Serial” is the object that we’re telling the compiler that we’re working with, and “begin” is the function we’re calling. Some functions have arguments that need to be passed to them, that is done inside the parentheses – “(9600)”. What we’re doing here is setting the baud rate to 9600. The baud rate is important, because it synchronizes the speed of data flow between your computer and the Arduino device.

Loop:

Here’s the juicy part, finally the loop! The loop is where your main code is run, this code is run over and over and over until the end of time, or until the device is unplugged/reset. This is a very simple loop that prints the text we defined earlier in a variable, waits 1 second, then repeats.

We have 2 functions being called here. The first is “Serial.println(myString);”, this tells the Serial object to print a new line using the variable named “myString”. There is another function to Serial that is simply “Serial.print”, which would print everything on the same line. That is useful if you have a lot of code determining what to print, and you don’t want to do it on a new line yet. The second function is delay, note that it’s lower case. Most built in Arduino functions are lower case, and the objects are upper case. The argument we’re passing to the “delay(1000)” function is amount of time in milliseconds. So 1000 = 1 second.

The final product:

//Hello world example code
 //This will be an introduction to Arduino, via serial communication
 char myString[] = "Hello World!";

void setup()                    // This only runs once, right when you start the sketch
 {
 Serial.begin(9600);           // Instantiate serial with a buad rate of 9600 bps

}

void loop()                       // Runs forever
 {
 Serial.println(myString);  // Prints Hello World! via the string that we created pre-setup
 delay(1000); // Pauses for 1 second
 }

 

Now let’s run the code! Go on to the next post to put your code to work!

Arduino USB Serial

Uploading Code to Arduino and Using Serial Monitor

This post is assuming you’ve read my previous post, Arduino Serial Hello World. There you learned how to write the “Hello World” code, in preparation for output to the Serial Monitor. By now you should also understand the Basics of Arduino. These 2 are the prerequisites of this project. You could, of course, just copy my code and upload it.

Let’s get started!

I’ll be using the Arduino Uno, this is the most commonly known device that is used for Arduino programming. If you’ve read the Arduino Serial Hello World post, you’ll already have the code in your IDE.  If not, you can copy the following code and paste it in the Arduino IDE.

//Hello world example code
//This will be an introduction to Arduino, via serial communication
char myString[] = "Hello World!";

void setup() // This only runs once, right when you start the sketch
{
 Serial.begin(9600); // Instantiate serial with a buad rate of 9600 bps
 
}

void loop() // Runs forever
{
 Serial.println(myString); // Prints Hello World! via the string that we created pre-setup
 delay(1000); // Pauses for 1 second
}

Let’s get connected

If you haven’t already, you may want to configure your IDE for connection with the board. Following the configuration process allows the IDE to properly communicate with the board. It’s a very simple process, so it shouldn’t take too long.

After you do your one time configuration process, you’re ready to start uploading! Let’s plug USB in to the Arduino, and the other side into your computer.

You may notice I’m not using the default USB that came with the Arduino Uno. I choose to use a longer USB, because it helps keep my work area clutter free. Once you start more complex projects, you may run out of room in your work area.

Let’s upload

Now that you’re connected, you may see that the LED’s came on when plugging in your device. It’s alive! If you have it configured properly, you’re ready to upload. Click the arrow that points to the right, at the top left of your screen.

Now that you’re uploading, you can watch the progress in the black area at the bottom of your screen. There’s also a small progress bar that shows how it’s going.

This process should be very fast, on such a small sketch. When you start diving in to libraries, and using more complex code, it’ll take a little longer.

Where’s my output?

Now you’ll open the serial monitor. This is where the Arduino can send messages back to your computer. This is a very good area to try to use for debugging things. Click the icon that looks like a magnifying glass, at the top right of your screen.

If all is going well,  you’ll see the Arduino communicating with the Serial Monitor. It should say “Hello World!”. You’d think it would have more to say than that, but it really only talks about the things we tell it to. If you’re not talkative, neither is your Arduino, unfortunately. Don’t expect your Arduino to be the conversation starter, you’re the one in control here.

Thanks!

I hope you found this easy to follow, let me know in the comments if you have any questions. I’m here to help you, and I’d be more than happy to do so. Feel free to Subscribe below, you’ll find that I’m going to slowly work you in to more complex development. I feel you’d benefit from it a lot, if you follow along.

arduino uno rev3

Intro to Arduino

The intent of this intro to arduino, is to explain the basics of Arduino. This is a great place to start, if you’re just starting out with Arduino programming.

What is an Arduino?

Arduino is actually the language running on your device. What people know as an Arduino is a microcontroller, which runs whatever code you’ve uploaded to the device. Arduino was created to simplify electronics prototyping, but it can be used in more permanent situations. The following is the most popular board, the Arduino UNO. You can get one here.

What is an IDE?

IDE stands for Integrated Development Environment. There are a lot of programming languages that provide an IDE for you to work in, compile your program for execution, and deploy the finished product to your Arduino. Download the IDE here.

What is compiling?

When your program is compiled, it is being built. What this does, is converts your more “people readable” code to a language that your Arduino can understand.

How does Arduino work?

There are 4 parts of Arduino code that you need to understand. They are very simple, and easy to follow. Arduino is a dumbed-down version of the C programming language. C has been around for a long time, and will be for years to come. The following are the 4 parts to Arduino code, the images are going to be from the code in my “Hello World:Serial” tutorial:

Pre-Setup

  • You define any libraries you’d like to include in your project, libraries will be explained in another post. You don’t need to know about these yet
  • You define any global variables you’d like to set before running the main part of your code.

Setup

  • This is a run-once part of your code that prepares things, some sensors need to be fired up, or initialized, before you can begin reading from them.
  • Some times you need to do things like connect to wifi, that may only get done once.

Loop

  • This is your main code, this loop will run forever until the world ends, or until you disconnect power from the device.

Post-Loop

  • I’m just calling this post loop, it’s actually an area where you can define functions for your code.
  • You’ll learn that functions are very handy when your code gets long. Some of my Loop statements are only 4 lines long, because they are looping through functions.
  • Anything you put here, is to simplify repetitive tasks, and/or clean up your code.

Is there code that isn’t run?

Yes, you can comment out lines of code. Commenting allows you to “hide” code from the compiler, if you’d like to test your code without a statement or have a reference inside your code for later. Commenting is also a great way to add a “bookmark” to your code, so you can identify sections of code easier, and remember what they are for. Adding a comment is as simple as putting // at the beginning of the line you’re commenting out.

You can keep reading, to find out how to communicate with your Arduino via a Hello World example.

Thanks!

I hope you enjoyed my introduction to Arduino. Let me know if you have any questions, I’d be happy to answer them! Please subscribe below to get the latest posts by Anarchy Development.