Arduino beginner programming

Arduino for Beginners: Your First Arduino Program!

Getting started with Arduino
  • by Matt (3)
  • Time to complete: 10 minutes

In this Arduino beginner's guide I'll cover what an Arduino is, how to set up the Arduino IDE, and how to create your first Arduino program.

About this guide

This guide is an absolute introduction that assumes the reader has little or no experience with an Arduino. I'm going to explain all the basics of an Arduino and show you how to write your first Arduino program: a variation on the classic "blinking LED" example. Even if you don't have an LED handy, this guide will be useful to you.

If you have experience using Arduino and are aware of all of its components and how they are utilized, you may use this guide as a refresher on the basics.

To complete this guide fully, you'll need an Arduino or cheaper Arduino clone.

Upcoming series

This will be the first in a series of articles that will broaden into more advanced uses with Arduino by adding sensors and consuming the data to make real-time graphs and other interesting things that I have not yet thought of.

Because I have a background in science and physics, I'll be doing some experiments with this data to prove and illustrate some already-understood scientific concepts in ways that are as ridiculous as I can get away with.

Follow Howchoo on Facebook to get notified when these new articles are released!

1

An Arduino is a microcontroller that's meant to have a cheap form factor for all kinds of DIY projects; it can easily read many different sensors, control servos, and more.

Arduino vs. Raspberry Pi

It's different from a Raspberry Pi in that it doesn't run a full operating system. It's meant primarily for directly controlling and reading external devices with precision and ease. You can learn more about the differences between Raspberry Pi and Arduino.

When should you use an Arduino?

Arduinos are deliberately limited in the scope of what they can accomplish but do a great job at what they're designed for: rapid, easy, flexible, and extendible input and output handling.

As more specifics of the hardware are explained later, I'll point out which aspects are unique and illustrate when you would turn to this hardware for your project.

Combining Raspberry Pi and Arduino

It's possible to connect one or more Arduinos to a Raspberry Pi to utilize the wide variety of things a full OS can accomplish or simply to read the Arduino data.

Since Arduinos are just better at integrating with and controlling external hardware with precise timing, the Pi can orchestrate the initiation of "sketches" and combine and make sense of all of the data coming in from each Arduino.

This illustrates where they are different and the relationship they have with each other.

2

Arduino online sketchbook IDE
Photo: Screenshot of Arduino online IDE

The Arduino IDE is the program you'll use to write code for the Arduino.

Here I'll be using the official Arduino Web Editor IDE because of its simplicity of getting set up quickly. and this method is independent of the Operating System that you use, but there are many ways to use some of your favorite IDEs to write Arduino programs.

Arduino programs are called "sketches".

Sketches

Arduino programs are called "sketches". Sketches control Arduino projects and are saved in a folder called a "sketchbook".

Get going with the Arduino Web Editor or download the Arduino IDE for Mac, Windows, or Linux.

3

Arduino Uno pin diagram
Photo: Arduino.cc via components101.com

The microcontroller

This is the brain of the Arduino. It's accessible via the black strip running vertically at the bottom left of the attached image.

Pins

There are 14 pins on the Arduino Uno, which was the earliest model available and has continually been updated since. These pins are capable of both input and output (I/O), but there are different groups of pins you'd use for different scenarios. For instance, there are both analog and digital pins, 5 volt (5V) and 3 volt (3V) pins and a ground (GND) to make sure your circuit is grounded with the board; this is also how the circuit is completed after connecting a different wire to one of the positive pins.

Analog

The analog pins are meant for taking input or for outputting continuous signals. A common example of this would be using a potentiometer to change the brightness of a dimmable LED. The continuous signal usually is split into a digital quantized signal by setting the lowest value to 0 and the highest to 255 so the computer has a way to use the information.

Digital

The digital pins are similar to the analog pins except that the signal doesn't need to be converted to digital (quantized) before use. However, it may still need to be normalized in the same manner by setting some low and high value to a corresponding number that can be used by the Arduino.

Pulse Width Modulation (PWM)

This is a large topic that I will not be able to do full justice here and will be covering in a future guide. The easiest way to think of PWM is that the pulse is a "square" wave and the width of each wave is the wavelength or half the wavelength.

Some devices, such as servos, require a very specific pulse width to activate and this pulse width can be changed, (or modulated), to achieve different motion or direction. Hence the name "Pulse Width Modulation".

This video illustrates PWM concepts well:

4

Selecting Arduino device
Selecting Arduino device

At the top of the online IDE, there's a dropdown that you can use to select which device will be used to upload the given sketch. If there is no device plugged in, you will see a list of all available devices. If your device is plugged in and working correctly, it should be the first device in the list for you to select.

5

This sketch comes as part of the standard sketch library examples in the online editor. The native desktop IDE also comes with similar examples.

/*
  Blink without Delay

  Turns on and off a light-emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin = LED_BUILTIN; // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

I wanted to make sure you could read the full code with all the credits and explanations but just to show how little code is needed, here is the same code without all of the comments.

const int ledPin = LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

This example does not rely on the delay function so the delay is determined by reading the number of milliseconds passed since the last loop and if the difference between the current run and the last blink is greater than or equal to the interval, 1000 ms, in this case, the LED's state is switched from its current state.

Essentially, that's all that's happening in this code. The rest is just the instantiation of the constants, such as setting up which pin is to be altered in the setup function. As described in the comments, the constant LED_BUILTIN refers to a specific pin on the Arduino and can depend on which model you are using. You can read about all of the constants available with the standard Arduino library.

6

Upload Arduino Sketch

To the left of the device selection, there's a right arrow and a checkmark. You can use the checkmark to verify that the sketch compiles and is valid. After that, click the right checkmark to upload the sketch and you will see the button turn into saying busy.

The bottom console shows information about the status of the upload. When the upload is complete, it will say "Success: saved your online sketchbook and done uploading". If there's an issue, it will let you know that it's time for some troubleshooting.

7
Arduino LED Blinking
Arduino LED Blinking

The code for this sketch will make the LED connected to digital pin 13 blink on each loop as long as enough time has passed to reach the next interval. This is the reason for keeping track of the difference between currentMillis and previousMillis in each loop.

Use a breadboard or some wires to connect the LED to pins 13 and GND. If you don't have a breadboard, I highly recommend investing in one for future projects.

8

I was wondering how many interesting things you can do with a blinking light, and short of introducing other sensors to go along to music or something, I came up with doing the S.O.S signal. This only required a slight modification to the existing code to blink in the S.O.S pattern in Morse code. If you don't know what the pattern is, it's three short bursts, followed by two long bursts, followed by three more short bursts, followed by a pause.

It sounds like:

beep beep beep...beeeeeeeeep beeeeeeep...beep beep beep.............(repeat)

...but using a light.

If you are actually trying to save yourself, you can use the audio or visual form of this message to get yourself unstranded from that darn island.

const int ledPin = LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
long interval = 1000;
int count = 1;

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {

  if(count > 17) {
    count = 1;
  }
  if(count <= 6) {
    interval = 150;
  } else if(count > 6 && count <= 10) {
    interval = 500;
  } else if(count > 10 && count <= 16) {
    interval = 150;
  } else if(count == 17) {
    interval = 2000;
    ledState = HIGH;
  }

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
    count++;
  }
}

There may be a more clever way to do this, but without the native delay function or breaking some of this down into functions outside the main loop, I decided just to count out the ways that the beep should go.

For every blink, two intervals are traversed, so we need 6 intervals for each of the short blinks and 4 intervals for each of the long blinks, followed by a pause. The counter is only increased when the light's state is changed, which is why it is inside the if statement where it is determined that an interval has passed.

After watching the delay on count 17, every other time the full sequence was complete, the light would be left in the HIGH position for the delay, so on count 17, I switched the ledState to HIGH so when the LED's state was flipped for the last interval in the sequence the light would be in the off position giving the pause needed.

9

The possibilities are quite endless with what you can accomplish messing around with an Arduino, and it's pretty fun to work with. Unlike many, many computer hardware interfaces for hobbyists, the Arduino really is plug-and-play as advertised. You don't have to spend hours with driver configurations or reflashing SD cards, you just make a change to the sketch and click play and I find that quite refreshing.

I'm excited for the upcoming guides in my series where we'll be adding sensors and reading the information and hopefully using it in some interesting ways. If you don't have an Arduino yet, I recommend picking one up since they're very inexpensive.