constants
Constants are predefined expressions in the Arduino language. They are used to make the programs easier to read. We classify constants in groups:
Defining Logical Levels: true and false (Boolean Constants)
There are two constants used to represent truth and falsity in the Arduino language: true , and false .
false
false is the easier of the two to define. false is defined as 0 (zero).
true is often said to be defined as 1, which is correct, but true has a wider definition. Any integer which is non-zero is true, in a Boolean sense. So -1, 2 and -200 are all defined as true, too, in a Boolean sense.
Note that the true and false constants are typed in lowercase unlike HIGH , LOW , INPUT , and OUTPUT .
Defining Pin Levels: HIGH and LOW
When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW .
The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT . When a pin is configured as an INPUT with pinMode() , and read with digitalRead() , the Arduino (ATmega) will report HIGH if:
a voltage greater than 3.0V is present at the pin (5V boards)
a voltage greater than 2.0V is present at the pin (3.3V boards)
A pin may also be configured as an INPUT with pinMode() , and subsequently made HIGH with digitalWrite() . This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This can be done alternatively by passing INPUT_PULLUP as argument to the pinMode() function, as explained in more detail in the section «Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT» further below.
When a pin is configured to OUTPUT with pinMode() , and set to HIGH with digitalWrite() , the pin is at:
5 volts (5V boards)
3.3 volts (3.3V boards)
In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.
The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT . When a pin is configured as an INPUT with pinMode() , and read with digitalRead() , the Arduino (ATmega) will report LOW if:
a voltage less than 1.5V is present at the pin (5V boards)
a voltage less than 1.0V (Approx) is present at the pin (3.3V boards)
When a pin is configured to OUTPUT with pinMode() , and set to LOW with digitalWrite() , the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).
Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT
Digital pins can be used as INPUT , INPUT_PULLUP , or OUTPUT . Changing a pin with pinMode() changes the electrical behavior of the pin.
Pins Configured as INPUT
Arduino (ATmega) pins configured as INPUT with pinMode() are said to be in a high-impedance state. Pins configured as INPUT make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 Megohms in front of the pin. This makes them useful for reading a sensor.
If you have your pin configured as an INPUT , and are reading a switch, when the switch is in the open state the input pin will be «floating», resulting in unpredictable results. In order to assure a proper reading when the switch is open, a pull-up or pull-down resistor must be used. The purpose of this resistor is to pull the pin to a known state when the switch is open. A 10 K ohm resistor is usually chosen, as it is a low enough value to reliably prevent a floating input, and at the same time a high enough value to not draw too much current when the switch is closed. See the Digital Read Serial tutorial for more information.
If a pull-down resistor is used, the input pin will be LOW when the switch is open and HIGH when the switch is closed.
If a pull-up resistor is used, the input pin will be HIGH when the switch is open and LOW when the switch is closed.
Pins Configured as INPUT_PULLUP
The ATmega microcontroller on the Arduino has internal pull-up resistors (resistors that connect to power internally) that you can access. If you prefer to use these instead of external pull-up resistors, you can use the INPUT_PULLUP argument in pinMode() .
See the Input Pullup Serial tutorial for an example of this in use.
Pins configured as inputs with either INPUT or INPUT_PULLUP can be damaged or destroyed if they are connected to voltages below ground (negative voltages) or above the positive power rail (5V or 3V).
Pins Configured as OUTPUT
Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. ATmega pins can source (provide current) or sink (absorb current) up to 40 mA (milliamps) of current to other devices/circuits. This makes them useful for powering LEDs because LEDs typically use less than 40 mA. Loads greater than 40 mA (e.g. motors) will require a transistor or other interface circuitry.
Pins configured as outputs can be damaged or destroyed if they are connected to either the ground or positive power rails.
Defining built-ins: LED_BUILTIN
Most Arduino boards have a pin connected to an on-board LED in series with a resistor. The constant LED_BUILTIN is the number of the pin to which the on-board LED is connected. Most boards have this LED connected to digital pin 13.
#1 · Blinking Arduino’s builtin LED
When I bought my first Arduino there was no YouTube with fancy instruction videos. What I saw was: a printed circuit board with chips, pins, a button and LEDs. The only thing I could think of was to start as fast as possible by just trying. I skipped explanations of the basics because I wanted to get my LCD display working now, not after reading boring theory.
Soon I discovered that getting things to work was not as simple as it looked in the first place. A tough lesson was that I could even damage components when I wired things the wrong way. If you don't mind things being damaged, by all means go ahead and discover yourself . If you want a little bit more guidance, please continue reading.
I could a start an endless story on electronics, bombarding you with circuit diagrams and stories about signals. That is exactly what Bas on Tech tends not to do. You find this information on many webpages with a click of the mouse. This is our first Arduino tutorial and therefore I have to explain some things to get you started. This will make it easier for you to understand the working of the circuit. Something which I prefer over just copy/pasting the Arduino code (can't wait? You can download the code with the course material button at the bottom of this page).
Course material
At the bottom of this page you'll find the course material button. This button allows you to download the code, circuit diagram and other files relevant to this Arduino tutorial.
What is an Arduino?
The Arduino is a so called microcontroller. It processes analog and digital signals and can react to these. The heart of the Arduino is the AVR-chip. What this chip has to do is written in a program written in Arduino code. Via an USB cable the compiled program could be uploaded to the Arduino. The possibilities are endless: mp3 player, mobile phone, robot, weather station, game computer, RC cards, home automation and much much more!
The design of the Arduino is open source. This means that the manufacturer is allowed to bring its own Arduino to market. There are lots of Chinese "Arduino clones" sold. These can do exactly the same as the original Arduino. Often cheaper components are being used which is not an advantage. Clones could need special drivers being installed, while the original is just plug and play.
In this tutorial I am using the Arduino Uno, but there are many more like the Nano, Pro Mini, Micro and Mega. Each one has its own pros and cons. This could be the amount of inputs / outputs, speed but als the form factor. In this video I show the differences between several Arduino boards.
How to progam with the Arduino IDE?
In this Arduino tutorial we're going to program the builtin LED. The tool we are going to use is the Arduino IDE which is freely available on the Arduino website
IDE is an abbreviation of Integrated Development Environment. A tool which converts your code into the bits and bytes which the Arduino understands. This process is called compiling. Besides compiling the IDE also checks if the code is correct. In the next tutorials you'll learn more about this.
Arduino CH340/CH341 drivers
Some non-original Arduinos might require a driver to be installed. This is because these boards are using the CH340/CH341 chip for USB communication with your computer. You'll find more information about this driver on the Sparkfun website.
Which pins does the Arduino have?
For this tutorial I use the Arduino UNO, which has many pins to connect components to. When reading the word pins you might expect solid metal pins. For the UNO this is not the case. The UNO uses female headers. Instead the Arduino Nano uses real pins. Since the hardware implementation can differ per Arduino the common name is pins.
Arduino UNO with large AVR-chip by Arduino.cc
At the top of the Arduino you'll see the digital pins. These can only have one of these two values: HIGH or LOW . When high, a small current flow through the pin. For low it does not. On a 5V Arduino, this current is 5V, for the 3.3V variant this is 3.3V.
The bottom right shows the analog pins, which has 1024 possible values: 0 to 1023. On the bottom left you'll see the current pins like 5V, 3.3V, ground GND and the reset pin RES .
The Arduino UNO is also equipped with some special pins. One of these is pin 13 (top right). This pin is connected with the builtin LED. This is a LED which you can program and is not being used by the Arduino. The builtin LED is marked L on the PCB.
In the picture of the Arduino UNO you see a large chip. This is the AVR-chip, the heart of the Arduino. You might see a smaller chip in the center of your Arduino. This is the SMD variant of the chip. It is a lot smaller and not easy to replace.
Arduino Code
Time to dive into the code For this tutorial we are going to use off the shelf example code. In the op menu of the Arduino IDE you can choose:
File ▸ Examples ▸ 01. Basics ▸ Blink
The IDE should open the code to blink the builtin LED automatically. Take some time to read the code before you continue. Are you able to figure what each line does?
In the code you see all kinds of commands. These commands are written in a syntax that the computer understands. Misplacing a dot or comma could result in the computer being unreadable to read your code. No worries, as a software developer this where you run into many times and is part of the job.
Comments in the code
Line 1, 2 and 8 start with two slashes // . This line of code is what we call comment. Comments allow you to provide human readable additional information which is completely ignored by the computer. Another form of comment starts with /* and ends with */ . Everything between the start and end will be seen as part of the comment e.g.:
You can use this syntax for a single line comments as well:
The setup() function
The code has been split into two parts: setup and loop. We refer to these blocks as functions. In another tutorial we are going to dive deeper in how to make your own functions. The indenting is not mandatory, but helps to quickly see what lines belong to the function.
When the program starts it executes the setup() function once. After this the program continues with the loop() . The setup() is for example used to assign pins.
In this example we are using the pinMode function to specify we want to use the LED_BUILTIN pin as a OUTPUT . On the Arduino UNO, LED_BUILTIN is an alias for 13 (the builtin LED pin). Therefore you could have typed 13 as well. The advantage of using LED_BUILTIN is that it works on all Arduinos. Even when the builtin LED is connected to another pin.
The loop() function
After the setup() , the program continues with the loop() . This function will be called over and over again. Every time the function has finished, it will be called again. The only way to stop the program is to disconnect the power or to upload a new program.
If you look closely at the code you see two other functions being called: digitalWrite() and delay() . digitalWrite() writes the value ( LOW or HIGH ) specified to a given pin. The pin we are using is specified by the function's first parameter, in our case LED_BUILTIN . The second parameter specifies the written value, here HIGH . digitalWrite() in this case, makes sure that the LED on pin 13 will be lit.
The next line shows the delay() function with a single parameter. Can you think about what the value of this parameter represents?
Its value is the amount milliseconds the program has to wait. In our case this is 1000 milliseconds, which is the equivalent of 1 second.
After this brief pause, the program continues and writes LOW to the LED_BUILTIN pin. As a result the LED goes off.
Uploading code to the Arduino
Now our program is ready to upload to the Arduino. First we have to connect our Arduino to the computer with the USB cable. Make sure you've selected the correct board in the IDE:
Tools ▸ Board ▸ Arduino/Genuino UNO
and the correct port:
If you are not sure which port to use, try them all until you can successfully upload your code.
The top left shows a round button with a checkmark. By pressing this button you tell the IDE to verify your code for possible errors. The IDE only checks if it can read your code. It does not check if you have written correct code for what you are trying to program.
If everything works the IDE shows the Compiling completed message. You can now upload your code by pressing the round button with the arrow to the right. The uploading is complete when the Avrdude done. Thank you. messages appears. Your program will immediately start after uploading. As a result you should now see your Arduino LED blink with 1000ms intervals.
Challenge
Great to see you made it this far! Are you ready for a challenge?
Change the code so the LED tuns on, wait for 0.5 second, turn off the LED and wait for 2 seconds.
The Arduino built-in LED
Arduino boards come with a little utility: the built-in LED.
It is identified by the letter L next to it. On the Arduino Uno, it is near pin #13:
On the Arduino MKR 1010 WiFi it is near the 5V output pin:
This LED is connected to the digital I/O pin #13 in most boards. In some boards, like the Arduino MKR series, it’s linked to the pin #6.
In any case you can reference the exact pin using the LED_BUILTIN constant, that is always correctly mapped by the Arduino IDE to the correct pin, depending on the board you are compiling for.
To light up the LED, first you need to set the pin to be an output in setup() :
Урок 3. Управление светодиодом
Это третий урок из цикла «Знакомство с Arduino». В этом уроке Вы научитесь управлять как установленным на плате Arduino светодиодом, так и внешним светодиодом.
Для урока Вам понадобится следующие детали:
- Arduino Nano;
- беспаечная макетная плата (она же breadboard);
- провода типа папа-папа;
- светодиод;
- резистор номиналом 220 Ом.
Если на компьютере не установлена среда Arduino IDE, то необходимо её скачать и установить. Урок по основам работы с IDE можно прочитать здесь.
Первым проектом на Arduino у большинства людей является обычное мигание установленным на плату светодиодом. Пожалуй и мы начнём с этого. Кроме модуля Arduino и кабеля для его подключения к компьютеру Вам больше ничего не понадобится.
Итак, подключите модуль Arduino к компьютеру. Далее откройте среду разработки Arduino IDE и при помощи неё загрузите следующую программу в Arduino. Если забыли или не знаете как это делается, то прочтите предыдущий урок.
Текст программы:
LED_BUILTIN — константа, которая заранее определена в языке программирования модулей Arduino и она равна 13 (LED_BUILTIN = 13). Функция setup() запускается однократно при запуске программы. В ней устанавливается режим работы вывода № 13 (к нему подключён установленный на плату светодиод) Arduino — как выходной порт. Функция loop() вызывается после функции setup(). Функция представляет собой бесконечный цикл, в котором выполняется пользовательская программа. В ней при помощи функции digitalWrite (LED_BUILTIN , HIGH) на порт № 13 подаётся высокий уровень напряжения (5 В), тем самым мы зажигаем светодиод. Функция delay (1000) устанавливает задержку при выполнении программы на 1000 мс, т.е. светодиод продолжает гореть 1 секунду. Далее при помощи функции digitalWrite (LED_BUILTIN , LOW) мы гасим светодиод (подаём на вывод № 13 низкий уровень напряжения (0 В)) и также ждём 1 секунду, т.е. наш светодиод погашен в течении 1 секунды. Таким образом, мы поочерёдно зажигаем и гасим светодиод с периодом в 1 секунду.
После загрузки программы, установленный на плате Arduino Nano светодиод начнёт мигать с периодом в 1 секунду.
Ну что ж, мигать светодиодом на плате Arduino мы научились. Скажете совсем просто? Давайте усложним задачу. Подключим к Arduino внешний светодиод.
Когда все необходимые детали находятся под рукой можно начинать собирать наш пример. Для этого необходимо воспользоваться следующими схемами:
Электрическая принципиальная схема:
Схема подключения на макетной плате:
Обратите внимание на полярность светодиода! Если его неправильно подключить, то он запросто сгорит.
Светодиод имеет два вывода, один из которых катод («минус», короткая нога), а другой — анод («плюс», более длинная нога).
Также не забудьте подключить токоограничивающий резистор 220 Ом. Можно взять резистор и большего сопротивления, но в таком случае светодиод будет гореть чуть тусклее.