1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

BÀI TẬP ARDUNIO CƠ BẢN ĐẾN NÂNG CAO

97 685 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 97
Dung lượng 2,94 MB

Nội dung

Như các bạn đã biết, hệ thống bài tập của Cộng đồng Arduino Việt Nam đã được ra đời từ đầu năm Bính Thân đến bây giờ, trải qua quá trình thử nghiệm với kết quả là sự hoạt động hoàn hảo của hệ thống. Hôm nay, đại diện cho BQT Arduino, tôi sẽ hướng dẫn các bạn tham gia làm bài tập tại đây. Với các bài tập được chọn lọc kỹ từ ban Kiểm tra viên, các bạn hoàn toàn có thể tin tưởng vào chất lượng và các đề bài mà BQT đưa ra nhé.

Trang 1

1 ATmega168/328-Arduino Pin Mapping 2

2 Blink Led – Turn a LED on and off – Digital out 3

3 Blink Without Delay - Blink an LED without using the delay() function – Digital out 4

4 Button – Input Pullup Serial - Demonstrates the use of INPUT_PULLUP with pinMode() 6

5 Button - Digital Read Serial - Read a switch, print the state out to the Arduino Serial Monitor 9

6 Button – Digital input - Use a pushbutton to control an LED 11

7 Button – Debounce - Read a pushbutton, filtering noise 13

8 Button – State Change Detection (Edge Detection) for pushbuttons – Digital input & output 15

9 Analog Input Pins 17

10 Analog Input – Variable Resistor or Photoresistor 18

11 Analog Read Serial, Read Analog Voltage - Read a potentiometer, print its state out to the Arduino Serial Monitor 21

12 Analog In, Out Serial - Read an analog input pin, map the result, and then use that data to dim or brighten an LED 23

13 Calibration - Define a maximum and minimum for expected analog sensor values 26

14 Fading - Use an analog output (PWM pin) to fade an LED 30

15 Connect and use an RGB LED with an Arduino 33

16 RGB LED – analog output 36

17 Arduino 8 bit Binary LED Counter 43

18 8 More LEDs 46

19 Serial to Parallel Shifting-Out with a 74HC595 50

20 Smoothing - Smooth multiple readings of an analog input 69

21 7 Segment Display On Arduino 74

Trang 2

1 ATmega168/328-Arduino Pin Mapping

Note that this chart is for the DIP-package chip The Arduino Mini is based upon a smaller physical IC package that includes two extra ADC pins, which are not available in the DIP-package Arduino implementations

Trang 3

2 Blink Led – Turn a LED on and off – Digital out

Most Arduino boards already have an LED attached to pin 13 on the board itself If you run this example with no hardware attached, you should see that LED blink

Figure 1: Led circuit

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

delay(500); // wait for a second

digitalWrite(pin, LOW); // turn the LED off by making the voltage LOW

delay(5000); // wait for a second

}

Trang 4

3 Blink Without Delay - Blink an LED without using the delay() function – Digital out

Sometimes you need to do two things at once For example you might want to blink an LED while reading a button press In this case, you can't use delay(), because Arduino pauses your program during the delay()

If the button is pressed while Arduino is paused waiting for the delay() to pass, your program will miss the button press

This sketch demonstrates how to blink an LED without using delay() It turns the LED on and then makes note of the time Then, each time through loop(), it checks to see if the desired blink time has passed If it has, it toggles the LED on or off and makes note of the new time In this way the LED blinks continuously while the sketch execution never lags on a single instruction

An analogy would be warming up a pizza in your microwave, and also waiting some important email You put the pizza in the microwave and set it for 10 minutes The analogy to using delay() would be to sit in front of the microwave watching the timer count down from 10 minutes until the timer reaches zero If the important email arrives during this time you will miss it

What you would do in real life would be to turn on the pizza, and then check your email, and then maybe do something else (that doesn't take too long!) and every so often you will come back to the microwave to see if the timer has reached zero, indicating that your pizza is done

In this tutorial you will learn how to set up a similar timer

// constants won't change Used here to set a pin number :

const int ledPin = 13; // the number of the LED pin

// Variables will change :

int ledState = LOW; // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time

// The value will quickly become too large for an int to store

unsigned long previousMillis = 0; // will store last time LED was updated

// constants won't change :

const long interval = 1000; // interval at which to blink (milliseconds) void setup() {

// set the digital pin as output:

pinMode(ledPin, OUTPUT);

}

void loop()

{

// here is where you'd put code that needs to be running all the time

// check to see if it's time to blink the LED; that is, if the

Trang 5

// difference between the current time and last time you blinked // the LED is bigger than the interval at which you want to // blink the LED

unsigned long currentMillis = millis();

if(currentMillis - previousMillis >= interval) {

// save the last time you blinked the LED

Trang 6

4 Button – Input Pullup Serial - Demonstrates the use of INPUT_PULLUP with pinMode()

This example demonstrates the use of INPUT_PULLUP with pinMode() It monitors the state of a switch by establishing serial communication between your Arduino and your computer over USB

Additionally, when the input is HIGH, the onboard LED attached to pin 13 will turn on; when LOW, the LED will turn off

Figure 2: Button circuit

Connect two wires to the Arduino board The black wire connects ground to one leg of the pushbutton The second wire goes from digital pin 2 to the other leg of the pushbutton

Pushbuttons or switches connect two points in a circuit when you press them When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton Because the internal pull-up on pin 2 is active and connected to 5V, we read HIGH when the button is open When the button is closed, the Arduino reads LOW because a connection to ground is completed

Trang 7

Code

In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your Arduino and your computer with the line: Serial.begin(9600);

Next, initialize digital pin 2 as an input with the internal pull-up resistor enabled:

The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch Since the information coming in from the switch will be either a "1"

or a "0", you can use an int datatype Call this variable sensorValue, and set it to equal whatever is being read on digital pin 2 You can accomplish all this with just one line of code:

int sensorValue = digitalRead(2);

Once the Arduino has read the input, make it print this information back to the computer as a decimal (DEC) value You can do this with the command Serial.println() in our last line of code:

//read the pushbutton value into a variable

int sensorVal = digitalRead(2);

//print out the value of the pushbutton

Serial.println(sensorVal);

// Keep in mind the pullup means the pushbutton's

// logic is inverted It goes HIGH when it's open,

// and LOW when it's pressed Turn on pin 13 when the

Trang 8

// button's pressed, and off when it's not:

Trang 9

5 Button - Digital Read Serial - Read a switch, print the state out to the Arduino Serial Monitor

This example shows you how to monitor the state of a switch by establishing serial communication between your Arduino or Genuino and your computer over USB

Hardware Required

 Arduino or Genuino Board

 A momentary switch, button, or toggle switch

 10k ohm resistor

 hook-up wires

 breadboard

Circuit

Trang 10

Code

In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your board and your computer with the line: Serial.begin(9600);

Next, initialize digital pin 2, the pin that will read the output from your button, as an input:

pinMode(2,INPUT);

Now that your setup has been completed, move into the main loop of your code When your button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be connected to ground through the 10k ohm resistor This is a digital input, meaning that the switch can only be

in either an on state (seen by your Arduino as a "1", or HIGH) or an off state (seen by your Arduino as a "0",

or LOW), with nothing in between

The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch Since the information coming in from the switch will be either a "1"

or a "0", you can use an int datatype Call this variable sensorValue, and set it to equal whatever is being read on digital pin 2 You can accomplish all this with just one line of code:

int sensorValue = digitalRead(2);

Once the bord has read the input, make it print this information back to the computer as a decimal value You can do this with the command Serial.println() in our last line of code:

// read the input pin:

int buttonState = digitalRead(pushButton);

// print out the state of the button:

Serial.println(buttonState);

delay(1); // delay in between reads for stability

}

Trang 11

6 Button – Digital input - Use a pushbutton to control an LED

Pushbuttons or switches connect two points in a circuit when you press them This example turns on the built-in LED on pin 13 when you press the button

Hardware

 Arduino or Genuino Board

 Momentary button or Switch

 220 ohm, 10K ohm resistor

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed If so, the behavior of the sketch will be reversed, with the LED normally

on and turning off when you press the button

If you disconnect the digital I/O pin from everything, the LED may blink erratically This is because the input is "floating" - that is, it will randomly return either HIGH or LOW That's why you need a pull-up or pull-down resistor in the circuit

Trang 12

Code

const int buttonPin = 2;

const int ledPin = 13;

- Đổi sao cho khi nhấn thì LED tắt, thả thì LED sáng

C1: Reverse HIGH to LOW to revert the state

C2: đổi cực của mạch trên

Instead of connecting pin 2 to a resistor and then GND, connect that resistor to 5V and move the GND wire

to the other side of the button

Trang 13

7 Button – Debounce - Read a pushbutton, filtering noise

Pushbuttons often generate spurious open/close transitions when pressed, due to mechanical and physical issues: these transitions may be read as multiple presses in a very short time fooling the program This

example demonstrates how to debounce an input, which means checking twice in a short period of time to

make sure the pushbutton is definitely pressed Without debouncing, pressing the button once may cause unpredictable results This sketch uses the millis() function to keep track of the time passed since the button was pressed

Circuit

Like 3b

Code

The sketch below is based on Limor Fried's version of debounce, but the logic is inverted from her

example In her example, the switch returns LOW when closed, and HIGH when open Here, the switch returns HIGH when pressed and LOW when not pressed

// constants won't change They're used here to

// set pin numbers:

const int buttonPin = 2; // the number of the pushbutton pin

const int ledPin = 13; // the number of the LED pin

// Variables will change:

int ledState = HIGH; // the current state of the output pin

int buttonState; // the current reading from the input pin

int lastButtonState = LOW; // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,

// will quickly become a bigger number than can be stored in an int

long lastDebounceTime = 0; // the last time the output pin was toggled

long debounceDelay = 50; // the debounce time; increase if the output flickers

// read the state of the switch into a local variable:

int reading = digitalRead(buttonPin);

// check to see if you just pressed the button

// (i.e the input went from LOW to HIGH), and you've waited

// long enough since the last press to ignore any noise:

// If the switch changed, due to noise or pressing:

if (reading != lastButtonState) {

// reset the debouncing timer

lastDebounceTime = millis();

}

Trang 14

if ((millis() - lastDebounceTime) > debounceDelay) {

// whatever the reading is at, it's been there for longer

// than the debounce delay, so take it as the actual current state:

// if the button state has changed:

// save the reading Next time through the loop,

// it'll be the lastButtonState:

lastButtonState = reading;

}

Trang 15

8 Button – State Change Detection (Edge Detection) for pushbuttons – Digital input & output

Once you've got a pushbutton working, you often want to do some action based on how many times the button is pushed To do this, you need to know when the button changes state from off to on, and count how

many times this change of state happens This is called state change detection or edge detection In this

tutorial we learn how to check the state change, we send a message to the Serial Monitor with the relevant information and we count four state changes to turn on and off an LED

The sketch also checks the button push counter's value, and if it's an even multiple of four, it turns the LED

on pin 13 ON Otherwise, it turns it off

// this constant won't change:

const int buttonPin = 2; // the pin that the pushbutton is attached to

const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:

int buttonPushCounter = 0; // counter for the number of button presses

int buttonState = 0; // current state of the button

int lastButtonState = 0; // previous state of the button

// if the current state is HIGH then the button

// wend from off to on:

Trang 16

// if the current state is LOW then the button // wend from on to off:

// save the current state as the last state,

//for next time through the loop

lastButtonState = buttonState;

// turns on the LED every four button pushes by // checking the modulo of the button push counter // the modulo function gives you the remainder of // the division of two numbers:

Trang 17

9 Analog Input Pins

A description of the analog input pins on an Arduino chip (Atmega8, Atmega168, Atmega328, or Atmega1280)

A/D converter

The Atmega controllers used for the Arduino contain an onboard 6 channel analog-to-digital (A/D) converter The converter has 10 bit resolution, returning integers from 0 to 1023 While the main function of the analog pins for most Arduino users is to read analog sensors, the analog pins also have all the functionality of general purpose input/output (GPIO) pins (the same as digital pins 0 - 13)

Consequently, if a user needs more general purpose input output pins, and all the analog pins are not in use, the analog pins may be used for GPIO

digitalWrite(A0, HIGH); // set pullup on analog pin 0

while the pin is an input

Be aware however that turning on a pullup will affect the values reported by analogRead()

Details and Caveats

The analogRead command will not work correctly if a pin has been previously set to an output, so if this is the case, set it back to an input before using analogRead Similarly if the pin has been set to HIGH as an output, the pullup resistor will be set, when switched back to an input

The Atmega datasheet also cautions against switching analog pins in close temporal proximity to making A/D readings (analogRead) on other analog pins This can cause electrical noise and introduce jitter in the analog system It may be desirable, after manipulating analog pins (in digital mode), to add a short delay before using analogRead() to read other analog pins

Trang 18

10 Analog Input – Variable Resistor or Photoresistor

In this example we use a variable resistor (a potentiometer or a photoresistor), we read its value using one analog input of an Arduino or Genuino board and we change the blink rate of the built-in LED accordingly The resistor's analog value is read as a voltage because this is how the analog inputs work

Hardware Required

 Arduino or Genuino Board

Potentiometer or

 10K ohm photoresistor and 10K ohm resistor

built-in LED on pin 13 or

 220 ohm resistor and red LED

Circuit

With a photoresistor

Trang 19

Connect three wires to the Arduino or Genuino board The first goes to ground from one of the outer pins of the potentiometer The second goes from 5 volts to the other outer pin of the potentiometer The third goes from analog input 0 to the middle pin of the potentiometer

For this example, it is possible to use the board's built in LED attached to pin 13 To use an additional LED, attach its longer leg (the positive leg, or anode), to digital pin 13 in series with the 220 ohm resistor, and it's shorter leg (the negative leg, or cathode) to the ground (GND) pin next to pin 13

The circuit based on a photoresistor uses a resistor divider to allow the high impedence Analog input to measure the voltage These inputs do not draw almost any current, therefore by Ohm's law the voltage measured on the other end of a resistor connected to 5V is always 5V, regardless the resistor's value To get a voltage proportional to the photoresistor value, a resistor divider is necessary This circuit uses a variable resistor, a fixed resistor and the measurement point is in the middle of the resistors The voltage measured (Vout) follows this formula:

The analogRead() command converts the input voltage range, 0 to 5 volts, to a digital value between 0 and

1023 This is done by a circuit inside the microcontroller called an analog-to-digital converter or ADC

By turning the shaft of the potentiometer, you change the amount of resistance on either side of the center pin (or wiper) of the potentiometer This changes the relative resistances between the center pin and the two outside pins, giving you a different voltage at the analog input When the shaft is turned all the way in one direction, there is no resistance between the center pin and the pin connected to ground The voltage at the center pin then is 0 volts, and analogRead() returns 0 When the shaft is turned all the way in the other

Trang 20

direction, there is no resistance between the center pin and the pin connected to +5 volts The voltage at the center pin then is 5 volts, and analogRead() returns 1023 In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin

That value, stored in sensorValue, is used to set a delay() for your blink cycle The higher the value, the longer the cycle, the smaller the value, the shorter the cycle The value is read at the beginning of the cycle, therefore the on/off time is always equal

int sensorPin = A0; // select the input pin for the potentiometer

int ledPin = 13; // select the pin for the LED

int sensorValue = 0; // variable to store the value coming from the sensor

Trang 21

11 Analog Read Serial, Read Analog Voltage - Read a potentiometer, print its state out

to the Arduino Serial Monitor

This example shows you how to read analog input from the physical world using a potentiometer A

potentiometer is a simple mechanical device that provides a varying amount of resistance when its shaft is

turned By passing voltage through a potentiometer and into an analog input on your board, it is possible to

measure the amount of resistance produced by a potentiometer (or pot for short) as an analog value In this

example you will monitor the state of your potentiometer after establishing serial communication between your Arduino or Genuino and your computer running the Arduino Software (IDE)

By turning the shaft of the potentiometer, you change the amount of resistance on either side of the wiper, which is connected to the center pin of the potentiometer This changes the voltage at the center pin When the resistance between the center and the side connected to 5 volts is close to zero (and the resistance on the other side is close to 10k ohm), the voltage at the center pin nears 5 volts When the resistances are reversed,

the voltage at the center pin nears 0 volts, or ground This voltage is the analog voltage that you're reading as

an input

The Arduino and Genuino boards have a circuit inside called an analog-to-digital converter or ADC that

reads this changing voltage and converts it to a number between 0 and 1023 When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and the input value is 0 When the shaft is turned all the way in the opposite direction, there are 5 volts going to the pin and the input value is 1023 In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin

Trang 22

Code

In the sketch below, the only thing that you do in the setup function is to begin serial communications, at

9600 bits of data per second, between your board and your computer with the command:

Serial.begin(9600);

Next, in the main loop of your code, you need to establish a variable to store the resistance value (which will

be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer:

int sensorValue = analogRead(A0);

Finally, you need to print this information to your serial monitor window You can do this with the command Serial.println() in your last line of code:

Serial.println(sensorValue)

Now, when you open your Serial Monitor in the Arduino Software (IDE) (by clicking the icon that looks like

a lens, on the right, in the green top bar or using the keyboard shortcut Ctrl+Shift+M), you should see a steady stream of numbers ranging from 0-1023, correlating to the position of the pot As you turn your potentiometer, these numbers will respond almost instantly

// the setup routine runs once when you press reset:

// read the input on analog pin 0:

int sensorValue = analogRead(A0);

// print out the value you read:

by 1023.0 and multiply that by sensorValue :

float voltage= sensorValue * (5.0 / 1023.0);

Trang 23

12 Analog In, Out Serial - Read an analog input pin, map the result, and then use that data to dim or brighten an LED

This example shows you how to read an analog input pin, map the result to a range from 0 to 255, use that result to set the pulse width modulation (PWM) of an output pin to dim or brighten an LED and print the values on the serial monitor of the Arduino Software (IDE)

Trang 24

Connect one pin from your pot to 5V, the center pin to analog pin 0 and the remaining pin to ground Next, connect a 220 ohm current limiting resistor to digital pin 9, with an LED in series The long, positive leg (the anode) of the LED should be connected to the output from the resistor, with the shorter, negative leg (the cathode) connected to ground

Code

In the sketch below, after declaring two pin assignments (analog 0 for our potentiometer and digital 9 for your LED) and two variables, sensorValue and outputValue, the only things that you do in the setup() function is to begin serial communication

Next, in the main loop, sensorValue is assigned to store the raw analog value read from the potentiometer Arduino has an analogRead range from 0 to 1023, and an analogWrite range only from 0 to 255, therefore the data from the potentiometer needs to be converted to fit into the smaller range before using it to dim the LED

In order to convert this value, use a function called map():

outputValue = map(sensorValue, 0, 1023, 0, 255);

outputValue is assigned to equal the scaled value from the potentiometer map() accepts five arguments: The value to be mapped, the low range and high values of the input data, and the low and high values for that data to be remapped to In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0

to 255

The newly mapped sensor data is then output to the analogOutPin dimming or brightening the LED as the potentiometer is turned Finally, both the raw and scaled sensor values are sent to the Arduino Software (IDE) serial monitor window, in a steady stream of data

// These constants won't change They're used to give names

// to the pins used:

const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot

int outputValue = 0; // value output to the PWM (analog out)

Trang 25

Serial.println(outputValue);

// wait 2 milliseconds before the next loop

// for the analog-to-digital converter to settle

// after the last reading:

delay(2);

}

Trang 26

13 Calibration - Define a maximum and minimum for expected analog sensor values

This example demonstrates one techinque for calibrating sensor input The board takes sensor readings for five seconds during the startup, and tracks the highest and lowest values it gets These sensor readings during the first five seconds of the sketch execution define the minimum and maximum of expected values for the readings taken during the loop

Analog sensor (e.g potentiometer, light sensor) on Analog input 2 LED on Digital pin 9

click the image to enlarge

image developed using Fritzing For more circuit examples, see the Fritzing project page

Connect an LED to digital pin 9 with a 220 ohm current limiting resistor in series Connect a photoresistor to 5V and then to analog pin 0 with a 10K ohm resistor to ground

Schematic

click the image to enlarge

Trang 27

Code

Before the setup, you set initial values for the minimum and maximum like so:

int sensorMin = 1023; // minimum sensor value

int sensorMax = 0; // maximum sensor value

These may seem backwards Initially, you set the minimum high and read for anything lower than that, saving it as the new minimum Likewise, you set the maximum low and read for anything higher as the new maximum, like so:

// calibrate during the first five seconds

Trang 28

// apply the calibration to the sensor reading

sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

Here's the whole program:

/*

Calibration

Demonstrates one technique for calibrating sensor input The sensor readings during the first five seconds of the sketch

execution define the minimum and maximum of expected values

attached to the sensor pin

The sensor minimum and maximum initial values may seem backwards Initially, you set the minimum high and listen for anything

lower, saving it as the new minimum Likewise, you set the

maximum low and listen for anything higher as the new maximum

The circuit:

* Analog sensor (potentiometer will do) attached to analog input 0

* LED attached from digital pin 9 to ground

// These constants won't change:

const int sensorPin = A0; // pin that the sensor is attached to const int ledPin = 9; // pin that the LED is attached to // variables:

int sensorValue = 0; // the sensor value

int sensorMin = 1023; // minimum sensor value

int sensorMax = 0; // maximum sensor value

Trang 29

// apply the calibration to the sensor reading

sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

// in case the sensor value is outside the range seen during calibration sensorValue = constrain(sensorValue, 0, 255);

// fade the LED using the calibrated value:

analogWrite(ledPin, sensorValue);

}

Trang 30

14 Fading - Use an analog output (PWM pin) to fade an LED

This example demonstrates the use of analog output (Pulse Width Modulation (PWM)) to fade an LED PWM is a technique for getting an analog-like behavior from a digital output by switching it off and on very fast and with different ratio between on and off time

This example demonstrates the use of the analogWrite() function in fading an LED off and on AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratio between on and off, to create a fading effect

Width Modulation (PWM), which is necessary to fade the LED However, note that pin 9 requires a resistor

to limit the amount of current supplied to the LED On pin 13, this resistor is already included on the Arduino board itself, so you didn’t need to worry about this

In this circuit, the resistor can be either before or after the LED, as long as it is in the circuit

Other diagram

Trang 31

// change the brightness for next time through the loop:

brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:

Trang 32

// the loop routine runs over and over again forever:

// change the brightness for next time through the loop:

brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:

Trang 33

15 Connect and use an RGB LED with an Arduino

OVERVIEW

RGB LEDs are a fun and easy way to add some colour to your projects Since they are like 3 regular LED in one, the way to use and connect them is not much different

They come mostly in 2 versions: Common Anode or Common Cathode

Common Anode uses 5V on the common pin, while Common Cathode connects to Ground

As with any LED, we need to connect some resistors inline (3 total) so we limit the current being drawn

In our sketch we will start with the LED in the Red colour state, then fade to Green, then fade to Blue and finally back to the Red colour By doing this we will cycle through most of the colour that can be achieved

SCHEMATIC

The RGB LED we are using is a Common Anode, so it requires 5V to the common pin

* If we were using a Common Cathode, we would connect it to Ground(GND) instead

Trang 34

We are using 3 resistor to limit the current drawn for the Red, Green, Blue pins Each of them are 330 Ohms The connections are: Pin3-Pin1(red), 5V-Pin2(Anode), Pin5-Pin3(blue), Pin6-Pin4(green)

Code

Our code will use FOR loops to cycle through the colours

The First FOR loop will go from RED to GREEN

The Second FOR will go from GREEN to BLUE

and finally the last FOR will go from BLUE to RED

Trang 36

16 RGB LED – analog output

Overview

In this lesson, you will learn how to use a RGB (Red Green Blue) LED with an Arduino

You will use the analogWrite function of Arduino to control the color of the LED

At first glance, RGB (Red, Green, Blue) LEDs look just like regular LEDs, however, inside the usual LED package, there are actually three LEDs, one red, one green and yes, one blue By controlling the brightness of each of the individual LEDs you can mix pretty much any color you want

We mix colors just like you would mix audio with a 'mixing board' or paint on a palette - by adjusting the brightness of each of the three LEDs The hard way to do this would be to use different value resistors (or variable resistors) as we played with in lesson 2 That's a lot of work! Fortunately for us, the Arduino has an

analogWrite function that you can use with pins marked with a ~ to output a variable amount of power to the

appropriate LEDs

Parts

To build the project described in this lesson, you will need the following parts

Diffuse RGB LED 10mm 1

Trang 37

270 Ω Resistors (red, purple, brown stripes) - you can use up to 1K ohm although it will be a little dimmer

Trang 38

The common negative connection of the LED package is the second pin from the flat side of the LED

package It is also the longest of the four leads This lead will be connected to ground

Each LED inside the package requires its own 270Ω resistor to prevent too much current flowing through it The three positive leads of the LEDs (one red, one green and one blue) are connected to Arduino output pins using these resistors

If you are using a common ANODE LED instead of common CATHODE, connect the long pin to +5 instead

of ground

Colors

The reason that you can mix any color you like by varying the quantities of red, green and blue light is that your eye has three types of light receptor in it (red, green and blue) Your eye and brain process the amounts

of red, green and blue and convert it into a color of the spectrum

In a way, by using the three LEDs we are playing a trick on the eye This same idea is used in TVs, where the LCD has red, green and blue color dots next to each other making up each pixel

Trang 39

If we set the brightness of all three LEDs to be the same, then the overall color of the light will be white If

we turn off the blue LED, so that just the red and green LEDs are the same brightness, then the light will appear yellow

We can control the brightness of each of the red, green and blue parts of the LED separately, making it possible to mix any color we like

Black is not so much a color as an absense of light So the closest we can come to black with our LED is to turn off all three colors

Trang 40

Try the sketch out and then we will dissect it in some detail

The sketch starts by specifying which pins are going to be used for each of the colors:

Before we take a look at the 'loop' function, lets look at the last function in the sketch

1 void setColor(int red, int green, int blue)

If you look at the 'loop' function you can see that we are setting the amount of red, green and blue light that

we want to display and then pausing for a second before moving on to the next color

1 void loop()

2 {

3 setColor(255, 0, 0); // red

4 delay(1000);

Ngày đăng: 31/07/2018, 00:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w