Getting Started with Arduino: A Beginner’s Guide

Getting Started with Arduino: A Beginner's Guide

After several years of experimenting with Arduino, I decided it was time to share what I’ve learned. So here I am, presenting an Arduino guide that provides some basic knowledge for beginners and some more advanced explanations for those who are somewhat familiar with electronic devices.

Each step includes a detailed explanation, followed by a summary and then a more advanced approach.

If you are a beginner, I recommend reading the instructions first and then the summary. You will (almost certainly) have some unclear explanations. Don’t worry, this is absolutely normal, and after reading other examples in the next steps, it will become clear—just don’t lose heart!

I will provide links to the ARDUINO reference page, Wikipedia, and some other interesting sources. If you want to learn more about a topic, these are great starting points. Similarly, if you don’t understand a word in these links, don’t worry; this is not necessary for this guide, especially for beginners who might find it very confusing or even frustrating. If that’s the case, it’s better to skip it for now. But don’t give up!

While tutorials like this can be very helpful, you will mainly learn by experimenting on your own. Use this handout as a starting point, as a reference, but do your own projects, modify the given examples, try new things, search the internet— the possibilities are endless!

Step 1: What Is Arduino?

Getting Started with Arduino: A Beginner's Guide

After several years of experimenting with Arduino, I decided it was time to share what I’ve learned. So here I am, presenting an Arduino guide that provides some basic knowledge for beginners and some more advanced explanations for those who are somewhat familiar with electronic devices.

Each step includes a detailed explanation, followed by a summary and then a more advanced approach.

If you are a beginner, I recommend reading the instructions first and then the summary. You will (almost certainly) have some unclear explanations. Don’t worry, this is absolutely normal, and after reading other examples in the next steps, it will become clear—just don’t lose heart!

I will provide links to the ARDUINO reference page, Wikipedia, and some other interesting sources. If you want to learn more about a topic, these are great starting points. Similarly, if you don’t understand a word in these links, don’t worry; this is not necessary for this guide, especially for beginners who might find it very confusing or even frustrating. If that’s the case, it’s better to skip it for now. But don’t give up!

While tutorials like this can be very helpful, you will mainly learn by experimenting on your own. Use this handout as a starting point, as a reference, but do your own projects, modify the given examples, try new things, search the internet.

Step 2: Before You Begin…

Before you start plugging things into the new Arduino, it’s best to know what can damage the circuit board. Understanding this will make your learning easier later on.

1. Drawing more than 40mA of current from output pins.

Arduino can only supply 40mA per output pin, so you cannot directly drive motors or speakers; for example, you cannot directly connect an LED without a resistor. In this course, I will explain what you should do.

Shorting an output to +5V, +3.3V, or ground pin will also kill your circuit board: for example, if the output pin is 5V and you connect it to ground, it will draw a lot of current and almost immediately kill your Arduino.

Since pins go through the circuit board, be sure not to place the Arduino on a conductive (metal) surface, as it will short the pins.

2. Drawing more than 200mA of current from all output pins.

Your ARDUINO’s ATmega chip can only provide 200mA, so every time you drive more than 10 LEDs at 20mA, you will eventually damage your board.

3. Providing a voltage greater than 5V (3.3V) to input pins.

Providing power greater than the Arduino operating voltage to any pin is very dangerous. Some Arduinos that run at 3.3V have 5V tolerant pins, but that’s it. This also applies to other devices like sensors or wireless chips: always check the voltage; if you connect a 5V Arduino output to a 3.3V chip, you could kill it.

4. Providing a voltage greater than 5V to the 5V pin.

The 5V of the ARDUINO board goes directly to the ATmega chip, which has an absolute rating of 6V.

5. Providing a voltage greater than 12V to the pins. The board has a 5V voltage regulator, and if you give it more than 12V, it will overheat and get damaged.

6. Drawing more than 500mA of current from the 5V pin (when the external power supply is disconnected).

The onboard 5V voltage regulator can only provide 500mA of current. The 5V USB has a polyfuse that limits the current to 500mA.

7. Drawing more than 50mA from the 3.3V pin.

The onboard 3.3V voltage regulator can only supply 50mA of current. This means you cannot directly connect power-hungry 3.3V devices like the ESP8266 or NRF24L01 to the Arduino; you need an external 3.3V voltage regulator.

8. Reversing the polarity of the power supply. If you swap the 5V or VIN with GND, you will almost immediately kill the circuit board. The barrel jack has a diode to prevent reverse polarity.

9. Connecting a load to the VIN pin while using USB power.

If you connect a load to the VIN pin while the 5V to the Arduino comes from a USB connection, the current will flow back through the voltage regulator, damaging it.

10. Static electricity; while most chips have clamp diodes as protection against ESD (electrostatic discharge), it may be wise to wear an anti-static wristband or remove the carpet under your desk.

Step 3: Software

Getting Started with Arduino: A Beginner's Guide

ARDUINO IDE:

Windows:

1. Go to the site, go to download, and select the Windows installer.

2. If you want to support this project, consider donating some money, and then click download.

3. Click on the downloaded file to run it.

4. Grant administrator permissions.

5. Agree to the license agreement.

6. Select the appropriate boxes; you will need Arduino software and USB drivers; the other three are optional.

7. Accept the default installation folder or choose another. Then click “Install.”

8. When the system asks if you want to install the Arduino USB driver (device software), click “Install.”

9. Wait for the installer to finish, then launch the Arduino IDE.

(A complete installation guide can also be found on the Arduino website.)

Ubuntu:

1. Go to the site, go to download, and select the right Linux version.

2. Consider donating some money if you want to support the project and click download.

3. Open a terminal window (CTRL+ALT+T), and run these commands, changing the filename appropriately

4. cd Downloads

5. tar xf arduino-1.6.11-linux64.tar.xz

6. sudo mv arduino-1.6.11/ /opt/arduino-1.6.11/

7. /opt/arduino-1.6.11/install.sh

8. sudo usermod -a -G dialout $USER

This will go to the downloads folder, extract the downloaded files, move them to the /opt folder, and then run the install script. This install script will create a desktop file and a MIME type to associate .IO files with the ARDUINO IDE. Finally, the user must be added to the dialout group (-g) (-a=append) to access the serial port. ($USER is the system variable for the current user) If you now open the Arduino IDE, you will see the tools>port option greyed out. When your user is added to the dialout group, log out and log back in. The Arduino’s serial port should now be available in the IDE.

Step 4: Hardware & Electronics

Getting Started with Arduino: A Beginner's Guide

Before we start, I will explain some basic electronic components. If you are just starting with electronics, this is for you!

Sometimes I will use some physics to explain how a component works; this is just a side note, and if you still don’t understand, that’s okay. It takes some time to get used to.

However, if you want to study electronics further, you will find that electronics is just applied physics.

I will also provide links to some YouTube videos that helped me understand the basic principles of different components.

Basic Physics

Electricity is the flow of charge carriers: electrons (in most cases).

Electrons are negatively charged particles that orbit the positively charged nucleus of an atom (nucleus, plural, nuclei).

Electrons move easily through metals like copper, silver, and gold… We call these materials conductors.

These materials have free-moving electrons.

Materials like plastic, wood, glass, and air have poor conductivity. They are called insulators.

They have no moving electrons or other charge carriers.

A piece of material with more negative charge (electrons) than positive charge (positively charged atomic nuclei) is negatively charged.

A piece of material with less negative charge than positive charge is positively charged.

(Note that only electrons can move; the positive atomic nuclei are trapped in a lattice.)

Just like magnets, opposite charges attract each other: when there are more electrons in one material and fewer in another, the electrons in the negative piece will be attracted to the positive piece. If there is a conductor between these pieces, these electrons will “flow” to the positive part: this is electric current.

Electric current indicates the amount of charge flowing through a conductor per unit of time. Its unit is AMPS (AMP), defined as C/S, where C is coulombs (charge) and S is seconds (time). Its symbol is I.

The negative terminal of a battery has more electrons, while the positive terminal has fewer electrons. As I mentioned earlier, electrons will try to reach the positive terminal, but they cannot pass through the internal circuit of the battery itself. This gives the electrons potential energy. This is the energy released as light and heat in a bulb, or as motion (kinetic energy) in a motor… The difference in potential energy between positive and negative charges is called voltage. The unit is volts, defined as J/C, where J is joules (the international unit of energy) and C is coulombs (the international unit of charge). This indicates how much energy is released by a charge (read as: a certain number of electrons).

The symbol for volts is v or u (from the German word “unterschied,” difference, indicating potential difference).

Power is the amount of energy released per unit of time. The international unit is watts, defined as J/S, where J is joules and S is seconds. If you multiply current by voltage (C/S j/C), C will cancel out, so you get j/s. This means that voltage times current gives you watts.

In most schematics, conventional current is used: arrows are drawn from positive to negative. But in reality, only electrons can move, so the actual flow of current is from negative to positive.

Resistors

A resistor is a component that has resistance, which limits the flow of electrons, so they are often used to limit current.

The international unit of resistance is ohms, usually written as the Greek letter omega (Ω). They are often used with unit prefixes kilo (k) and mega (M). For example, 1.2MΩ = 1M2Ω = 1200KΩ = 1200000Ω = 1200000Ω (note that writing a number after the unit prefix is the same as writing it after the decimal point). Additionally, in some schematics, e or r is used instead of Ω).

The value of a resistor is represented by 4 (or 5) color bands using resistor color code:

The first 2 (or 3) bands are the first 2 (or 3) significant digits of the value, the 3rd (or 4th) band is the power of ten after those 2 (or 3) digits. This is also called the multiplier, which is just the number of zeros you need to add. The last band is the tolerance, mainly silver or gold.

For example, red-red-gold = 22×100Ω = 2200Ω = 22×10Ω = 2K2Ω = 2.2KΩ, tolerance 5%; green-blue-black-brown-red = 560×10Ω = 5600Ω = 5k6Ω = 5.6KΩ, tolerance 2%.

The relationship between resistance, voltage, and current can be calculated using Ohm’s law.

I = V/R

Where I is current (amperes), V is voltage (volts), R is resistance (ohms).

This is a very, if not the most important formula in electronics, so try to remember it!

Step 5: Blink: Digital Outputs

Getting Started with Arduino: A Beginner's Guide

Blink: The first Arduino code

When you first plug in your ARDUINO, you will see a green light (labeled ‘ON’—this is the power LED) and a blinking orange light (labeled ‘L’). This is the default “blink” program, which turns the internal LED on for one second, then off for one second, repeating indefinitely.

Let’s take a look at the code: open the Arduino IDE and go to file>examples>01.basics>blink.

The first thing you will notice is that the first 14 lines are lighter than the others. All text placed between /* and */ is a comment. This is a multi-line comment. On line 17, there are some comments using the // operator, everything on that line after // is a comment. The next line is again ordinary code, unlike multi-line comments; you don’t have to close this single-line comment.

Comments are used to make the code more readable, so it’s highly recommended that you use these comments in your own programs. In small programs like blink, this isn’t really necessary, but when you write over 1000 lines of code, you will be very grateful for adding some comments to help you understand what a specific piece of code is and how it works.

You can also use the comment operator to temporarily disable a section of code without having to delete it permanently. This is effective because comments won’t upload to Arduino. (They are ignored by the compiler, which converts the code written in the ARDUINO IDE into commands that ARDUINO can understand.) This also means they don’t take up any space in the ARDUINO (limited) memory, only on the computer’s hard drive.

Arduino Reference: Comments

The next piece of code we encounter is “void setup() {”

This is the setup function, which runs only once every time you run the ARDUINO. (void is a data type that means the setup function does not return any information, we will detail this later. Every function uses two parentheses to pass data; the setup function does not need any data, so the parentheses are empty. If you don’t understand this yet, don’t worry; we will go into detail about functions in a later step.)

Everything between the two curly braces or brackets after “void setup()” is the code that gets executed during setup. Be sure to close the brackets; otherwise, you will get strange errors. If you choose another bracket, the IDE will help you by highlighting the other bracket.

Arduino Reference: void

Arduino Reference: setup

Arduino Reference: curly braces

The first real command is ‘pinMode(13, OUTPUT);’. As you might have guessed, this relates to the two pins on the Arduino: these pins can be used as either input or output. The first number is the pin we want to use as output, in this case, 13, since all Arduino boards have an onboard LED connected to pin 13. The second parameter of the pinMode function, OUTPUT, is a constant. This is a value defined by the software itself and given a simple name. Constants will appear in blue.

(The output value is 1, which is a bit counterintuitive because its o looks like 0, while the input constant’s i looks like 1. pinMode(13, OUTPUT) is exactly the same as pinMode(13, 1).

By default, the pins of the Arduino are set to input, but by using the pinMode function, we now set pin 13 to output. We still haven’t told it what value we want to output, so it’s just 0. This means that, internally, pin 13 is connected to 0V, which is ground. If you now connect the 5V pin to pin 13, it will cause a short circuit! Be careful!

Arduino Reference: pinMode

Arduino Tutorials: Digital Pins

In the ARDUINO IDE and other C-like programming languages, every statement ends with a semicolon (;), as you can see in this blink example. When you encounter mysterious errors while trying to upload, the first thing to check is the semicolon. Most of the time, you will get an error like this: blink:16: error: expected ‘,’ or ‘…’ before…

16 is not the line missing the semicolon, but the line with the next command/statement.

Summary:

  1. In the setup, which only runs once when the program starts, we set pin 13 as an output.

  2. In the loop, we set the output of the LED HIGH (5V), wait 1,000ms, set it LOW (0V), and wait for another second. This loop will repeat forever (at least until you restart the Arduino or upload another program).

  • /*this is a comment */ this is not

  • this is not a comment // this is a comment

  • every statement ends with a semicolon;

  • void setup() { } is the function that runs once when the Arduino starts up.

  • void loop() { } is the function that repeats forever after the setup has run.

  • pinMode(pin, OUTPUT); or pinMode(pin, 1); sets the given pin as an output.

  • digitalWrite(pin, state); sets a given pin high (5V) or low (0V). State can be HIGH or LOW, 1 or 0, true or false.

  • delay(time); waits for a given amount of time, in milliseconds.

Step 6: Uploading a Program to the Arduino

Getting Started with Arduino: A Beginner's Guide

As an example, we will upload the blink example to the Arduino, but since it is already installed by default, we will change the value of the delay function to 500 instead of 1000; otherwise, we won’t see any difference.

Now plug your Arduino into your computer if you haven’t already. Wait for the computer to recognize the new USB device, then go to the Tools>Board menu in the Arduino IDE and select your board. Then in Tools>Port, select the correct port. On Windows, this may be a COM port. If multiple ports are available, unplug your ARDUINO and plug it back in to see which port disappears and reappears, identifying your ARDUINO’s port.

On Linux, it may be /dev/ttyacm0 (/dev/ttys0 is the serial port on the mainboard, so that’s not the right port. If you are using an old Arduino or a cheap Chinese clone, it might list as /dev/ttyUSB0).

In the bottom right corner, you should now see the name of your board and the port it is connected to.

Now click the right arrow in the top left to upload blink to the board. You can also use the shortcut Ctrl+U.

If all goes well, it should start compiling and then upload. When it uploads, the TX and RX lights should blink.

When finished, the LED on pin 13 should now blink at twice the speed.

Compiling means the human-readable code you wrote is converted into a series of binary numbers that ARDUINO can understand. Then this binary file is copied into the ARDUINO’s memory during the upload process.

Step 7: Driving More LEDs

Getting Started with Arduino: A Beginner's Guide

Alright, let’s face it: blinking a small LED isn’t that impressive… In this step, I will show you how to drive more LEDs.

Calculating the resistor value for the LED

Before you start, we will need to calculate the resistor to use in series with our LED. If you connect the LED directly to the Arduino, it will draw too much current, causing the LED to blow up, or even explode.

The formula we need is Ohm’s law: R = V/I

But the problem is we don’t know the voltage and current for the resistor yet… Let’s find out!

We will put the resistor and LED in series, and we know the output voltage of the Arduino pin is 5V, so if we add the voltage across the LED to the voltage across the resistor, it should equal 5V. So: VR + VL = 5V, VR = 5V – VL.

Since they are in series, this also means that all electrons passing through the LED will also pass through the resistor. Since current is defined as the amount of electrons passing through per unit time, we know that the current through the resistor is equal to the current through the LED. So: IR = IL.

Now we can use Ohm’s law to calculate the resistor: R = VR/IL = (5V – VL)/IL.

(Image 1)

Note that if the current is given in milliamps (mA), it must be divided by 1000 to get the SI unit of current in AMPS. Otherwise, you will not get the answer in ohms (but in kiloohms). This applies to every physical formula: if you input your values in their respective international units, you will always get an answer in international units.

If you are using a 3.3V Arduino, you can substitute 3.3V for 5V. This is just the supply voltage, and it can be anything.

VL and IL values can be found in your LED datasheet, or you can use the table below.

IL should be less than 20mA; otherwise, you will kill your LED.

VL is the forward voltage drop of the LED. (LEDs emit lower energy light with longer wavelengths, such as red and infrared, which have much lower voltage drops than higher energy photons such as blue or ultraviolet.)

Color Forward voltage (VL)
Red 1.7V – 2.2V
Orange 2.0V
Yellow 2.1V
Green 2.2V
Blue 3.2V – 3.8V
White 3.2V – 3.8V

This is just an approximation, but it does not hold for every LED.

You might not have an exact value for the resistor you just calculated, so round up to the next value in the E-12 series. This series of values includes only 1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2, multiplied by powers of ten like 10, 100, 1000, 10000, etc.

For example, if my result is 65Ω, I would take a 68Ω resistor.

It’s better to take a higher resistor value so you don’t damage your LED.

Connecting the LED to the Arduino

As I explained earlier, an LED is basically a diode, so it only allows current to flow in one direction. If we connect the LED the wrong way around, nothing will happen.

LEDs have a cathode and an anode: in schematics, the direction of the arrow indicates the conventional current flow, so it points to the negative terminal: cathode.

When you look closely at an LED, you will notice one side is flat, while the other is rounded. Also, one leg is shorter than the other: the flat side, the shorter leg, is the cathode, and we will connect this side to the negative or ground of the Arduino.

It doesn’t matter where you place the resistor as long as it is in series with the LED; you can connect it to either the cathode or anode.

If we know that only one LED will be on at a time, we can use one resistor for all our LEDs.

Take a look at images 2-3-4, then connect the resistor to ground and a horizontal track on your breadboard, and an LED with the short leg into the same track, the long leg into pin 12 on the Arduino.

Note that you must calculate the specific resistor for the LED. You can use the formula above, or use an online tool, or an application (I used this tool and this app). If you click the question mark next to the field, this tool will give you extra information, and the application has a drop-down menu to select colors.

If you have questions, or—like me—you’re just too lazy to look up and find the right resistor, you can use any resistor between 220Ω and 330Ω. This is only correct if you are using it with a 5V Arduino! 270Ω and 330Ω are a bit high for a 3.3V Arduino, in which case use values between 100Ω and 220Ω. If you want to use a higher voltage LED, you need to calculate it.

After connecting the LED and resistor to the Arduino, you can replace pin 13 in the blink example with 12. You can use the shortcut Ctrl+F: in the “find” field, type 13, in the “replace with” field, type 12, and then click “replace all.” Now upload the sketch to your Arduino: the LED you connected should now blink.

Still not impressed? No? You’re right…

But now that you have the basic knowledge, we can do some more spectacular things…

More LEDs

Connect 5 additional LEDs to pins 2, 4, 6, 8, and 10 with their long legs, and connect their short legs to the same track on the breadboard as the LED pin 12 and the resistor.

Now open the example blink6-a from the .zip file downloaded in step 3.

If you remember the blink example, it’s not hard to predict what this program will do. Upload it to your Arduino and check if your assumption is correct!

Optimizing the code

If you take a close look, you will see some code is just the same command repeated six times, just with a different PIN number… Well, there’s a way to solve this: we call it a for loop.

Open the blink6-b sketch from the .zip file. When you upload it to the ARDUINO, you will find it behaves exactly the same as blink6-a, but it has far fewer lines of code.

This is all thanks to the two for loops used.

But before I explain how for loops work, I first need to explain how variables work:

In the first line, there is a new expression “int delayTime = 200,” which is the declaration of a variable called “delayTime.” A variable is just a piece of memory where you can store anything you like. Variables have a data type, a name, and a value: in this case, the data type is “int”: an integer, a whole number that can be positive or negative. The name is ‘delayTime,’ which is just an arbitrary name you give the variable, and it can have letters and numbers, along with some symbols like underscores. If the name consists of multiple words, each new word begins with a capital letter, as spaces cannot be used. Choosing appropriate names for variables greatly impacts the readability of the code. Using “int delayTime,” the variable is correctly declared but has no value. Assigning an initial value to a variable is called initialization. In this case, we initialize the variable delayTime to 200. Now, whenever we use “delayTime” in the code, it will be replaced by the number 200. If you read a variable without first initializing it, it will just give you 0 at best, but it might just be a random value that happens to be in that spot in memory, potentially causing errors in your program.

Arduino Reference: Variables

Arduino Reference: int

Arduino Reference: Variable Scope

Another useful thing about variables is that you can change them while the code is running. That’s exactly what happens in the for loop. The first part between the parentheses just declares a variable “i” and initializes it to 2. The next part is “i <= 12,” which means the for loop will repeat as long as i is less than or equal to 12. The third and final part is ‘i = i + 2,’ which means every time the loop is repeated, the value of i will increase by 2.

This means it will first execute the code within the parentheses, where the value of i is 2, setting pin 2 as an output. Now it has reached the end of the code, so 2 is added to i → i now equals 4, the code runs again, i’s new value is: pin 4 is set as an output. 2 is added again, i now equals 6, the code runs again, 2 is added… and so on. Until i reaches 12. When i executes the loop at 12, everything is fine, but when it now reaches the end of the code and adds 2 again, it no longer satisfies the condition “i ≤ 12” (I’m now 14). The program exits the for loop.

Now, every pin with an LED is set as an output, and only two lines of code instead of six.

Arduino Reference: For Loops

Summary:

Find the right LED resistor.

Look for the forward voltage in the LED datasheet, or in the table above. This is VL.

Look up the forward current in the LED datasheet or use something between 2 to 20mA, and convert that number to AMPS. This is IL.

Find your supply voltage, which is usually 5V or 3.3V for most microcontrollers like Arduino. This is VS.

Now use this formula to calculate the resistor value: R = (VS – VL) / IL.

Round this value to the nearest resistor you have. You can always use a higher value than the one you calculated, but if you use a lower resistor, it will greatly shorten the lifespan of your LED. If the resistor is too high, the LED will be very dim.

The round side of the LED, with the longer leg, is the anode, and that is the positive side.

The flat side of the LED, with the shorter leg, is the cathode, and that is the negative side.

Ctrl+F opens the search/find/replace window in the Arduino IDE.

It delayTime; this is the declaration of a variable of data type int called “delayTime.”

It delayTime = 200; this is the declaration of a variable of data type int called “delayTime,” initialized to a value of 200.

Global variables can be accessed anywhere in the program, while local variables are only accessible within the scope they are declared.

for (int i = 0; i < 10; i = i + 1) {} is a for loop that initializes the variable i to a value of 0 and increments i by 1 every time it repeats, repeating only while i < 10 (10 times).

Extra: Calculating the power of the resistor.

If you use a 5V power supply, like the one on the Arduino, a normal 1/4 watt resistor will be sufficient, but when you use a higher supply voltage or an LED that draws more current, the power in the resistor will be too high and it will burn out.

Therefore, we need to calculate how much power the resistor dissipates.

(Image 6)

The formula for calculating power is P = V I. So we can calculate the voltage across the resistor: the supply voltage minus the voltage across the LED: VR = VS – VL.

The current through the resistor is the same as the current through the LED: IR = IL.

So: PR = (VS – VL) ∙ IL.

In the example shown in image 6, the power in the resistor is very low, so a 1/4 watt resistor is sufficient, but if the calculated value is higher, you will need a more powerful (= thicker) resistor.

However, these values are just theoretical assumptions.

If you really want to know the actual power dissipated by the resistor, you have to measure its current or voltage, or best of all.

In case A, where you can measure both current and voltage, you can use the same formula.

But if you can only measure one of the values, you can replace the voltage or current in the power formula with Ohm’s law. (Case B & C)

Only case A gives you the real power dissipated; in cases B & C, you need the resistor value. The value written on the resistor has a certain tolerance, so your wattage will also have some deviation.

Step 8: Even More Blinking LEDs

Getting Started with Arduino: A Beginner's Guide

Programming a sequence of LEDs

Open the example blink7.

In line 3, you will see a new structure: we call this an array. An array is basically a list of variables, in this case, a list of int type variables. We use square brackets to indicate that it is an array. To initialize an array, we use curly braces and separate the values with commas.

When we want to use a value from the array, we need to specify the position of the value we need in the array. For the array in blink7:

int array[] = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2};

If we want to get the first value of the array, we use

array[0]

Note that 10 is the number of elements, and the last element is array[9]!

If you initialize in the same line, as in blink7, the ARDUINO IDE will calculate the elements for you, and you don’t have to specify anything between the parentheses.

If you want to know the number of elements in the array, you can use the sizeof(array) function. This function returns the size of the array in bytes (1 byte = 8 bits). However, this is not the number of elements; in blink7, sizeof(array) will return 20. This is because each element is an int, and an int is 2 bytes long. So the total number of elements is 20/2 = 10.

When we read through the whole array, we use it to exit the for loop: as long as the index is less than the number of elements, we can safely read from the array. We start with i = 0 because the first element has an index of 0. This time we only increment by 1. The symbol “i++” is exactly the same as writing “i = i + 1,” just shorter. Another way to write it is “i += 1.”

Since LED 1 is connected to pin 2, LED 2 is connected to pin 4, LED 3 to pin 6, and so on, we multiply the LED number by 2 to get the pin number.

Arduino Reference: Array

Arduino Reference: Sizeof

Arduino Reference: Increment

Arduino Reference: Compound Addition

You can change the values in the array to generate your own sequence, and you can even add or remove elements, as we use the sizeof() function to make the program independent of the length of the array.

Summary:

An array is a list of values (or characters or other arrays) and uses square brackets [].

This is the declaration of an array: “int array[10];”

This is a declaration and initialization of an array: “int array[] = {1, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2};”

Array indexes are zero-based, meaning the index of the first element is 0.

sizeof(array) returns the byte size of the array.

sizeof(data type) returns the byte size of the data type.

sizeof(array) / sizeof(array data type) gives you the number of elements in the array.

Extra: Two-dimensional arrays (matrices)

In an array, elements can be other arrays as well as data types (like int). This allows you to have what is called a two-dimensional array, which can be compared to a matrix.

This is used in the example blink8: now you can set the LED numbers and delays in the array.

int array[][2] = { {1, 600}, {2, 100}, {3, 100}, {4, 100}, {5, 100}, {6, 600}, {5, 100}, {4, 100}, {3, 100}, {2, 100} };

Note that when declaring a multidimensional array, we must specify all dimensions except the first one between square brackets.

The syntax for getting a value from an array is

array[row][column]

Open the example matrix sum. This example does nothing; if you upload it, it will have no output, it is just for learning purposes.

It creates four matrices (2D arrays), two of which have values. Then it just calculates the sum of the two matrices, the transpose of the first matrix.

This is done using nested for loops. You can follow the explanation in the image above.

The numbers indicate the order in which the for loops iterate through them. I use i for rows and j for columns. They start at the first column and first row of the matrix (1, 1) for the array notation [0][0], then increment the column (1, 2) or [1][0], and when j increments again, the column increments (1, 3) or [2][0], and j exits because j is no longer less than three. i increments, j resets to zero: (2, 1) or [0][1], then j increments: (2, 2) or [1][1], and finally (2, 3) or [2][1]. Now j exits, and so does i.

The calculation of the transpose matrix is similar; it just swaps columns and rows:

transposeMatrix[i][j] = matrix[j][i];

In these arrays, you can use more arrays, essentially creating multi-dimensional space. Theoretically, the dimensions are infinite, but once you use more than three dimensions, it becomes very complex, so other methods are preferred.

Leave a Comment

×