Как подключить 12в диод к ардуино

от admin

Lesson 2: Blinking an LED

In our first lesson, we directly hooked up an LED circuit to the Arduino’s 5V and 3.3V pins. While this enabled us to learn about Arduino’s supply voltage and GND pins and gave us practical experience wiring electrical components into the Arduino ports, it was admittedly, a toy exercise.

In this lesson, we are going to do something more exciting: use the Arduino to turn the LED on and off by programmatically controlling the output voltage on one of Arduino’s GPIO pins. This begins our entrée into the two key aspects of working with microcontrollers: (1) building circuits and (2) writing code to interact with those circuits.

Materials

You will use the same materials as before, but you will also need the Arduino IDE and a USB cable to upload your program from your computer to your Arduino.

Arduino LED Resistor
Red LED 220 Ohm Resistor
Arduino Uno, Leonardo, or similar Red LED 220Ω Resistor

Making the circuit

Using the same resistor-wrapped red LED from before, plug the anode + resistor side into Pin 3 and the cathode into GND. See the wiring diagram below:

Wiring diagram showing LED cathode wired to GND and LED anode wired to a 220 Ohm resistor and then to Pin 3

TIP: Double check to make sure that you’ve correctly connected GND and Pin 3—it’s easy to be “off-by-one-pin” (a frustrating error!).

While it’s not necessary to use a breadboard for this simple circuit, here are two functionally equivalent breadboard-based wiring options. As our circuits get more complex, you will need to use a breadboard—so it’s good to start (or continue!) building up familiarity. Which breadboarded design makes most sense to you? Use your finger to trace the flow of current from Pin 3 to GND. To zoom in on the images, you can right click and select “Open Image in a New Tab.”

Breadboard Option 1 Breadboard Option 2
Breadboard wiring diagram showing LED cathode wired to GND and LED anode wired to a 220 Ohm resistor and then to Pin 3 Second breadboard wiring diagram showing LED cathode wired to GND and LED anode wired to a 220 Ohm resistor and then to Pin 3

You can always return to our breadboard lesson to refresh your memory!

Next, we’ll write C/C++ code for the Arduino’s microcontroller to turn on the LED from Pin 3, which will programmatically set Pin 3 to 5V.

NOTE:

The Arduino software is open source and consists of a development environment (called an IDE) and core libraries. The core libraries are written in the C and C++ programming language and compiled using avr-gcc and AVR libc. The source code for Arduino is hosted on GitHub. The libraries for AVR microcontrollers like the ATmega328 (which the Arduino Uno uses) is in GitHub here.

Get the Arduino IDE

But first, we need to download and install the Arduino IDE (if you haven’t already). Please follow our step-by-step installation and customization instructions here.

Introducing digital output

Now, we are going to write code to turn on our LED by setting Pin 3 to HIGH (or 5V). Then, we will modify this code to flash the LED both on and off. To do this, we have to introduce digital output.

The Arduino Uno has 14 general-purpose input/output (GPIO) pins that can be used for digital input/output (I/O)—that is, to read or write digital information ( HIGH or LOW ) using digitalRead() and digitalWrite() , respectively. We could have selected any of these pins for this lesson but we chose Pin 3 (in part, because we want to use this same pin in Lesson 4 and using it now simplifies things!).

Close-up image of the 14 digital I/O pins on the Arduino Uno

You can control any of these 14 digital I/O pins with three functions:

    configures a specified pin as either an INPUT or OUTPUT . In this case, we want to specify OUTPUT because we want to output a signal to turn on the LED. reads digital input from the specified pin, either HIGH or LOW . We will cover digitalRead in our Intro to Input lesson series. writes digital output to the specified pin, either HIGH or LOW . We’ll be using digitalWrite in this lesson.

What do we mean by HIGH and LOW?

An Arduino’s supply voltage is often written as \(V_S\), \(V_\), and \(V_

\) in datasheets. Sadly, there does not appear to be a consistent naming convention (link1, link2). We’ll try to consistently use \(V_\) or \(V_S\) but occasionally you’ll see others (e.g., \(V_
\)).

On the Arduino Uno and Leonardo, the supply voltage (\(V_\)) is 5V. So, when a pin as configured as an output via pinMode(<pin>, OUTPUT) , the pin can provide either a HIGH voltage (\(V_\)) or a LOW voltage (0V). Some microcontrollers operate at 3.3V. In this case, a HIGH state would be 3.3V but a LOW state would still be 0V.

We’ll look at actual digital output signals on an oscilloscope later in this lesson (in the section “What does digital output look like?”).

What can we use digital output pins for?

In general, digital output pins on microcontrollers are designed to send control signals and not act as power supplies. So, while these pins can supply enough current to use LEDs, piezo speakers, or control servo motors, if you need to control a high-current DC load such as a DC motor, you’ll need to use a transistor—which is an electronically controlled switch.

NYU’s ITP course has a nice tutorial on how to use a transistor, external power supply, and an Arduino to drive a DC motor. For students enrolled in our courses, we will tell you when you would need to do this. Rest assured, none of the introductory lessons require this circuit configuration.

What’s the maximum amount of current a digital output pin can supply?

The Arduino Uno uses the ATmega328P microcontroller, which can supply an absolute maximum of 0.04A (40 mA) per digital output pin or about

4 LEDs in parallel (with 10mA per branch).

According to Section 28.1 in the ATmega328P datasheet, anything beyond these limits “may cause permanent damage to the chip”. The maximum total current draw across all I/O pins together should not exceed 200mA. Again, this limit is not a concern for our introductory lessons (unless you deviate significantly from them).

Importantly, once you configure a digital I/O pin as OUTPUT , do not connect it directly to GND or \(V_\) or you may damage the microcontroller (typically, just that particular pin will be damaged). So, for example, if you’ve accidentally connected Pin 3 directly to 5V and write pinMode(3, OUTPUT); digitalWrite(3, LOW); , a whole bunch of current will “sink” into Pin 3 and potentially damage the pin.

You may be thinking: “um, what?” That’s OK. In our years of teaching, we have had very few Arduinos damaged due to current overdraw (though it’s worth watching this video on “5 Ways to Destroy an Arduino”). And you won’t need to worry about these limits for any of the introductory lessons.

Internally, how does the Arduino set a pin HIGH or LOW?

Though it’s not necessary to understand the following in order to use an Arduino, you might be curious about how the Arduino controls the voltage output of a pin? Using transistors. As the (simplified) schematic below highlights, a digital output pin provides either \(V_

\) (5V on the Uno and Leonardo) or \(GND\) (0V) by dynamically turning on/off transistors (an inverter ensures that only one transistor can be on at a time).

A simplified schematic by Chuan-Zheng Lee showing that an output pin provides VDD or 0 V by making a connection to VDD or ground via a transistorSchematic by Chuan-Zheng Lee for his “Intro to Arduino” course at Stanford.

Turn on LED programmatically via Pin 3

OK, so let’s write an initial program to set Pin 3 to HIGH (5V). We’re not blinking yet—just using code to set Pin 3’s output voltage to \(V_\).

Step 1: Start a new sketch in the Arduino IDE

Start a new sketch in the Arduino IDE:

Screenshot of the Arduino IDE showing a new empty sketch

Step 2: Set the pinMode for Pin 3

Because the 14 digital I/O pins can used for either input or output, we need to specify that Pin 3 should be used for output. That is, we want the Arduino to output a 5V signal on Pin 3 to turn on our LED. We configure pins in the setup() block and use the pinMode(int pin, int mode) command, which takes in a pin as the first parameter and a mode ( INPUT or OUTPUT ) as the second.

Step 3: Set Pin 3 HIGH

Lastly, we need to actually set the Pin 3 signal to HIGH . For this, we use the digitalWrite(int pin, int value) command, which takes in a pin as the first parameter and a value ( HIGH or LOW ) as the second. We could do this either in setup() or in loop() but since we’re not currently changing the output signal, there is no reason to put it in loop() , so let’s put it in setup() along with the pinMode code.

Step 4: Compile the code

We did it! Now it’s time to compile and upload the code to Arduino.

Compile the code by clicking on the “verify” checkmark button in the upper-left corner of the Arduino IDE. If you haven’t already, the Arduino IDE will also ask you to save your sketch. If there are any syntax or other identifiable errors in the code, the Arduino IDE will print them out in the console window at the bottom.

Step 5: Upload the code to Arduino

Finally, upload the code to the Arduino by clicking on the “right arrow” button (next to verify). Importantly, you must have already set your Arduino board and port in Tools->Board and Tools->Port , respectively.

Once uploading is complete, the code automatically runs on the Arduino and the LED should immediately turn on!

Note: On my Windows machine, I use a dark theme for the Arduino IDE.

Here’s an illustrative animation of what’s happening in your circuit when the Arduino drives Pin 3 HIGH —hopefully, this matches your conceptual understanding as well:

Turn on and off the LED programmatically via Pin 3

Now, let’s modify our code to turn on and off the LED programmatically. More specifically, we will alternate between having the LED on for one second and having the LED off for one second. To do this, we’ll use the delay(int ms) function, which pauses the program for the specified amount of time (in milliseconds).

Step 1: Move the digitalWrite code from setup() to loop()

First, move the digitalWrite code from setup() to loop() :

Step 2: Add in delays and code to turn off LED

Now, add in code to pause (for one second) and then turn off the LED (for one second) using delay() . Remember, when loop() completes, it is automatically called again (making the LED blink continuously).

Step 3: Compile and upload

We’re done! Now, compile and upload the code and see it run!

Step 4: Replace constants

Typically, we want to limit the use of literal constants in our code and replace them by variables. In this case, let’s replace 3 with LED_OUTPUT_PIN defined as a global variable at the top of our program ( const int LED_OUTPUT_PIN = 3; ). This will make our code more maintainable, more readable, and less prone to accidental mistakes. Try to do this for all literals in the future.

Walking through the code

How does this work? See the code walkthrough video below:

Our Blink code is in GitHub

You can access our Blink code in our Arduino GitHub repository. A “live” version is also embedded directly from the GitHub repo below.

This source code is on GitHub.

What does the digital output look like?

A common and important question when first working with microcontrollers is: what does the digital output look like?

In your mind, imagine what the voltage out of Pin 3 looks like over time (the x-axis is time and the y-axis is voltage output). You should envision a 5V output signal HIGH for the delay length followed by a 0V output signal, which is LOW delay length. Indeed, this type of graph is exactly what an oscilloscope is for—it graphs voltage values over time.

Using Tinkercad Circuits, we built the same LED-based circuit as above running the Blink program and hooked it up to an oscilliscope. Then, we recorded different delay values (400, 200, and 50) and created this movie. Is the graph what you expected? Why or why not. We suggest opening the video in its own tab or viewing it in fullscreen to see the details.

Video. A video of this Tinkercad project with three different delay values for both HIGH and LOW : 400, 200, and 50.

We encourage you to play with this Tinkercad project yourself and investigate different delays and their output on the oscilloscope.

Setting and visualizing different blinking frequencies

We duplicated the above Tinkercad setup (circuit + oscilloscope) in our laboratory and recorded a video. Notably, we used slightly different code that allows us to set the blink frequency by rotating a potentiometer.

Video A video showing the digital output voltage waveform at different “blinking” frequencies.

You can play with the Tinkercad version of this experiment here:

Figure. Tinkercad Circuits version of the settable delay circuit+code (link).

Mental model check: code is loaded and running on the Arduino

As a quick mental model check, it’s worth emphasizing that once you upload the code to your Arduino, you no longer need the USB cable. Why? Because a compiled version of the code is stored locally on your Arduino and stays there even when the Arduino loses power. Your Arduino is the computer! So, you could use some other power source like a 9V battery plugged in to the barrel jack port.

Blink without using delays()

Before moving on, it’s worth emphasizing that, in general, long delay() calls should be avoided. Why? Because while in a delay() , the Arduino is no longer responsive. So, for example, imagine updating your Blink program to also react to a button press from the user. If the user happens to press the button while the Arduino is in a delay() , your program would never be able to process that a button was pressed! This is a problem.

NOTE:

It’s OK to stop here and move on to the next lesson. It’s sufficient to be aware that long delay() calls can be dangerous and should probably be avoided. However, if you’re curious, you can continue this sub-section to see a Blink example that works without delays. We will return to this concept for our final Intro to Output lesson on multi-rate blinking LEDs.

If you want to know how delay() actually works, read “What does delay() actually do” in our Inside Arduino guide.

Because delay() usage can be so troublesome, as part of their introductory tutorial series, Arduino publishes another Blink example with a tutorial called BlinkWithoutDelay. As with the regular Blink, this example can be accessed directly in the Arduino IDE:

Screenshot of accessing the official BlinkWithoutDelay example directly from the Arduino IDE

To avoid delay() calls, the code tracks time, LED state changes (when the LED switches from HIGH to LOW or LOW to HIGH ), and when these state changes occur. The BlinkWithoutDelay main loop is below. Notice that there are no delay() calls!

We’ve also made our own BlinkWithoutDelay version, which is available on GitHub and shown below. This version is functionally equivalent to Arduino’s official example but uses our own coding style and is, in our opinion, more understandable.

This source code is on GitHub.

Next Lesson

In the next lesson, we are going to learn about a few basic debugging strategies before moving on to analog output, which lets us control the output voltage not just at two levels, LOW (0V) or HIGH (5V), but at finer levels between 0 and 5V using analogWrite(int pin, int value) .

Светодиоды и ленты

Светодиод – простейший индикатор, который можно использовать для отладки кода: его можно включить при срабатывании условия или просто подмигнуть. Но для начала его нужно подключить.

Подключение светодиода

Светодиод – это устройство, которое питается током, а не напряжением. Как это понимать? Яркость светодиода зависит от тока, который через него проходит. Казалось бы, достаточно знания закона Ома из первого урока в разделе, но это не так!

  • Светодиод в цепи нельзя заменить “резистором”, потому что он ведёт себя иначе, нелинейно.
  • Светодиод полярен, то есть при неправильном подключении он светиться не будет.
  • Светодиод имеет характеристику максимального тока, на котором может работать. Для обычных 3 и 5 мм светодиодов это обычно 20 мА.
  • Светодиод имеет характеристику падение напряжения (Forward Voltage), величина этого падения зависит от излучаемого цвета. Цвет излучается кристаллом, состав которого и определяет цвет. У красных светодиодов падение составляет

2.5 вольта, у синих, зелёных и белых

blank Если питать светодиод напряжением ниже его напряжения падения, то яркость будет не максимальная, и здесь никаких драйверов не нужно. То есть красный светодиод можно без проблем питать от пальчиковой батарейки. В то же время кристалл может деградировать и напряжение уменьшится, что приведёт к росту тока. Но это редкий случай. Как только мы превышаем напряжение падения – нужно стабилизировать питание, а именно – ток. В простейшем случае для обычного светодиода ставят резистор, номинал которого нужно рассчитать по формуле: R = (Vcc — Vdo) / I , где Vcc это напряжение питания, Vdo – напряжение падения (зависит от светодиода), I – ток светодиода, а R – искомое сопротивление резистора. Посчитаем резистор для обычного 5 мм светодиода красного цвета при питании от 5 Вольт на максимальной яркости (2.5 В, 20 мА): (5-2.5)/0.02=125 Ом. Для синего и зелёного цветов получится 75 Ом. Яркость светодиода нелинейно зависит от тока, поэтому “на глаз” при 10 мА яркость будет такая же, как на 20 мА, и величину сопротивления можно увеличить. А вот уменьшать нельзя, как и подключать вообще без резистора. В большинстве уроков и проектов в целом для обычных светодиодов всех цветов ставят резистор номиналом 220 Ом. С резистором в 1 кОм светодиод тоже будет светиться, но уже заметно тусклее. Таким образом при помощи резистора можно аппаратно задать яркость светодиода. Как определить плюс (анод) и минус (катод) светодиода? Плюсовая нога длиннее, со стороны минусовой ноги бортик чуть срезан, а сам электрод внутри светодиода – крупнее: blank

Мигаем

blank

Мигать светодиодом с Ардуино очень просто: подключаем катод к GND, а анод – к пину GPIO. Очень многие уверены в том, что “аналоговые” пины являются именно аналоговыми, но это не так: это обычные цифровые пины с возможностью оцифровки аналогового сигнала. На плате Nano пины A0-A5 являются цифровыми и аналоговыми одновременно, а вот A6 и A7 – именно аналоговыми, то есть могут только читать аналоговый сигнал. Так что подключимся к A1, настраиваем пин как выход и мигаем!

Как избавиться от delay() в любом коде я рассказывал вот в этом уроке.

Мигаем плавно

Как насчёт плавного управления яркостью? Вспомним урок про ШИМ сигнал и подключим светодиод к одному из ШИМ пинов (на Nano это D3, D5, D6, D9, D10, D11). Сделаем пин как выход и сможем управлять яркостью при помощи ШИМ сигнала! Читай урок про ШИМ сигнал. Простой пример с несколькими уровнями яркости:

blank

Подключим потенциометр на A0 и попробуем регулировать яркость с его помощью:

Как вы можете видеть, все очень просто. Сделаем ещё одну интересную вещь: попробуем плавно включать и выключать светодиод, для чего нам понадобится цикл из урока про циклы.

Плохой пример! Алгоритм плавного изменения яркости блокирует выполнение кода. Давайте сделаем его на таймере аптайма.

Теперь изменение яркости не блокирует выполнение основного цикла, но и остальной код должен быть написан таким же образом, чтобы не блокировать вызовы функции изменения яркости! Ещё одним вариантом может быть работа по прерыванию таймера, см. урок.

blank

Ещё один момент: если подключить светодиод наоборот, к VCC, то яркость его будет инвертирована: 255 выключит светодиод, а 0 – включит, потому что ток потечет в другую сторону:

Светодиодные ленты

Светодиодная лента представляет собой цепь соединённых светодиодов. Соединены они не просто так, например обычная 12V лента состоит из сегментов по 3 светодиода в каждом. Сегменты соединены между собой параллельно, то есть на каждый приходят общие 12 Вольт. Внутри сегмента светодиоды соединены последовательно, а ток на них ограничивается общим резистором (могут стоять два для более эффективного теплоотвода): Таким образом достаточно просто подать 12V от источника напряжения на ленту и она будет светиться. За простоту и удобство приходится платить эффективностью. Простая математика: три белых светодиода, каждому нужно по

3.2V, суммарно это 9.6V. Подключаем ленту к 12V и понимаем, что 2.5V у нас просто уходят в тепло на резисторах. И это в лучшем случае, если резистор подобран так, чтобы светодиод горел на полную яркость.

Подключаем к Arduino

Здесь всё очень просто: смотрите предыдущий урок по управлению нагрузкой постоянного тока. Управлять можно через реле, транзистор или твердотельное реле. Нас больше всего интересует плавное управление яркостью, поэтому продублирую схему с полевым транзистором: blank Конечно же, можно воспользоваться китайским мосфет-модулем! Пин VCC кстати можно не подключать, он никуда не подведён на плате. blank

Управление

Подключенная через транзистор лента управляется точно так же, как светодиод в предыдущей главе, то есть все примеры кода с миганием, плавным миганием и управление потенциометром подходят к этой схеме. Про RGB и адресные светодиодные ленты мы поговорим в отдельных уроках.

Питание и мощность

Светодиодная лента потребляет немаленький ток, поэтому нужно убедиться в том, что выбранный блок питания, модуль или аккумулятор справится с задачей. Но сначала обязательно прочитайте урок по закону Ома! Потребляемая мощность светодиодной ленты зависит от нескольких факторов:

  • Яркость. Максимальная мощность будет потребляться на максимальной яркости.
  • Напряжение питания (чаще всего 12V). Также бывают 5, 24 и 220V ленты.
  • Качество, тип и цвет светодиодов: одинаковые на вид светодиоды могут потреблять разный ток и светить с разной яркостью.
  • Длина ленты. Чем длиннее лента, тем больший ток она будет потреблять.
  • Плотность ленты, измеряется в количестве светодиодов на метр. Бывает от 30 до 120 штук, чем плотнее – тем больший ток будет потреблять при той же длине и ярче светить.

Лента всегда имеет характеристику мощности на погонный метр (Ватт/м), указывается именно максимальная мощность ленты при питании от номинального напряжения. Китайские ленты в основном имеют чуть меньшую фактическую мощность (в районе 80%, бывает лучше, бывает хуже). Блок питания нужно подбирать так, чтобы его мощность была больше мощности ленты, т.е. с запасом как минимум на 20%.

    Пример 1: нужно подключить 4 метра ленты с мощностью 14 Ватт на метр, лента может работать на максимальной яркости. 14*4 == 56W, с запасом 20% это будет 56*1.2

Подключение светодиода к Arduino

Светодиод это полупроводниковый прибор, создающий оптическое излучение при пропускании через него электрического тока. С электрической точки зрения светодиод ведет себя как обычный диод, пропуская ток в прямом направлении и не пропуская в обратном. Светодиод излучает только при прохождении тока в прямом направлении, по этому при его подключении необходимо соблюдать полярность. При этом сила излучения напрямую зависит от силы тока. Однако нельзя превышать максимально допустимый ток, установленный для светодиода его характеристиками, иначе светодиод выйдет из строя.

Так же светодиод характеризуется падением напряжения при прохождении тока в прямом направлении. Падение напряжения существенно выше чем у обычных диодов и составляет 2-3 вольта, в зависимости от цвета свечения светодиода. Точное значение указывается в характеристиках. Это означает, что светодиод не будет светиться если поданное на него напряжение меньше этого значения. Но если на светодиод подать напряжение больше этого порога, то через него потечет максимально возможный ток, и светодиод выйдет из строя. Что бы этого не произошло светодиод необходимо подключать через токоограничивающий резистор.

Расчет сопротивления токоограничивающего резистора производится по следующей формуле:

Rсв = (Vупр — Vсв) / Iсв ;

где:
Vупр — напряжение управления, это напряжение вывода микроконтроллера, равное 5 В;
Vсв — падение напряжения на светодиоде, указанное в характеристиках;
Iсв — сила тока светодиода, указанная в характеристиках, обычно в пределах 10-20 мА.

Для обычных светодиодов падение напряжения составляет 2 В и рекомендуемый ток свечения 15 мА. При подключении к выводу Arduino, запитанному от напряжения 5 В:

Rсв = (5-2) / 0.015 = 200 Ом

С учетом допуска можно использовать резисторы номиналом 220 Ом.

Сам светодиод имеет ножки разной длины, именно по ним определяется полярность при его подключении. Длинная ножка это Анод и подключается к плюсу. Короткая ножка — Катод и подключается к минусу. Токоограничивающий резистор можно подключить к любой ножке светодиода включив его последовательно.

Схема подключения светодиода к Arduino изображена на рисунке. Светодиод подключен к выводу 8 контроллера Arduino. Этот факт необходимо учесть в программе.

Схема подключения светодиода к Arduino

Приведенный ниже скетч включает и выключает светодиод один раз в секунду. Для отсчета времени используется функция delay(), которая делает паузу в выполнении программы на заданное количество миллисекунд.

// функция инициализации запускается при старте программы
void setup() <
pinMode(8, OUTPUT); // инициализация вывода 8 как «Выход»
>

// функция цикла запускается снова и снова после окончания ее выполнения
void loop() <
digitalWrite(8, HIGH); // включение светодиода на выводе 8
delay(500); // пауза выполнения программы на пол секунды
digitalWrite(8, LOW); // выключение светодиода на выводе 8
delay(500); // пауза выполнения программы на пол секунды
>

Arduino Tutorial Series: LED Blinking

interface-lab

We will go through the steps of connecting Arduino Nano 33 IoT to two resistors and two LEDs, blinking them from code we upload from our computer. There are more resources and guides about how to set the Arduino IDE, Arduino Web Editor, and details about the hardware used at:

The first step will need us to download and install the Arduino IDE. You can get it at https://www.arduino.cc/en/main/software.

You will also need the board definition for the Arduino Nano 33 IoT. For that step, you should use the menu within the Arduino IDE inside Tools / Boards / Board Manager. You will have to search for Nano 33 and install the latest version.

Once you have downloaded that, you will have a new option in the Tools / Boards that will say Arduino Nano 33 IoT. After you choose that, we will be able to program our board.

We will use the code example provided in the option File / Examples / Basics / Blink. You will see a code that pops up and you will have access to a chunk of code that is pretty standard, a little like the “Hello World” that computer scientists program to see if things are working well.

At this point, you should check that your board is connected and that your computer recognizes it. In order to do that, you should check Tools / Port and choose the option that points to your board. This part of the process depends on each computer, but in general, you will see something like /dev/cu.usbmodemXXXXX if you have a Mac computer or a COMXXXX if you have a Windows computer. The options refresh every time you click on the menu, so if you are a bit lost, you might want to click somewhere else, unplug your Arduino, check the options listed in Tools / Port, plug your Arduino back and see if anything new is listed there.

If everything went well, you should be able to upload the Blink code by pressing the icon with an arrow shape or by choosing Sketch / Upload. If the code was uploaded successfully, the onboard LED, next to the USB micro connector, should be blinking once a second. If something went wrong, you will know for sure because you will see a screen like this one:

Our Discord channel should be the right place to seek for help! But if it did upload successfully, you could try changing the “delay(1000);” instructions. Another interesting exercise is to connect an external LED. In order to do that you might like to know that the name “ LED_BUILTIN” for our case is exactly the same as writing the number 13. You can try it out replacing the three “ LED_BUILTIN” and re-uploading the code. Knowing that pin 13 is where the LED is connected, it would be quite straight-forward to add an external LED. Remember you will need a resistor in series and suitable values could be between 100 and 1000 ohms.

If that worked well, you might want to try connecting a second LED to pin 12. Remember to unplug your circuit at every step you are connecting new components to avoid a short circuit and protect your Arduino and computer.

Once you get a blinking LED on pin 12 as well, you can also code both of the LEDs on pin 12 and 13 to blink one after the other. Below you can see the code we used in the video and the circuit diagram.

Читать:
Диско шар отзывы какой лучше

Похожие публикации