Skip to content
Home » Led On Off Arduino | Turn An Led On And Off With The Arduino

Led On Off Arduino | Turn An Led On And Off With The Arduino

Arduino Blinking LED Tutorial

Electrical Signals

The Arduino communicates with modules and sensors by switching on and off electrical current. It’s very similar to the one’s and zero’s in binary code. When current is switched on, it’s known as a “HIGH signal”. That’s comparable to the “one” in binary code. When the current is switched off, that’s a “LOW signal”, which is similar to the zero in binary code. The length of time the current stays on or off can be changed from a microsecond up to many minutes.

Watch the video for this tutorial:

Controlling an External LED

An external LED or any other powered module can be controlled in a similar way.

LEDs need to have a resistor placed in series (in-line) with it. Otherwise, the unrestricted current will quickly burn out the LED. The resistor can be any value between 100 Ohms and about 10K Ohms. Lower value resistors will allow more current to flow, which makes the LED brighter. Higher value resistors will restrict the current flow, which makes the LED dimmer.

Also, most LED’s have polarity, which means that they need to be connected the right way around. Usually, the LED’s shortest lead connects to the ground side.

If you connect the LED to pin 13 as shown in the image below, you can use the same code we used above to make the LED flash on and off.

Arduino Blinking LED Tutorial
Arduino Blinking LED Tutorial

Sơ đồ Lắp Đặt :

Mã code

// the setup function runs once when you press reset or power the board

// the loop function runs over and over again forever

Tải file IDE : Điều Khiển Led Đơn

Bạn đang xem: Lập Trình Arduino Uno R3 Điều Khiển Led Đơn

Tổng kết

Qua bài học đầu tiên các bạn sẽ nắm được những kiến thức về kiểu dữ liệu số nguyên (int), cách sử dụng biến như thế nào, sử dụng hàm và cách làm việc của vòng lặp.

Nếu các bạn bạn thấy bài viết bổ ích nhớ Like và Share để mọi người cùng học nha.

  • Để nhận thêm nhiều kiến thức bổ ích Đăng ký để nhận thông báo khi có bài viết mới nhất.
  • Tham gia Cộng đồng Arduino KIT trên Fanpage.

Chúc các bạn thành công!

Trân trọng.

    • Tổng tiền thanh toán:
Arduino tutorial 2- LED Blink program with code explained | How to blink an LED using Arduino |
Arduino tutorial 2- LED Blink program with code explained | How to blink an LED using Arduino |

Toggle LED’s state with the push button – first iteration

What we want to do is to toggle the LED’s state when you press + release the button. So, the first time you release the button, the LED will turn on. The second time, it will turn off. Etc.

The code

#define LED_PIN 8 #define BUTTON_PIN 7 byte lastButtonState = LOW; byte ledState = LOW; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { byte buttonState = digitalRead(BUTTON_PIN); if (buttonState != lastButtonState) { lastButtonState = buttonState; if (buttonState == LOW) { ledState = (ledState == HIGH) ? LOW: HIGH; digitalWrite(LED_PIN, ledState); } } }

Let’s analyze the code.

Setup

#define LED_PIN 8 #define BUTTON_PIN 7

Those defines are the same as before.

byte lastButtonState = LOW; byte ledState = LOW;

We need to create 2 global variables, to keep the state of the button and the LED. In the loop we’ll use those variables to compare the previous state to the new state.

void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); }

The void setup stays the same. We just set the mode for both pins.

And now the serious stuff is coming. We enter the void loop function.

Monitor the button’s state

void loop() { byte buttonState = digitalRead(BUTTON_PIN);

The first thing we do is to read the button’s state and to store it inside a new local variable.

if (buttonState != lastButtonState) {

Then we can compare the current state to the last one (from the previous execution of the loop function). 4 possibilities here:

  1. LOW -> LOW (last -> current).
  2. LOW -> HIGH.
  3. HIGH -> LOW.
  4. HIGH -> HIGH.

With the condition, we only enter the next block of code if the current and last state are different. If the 2 states are the same, then we don’t enter the if and the loop function is finished for this turn.

lastButtonState = buttonState;

Also, now that we have the information we want, we directly store the current state into the last state variable, so that we have the correct value for the next time we enter the loop.

if (buttonState == LOW) {

At this point we have only 2 possibilities left:

  • Either the previous state was LOW and the current state is HIGH (not pressed to pressed).
  • Or the previous state was HIGH and the current state is LOW (pressed to not pressed).

We are only interested in the second option, so here we just have to check if the current button’s state is LOW. If that’s the case, we can now turn the LED on or off.

Toggle the LED when the button has been released

ledState = (ledState == HIGH) ? LOW : HIGH;

Here we toggle the state of the LED. I’m not a big fan of one-liners but this one is really handful when you just need to toggle a state. This will save you 3-4 lines of code for something really trivial.

Here’s the template for this one-liner: (condition to evaluate) ? if true use this value : if false use this value.

So, if the LED is currently powered on (ledState == HIGH), we assign the value LOW. If the LED is powered off (ledState != HIGH), we assign the value HIGH.

digitalWrite(LED_PIN, ledState); } } }

And the last thing we need to do is of course to physically set the state for the LED, with the new computed state.

Turn on the LED when button is pressed, turn it off otherwise

What we want to achieve is simple: when the button is not pressed, the LED is off. And when we press the button the LED should be on.

The code

#define LED_PIN 8 #define BUTTON_PIN 7 void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_PIN, HIGH); } else { digitalWrite(LED_PIN, LOW); } }

Let’s break this code down line by line.

Setup

#define LED_PIN 8 #define BUTTON_PIN 7

First, as a best practice, we use some defines to keep the pin number for the LED and push button. That way, if you have used different pins than I, you just need to modify those 2 lines. Also, in the future if you want to change the LED from pin 8 to pin 11 for example, you can modify this line without touching anything else in the code.

void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); }

The setup function is executed once at the beginning of the program. This is the perfect time to initialize our pins with the pinMode() function:

  • OUTPUT for the LED, as we’re going to write data to it.
  • INPUT for the push button, as we’re going to read data from it.

Now, the digital pins are correctly set up.

Loop – Turn on the LED when button is pressed

void loop() { if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_PIN, HIGH); } else { digitalWrite(LED_PIN, LOW); } }

In the loop function, we start by reading the button’s state with the digitalRead() function. As we have a pull down resistor on the button, we know that the non-pressed state will give us the value LOW.

(Note: if you were using a pull up resistor, or no resistor at all – with the INPUT_PULLUP option for pinMode – this would be the opposite. HIGH when the button is not pressed, and LOW when it’s pressed.)

So, once we get the button’s state, we check if it’s HIGH or LOW:

  • HIGH (pressed): we power on the LED with digitalWrite() and the HIGH state.
  • LOW (not pressed): we power off the LED with digitalWrite() and the LOW state.

OK, now let’s do something a little bit more complex.

Arduino Tutorial: LED Sequential Control- Beginner Project
Arduino Tutorial: LED Sequential Control- Beginner Project

Controlling Multiple LEDs Together

You can control as many LEDs as you want as long as you have enough pins available. Let’s make the external LED flash along side the on-board LED to demonstrate. All we need to do is duplicate the code for pin 8, and change the pin numbers to pin 13.

Here’s an example of that:


void setup() { pinMode(8, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(8, HIGH); delay(1000); digitalWrite(13, HIGH); delay(1000); digitalWrite(8, LOW); delay(1000); digitalWrite(13, LOW); delay(1000); }

You should be able to see both LEDs blinking. But they won’t be blinking in sync, they’ll be alternating.

The Arduino executes the instructions in the code from top to bottom. It reads each line and performs the task before moving onto the next line. Once it has read through to the end, it loops back to line 6 and starts over again.

In the program above, the code is executed in this order:

  1. HIGH signal sent to pin 8
  2. Wait for 1000 ms
  3. HIGH signal sent to pin 13
  4. Wait for 1000 ms
  5. LOW signal sent to pin 8
  6. Wait for 1000 ms
  7. LOW signal sent to pin 13
  8. Wait for 1000 ms
  9. Return to step 1

To get both LEDs blinking at the same time, we need to remove the delay between the HIGH and LOW signals of each pin, as shown in this program:


void setup() { pinMode(8, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(8, HIGH); digitalWrite(13, HIGH); delay(1000); digitalWrite(8, LOW); digitalWrite(13, LOW); delay(1000); }

Now both LEDs should turn on and off at the same time. The tasks are executed in this order:

  1. HIGH signal sent to pin 8
  2. HIGH signal sent to pin 13
  3. Wait for 1000 ms
  4. LOW signal sent to pin 8
  5. LOW signal sent to pin 13
  6. Wait for 1000 ms
  7. Return to step 1

Now that you’ve seen how to control LEDs with the Arduino, check out part 2 of this series, where I’ll show you how to use a light dependent resistor to control how fast the LED flashes and how to control the pitch of sound output by a speaker.

If you have any questions or have trouble getting this project to work, just leave a comment below and I’ll try help you get it going. And be sure to subscribe! We send out an email each time we publish a new tutorial…

1
6
7 #include

8
9 int RECV_PIN = 12;
10 int led1 = 8;
11 int led2 = 9;
12 int led3 = 10;
13 int led4 = 11;
14 int itsONled[] = {0,0,0,0,0};
15
19 #define code1 33772
20 #define code2 52972
21 #define code3 3494
22 #define code4 65160
23 IRrecv irrecv(RECV_PIN);
24
25 decode_results results;
26
27 void setup()
28 {
29 Serial.begin(9600);
30 irrecv.enableIRIn();
31 pinMode(led1, OUTPUT);
32 pinMode(led2, OUTPUT);
33 pinMode(led3, OUTPUT);
34 pinMode(led4, OUTPUT);
35 }
36
37 void loop() {
38 if (irrecv.decode(&results)) {
39 unsigned int value = results.value;
40 switch(value) {
41 case code1:
42 if(itsONled[1] == 1) {
43 digitalWrite(led1, LOW);
44 itsONled[1] = 0;
45 } else {
46 digitalWrite(led1, HIGH);
47 itsONled[1] = 1;
48 }
49 break;
50 case code2:
51 if(itsONled[2] == 1) {
52 digitalWrite(led2, LOW);
53 itsONled[2] = 0;
54 } else {
55 digitalWrite(led2, HIGH);
56 itsONled[2] = 1;
57 }
58 break;
59 case code3:
60 if(itsONled[3] == 1) {
61 digitalWrite(led3, LOW);
62 itsONled[3] = 0;
63 } else {
64 digitalWrite(led3, HIGH);
65 itsONled[3] = 1;
66 }
67 break;
68 case code4:
69 if(itsONled[4] == 1) {
70 digitalWrite(led4, LOW);
71 itsONled[4] = 0;
72 } else {
73 digitalWrite(led4, HIGH);
74 itsONled[4] = 1;
75 }
76 break;
77 }
78 Serial.println(value);
79 irrecv.resume();
80 }
81 }

Use a Push Button with Arduino

Turn an LED on and off with the Arduino

Written By: Marcus Schappi

Difficulty

Easy

Steps

Push button switches are inexpensive and versatile components that have many uses.

In this guide, we will learn how to use a push button switch together with an Arduino, to turn an LED on and off. The circuit we will be building, uses a Little Bird Uno R3, a fully compatible Arduino development board. A mini pushbutton switch, a 5mm LED, jumper wires, and a mini breadboard is also required.

Other uses for push buttons are in custom gamepads, DIY radio buttons, MIDI controllers with push buttons that in conjunction with LEDs would light up when pressed, and many more!

Insert an LED into the breadboard with the Anode (positive leg) on the left and the Cathode (negative leg on the right).

Insert a 220 Ohm Resistor so that one leg is inline with the LED’s Cathode leg.

Resistors are not polarised, so orientation doesn’t matter.

This resistor will be used to limit the current going to our LED.

const int ledPin = 13;// We will use the internal LED const int buttonPin = 7;// the pin our push button is on void setup() { pinMode(ledPin,OUTPUT); // Set the LED Pin as an output pinMode(buttonPin,INPUT_PULLUP); // Set the Tilt Switch as an input } void loop() { int digitalVal = digitalRead(buttonPin); // Take a reading if(HIGH == digitalVal) { digitalWrite(ledPin,LOW); //Turn the LED off } else { digitalWrite(ledPin,HIGH);//Turn the LED on } }

Upload this code to your Arduino.

When you run this code, the LED on Pin 13 will turn on when the button is held down. That is all.

const unsigned int buttonPin = 7; const unsigned int ledPin = 13; int buttonState = 0; int oldButtonState = LOW; int ledState = LOW; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); } void loop() { buttonState = digitalRead(buttonPin); if (buttonState != oldButtonState && buttonState == HIGH) { ledState = (ledState == LOW ? HIGH : LOW); digitalWrite(ledPin, ledState); delay(50); } oldButtonState = buttonState; }

Upload this code to your Arduino.

This program will toggle on and off the LED every time you push the button.

Bài 1: Chớp tắt LED trên Arduino Uno

Trong bài viết hôm nay mình xin giới thiệu với các bạn cách chớp tắt Led trên Arduino Uno.

Và cách tạo một biến ra sao, cách thức làm việc của các hàm trên Arduino IDE.

Nếu bạn là một người mới chưa biết Arduino là cái quái gì? Và cần học Arduino để làm gì?

Thì xem 2 bài viết bên dưới nhé.

  • Xem bài viết: Arduino IDE là gì?
  • Xem bài viết: Arduino Uno là gì?
Arduino for Beginners: Using Push button to turn ON LED light
Arduino for Beginners: Using Push button to turn ON LED light

Controlling the Arduino’s LED

To turn on an LED, the Arduino needs to send a HIGH signal to one of it’s pins. To turn off the LED, it needs to send a LOW signal to the pin. You can make the LED flash by changing the length of the HIGH and LOW states.

The Arduino has an on-board surface mount LED that’s hard wired to digital pin 13. It’s the one with an “L” next to it:

To get this LED flashing, upload the “Blink” program to your Arduino:


void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }

The LED should now be blinking on and off at a rate of 1000 milliseconds (1000 milliseconds = 1 second).

The

delay()

function on line 6 tells the Arduino to hold the HIGH signal at pin 13 for 1000 ms. The

delay()

function on line 8 tells it to hold the LOW signal at pin 13 for 1000 ms. You can change the blinking speed by changing the number inside the parentheses of the

delay()

functions.

Code ví dụ chớp tắt Led

/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 10 has an LED connected on most Arduino boards. // give it a name: int ledPin = 10; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(ledPin, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(ledPin,LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }

Arduino - Turn LED On and Off With Push Button
Arduino – Turn LED On and Off With Push Button

Sơ đồ đấu nối

Các linh kiện cần thiết cho bài học

Tên linh kiện Số lượng Shopee
Arduino Uno R3 Mua ngay
Cáp nạp Mua ngay
Dây cắm (Đực – Đực) Mua ngay
Điện trở 220R Mua ngay
Led 5mm Mua ngay
Breadboard Mua ngay

Conclusion – Arduino turn Led ON and OFF with button

In this tutorial you have seen how to build an Arduino circuit with an LED and a push button, and also how to control this circuit to turn the LED on and off with the button.

Even if it’s a rather simple application, there are many ways to program it. You can power on the LED only when the button is pressed, or make the LED blink when you release the button, and so on.

Another way to write the code (for the exact same functionalities) is to use Arduino interrupts – available for the boards having interrupt pins.

To go further from here, check out:

Blink

Turn an LED on and off every second.

This example shows the simplest thing you can do with an Arduino to see physical output: it blinks the on-board LED.

Hardware Required

  • Arduino Board

optional

  • LED

  • 220 ohm resistor

Circuit

This example uses the built-in LED that most Arduino boards have. This LED is connected to a digital pin and its number may vary from board type to board type. To make your life easier, we have a constant that is specified in every board descriptor file. This constant is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence between the constant and the digital pin.

  • D13 – 101

  • D13 – Due

  • D1 – Gemma

  • D13 – Intel Edison

  • D13 – Intel Galileo Gen2

  • D13 – Leonardo and Micro

  • D13 – LilyPad

  • D13 – LilyPad USB

  • D13 – MEGA2560

  • D13 – Mini

  • D6 – MKR1000

  • D13 – Nano

  • D13 – Pro

  • D13 – Pro Mini

  • D13 – UNO

  • D13 – Yún

  • D13 – Zero

If you want to light an external LED with this sketch, you need to build this circuit, where you connect one end of the resistor to the digital pin correspondent to the LED_BUILTIN constant. Connect the long leg of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the short leg of the LED (the negative leg, called the cathode) to the GND. In the diagram below we show an UNO board that has D13 as the LED_BUILTIN value.

The value of the resistor in series with the LED may be of a different value than 220 ohms; the LED will light up also with values up to 1K ohm.

Schematic

Code

After you build the circuit plug your Arduino board into your computer, start the Arduino Software (IDE) and enter the code below. You may also load it from the menu File/Examples/01.Basics/Blink . The first thing you do is to initialize LED_BUILTIN pin as an output pin with the line


pinMode(LED_BUILTIN, OUTPUT);

In the main loop, you turn the LED on with the line:


digitalWrite(LED_BUILTIN, HIGH);

This supplies 5 volts to the LED anode. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line:


digitalWrite(LED_BUILTIN, LOW);

That takes the LED_BUILTIN pin back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the

commands tell the board to do nothing for 1000 milliseconds, or one second. When you use the

delay()

command, nothing else happens for that amount of time. Once you’ve understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things.

delay()

Once you’ve understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the board.

See Also

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/07/28 by SM

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

In this tutorial, I’ll show you how to use an Arduino to control LEDs. This is a pretty simple project, but you should learn how to do it early on because lots of other sensors and modules are programmed the exact same way.

First I’ll show you how to turn on and off the Arduino’s on-board LED. Then I’ll show you how to turn on and off an LED connected to one of the Arduino’s digital pins. I’ll explain how to change the LEDs flashing rate, and how to change the pin that powers the LED. At the end I’ll show you how to control multiple LEDs. Before starting, you should have the Arduino IDE software installed on your computer.

How LEDs Work - Unravel the Mysteries of How LEDs Work!
How LEDs Work – Unravel the Mysteries of How LEDs Work!

Turn LED on and off with button – using debounce

One thing you might notice with the previous experiment: sometimes when you press and release the button, the LED’s state doesn’t change, or blinks quickly multiple times.

This is because the button is physically bouncing when you press it. Thus, many false positives will be interpreted by the Arduino. What you can do to prevent that is to add a debounce delay in your code. For example, you can decide that when the program detects a change in the button’s state, it will wait 50 milliseconds before considering another change viable.

Let’s add a few lines to our previous code.

The improved code

#define LED_PIN 8 #define BUTTON_PIN 7 byte lastButtonState = LOW; byte ledState = LOW; unsigned long debounceDuration = 50; // millis unsigned long lastTimeButtonStateChanged = 0; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { if (millis() – lastTimeButtonStateChanged > debounceDuration) { byte buttonState = digitalRead(BUTTON_PIN); if (buttonState != lastButtonState) { lastTimeButtonStateChanged = millis(); lastButtonState = buttonState; if (buttonState == LOW) { ledState = (ledState == HIGH) ? LOW: HIGH; digitalWrite(LED_PIN, ledState); } } } }

Now, if you run this program, you won’t have any problem with the LED’s state being changed quite randomly when you press/release the button.

And here is how we achieve that.

Debounce explained

unsigned long debounceDuration = 50; // millis unsigned long lastTimeButtonStateChanged = 0;

We create 2 new global variables:

  • One to decide how long we want to wait before validating a second change in the button’s state. Here it means that if the state changes, any changes after that in the next 50 milliseconds will be ignored. 50 millis is a good value, you can experiment with lower and upper values to check the behavior.
  • Another one to keep the last time the state was changed, so we have a starting point to compare to.

void loop() { if (millis() – lastTimeButtonStateChanged > debounceDuration) {

Then, in the loop, we only start the button/LED functionality if enough time has passed since the last time the button’s state was changed.

To do that it’s quite simple: we compare the duration since the last update time to the required debounce duration.

if (buttonState != lastButtonState) { lastTimeButtonStateChanged = millis();

Once the debounce delay has been passed, then we can do what we did before. And don’t forget to update the starting point for the “debounce timer” just after you detect a change in the button’s state. So, the next time the program enters the loop, it will wait for 50 milliseconds (or the value you’ve chosen) to detect new changes in the button’s state.

Arduino circuit with an LED and a button

To build the circuit you will need those components:

  • Arduino board (any board, if you don’t have Uno you can easily adapt by finding corresponding pins).
  • Breadboard.
  • LED – any color.
  • Push button.
  • 220 Ohm resistor for the LED. If you don’t have this specific value, any resistor from 330 to 1k Ohm will do.
  • 10k Ohm resistor for the push button. If you don’t have, you can go until 20k-50k Ohm.
  • A bunch of male to male wires (including if possible black, red, and other colors).

Here’s the circuit you have to make.

Step by step instructions to build the circuit (more info about Arduino pins here):

  • First, make sure to power off your Arduino – remove any USB cable.
  • Plug a black wire between the blue line of the breadboard and a ground (GND) pin on the Arduino board.
  • Plug the LED. You can notice that the LED has a leg shorter than the other. Plug this shorter leg to the ground (blue line here) of the circuit.
  • Connect the longer leg of the LED to a digital pin (here pin no 8, you can change it). Add a 220 Ohm resistor in between to limit the current going through the LED.
  • Add the push button to the breadboard, like in the picture.
  • Connect one leg of the button to the ground, and put a 10k Ohm resistor in between. This resistor will act as a “pull down” resistor, which means that the default button’s state will be LOW.
  • Add a red wire between another leg of the button and VCC (5V).
  • Finally, connect a leg of the button (same side as the pull down resistor) to a digital pin (here 7).

All right your circuit is now finished. You can start writing code.

Dancing lights || LED chaser circuit with 32 cool effects || Arduino Project
Dancing lights || LED chaser circuit with 32 cool effects || Arduino Project

In this Arduino tutorial I will show you how to turn an LED on and off with a push button. In fact, we’ll do 2 slightly different applications.

First, we will power on the LED when the button is pressed, and power off the LED when the button is not pressed.

And then we’ll modify the program to toggle the LED’s state only when we release the button.

For more info on each component, also check out this Arduino LED tutorial and this Arduino push button tutorial.

Let’s get started!

>> Watch this video as an additional resource:

You are learning how to use Arduino to build your own projects?

Check out Arduino For Beginners and learn step by step.

After watching the video, subscribe to the Robotics Back-End Youtube channel so you don’t miss the next tutorials!

Table of Contents

Giải thích Code

Comment

Trong Arduino bạn sẽ bắt gặp 2 dạng comment: Comment đơn dòng và đa dòng

  • Comment theo kiểu đa dòng

Mở đầu bằng /* và kết thúc */ ở dạng comment này không giới hạn ký tự và số dòng.

/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */

  • Comment theo kiểu đơn dòng

Mở đầu bằng // và kéo dài cho tới cuối dòng

digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level)

Kiểu số nguyên int

int ledPin = 10;

Kiểu dữ liệu Độ rộng bit Dãy giá trị
int (số nguyên) 2 byte (16bit) -32,768 đến 32,767
  • ledPin = 10: Là tên biến (ở đây bạn có thể đặt tên gì mà bạn mong muốn, tốt nhất là các bạn đặt theo tên của chức năng để dễ dàng nhớ khi code. Ở đây mình kết nối LED vào chân số 10 trên Arduino UNO).
  • Kết thúc khai báo bằng dấu (;): Trong trường hợp bạn không có (;) thì trình biên dịch sẽ báo lỗi.

Hàm setup()

void setup() {}

Hàm setup() được Arduino đọc khi bắt đầu khởi động. Nó dùng để khởi tạo biến, khởi tạo thư viện và thiết lập thông số.


Hàm setup()

chỉ chạy một lần khi bật nguồn hoặc reset lại chương trình.

Changing the Pin

If you want to use a different pin to power the LED, it’s easy to change it. For example, say you want to use pin 8 instead of pin 13. First move the signal wire from pin 13 over to pin 8:

Now you’ll need to edit a line of code in the program so the Arduino knows which pins to use as output pins. That’s done on line 2 of the code above, where it says:


pinMode(13, OUTPUT);

To use pin 8, you just have to change the 13 to an 8:


pinMode(8, OUTPUT);

Next you’ll need to change the code that tells the Arduino which pins will get the HIGH and LOW output signals. That’s done everywhere there’s a

digitalWrite()

function. In the program above, there’s one on line 5 and one on line 7:


digitalWrite(13, HIGH);


digitalWrite(13, LOW);

To specify that pin 8 should get the HIGH and LOW signals, you just need to change the 13’s to 8’s:


digitalWrite(8, HIGH);


digitalWrite(8, LOW);

The finished program should look like this:


void setup() { pinMode(8, OUTPUT); } void loop() { digitalWrite(8, HIGH); delay(1000); digitalWrite(8, LOW); delay(1000); }

After uploading, the LED should flash just like it did when it was connected to pin 13.

How to make a 16x16x16 LED CUBE at home with Arduino platform
How to make a 16x16x16 LED CUBE at home with Arduino platform

pinMode

pinMode(ledPin, OUTPUT);


  • "pinMode"

    : Cấu hình quy định hoạt động của một chân như là một đầu vào (INPUT) hoặc đầu ra (OUTPUT).
  • “Pin”: Là chân mà bạn muốn đặt.
  • “Mode”: INPUT, OUTPUT hoặc INPUT_PULLUP.

Vòng lặp

void loop() {}

Sau khi hàm

setup ()

chạy xong, những lệnh trong vòng

loop ()

sẽ thực hiện và chúng sẽ lặp đi lặp lại cho đến khi Arduino bị ngắt nguồn hoặc reset lại chương trình.

digitalWrite(ledPin,HIGH); // turn the LED on (HIGH is the voltage level)


digitalWrite

ghi giá trị mức “CAO” (bật) hoặc mức “THẤP” (tắt) vào chân được cấu hình. Nếu chân được cấu hình là OUTPUT bởi pinMode, thì điện áp của nó sẽ tương ứng với giá trị được đặt: 5V (hoặc 3.3V trên bo là 3.3V) là mức “CAO”, 0V là mức “THẤP”.

Delay()

delay(1000); // wait for a second


  • delay()

    : Tạm dừng chương trình trong khoảng thời gian chỉ định (được tính bằng mili giây) và ở đây (1000 mili giây sẽ bằng 1 giây).

Keywords searched by users: led on off arduino

Blink | Arduino Documentation
Blink | Arduino Documentation
Arduino 2 Push Button One Led : Switch On/Off
Arduino 2 Push Button One Led : Switch On/Off
Turn On An Led With A Push Button (Arduino Tutorial)
Turn On An Led With A Push Button (Arduino Tutorial)
Arduino Ir Remote To Control Leds On And Off
Arduino Ir Remote To Control Leds On And Off
Use Keypad To Turn Led'S On And Off - Leds And Multiplexing - Arduino Forum
Use Keypad To Turn Led’S On And Off – Leds And Multiplexing – Arduino Forum
Arduino - Turn Led On And Off With Push Button - Youtube
Arduino – Turn Led On And Off With Push Button – Youtube
Turn Led On And Off With Button Arduino Code - Arduino Circuit
Turn Led On And Off With Button Arduino Code – Arduino Circuit
How To Use Keypad 4X4 Control Led On/Off With Arduino - Youtube
How To Use Keypad 4X4 Control Led On/Off With Arduino – Youtube
Using Led Touch Switch To Turn On/Off Arduino Pro Mini (3V3) - General  Electronics - Arduino Forum
Using Led Touch Switch To Turn On/Off Arduino Pro Mini (3V3) – General Electronics – Arduino Forum
Turning On And Off Led According To The Toggle Switch State - Leds And  Multiplexing - Arduino Forum
Turning On And Off Led According To The Toggle Switch State – Leds And Multiplexing – Arduino Forum

See more here: kientrucannam.vn

Leave a Reply

Your email address will not be published. Required fields are marked *