A suitable starter kit for training Arduino beginner is designed to be used without
having to configure a separate circuit for 15 input and output units around Arduino
Uno.
Coding array kit is training toys designed to provide easy, fast and safe access to digital
computing without the need for electrical engineering knowledge.
•Supplied from the coding array kit "Arduino Story" used in this guidebook.
•This guidebook is version 0.1 modified, translated, and written by Arduino story and
owns the Arduino Story.
※ You may not modify, delete or distribute without permission from the owner, and may be
subject to legal punishment in the event of a violation.
0203
수정 -6월 5일.indd 2-32019-06-05 오후 6:18:50
The modules are arranged in an analog wing on the left side of the Uno Board and
a digital wing on the right You can use and control modules at the same time as you
upload sketch files.
After learning, modules can be disconnected and have the advantages to use in the
project.
CAUTION!
Do not disconnect the module using the Tap Cutter before board testing and learning
is complete.
THE BEGINNER’S GUIDE 1st Edition
Page 4
Converter
Analog Wing
Digital Wing
Platform
Shield
I2C 1602 LCD
(SCL, SDA)
Temperature & humidity Module
RGB LED
RGB LED Module
DHT-11 Module
Passive Buzzer Module
Red LED Module
Touch Module
Button Module
SG90 Servo Motor Shield
UltraSonic Distance Module
DHT-11 Module
Temperature & humidity Module
Touch Module
Ultrasonic Distance Module
Sensors
Hall Effect Module
Photoresistor Module
Thermistor Module
1602 I2C LCD Module
Red LED
RGB LED
Button Module
Passive Buzzer Module
Actuators
MIC Module
Flame Module
Slide Potentiometer
SG90 Mini Servo Motor
INTERNAL POWER CIRCUIT DIAGRAM OF CODING ARRAY STARTER KIT FOR ARDUINO
Coding Array Kit PINOUT
Slide Potentiometer Module
Arduino UNO R3 Compatible
Hall Effect Module
Photoresistor Module
MIC Module
Flame Module
Thermistor Module
Arduino Sensor
Bi-Directional Logic
Level Converter
IO Shield
Max. 1000 mA
DC Current for 3.3V
PlatformAnalog WingDigital Wing
ATmega328P
Microcontroller
Sensors
32 KB (ATmega328P)
of which 0.5 KB used by
bootloader
2 KB (ATmega328P)
1 KB (ATmega328P)
SRAM
EEPROM
Flash memory Size
5V
7-12V
6-20V
14 (of which 6 provide PWM output)
Input voltage
Operating voltage
Digital I/O Pins
Input voltage (limit)
Actuators
16 MHz
13
Clock speed
LED_BUILTIN
Arduino Sensor IO Shield
6
Analogue Input Pins
Bi-Directional Logic Level Converter
Max. 20 mA
Shield
Converter
DC Current per I/O Pin
0405
THE BEGINNER’S GUIDE 1st Edition
수정 -6월 5일.indd 4-52019-06-05 오후 6:18:52
Page 5
CODING ARRAY Kit’s another advantage
Digital Array on/off Switch
Power Switch 3.3V Power, 5V Power
To ensure the use of the coding array kit without
damage, observe the following
Analog Array on/off Switch
ONOFF
CODING ARRAY Board Switches are set as ON mode
by default, but you may off entire power supply if necessary.
By default, aduino analog, digital I/O is connected to the I/O expansion shield.
When the switch is turned off analog arrays, digital arrays, additional modules
can be newly configured and used.
Left switch:
select analogue module
Right switch:
select I2C LCD
When shipping the product, it will be shipped to the 'I2C LCD Selection' position. The
switch must be moved as shown in the Figure to use the Analog Temperature Sensor (A4)
and Analog Fire Detection Sensor (A5) modules.
Anti-static Packaging
Array kits are
packaged in
anti-static bags.
Break
Do not place heavy
or sharp objects on
the product.
CAUTION!
Optimal Temperature
Do not store and use at
extreme hot or cold
temperatures.
Wet Hand
Do not touch the
product with wet hands.
Conductive object
Take care not to contact any
conductive object, such as
metal, in the circuit. Risk of
damage to the circuit
or burn or fire.
Hand care
The pins are sharp.
Be careful of injuries.
Chemicals
Keep the product
away from water
or chemicals.
Separate storage
Be sure to keep the power
separate when you are not
using the product.
Disconnect power
Turn off the power to
connect to the board
using a separate module.
0607
수정 -6월 5일.indd 6-72019-06-05 오후 6:18:54
THE BEGINNER’S GUIDE 1st Edition
Page 6
STARTER KIT FOR ARDUINO
codingarray
THE BEGINNER’S GUIDE
INDEX
Chapter1. Prepare
1. Arduino? 12
2. Arduino IDE (Integrated Development Environment ) Download 14
3. Arduino Software IDE Open 16
4. Menu Bar Function Overview 18
5. For Windows 20
6. For MAC 22
1ST EDITION
Chapter 2. Follow Example
1. IDE Structure – setup and loop 26
2. Serial communication 28
3. LED On/Off with Digital Output 30
4. Read button switch values with Digital Input 36
5. Change RGB LED Color Using Digital Output and PWM 42
6. Enables mood light with Electrostatic Touch Sensor 52
7. Read slide variable resistance value with Analog Input 60
8. Play melodies with manual buzzer 68
9. Displaying text on 1602 I2C LCD 76
10. Distance measurement with ultrasonic sensor 92
11. Magnet sensing with Hole sensor 98
12. Light intensity detection and calibrate sensor values with
light sensing sensors 102
13. Flame Detection Sensor Detects Fire 116
14. Temperature measurement with NTC thermistor 122
15. Sound Detection with Microphone Sensor 130
16. Temperature and humidity measurement with sensors 136
17. Servo motor control 146
FAQ and solutions
153
0809
수정 -6월 5일.indd 8-92019-06-05 오후 6:18:54
THE BEGINNER’S GUIDE 1st Edition
Page 7
CHAPTER
- PREPARE
Install Arduino IDE and download
example code
Install the IDE installation, an integrated
development environment, for use the Arduino
board, and check use methods and function of the
IDE. Learn how to download and open an example
file for using a coding array kit..
1
1. Arduino?
2. Arduino IDE (Integrated Development
Environment ) Download
3. Arduino Software IDE Open
4. Menu Bar Function
5. For Windows
6. For MAC
CODING ARRAY STARTER Kit for Arduino
1011
수정 -6월 5일.indd 10-112019-06-05 오후 6:18:54
THE BEGINNER’S GUIDE 1st Edition
Page 8
USB port
Reset button
I2C communication pin
GND
Digital input/output pin
Power
LED
Vcc
MOSI
GND
Analog input pinPower
Internal LED
TX LED
RX LED
External
power
supply
1
CHAPTER 1
Arduino?
Arduino is a typical Microcontroller Unit (MCU) of an open source base
(hardware + software) that is easy to use.
Microcontrollers are made of a single chip to perform a series of tasks in the CPU and
memory, and to send the results to the I/O port with an electrical signal.
Arduino was designed in 2005 by Professor Massimo Banzi, who taught interactive design
called "physical computing" at Italy's Interaction Design Institute Ivrea (IDII) that taught art
and IT. Professors and students used Parllax's Basic Stamp program, but it was expensive
and inconvenient to use. The programming language developed by MIT is open-source and
allows even those who are not well-programmed to implement graphics in simple codes,
starting with Arduino's idea of how to make it easy for students who are not familiar with
hardware to control.
The most used and documented board of Arduino is Uno, the best board to start Arduino.
Uno means one in Italian and has been chosen to celebrate the release of Arduino IDE 1.0.
The USB communication chip is built into the main processor, so it can be connected directly
to the PC's USB, and has 14 digital input/output pins (including 6 PWM pins) and six analog
input pins.
MicrocontrollerATmega328P
Dynamic voltage5V
Input voltage (recommended)7-12V
Input voltage (limit)6-20V
Digital input/output pin14 ea (including 6 PWM pins)
Analog input pin6 ea
DC current per input/output pinMax. 20 mA
DC current of 3.3V pinMax. 1000 mA (150mA Existing Uno)
Flash memory size32 KB (ATmega328P) 0.5 KB Include Bootloader
SRAM2 KB (ATmega328P)
EEPROM1 KB (ATmega328P)
Clock speed16 MHz
LED_BUILTIN13
< Uno-compatible board details used in array kits >
1USB port
2Reset buttonRestart button
3I2C communication pinSDA, SCLpins for I2C communication
4GNDGrouding
5Digital input/output pin14 Digital input/output pin (including 6 PWM pins)
6Power LEDIlluminates when power is supplied.
7VccGrouding
8MOSIMaster output.
9GND5V Power supply
10Analog input pin6 Analog pin
11Power3.3V, 5V, Grounding, External power supply
12Internal LEDConnect digital pin 13
13TX LEDIndicates that the FTDI chip sends data to the computer.
14RX LEDIndicates that the FTDI chip receives data from the computer.
15External power supply7V to 12V DC power supply. (Battery Pack)
It receives a 5V power supply from the computer and
performs serial communication.
The Beginner’s Guide 1st edition - Chapter 1 - 1
1213
수정 -6월 5일.indd 12-132019-06-05 오후 6:18:54
Page 9
2
CHAPTER 1
Arduino IDE
Download
(Integrated Development Environment )
STEP 03
Free download of Arduino Software IDE
STEP 01
Connecting a Board with Computer
Connecting the computer and Arduino with a USB cable allows users to receive 5V power
supply to operate the Arduino as well as send and receive data.
supplies shall be used for modules requiring a power supply greater than 5 V.).
(However, separate power
STEP 02
Access the Arduino Software Download Site
from the Internet
Select and download the installation file that matches your computer's
operating system
The Beginner’s Guide 1st edition - Chapter 1 - 2
Windows and Mac OS users run the program by selecting Download
without Donation or Donation
When a compressed file such as "ardino-1.8.5-lunux64.tar.xz" is
https://www.arduino.cc/en/Main/Software
1415
수정 -6월 5일.indd 14-152019-06-05 오후 6:18:56
downloaded, Linux users run a terminal to decompress as follows:
Run the install.sh file in the extracted folder.
tar xvfz [File name]
Page 10
STARTER KIT FOR ARDUINO
codingarray
3
CHAPTER 1
Arduino Software IDE Open
Let's open the Arduino IDE installed on the computer and look at the
configuration.
IDE is largely divided into menu bars, tool bars, code windows, and
console windows
Menu bar
File Edit Sketch Tools Help
1) Menu bar: Contains the functions of files, editing, sketching, tools, and help.
2) Tool bar: The most commonly used functions of the menu are buttoned together and have
the following functions.
Contains the functions of files, editing, sketching, tools, and help.
File name
The file name of the sketch you are currently creating is displayed.
Code window
This is where the source code is written.
Console window
Show error message of source code.
Check : Check and compile code for grammar errors
Upload : Send code to Arduino board. When the upload button is
pressed, the lamp on the board flashes quickly.
New File : Create a new file for creating a new sketch
Open : Open saved Sketch file
The Beginner’s Guide 1st edition - Chapter 1 - 3
3) File name: The file name of the sketch you are currently creating is displayed.
4) Code window: This is where the source code is written.
5) Console window: Show error message of source code.
1617
수정 -6월 5일.indd 16-172019-06-05 오후 6:18:56
Save : Save the currently active sketch
Serial monitor : Open a new window to show data communication
between Arduino and the computer.
Page 11
4
CHAPTER 1
Menu Bar Function
FileEditingSketchToolHelp
New file
Open
Open Recent Files
Sketchbook
Example
Close
Save
Save As
Page Setting
Print
Setting
Exit
When creating a new sketch
When opening a saved sketch
View and open a list of recently opened sketches
When you open one of the sketches stored in the Sketchbook folder
When opening a built-in example, library example, and so on
Exit sketch
Save Sketch File
Save Sketch Files As other name
Page Setting window for printing
Print the current sketch
Sketchbook folders, font sizes, compiler warnings, etc.
Exit sketch at once, and open all when re-run
FileEditingSketchToolHelp
Cancel
Redo
Crop
Copy
Copy for Forum
Copy to HTML
Paste
Select All
Go to line...
Add/Delete Annotations
Add indentation
Reduce indentation
Increase Font Size
Decrease Font Size
Find
Find next
Find previous
Revert to Previous
Re-run Cancel
Cut Selection
Copy Selection
form for posting sources on Arduino Formal Forum notice
Copy to Clipboard as HTML when you want to upload to a webpage
Paste cut or copied part to cursor position
Select All Code
Shortcut to a specific code line
Process Annotations // When Displaying or Deleting Annotations
When adding indentation
When reducing indentation
When increasing the size of the editor's font (Ctrl + over the mouse wheel)
When reducing the size of the editor's font (Ctrl + below the mouse wheel)
When looking for a specific character
When you grow a specific character and find it in a later sentence
When you grow a specific character and find it in this previous sentence
FileEditingSketchToolHelp
Check/comfile
Upload
Upload using a programmer
Export comfiled binary
Show Sketch Folder
Include Libraries
Add File
Check for code errors and comfile
Send Code to Arduino Board
Overwrite to a bootloader on the board
Save as .hex file
Open Current Sketch Folder
Use the #include to add librarie
Add Source Files to Sketch
FileEditingSketchToolHelp
Auto Format
Archive Sketches
Modify Encoding & Refresh
Serial monitor
Serial plotter
WiFi101 Firmware Updater
Board:"Arduino/Genuino Uno"
Port
Formatting code to look good
Keep a copy of your sketch in a .zip file
Reduce encoding differences between editor and other editors
where you see the communication data between Arduino and the computer.
Graphical representation of communication data between Arduino and computer
Send Code to Arduino Board
Select the board you are using
Choose the computer port to which the Arduino board is connected
Get board information
Programmer : "AVRISP mkll"
Burning a bootloader
Used to program boards or chips
When using IDE for a MCU other than Arduino
FileEditingSketchToolHelp
Getting started
Environment
Trouble shooting
Reference
Galileo Help
Getting started
Trouble shooting
Edison Help
Access and help with the various documents and other descriptions
provided with Arduino IDE at www.arduino.cc
Getting started
Trouble shooting
Find in Reference
FAQ
Visit Arduino.cc
About Arduino
The Beginner’s Guide 1st edition - Chapter 1 - 4
1819
수정 -6월 5일.indd 18-192019-06-05 오후 6:18:56
Page 12
5
CHAPTER 1
For Windows
The Beginner’s Guide 1st edition - Chapter 1 - 5
File Edit Sketch Tools Help
03_01_BlinkingLED
void setup() {
pinMode(13,OUTPUT); //
}
void loop() {
digitalWrite(13,HIGH); //
During upload, the TX.RX.LED on the
Unoboard flashes quickly and then turns off.
delay(1000); //
Done uploading.
Sketch uses 930 bytes (2%) of program storage
If a message is displayed at the top
of the IDE console window, it means
that the upload was successful.
Done uploading.
Arduino/Genuino Uno on
2021
수정 -6월 5일.indd 20-212019-06-05 오후 6:18:58
Page 13
6
CHAPTER 1
For Mac
The Beginner’s Guide 1st edition - Chapter 1 - 1
03_01_BlinkingLED
void setup() {
pinMode(13,OUTPUT); //
}
void loop() {
digitalWrite(13,HIGH
Done uploading.
Sketch uses 930 bytes (2%) of progr
During upload, the TX.RX.LED on the
Unoboard flashes quickly and then turns off.
2223
수정 -6월 5일.indd 22-232019-06-05 오후 6:18:59
If a message is displayed at the top
of the IDE console window, it means
that the upload was successful.
Done uploading.
Arduino/Genuino Uno on
Page 14
CHAPTER
2
Shows the characteristics of the module used in the
example file supplied with the board, as well as the
default usage code and results.
Example contents
1. IDE structure – setup and loop
2. Serial communication
3. Turn LED on and off with digital output
- FOLLOW EXAMPLE
2425
수정 -6월 5일.indd 24-252019-06-05 오후 6:19:00
4. Read button switch values with digital input
5. Change RGB LDE color using digital output and
PWM function
6. Implementing moods, etc. with capacitive touch
sensors
CODING ARRAY STARTER Kit for Arduino
THE BEGINNER’S GUIDE 1st Edition
Page 15
1
CHAPTER 2
IDE structure – setup and loop
Running Arduino IDE creates a sketch file consisting of two parts: void
setup and void loop
.
CAK Starter Code > 01_ IDEStructure
IDE structure – setup and loop
01_IDEStructure | Arduino 1.8.7
File Edit
Sketch Tools Help
voidsetup() {
// Put the code that runs only once, such as variable declaration and
pinMode, in the medium brackets.
}
voidloop() {
// Put in the main code that runs repeatedly..
// If there is no repeat statement, the parentheses should be left blank.
}
voidsetup ( ) { }
■
Runs only once when the program starts.
●
Declares variables between medium brackets, includes pinMode settings, etc.
●
voidloop ( ) { }
■
The main content of a program that runs repeatedly between medium brackets.
●
Even if there are no repeat statements, the medium brackets shall remain blank.
●
Let's run the IDE on Arduino and open an example above.
There are two main screens, void setup { } and void loop { }.
Powering up Arduino will execute the previously uploaded code, which can act as a clearing of
the previous code.
1voidsetup() {
2
3
4}
5
6voidloop() {
7 // Put in the main code that runs repeatedly..
8 // If there is no repeat statement, the parentheses should be left blank.
9
10
// Put the code that runs only once, such as variable declaration and pinMode, in the
medium brackets.
Precautions for creating a sketch file
When you create a sketch file, make sure to write case-sensitive characters.
●
At the end of the command statement, a semicolon (;) should be added at all times.
●
Comments are part of the program that does not affect the program
The USB cable allows data to be exchanged
between Arduino and the computer, called serial
communication (serial communication, UART
communication). When uploading sketch files,
you can see the RX (:data received) and TX (data
sent) lights on the board flickering quickly. Since
Arduino's digital No. 0 pin (RX) and Digital No.
1 pin (TX) are used for serial communication, use
Pin 2 to connect modules to the digital pin.
Serial communications make it easy to debug the computer to give data to Arduino, check
the program results value of Arduino through the computer window, or find and correct
errors in the program.
After uploading the sketch file, touch the same icon to the right to display a serial monitor
pop-up window.
CAUTION!
do not open the serial window during program upload.
STEO 02
01_IDEStructure | Arduino 1.8.7
SEND
Data Input WindowData Transfer
This sketch shows how to print messages entered on a computer into a serial window.
voidsetup() {
1
.begin(9600); // Prepare serial communication. Set the communication speed to 9600.
Serial
2
3
}
4
5
voidloop() {
6
.println("Hello Coding Array Kit ~!"); // Print Hello Coding Array Kit~! in the serial window.
Serial
7
delay(1000); //Wait for 1000 milliseconds (=1 second).
8
}
9
Serial.
It is usually set to 9600.
Serial.
Values can contain both letters and numbers to be printed.
However, the letters must be in between ' or ' .
》 Serial.println("A") outputs A
The format specifies an integer or decimal number.
matched with the communication speed defined in Serial Begin(9600)
Autoscroll9600 baud
The message can be viewed only when it is
Both NL & CR
Send
Clear output
2829
수정 -6월 5일.indd 28-292019-06-05 오후 6:19:00
Page 17
Let's find out about digital output
3
CHAPTER 2
Turn LED on and off with digital output
LED (Light Emitting Diode)
LEDs are semiconductor devices that emit light when current
flows through LEDs. LEDs are of type lamp (lead) and surface
seal (SMD) type. The red LED used in the array kit is a lamp
type and has two legs. A long pin (+) connects to Arduino's No.
13 pin, and a short pin (-) connects to Arduino's GND (ground)
Since the operating voltage of the LED used is 1.6 to 2 volts, the
module is also equipped with a resistance (220 ohms) that limits
the current at 5 volt supply
CAUTION: ★)
polarity changes.
CAUTION: ★)
work or reduce its service life.
LED's do not illuminate when connected with (+) (-)
If the LED is powered without resistance, it will not
Arduino Uno's digital input/output pin
Arduino's input and output signals are largely
divided into two categories: digital and analog
Digital signals refer to the high voltage of two
signals, HIGH / LOW, 1 / 0, True / False , and On /Off..
First, let's learn about digital output signals.
Arduino has 14 digital I/O pins from 0 to 13.
However, since 0 and 1 are connected to the
computer, it is preferable to use pins 2 if possible.
The Beginner’s Guide 1st edition - Chapter 2- 3
Digital input digitalWrite (Pin Number, HIGH);
Since digital pins are specified by default as input
pins, when used as output pins, the setup declares
the output as pinMode (pin number, OUTPUT).
digitalWrite (pin number, HIGH) after declaration;
can command 5V output to pin number or
digitalWrite (pin number, LOW) to 0V output to pin
number..
Let's find out about variables
LEDs are smaller in size and longer in life compared to light bulbs or fluorescent light bulbs,
and use less power, but produce brighter light. It is often used for portable flashlights, lights,
billboards, car lights, flat-screen TVs and monitors. Two or more LED lights can be used to
implement a beam walker signal lamp or to indicate the device's on/off indicator.
3031
수정 -6월 5일.indd 30-312019-06-05 오후 6:19:01
Variables
Variable means the name or space
itself of a space that stores values
that can change during a program
to process or store data.
In order to define a variable in C
programming, the data type for the
value that goes into the variable
must be declared together.
Data
Variable
Data type
For Food
For Clothing
For Toys
For Shoes
Page 18
For numeric data types, appropriate numeric data types should be declared according
to the size of the data. If the data type is incorrectly declared, the desired result value
cannot be obtained.
If a variable is declared at the top of the previous program, it becomes a global
variable that can be used in all parts of the program
Variable data type
TypeScopebyteUse
void
Function declaration, used when return value is missing
ex ) void setup() { }
void loop() { }
CAK Starter Code > 03_01_BlinkingLED
void setup() {
1
pinMode(13,OUTPUT); // Set 13 to output pin
2
}
3
4
void loop() {
5
digitalWrite(13,HIGH); // Give digital signal 1 (HIGH) to pin 13. LED illuminated
6
delay(1000); // Wait for 1000 milliseconds (=1 second).
7
digitalWrite(13,LOW); // Give digital signal 0 (LOW) to pin 13. LED Off
8
delay(1000); // Wait for 1000 milliseconds (=1 second
9
}
10
boolean1
char-128~1271
unsinged
char
byte0~2551Similar to char, but having a positive integer value.
int-32768~327672
unsinged int0~655352Use for positive integer values
word0~655352Use for positive integer values
long
unsinged
long
short-32768~327672Use for integer values
float
double
0~2551Same as byte data type. Byte data type is preferred.
-2147483648
~ 2147483647
0~42949672954Use for positive integer values in large ranges
-3.4028235E+38
~3.4028235E+38
-3.4028235E+38
~3.4028235E+38
Use only true or false values
ex ) boolean state= true ;
Save character values, one character value is enclosed in
single quotes, and stored as ASCII code (number) values.
The two examples below store the same values.
e.g. ) char myChar= 'A';
char myChar = 65;
Multiple characters are enclosed in double quotes.
e.g. ) char array[ ]"ardinostory"
Basic data type for storing integers with symbols
If data is out of range, it will result in unexpected values
and should be replaced with double or long.
4Use for integer values in a range greater than int
4True (numeric) data type
4In Arduino, the same data type as float
pinMode(pin number, value);
pin number puts the digital pin number of Arduino, where the (+) pole of the LED is connected. The value
specifies the input/output role of the pin. You can giveINPUTorOUTPUTor INPUT_PULLUP.
digitalWrite(pin number, value);
can give HIGH (5V) or LOW (0V) digital output value to parts connected to pin number..
CAK Starter Code > 03_02_BlinkingLED2
int redLED = 13; // Red LED to 13
1
2
void setup() {
3
pinMode(redLED,OUTPUT); // Set No. 13 to output pin
4
}
5
6
void loop() {
7
digitalWrite(redLED, HIGH); // Give digital signal 1 (HIGH) to pin 13. Red LED illuminated
8
delay(1000); // Wait for 1000 milliseconds (=1 second)
9
10
digitalWrite(redLED, LOW); // Give digital signal 0 (LOW) to pin 13. Red LED Off
11
delay(1000); // Wait for 1000 milliseconds (=1 second).
12
}
13
Int variable name = value;
int is a data type that stores integers. The redLED variable stores pin number 13 and can be represented
using variable names instead of pin numbers.
The Beginner’s Guide 1st edition - Chapter 2- 3
3233
수정 -6월 5일.indd 32-332019-06-05 오후 6:19:02
Page 19
3
CODING ARRAY CIRCUIT
Once the program is uploaded, depending on the digitalWrite function representing the digital output and
the time setting of the delay function, the LED can be repeatedly lit for one second and then turned off for
one second. At this point, you can see the 'L' LED with built-in on the 13th Uno Board flickering Different
Let's set the red LEDs connected to pin 13 to the output and repeat the execution of the LED turning on for 1 second and off
for 1 second, depending on the time settings of the digitalWrite function indicating the digital output and the delay function..
View Results
3435
delay function times can control the flashing speed of LEDs.
수정 -6월 5일.indd 34-352019-06-05 오후 6:19:03
Page 20
CAK Starter Code > 04_01_Button
4
CHAPTER 2
Read button switch values with digital input
Push Button
The button switch is used to open and close the circuit by
pressing the button at the top. When a button is pressed, a
circuit is connected and an electrical current flows between
1,2 and 3,4. Therefore, when connecting wires, select one
from 1,2 and one from 3,4. Button switches are used in
everyday life such as game consoles, bus exit notification
buttons, keyboard buttons, etc. as well as control of
opening and closing circuits.
When the circuit of the button switch is open, the Arduino
board cannot logically predict the HIGH, LOW for the pin
Button Switch
Push HIGH
10KΩ
Pull-up circuit
Connect the normal state of the input
pin to HIGH. With the resistance
connected to power 5V, HIGH returns
1 in digitalRead.
Digital Pin
Electric
current
Button
switch
open
that is not connected, resulting in a floating phenomenon that
moves high and low fast. To prevent floating, a button switch
can be received as a digital input after a pull-up or pull-down
resistance is hung.
The coding array starter kit is connected to a button switch
using a pull down resistance that defines the LOW voltage in
normal situations without a drive signal. Therefore, the HIGH
(1) value is entered when the button switch is pressed and the
LOW (0) value is entered if the button switch is not pressed.
Pull-Down circuit
Connect the normal state of the input
pin to LOW. With the resistance
connected to GND 0V, HIGH returns
1 in digitalRead.
Electric
current
Digital Pin
Button
switch
closed
Button
switch
open
Digital Pin
Electric current
Electric
current
Button
switch
closed
Digital Pin
/ * If condition statement is used
1
* Press button switch to connect circuit and return HIGH (1) value to light LED
2
* If the button switch is not pressed, the circuit will open and the LOW (0) value will be returned
3
to turn off the LED.
*
4
*/
5
6
int redLED = 13; // Set red LED pin to 13.
7
int Button = 8; // Button switch pin set to 8
8
9
void setup() {
10
pinMode(Button, INPUT); // Set button pin to input
11
pinMode(redLED, OUTPUT); // Set redLED pin to output
12
13
.begin(9600); // Starts serial communication at 9600 speed
Serial
14
15
}
16
17
void loop() {
18
19
int sensorVal = digitalRead(Button); // Receive button input value for sensorVal variable.
20
// Variables inserted in void function are regional variables
21
22
.println(sensorVal); // Mark the value of the button one line in the serial window.
Serial
23
// If the pull-down resistance is connected, give LOW (0) when the button is open and HIGH (1)
24
when pressed.
// give HIGH (1) value when the button is open and LOW (0) when pressed.
25
26
if (sensorVal == LOW) { // If the button is open,
27
digitalWrite(redLED, LOW); // RedLED OFF
28
}
29
30
else { // If the button is pressed,
31
digitalWrite(redLED, HIGH); // Turn on the redLED.
32
}
33
delay(10);
34
}
35
digitalRead(pin number, value);
==
The voltage entering the pin is read by HIGH (1) EH as a LOW (0) digital input value.
It means that the left and right values are the same.
The Beginner’s Guide 1st edition - Chapter 2- 4
3637
수정 -6월 5일.indd 36-372019-06-05 오후 6:19:04
Page 21
While the sketch is uploaded and the button
4
switch is pressed, the HIGH value is entered to
illuminate the LED.
While the button is not pressed, the LOW value is
entered and the LED is turned off.
The pull-up resistance circuit may be configured
separately on the button switch, but it may also
be used to use a 20KΩ pull-up resistance inside
the Uno Board using INPUT_PULLUP. When
connecting a sensor to a pin consisting of INPUT_
PULLUP, the other end must be connected to the
GND (0V). Uno board does not have INPUT_
PULLDOWN function.
CODING ARRAY CIRCUIT
Use a button switch connected to pin 8 using a pull-down resistance inside the module. Use the digitalRead function to receive the
digital input value of the button switch and to issue a digital output command to the LED. Let's also find out how button switches
divaunhings..
Set to input pin using pull-up resistance inside (available from arduino 1.0.1)
pinMode(pin number, INPUT_PULLUP);
When a button switch is opened and closed, it can often be caused by mechanical and physical problems. This situation can
be avoided by pressing and reading multiple times in a very short time when a program can be deceiving. Learn more about
divauning in 04_02
View Results
3839
수정 -6월 5일.indd 38-392019-06-05 오후 6:19:06
Page 22
CAK Starter CODE > 04_02_Button_Debounce
/* When a button switch is opened and closed, it often generates incorrect signals due to mechanical and
1
physical problems.
2 * Avoid this situation by pressing and reading multiple times in a very short time that can fool a program
3 * This process is called divauning.
4 */
5
6const int Button =8; // Set button switch pin to 8
7const int redLED = 13; // Set LED pin to 13
8
9int ledState =HIGH; // Set output pin to HIGH
10int buttonState; // Variables that read and store the current button switch status
11int lastButtonState =HIGH; // Read and save the previous button switch status, reset to LOW
12
13unsigned long lastDebounceTime =0; // Save the last time the output pin was switched.
14unsigned long debounceDelay =50; // Time to wait for steady state (milliseconds)
15
16void setup() {
17pinMode(redLED, OUTPUT); // Set red LED pin to output
18pinMode(Button, INPUT);
19digitalWrite(redLED,ledState); // Turn the LED on and off according to the ledState.
20}
21
22void loop() {
23 int reading = digitalRead(Button); // Read button status and save to reading variable
24 if(reading != lastButtonState) { // If the status of the button changes to Noise or Press,
25 lastDebounceTime =millis(); // Reset the debounging timer,
26 }
27
28// Whatever value you've read, if it's longer than the debounce delay,
If the condition is true, perform the if execution
code, and if the condition is false, execute the
else execution code.
If (conditions1) {
If (conditions2) {execution code1 }
If (conditions3) {execution code2 }
}
If condition 1 is satisfied and condition 2 is satisfied at
the same time, process execution code 1 and execute
code 2 if condition 1 is satisfied and condition 3 is
satisfied at the same time. You can also put another
if statement inside the if statement. If a statement is
executed inside, then indentation is required.
The Beginner’s Guide 1st edition - Chapter 2- 4
4041
수정 -6월 5일.indd 40-412019-06-05 오후 6:19:07
Page 23
Change RGB LED Color Using Digital
STARTER KIT FOR ARDUINO
codingarray
5
CHAPTER 2
RGB LED
RGB LEDs are LEDs that use three different color combinations: red, green and blue.
In modules, red is connected to pin 9 digital, green to pin 10 and blue to pin 11. The
longest pin is the common pin..
Output and PWM Featuresinput
The Beginner’s Guide 1st edition - Chapter 2- 5
Since the operating voltage of the RGB LED used is approximately 2V, the module is
equipped with a resistance (220 Ohms) that limits the current at 5V power supply.
Using RGB LEDs, a variety of lighting effects can be obtained by producing different colors
from a single LED. It is often used to decorate the computer's main case with colorful lights
or change the color of billboards..
There are two types of RGB LEDs: common cathodes that connect the longest pins to the
GND and common anodes that connect the longest pins to 5 V. In the coding array kit, the
common cathode type SMD (surface mounted device) type was used in the module.
4243
수정 -6월 5일.indd 42-432019-06-05 오후 6:19:07
Page 24
CAK Starter Code > 05_01_RGB_DigitalMixing
/* RGB LEDs combine the three primary colors of red, green and blue to release a variety of
1
colors.
* Pin 910 and 11 are connected to pins that control red, green and blue LEDs respectively.
2
* In this example, we will use a common cathode RGB LED to find out the tri-circular mixture of
3
light from the digital output.
*/
4
5
const int red Pin =9; // Red LED No. 9
6
const int greenPin = 10; // Green LED No.10
7
const int bluePin=11 ; // Blue LED No.11
8
9
voidsetup() {
10
pinMode(redPin, OUTPUT); // Set pin 9 to output
11
pinMode(greenPin, OUTPUT); // Set pin 10 to output
12
pinMode(bluePin, OUTPUT); //Set pin 11 to output
13
.begin(9600); // 9600-speed serial communication start
Serial
14
}
15
16
void loop() {
17
.println("RED on"); // Red LED illuminated
Serial
18
digitalWrite(redPin,HIGH);
19
digitalWrite(greenPin,LOW);
20
digitalWrite(bluePin,LOW);
21
delay(1000); // for a second
22
23
.println("GREEN on"); // Green LED illuminated
Serial
24
digitalWrite(redPin,LOW);
25
digitalWrite(greenPin,HIGH);
26
digitalWrite(bluePin,LOW);
27
delay(1000); // for a second
28
29
.println("BLUE on"); // Blue LED illuminated
Serial
30
digitalWrite(redPin,LOW);
31
digitalWrite(greenPin,LOW);
32
digitalWrite(bluePin,HIGH);
33
delay(1000); // for a second
34
35
.println("Yellow on"); // Yellow LED illuminated
Serial
36
digitalWrite(redPin,HIGH);
37
digitalWrite(greenPin,HIGH);
38
digitalWrite(bluePin,LOW);
39
delay(1000); // for a second
40
41
.println("Magenta on"); // Magenta illuminated
Serial
42
digitalWrite(redPin,HIGH);
43
digitalWrite(greenPin,LOW);
44
digitalWrite(bluePin,HIGH);
45
delay(1000); // for a second
46
47
.println("Cyan on"); // Cyan LED illuminated
Serial
48
digitalWrite(redPin,LOW);
49
digitalWrite(greenPin,HIGH);
50
digitalWrite(bluePin,HIGH);
51
delay(1000); // for a second
52
53
.println("White on"); // White LED illuminated
Serial
54
digitalWrite(redPin,HIGH);
55
digitalWrite(greenPin,HIGH);
56
digitalWrite(bluePin,HIGH);
57
delay(1000); // for a second
58
}
59
The Beginner’s Guide 1st edition - Chapter 2- 5
4445
수정 -6월 5일.indd 44-452019-06-05 오후 6:19:08
Page 25
5
CODING ARRAY CIRCUIT
Use RGB LEDs that are connected with red, green, and blue LEDs in digital 9, 10 and 11 that can use PWM function. Three LED's are
simultaneously controlled by digital outputs to achieve a three-circular mixture of light. Also learn how to adjust the brightness of LEDs
using the PWM function.
When a program is uploaded, it uses digital outputs to
implement a three-way color mixture of light
Red
Green
RGB LED Digital Output
Blue
Control Table of Common
Yellow
Negative Type for
Cyan
Magenta
Implementing the Three
Circular Color of Light
White
View Results
4647
수정 -6월 5일.indd 46-472019-06-05 오후 6:19:10
Page 26
Let's learn about analog output /
pulse width modulation (PWM).
Unlike turning on and off LEDs, opening and closing circuits, many values such as light
intensity, temperature, distance, sound size adjustment, and light intensity are made up of
continuous analog signals..
The digitally operated Arduino does not contain a DAC (Digital-Analog Converter) and cannot output
analog signals. Instead,
look analog digitally
PWM (Pulse Width Modulation)
is used to
. If the digital signal ON (5 V) OFF (0 V) signal changes the time portion of the
duration (change the pulse width) and this pattern is repeated at a speed that is not recognized by the
eye, it appears to be a voltage between 0 and 5 V. This is a logic that feels like 24 frames per second of
animation show a series of movements.
The PWM brightness measurement is described by the term duty cycle (assuming a duration of 5 V
voltage). The duty cycle is the percentage of the time the circuit is switched on versus the total run time,
with 100% representing the maximum brightness and the low percentage representing the low light
output. The PWM output can be adjusted to a number between
STEO 02
Among Arduino's 0-13, the six pins marked
a pinMode ( ) setting.
(3, 5, 6, 9,10,11)
output signals that make them
0 and 255
are PWM pins.
analogWrite( )
via
These pins do not need
..
CAK Starter Code > 05_02_RGB_LED_Fading
1 /* In this example, we use a common cathode RGB LED
2 * Pin 910 and 11 are connected to pins that control red, green and blue LEDs respectively.
3 * Use the PWM (Pulse-Width Modulation) function to adjust the brightness of the LEDs.
4 * The 'radom' command adjusts the brightness of the three colors of RGB to enable a variety of color blends.
5 */
6
7const int red Pin =9; // Red LED No. 9
8const int green Pin = 10; // Green LED No. 10
9const int blue Pin=11 ; // Blue LED No. 11
10
11int delayTime=30; // Delay time setting
12
13int redV; // Set red LED analog value (0-255)
14int greenV; // Set green LED analog value (0-255)
15int blueV; // Set blue LED analog value (0-255)
16
17int fadeAmount =5; // fade storage variable
18
19voidsetup() {
20 pinMode(redPin, OUTPUT); // Set pin 9 to output
21pinMode(greenPin, OUTPUT); // Set pin 10 to output
22pinMode(bluePin, OUTPUT); // Set pin 11 to output
23}
24
25voidloop() {
26// Red LED brightness adjustment
27 greenV=0;
28 blueV=0;
29for(redV =0; redV <=255;redV +=5) {
30 // Increase the value by 5 times from 0 to 255.
31analogWrite(redPin,redV); // Turn on the LED more and more and more.
32analogWrite(greenPin,greenV);
33analogWrite(bluePin,blueV);
34delay(delayTime); // 30-millisecond wait
35 }
36
37 for(int redV=255 ;redV >=0; redV -=5) {
38// Reducing the value by 5 times from 255 to 0.
39analogWrite(redPin,redV); // Turn on the darker LEDs.
40analogWrite(greenPin,greenV);
41analogWrite(bluePin,blueV);
42delay(delayTime); // 30-millisecond wait
The Beginner’s Guide 1st edition - Chapter 2- 5
4849
수정 -6월 5일.indd 48-492019-06-05 오후 6:19:11
Page 27
43 }
44
45// Green LED brightness adjustment
46 redV=0;
47 blueV=0;
48 for(greenV=0 ; greenV <=255; greenV +=5) {
49 // Increase the value by 5 times from 0 to 255.
50analogWrite(redPin,redV); // Turn on the LED more and more and more.
51analogWrite(greenPin,greenV);
52 analogWrite(bluePin,blueV);
53delay(delayTime); // 30-millisecond wait
54 }
55
56for(int greenV =255 ; greenV >=0; greenV -=5) {
57 // Reducing the value by 5 times from 255 to 0.
58analogWrite(redPin,redV); // Turn on the darker LEDs.
59analogWrite(greenPin,greenV);
60analogWrite(bluePin,blueV);
61delay(delayTime); // 30-millisecond wait
62 }
63
64// Blue LED brightness adjustment
65 redV=0;
66 greenV=0;
67 for(blueV=0 ; blueV <=255; blueV +=5) {
68// Increase the value by 5 times from 0 to 255.
69analogWrite(redPin,redV); // Turn on the LED more and more and more.
70analogWrite(greenPin,greenV);
71 analogWrite(bluePin,blueV);
72
73delay(delayTime); // 30-millisecond wait
74 }
75
76 for(int blueV=255 ;blueV >=0; blueV -=5) {
77// Reducing the value by 5 times from 255 to 0.
78 analogWrite(redPin,redV); // Turn on the darker LEDs.
79analogWrite(greenPin,greenV);
80 analogWrite(bluePin,blueV);
81 delay(delayTime); // 30-millisecond wait
82 }
83
84// 20 Random colors
85 for (int i=0; i<20; i++){
86 analogWrite(redPin,random(0,255));
87 analogWrite(greenPin,random(0,255));
88analogWrite(bluePin,random(0,255));
89delay(1000);
90 }
91}
random (Min, Max);
The random function sets the range and returns the random integer values
within the maximum value-1. Maximum value: Maximum value of random number (optional),
Maximum value: Maximum value of random number
analogWrite (Pin number ,
Value); Only PWM pin numbers 3, 5, 6, 9, 10, 11 are available.
Values can be expressed as analog outputs with integers of 0 to 255.
View Results
Red LEDs connected to pin 13 are not only lit/off outputs, but three-color LEDs connected to pins with
PWM function can also be brightness controlled as well as on and off. Once the RGB_LED_Fading
program is uploaded, you can see that it is getting brighter and darker in the order of red, green and blue
LEDs. In addition, a random mix of RGB colors using the random function shows 20 colors..
The Beginner’s Guide 1st edition - Chapter 2- 5
5051
수정 -6월 5일.indd 50-512019-06-05 오후 6:19:13
Page 28
Implementing moods, etc. with
CAK Starter Code > 06_01_TouchSensor
6
CHAPTER 2
capacitive touch sensors
Capacitive Touch Sensor
The touch module used in the coding array starter kit used
Touch sensor
PowerLED
Notice LED
Illuminates when
touch sensor is
pressed
Pin D7
The operating voltage of the touch sensor is 2.0 to 5.5 V and the response time is 60 milliseconds
to 220 milliseconds. When the module is energized, the power LED turns on. The notification LED
turns on while the body is in contact with the touch sensor and continues to read the HIGH value.
If there is no physical contact, the notification LED turns off and reads the LOW value.
Touch sensors are often used for hand-touch smartphone screens without using touch pens.
a capacitive touch sensor. A touch-piece consisting of
metal from a capacitive touch sensor has a small amount
of current between the outgoing and incoming electrodes
and is (operating standby). When a body such as a finger
touches a touch surface, part of the electrical power
flowing toward the receiving electrode moves to the body,
which weakens the electric field detected by the receiving
electrode. A slight touch of the human body can detect a
slight change in the capacitance and indicate a HIGH or
LOW value.
CMOS
Driver
X Electrode
Y Electrode
1 /* The touch sensor is a sensor that returns a digital input value when the body touches it.
2 * Can be used as a button switch.
3 * Short delay time will not count the number of touch accurately.
4
5 */
6
7#define Touch 7 // Electrostatic Touch Sensor to 7
8
9int touchCounter = 0; // Variables that store the number of times a touch sensor is pressed
10int lastTouchState = 0; // Read and save the previous button switch status
11
12voidsetup() {
13pinMode(Touch, INPUT); // Set the touch sensor connected to pin 7 to input
14Serial.begin(9600); // Starts serial communication at 9600 speeds
15}
16
17voidloop() {
18 int touchState = digitalRead(Touch); // Read touch sensor switch values and store them in touchState
19
20 if (touchState != lastTouchState) { // Touch sensor status has changed
21if (touchState == HIGH) { // When the touch sensor is pressed,
22 touchCounter ++; // Increase the number of touch sensors pressed
23
24Serial.print("number of touch sensor pushes: "); // "~:" to the cereal window.
25Serial.println(touchCounter); // Connect and press and replace touch sensor
26 } else { // If the touch sensor has changed from TOUCHED to not touched
27Serial.println("not touched"); // Write "not touched" in the serial window and replace lines
28 }
29 delay(100);
30 }
31 lastTouchState = touchState; // Use current touchState as lastTouchState in the next loop
32}
#define Constant name value : One of the pre-processing statements processed before program compilation is
named constant value (you cannot change the data value while the program is running). Constants created in
Define are compiled with all the constants of the source code replaced with values, so they do not take up memory.
Caution )Do not insert '=' between constant life and value. Don't use a semicolon at the end
* This sketch will learn how to use the touch sensor by default and how to count the number of times the sensor
has been pressed.
Serial.println("TOUCHED"); // Write "TOUCHED" in the serial window and replace lines
The Beginner’s Guide 1st edition - Chapter 2- 6
void function: Variables declared within { } are recognized as regional variables only in brackets.
void loop() {int touchState = digitalRead(Touch);
Caution) If a variable is declared before setting the void, use the variable in all parts of the program. :
global variable
touchCounter ++; Increase the value of the touchCounter variable by 1.
5253
수정 -6월 5일.indd 52-532019-06-05 오후 6:19:14
Page 29
6
CODING ARRAY CIRCUIT
Touch sensors connected to pin 7 digital can be used like button switches as sensors that return HIGH (1) digital input values when the
body touches them and LOW (0) digital input values if the body does not touch them. Continue to return the HIGH input value while the
body touches it, but by adjusting the delay time, you can count the number of touches.
After you upload the sketch file, open the serial
monitor. Each time you touch a touch sensor, you
can see in the serial window that the number of
clicks increases with the message "TOUCHED."
When the touch sensor is released, a "not
touched" message will be displayed.
View Results
5455
수정 -6월 5일.indd 54-552019-06-05 오후 6:19:15
Page 30
CAK Starter Code > 06_02_TouchStateChange
1/* This sketch shows a touch sensor
2 Touch 1, 2 and 3 to light up the green LED.
3 Touch four times to show the LED is off.
4 This allows users to set the desired brightness mood using the touch sensor.
5*/
6
7
#define Touch 7 // Connect the capacitive touch sensor to 7.
8
9const int greenPin = 10 ; // Green LED to No.10
10
11int touchCounter = 0; // Variables that store the number of times a touch sensor is pressed
12int lastTouchState = 0; // Read and save the previous Touch Sensor status
13int alanlogValue; // Set analog value of LED (0-255)
14
15voidsetup() {
16 pinMode(Touch, INPUT); // Set the touch sensor connected to pin 7 to input
17pinMode(greenPin, OUTPUT); // Set pin 11 to output
18 Serial.begin(9600); // Starts serial communication at 9600 speeds
19}
20
21voidloop() {
22 int touchState = digitalRead(Touch); // Read touch sensor switch values and store them in touchState
23
24if (touchState != lastTouchState) { // Touch sensor status has changed
25if (touchState == HIGH) { //
26 touchCounter ++; // Increase the number of touch sensors pressed
27 Serial.println("TOUCHED"); // Write "TOUCHED" in the serial window and replace lines
28 Serial.print("number of touch sensor pushes: "); // "~:" to the cereal window
29 Serial.println(touchCounter); // Connect and press and replace touch sensor
30
31 // Use current touchState as lastTouchState in the next loop
54 // Press the touch sensor to turn on the changed analog value.
55analogWrite(greenPin, alanlogValue);
56
57 } else { // If the touch sensor has changed from TOUCHED to not touched
58Serial.println("not touched"); // Write "not touched" in the serial window and replace lines
59 }
60 delay(100);
61 }
62
63// Use current touchState as lastTouchState in the next loop
64 lastTouchState = touchState;
65}
Using the remainder of the touchCounter divided by four values, the remaining values are only displayed in four
different levels, so you can set the number of touchings divided by four levels..
The Beginner’s Guide 1st edition - Chapter 2- 6
5657
수정 -6월 5일.indd 56-572019-06-05 오후 6:19:17
Page 31
View Results
STARTER KIT FOR ARDUINO
codingarray
The Beginner’s Guide 1st edition - Chapter 2- 6
5859
수정 -6월 5일.indd 58-592019-06-05 오후 6:19:18
After you upload the sketch file, open the serial
monitor. You can verify that the green LED's
brightness increases when you press the touch
sensor 1st, 2nd, and 3rd, and that the LED turns off
when you press the fourth time. Using this method,
it is possible to implement brightness adjustment
such as mood using touch sensor.
Page 32
Read slide variable resistance value
16-bit Resolution
3-bit Resolution
7
CHAPTER 2
Let's learn about analog input.
with analog input
Slide Potentiometer
Resistance is enough to interfere with the flow of
electric charges.
Unlike a typical set of values for resistance, variable
resistance is also called potentiometer and voltage
divider and is either turned around the center fireplace,
or adjusted by pushing the slider left and right. The
Power LEDSlider
Slider
coding array start kit uses a slide variable resistance
module
As you push the slider left and right, the resistance
values change according to the position, and you return
the value to the analog input pin connected to Aout
by converting the changing voltage values between 0
V and 5 V to the analog input values. Analog values
are read using the
of slide variable resistance, such as volume control and
boiler temperature control, are found in everyday life..
anlaogRead( )
function. Examples
Arduino's analog-to-digital converter converts analog
signals into 10-bit disassembly capabilities (2^10 =1024).
This means that the input voltage of 0 to 5 V is converted
into a digital signal and returned as an integer between 0
and 1023 and the voltage can be distinguished in units of
4.9 mV.
Analog-to-digital transducers require a certain amount of time (Conversion Time)
to change the analog input value to digital. Arduino takes about 100 microseconds
(0.0001 seconds), so you can read up to 10,000 analog input values per second. To
read analog values, analogRead can be declared as a table. If there is no analog input,
the A0 to A5 analogue input pins can be used the same as the digital pins (pins 14 to
19)...
16-bit Resolution
3-bit Resolution
If the analog-to-digital converter
has a 3-bit resolution, it means that
it is distinguished by converting
input voltages from 0 to 5 V into
2^3 digital signal stages. The higher
the disassembly ability, the higher
the accuracy, the better the analog
value can be measured.
The Beginner’s Guide 1st edition - Chapter 2- 7
Arduino contains 6 analog to digital converters
(ADC) so that analog values can be read from A0
to A5 pins using the
6061
수정 -6월 5일.indd 60-612019-06-05 오후 6:19:18
analogRead
function
analogRead(0)analogRead(A0)analogRead(14)
analogRead(1)analogRead(A1)analogRead(15)
analogRead(2)analogRead(A2)analogRead(16)
analogRead(3)analogRead(A3)analogRead(17)
analogRead(4)analogRead(A4)analogRead(18)
analogRead(5)analogRead(A5)analogRead(19)
Page 33
Let's find out about voltage distribution.
Calculate the Voltage Divider as follows:.
When a resistance is connected in series, the total
resistance value is the sum of each resistance, and the
current flowing to each resistor is equal to the supply
current.
In addition, the sum of the voltages applied to each
resistor is equal to the supply voltage..
According to Ohm's Law V=IR,
The size of the resistance increases as the length
of the resistance increases, and the larger the
cross-sectional area becomes smaller.
14// Analog input/output pins need not be declared..
15}
16
17voidloop() {
18
19// AnalogValue stores integer values in the range 0 to 1023.
20
21float voltage = analogValue * (5.0 / 1023.0); // Convert Analog Readings to Volts 0 to 5 V
22 // Store in float variable because the math result value is real
23
24//Serial.print("Analog Value : ")
25 //Serial.println(analogValue); // Indicate the value of analogValue one line in the serial window.
26Serial.print("Voltage : ");
27Serial.println(voltage); // Print the converted voltage value one line in the serial window
28
29 if (analogValue > threshold) { // If the value stored in analogValue is greater than 400
30digitalWrite(redLED, HIGH); // Turn on the LED.
31 } else { // If the value stored in analogValue is less than or equal to 400
32digitalWrite(redLED, LOW); // Turn off the LED.
33
34delay(1); // Wait 1 millisecond to read reliably
35 }
36}
int analogValue = analogRead(potentiometerPin); // Read the analog value of variable resistance and
store it in analogValue
The Beginner’s Guide 1st edition - Chapter 2- 7
CAK Starter Code > 07_01_SlidePotentiometer
1/* Change the resistance value by pushing the variable resistance from side to side.
2 As the resistance changes, 0 to 1023 analog values are entered as A0 pins.
3 Analog values are converted to voltages and expressed as values on the serial monitor.
4 Can use a serial plotter to express it in graphs.
5*/
6
7const int potentiometerPin = A0; // Output value of variable resistance is read from A0
8const int redLED = 13;
9const int threshold = 400;
10
11voidsetup() {
12pinMode (redLED, OUTPUT); // Set red LED to output
13Serial.begin(9600); // Starts serial communication at 9600 speed
analogRead (Pin);
per second). Respond to 0 - 5 V voltage with an integer value of 0 - 1023.
float Variables;
operations with float, you must add a decimal point. (Example: 5.0 /1023.0) Otherwise (e.g. 5
/1023= 0) treated as an integer int.
Tools Help
Auto Format
Archive Sketch
Fix Encoding & Reload
Manage Libraries
Serial Monitor
Serial Plotter
Read the analog value from the specified pin (read only about 10,000 times
declared for the purpose of storing decimal mistakes. When performing math
CAUTION!
The analog input/output does not have to be set in
Ctrl+T
Ctrl+Shift+I
Ctrl+Shift+M
Ctrl+Shift+L
•
pinMode separately.
Click Menu Bar > Tools > Serial Plotter (Ctrl+Shift+L)
•
to open the serial plotter. During the output of the
serial plotter, the serial monitor window does not open
simultaneously..
6263
수정 -6월 5일.indd 62-632019-06-05 오후 6:19:19
Page 34
7
CODING ARRAY CIRCUIT
After uploading a sketch file, moving the slider of variable resistance to the left and right changes the analog input value, and
you can graphically represent the changing voltage values in the serial plotter. Also, the red LED value turns on when the miniset
value is higher than the set value.
Touch sensors connected to pin 7 digital can be used like button switches as sensors that return HIGH (1) digital input values when the
body touches them and LOW (0) digital input values if the body does not touch them. Continue to return the HIGH input value while the
body touches it, but by adjusting the delay time, you can count the number of touches.
View Results
6465
수정 -6월 5일.indd 64-652019-06-05 오후 6:19:21
Page 35
CAK Starter Code > 07_02_SlidePotentiometer2
1/* As the variable resistance value increases, the color of the RGB LED changes to red->green->blue... */
2
3int potPin = A0; // Output of variable resistance connected to analogue pin A0
4int potVal = 0; // Variables that store analog (0-1023) values read from variable resistance
5
6const int redPin = 9; // Red LED No. 9
7const int greenPin = 10; // Green LED No. 10
8const int bluePin = 11 ; // Blue LED No. 11
9
10int redV = 0; // Set red LED analog value (0-255)
11int greenV = 0; // Set green LED analog value (0-255)
12int blueV = 0; // Set blue LED analog value (0-255)
13
14voidsetup() {
15pinMode(redPin, OUTPUT); // Set pin 9 to output
16pinMode(greenPin, OUTPUT); // Set pin 10 to output
17pinMode(bluePin, OUTPUT); // Set pin 11 to output
18}
19
20voidloop() {
potVal = analogRead(potPin); // The analog output value of variable resistance is read from the A0 pin (0-
21
1023).
int ledLevel = map(potVal, 0, 1023, 0, 255); // Converts the analog input value to the analog output value (0-
22
255)
23
24if (potVal < 341){ // When the value of variable resistance is 1 divided into three stages (0-340)
25 redV = 255 - ledLevel; // The red is getting lighter
26 greenV = ledLevel; // The green is getting darker
27 blueV = 1; // Blue has no effect
28 }
29
30else if (potVal < 682) { // When the value of variable resistance is 2 divided into three stages (341-681)
31 redV = 1; // Red has no effect
32 greenV = 255 - ledLevel; // The green is getting lighter
33 blueV = ledLevel; // The blue is getting darker
34 }
35
36else { // When the value of variable resistance is 3 divided into three stages (682-1023)
37 redV = ledLevel; // The Red is getting darker
38 greenV = 1; // Green has no effect
39 blueV = 255 - ledLevel; // The blue is getting lighter
40 }
41
42analogWrite(redPin, redV); // Write values to red pins
43analogWrite(greenPin, greenV); // Write values to green pins
44analogWrite(bluePin, blueV); // Write values to blue pins
45}
map (number to convert, current maximum value, current maximum value, current maximum value to be
converted, maximum value to be converted)
A function that simply represents the value that is converted using a proportional expression.
The value being converted is expressed as an integer (including negative numbers),
and the decimal number is not rounded up.
int ledLevel= map(potVal,0,1023,0,255);
Converts the number of 0 to 1023 accepted by portVal to a value between 0 and 255.
View Results
After uploading the sketch, pushing the slider of variable resistance left and right changes the analog input value.
As the resistance value increases, you can see that the color of the RGB LED changes to red - > green-> blue..
The Beginner’s Guide 1st edition - Chapter 2- 7
6667
수정 -6월 5일.indd 66-672019-06-05 오후 6:19:23
Page 36
8
CHAPTER 2
Melody with a Passive Buzzer
Let's find out how to give a constant name to a frequency
value with #define..
Passive Buzzer
Piezo buzzer is a small speaker that makes sound using piezo effect
Buzzer
Pin D6
The best way to distinguish between
these two buzzers is to connect the two
pins of the buzzer to the GND and
5V of the Arduino board to the active
buzzer if a constant sound occurs and
the manual buzzer if there is no sound.
The coding array kit uses a manual
buzzer module for digital No. 6 pin, so
you can play melodies..
To perform melodies with a manual buzzer, use the tone (pin number, negative frequency, negative
duration) function, which uses integer values as follows:.
octave
pitches
C (do)3365131262523104720934186
C#3569139277554110922174335
D (re)3773147294587117523494699
D#3978156311622124524894987
E (mi)4182165330659131926375274
F (fa)4487175349698139727945588
F#4693185370740148029605920
G (sol)4998196392784156831366272
G#52104208415831166133226645
A (La)55110220440880176035207040
A#58117233466932186537297459
B (Si)62123247494988197639517902
12345678
that creates vibrations when electricity is released. The downside is that
the sound isn't loud, but you can also play music if you manipulate it
carefully. The piezo buzzer is polar and should be connected to the (+)
pole by the side that reads (+) on the top or has a small groove dug.
The piezo buzzer is largely divided into active buzzer and passive
buzzer. The active buzzer has built-in circuits, so it is often used to
alert people as it makes only one sound of a certain frequency when
current flows. A manual buzzer is a buzzer that makes sound through a
tone function that can produce frequencies between 31 and 65535 Hz.
Beep~
Active Buzzer
Frequency by octave and pitches (in Hz)
Passive Buzzer
Each sound meter has its own frequency of shaking and should be predefined so that the frequency
(in units Herz HZ) value of the sound meter. Write the frequency required to play the melody by
defining it as the
function that gives a name to a constant value before a program compilation. Be careful not to put
"=" between the constant and the value, and not to use the semicolon at the end..
#define NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define
constant name value (e.g. #define NOTE_C1 33) before { }. #define is a
Let's learn how to save the pitches.h header file..
If you find it difficult to put a sound frequency value into a program each time, you can also
create a separate library of files for the sound frequency value. Let's learn how to create and store
a sound frequency file in a file called "pitches.h.".
Way 1. File > Preferences > Open the folder in the Sketchbook location..
Create pitches folder under libraries folder.
C:\Users\Test\Onedrive\Documents\Arduino
NameName
When you open the file > Example > 02. Digital > ToneMelody in the pitches folder, copy the pitches.h
on the right tab and save it as a file and make it a library.
The Beginner’s Guide 1st edition - Chapter 2- 8
6869
수정 -6월 5일.indd 68-692019-06-05 오후 6:19:23
Page 37
You can also edit and use it as needed. Bring up header file to #include "pitches.h" before void setup { }.
Way 2. New File > New Tab
Create a new tab by tapping the bottom
of the serial monitor icon..
Type pitches.h in the name for the new file and click OK..
When you open the file > Example > 02. Digital > ToneMelody, copy and paste the pitches.h on the right
tab to save. The pitches.h header file is stored in the same folder as the program. This file can also be
edited and used as needed. Stored header file is called #include "pitches. h" before void setup { }.
CAK Starter Code > 08_PassiveBuzzer
1/ * This sketch plays a note through a buzzer connected to pin 6.
2 * The * tone() function calls up the pitches.h header file to give a given frequency sound.
3 * Play a familiar 'school bell' song to us.
4 * In this sketch, the code is inserted in the setup part and played only once.
5 * If the loop part is coded, the performance may be repeated.
6 */
7
8#include"pitches.h"
9
10int buzzer=6; // Connect the Piezo buzzer to No. 6.
25tone(buzzer, melody[thisNote], noteDuration); // Connect the Piezo buzzer to No. 6
26 int pauseBetweenNotes =noteDuration *1.30; // phonetic delimiting
27 delay(pauseBetweenNotes); //delay
28noTone(buzzer); // Stop playing music
29 }
30}
31
32voidloop() {
33}
tone (pin number, sound frequency, sound duration);
Sound frequency: Hertz unit (Hz), rounded to the standard frequency to add an integer.
Sound duration: Milliseconds, unsigned long type, and optionally.
Only one note can be generated at a time.
The tone( ) function prevents PWM output on pins 3 and 11.
noTone (Pin Number);
Stop the waveform generated by tone( ).
In order to play different scales on different pins, you must call noTone before calling the next pin.
To make a sound of a specific frequency.
The Beginner’s Guide 1st edition - Chapter 2- 8
7071
수정 -6월 5일.indd 70-712019-06-05 오후 6:19:23
Page 38
8
CODING ARRAY CIRCUIT
Once the sketch is uploaded, you can check out the 'school bell' song. If you want to repeat the performance, you can insert the
code into the void loop.
Caution: passive buzzer can't produce frequency specific sounds.
Play the melody using the tone( ) function on the manual buzzer connected to digital pin 6..
View Results
7273
수정 -6월 5일.indd 72-732019-06-05 오후 6:19:25
Page 39
Let's find out about voltage distribution.
STARTER KIT FOR ARDUINO
codingarray
The array allows you to declare as many variables as in [ ]. If the length of the array is omitted in [ ],
the compiler will determine the length of the array by referring to the number of values in the list.
You can also initialize the values with the array declaration at the same time..
int array name [collection length]
The number of int variables is declared side by side.
Array name[0]=value1; store value1 on first element of array
Array name[1]value2; store value2 on second element of array
A number in [ ] is called an index, and the index value begins at zero..
int array name[ ] = {value1, value2, ... }
If the length of the array is omitted in [ ], the compiler will refer to the number of
values in the list.
Determine the length of the array.
You can also initialize the values with the array declaration at the same time..
Index
Array Name
The Beginner’s Guide 1st edition - Chapter 2- 8
7475
수정 -6월 5일.indd 74-752019-06-05 오후 6:19:25
Page 40
9
CHAPTER 2
Texting on 1602 I2C LCD
LCD (Liquid Crystal Display)
Piezo buzzer is a small speaker that makes sound using piezo effect that creates vibrations when electricity
is released. The downside is that the sound isn't loud, but you can also play music if you manipulate it
carefully. The piezo buzzer is polar and should be connected to the (+) pole by the side that reads (+) on
the top or has a small groove dug.
The piezo buzzer is largely divided into active buzzer and passive buzzer. The active buzzer has builtin circuits, so it is often used to alert people as it makes only one sound of a certain frequency when
current flows. A manual buzzer is a buzzer that makes sound through a tone function that can produce
frequencies between 31 and 65535 Hz.
Inter-Integrated Circuit Interface
The basic wiring for using a 1692 LCD uses a lot of digital pins, as shown in Figure
below..
The Beginner’s Guide 1st edition - Chapter 2- 9
But Arduino Uno has 14 digital input/output pins and six analog input pins. If you want to
connect other parts to Uno with 1602 LCD, there may not be enough connecting ports because it
requires a lot of pin connections.
To address these issues, the coding array starter kit uses the I2C interface module. The I2C
interface module has variable resistance that adjusts the clarity of the writing, so it does not have
to be connected to variable resistance..
Variable resistance for adjusting font clarity
The I2C interface module and 1602 LCD module are connected as shown in Figure above, and
the LCD can be removed and used as a normal 1602 LCD..
7677
수정 -6월 5일.indd 76-772019-06-05 오후 6:19:27
Page 41
I2C (Inter-Integrated Circuit) is an NFC that can
STARTER KIT FOR ARDUINO
codingarray
connect a 1 master (Arduino) : multiple slave (sensor
modules) in one direction using a SCL (Serial Clock)
pin and SDA (Serial Data) pin with full-up resistance
connected. Arduino can use SDA, SCL pins as I2C
communication pins or analog A4, A5 pins as functions
of SDA and SCL respectively. In the starter kit, the
SDA and SCL pins of the Uno board were placed for
easy selection with the slide switch in the center of the
Arduino Uno board.
CAUTION!
You cannot use the I2C communication interface and the A4, A5 pins at the same time
on the Arduino board. Therefore, the thermistor module and flame sensor module
cannot be used simultaneously with the I2C LCD in the starter kit. Therefore, when
using I2C LCD, define the module of use by placing the slide switch left and right as
shown in Figure below..
For I2C communication, the Wire library must be added. To add a library, click Sketch >
Include Library > Manage Libraries to run the Library Manager. Search for "I2C LCD" in the
search box and install "LiquidCrystal I2C by Frank de Brabander."
The Beginner’s Guide 1st edition - Chapter 2- 9
The default address is 0×27 (hexadecimal value), but sometimes an error
occurs when using a module, the address must be checked. Address scanning is
recommended first to find the address of the I2C LCD interface module you want to
use.
7879
수정 -6월 5일.indd 78-792019-06-05 오후 6:19:28
Page 42
CAK Starter Code > 09_01_1602LCD_AddressScanning
1/* This sketch is designed to use 1602 LCDs using I2C communication.
2 * Scans the address to show the results on the serial monitor.
3 */
4
5#include <Wire.h> // Includes the Wire Library for I2C communication.
6
7voidsetup() {
8Wire.begin();
9Serial.begin(9600); // Starts serial communication at 9600 speeds
10while(!Serial); // Wait for the serial monitor.
11Serial.println("\nI2C Scanner");
12}
13
14voidloop() {
15byte error,address;
16 int nDevices;
17Serial.println("Scanning...");
18 nDevices =0;
19
20for (address =1; address <127; address++) {
21// The i2c_scanner has determined whether the device has approved the address.
22 // Use the Write.endTransmission return value to know.
23Wire.beginTransmission(address);
24 error =Wire.endTransmission();
25
26if (error ==0) {
27Serial.print("I2C device found at address 0x");
28if(address<16)
29Serial.print("0");
30Serial.print(address,HEX);
31Serial.println(" !");
32 nDevices++;
33 }
34 else if(error==4) {
35Serial.print("Unknown error at address 0x");
36 if (address<16)
37Serial.print("0");
38Serial.println(address,HEX);
39 }
40 }
41 if (nDevices ==0)
42Serial.println("No I2C devices found\n");
43else
44Serial.println("done\n");
45
46delay(5000); // Wait five seconds for the next scan..
47}
Let's learn about the method used by LiquidCrystal_I2C.h..
LiquidCrystal_I2C lcd (0x27,16,2); The method under I2C communication address, 16-cand 2-line lcd object
creation is for example if the object was named lcd.
lcd.init();Initialize LCD.
lcd.backlight(); Turn on the LCD backlight.
lcd.noBacklight(); Turn off the LCD backlight.
lcd.setCursor(Rows);Sets the position of the cursor.
Print the text on the LCD screen.
lcd.print(data, BASE);
lcd.scrollDisplayLeft();Scroll text and cursors one space to the left
lcd.scrollDisplayRight();Scroll text and cursors one space to the right
lcd.noDisplay();
lcd.display();
lcd.autoscroll();Scroll text and cursors one space to the left
lcd.noAutoscroll(); Scroll text and cursors one space to the right
lcd.clear(); Clear the LCD screen and place the cursor in the upper left corner.
lcd.cursor();
lcd.noCursor(); Hide the LCD cursor.
lcd.rightToLeft();
lcd.leftToRight();
lcd.write(
lcd.createChar(number,data);
lcd.noBlink(); Turn off the blinking LCD cursor.
lcd.blink();Turn on the blinking LCD cursor.
lcd.home(); Position the cursor in the upper left corner of the LCD and output the string.
); Text is written on the LCD.
data
Data : Data to be printed, char, byte, int, long, stringable.
Characteristic data is displayed in "In"
BASE (Optional) : The standard by which a number is printed.
BIN (binary), DEC (decimal), OCT (8 decimal), HEX (16 decimal)
urn off the screen. The string on the face disappears, but the contents remain in
internal memory. lcd.display(); when a function is called, the string is revived.
Turn on the screen. lcd.noDisplay(); and lcd.display(); two functions can have a
flicker effect on the entire screen.
Indicates the underscore of the position in which the following characters are
written
Set the direction of the string used for the LCD from right to left. The default value
is left to right. It does not affect previously printed text.
Set left to right direction of string written to LCD. It does not affect previously
printed text.
Create a custom character to use for LCD. Up to 8 characters 5*8 pixels are
supported.
Numeric : Numbers from 0 to 7. Specify the number of characters to create.
Data: Pixel Data for Text
The Beginner’s Guide 1st edition - Chapter 2- 9
8081
수정 -6월 5일.indd 80-812019-06-05 오후 6:19:29
Page 43
Learn how to print characters on an LCD using method and how it works..
CAK Starter Code > 09_02_1602LCD_HelloCAK
1 /* This sketch shows Hello! ^ _ ^ ! Coding Array Kit for 1602 LCDs using I2C communication
2 * Show the string, using scrollDisplayRight and scrollDisplayLeft methods
3 * Scrolls to the left and right.
4 * Flashes the screen using noDisplay and discaly method to indicate that one loop is complete.
5 */
6
7#include <Wire.h>
8#include <LiquidCrystal_I2C.h>
9
10LiquidCrystal_I2C lcd(0x27,16,2); // Set the LCD I2C address. Use 16-kan2 line LCD.
11 // Put the scanned address instead of 0x27.
12voidsetup(){
13 lcd.init();
14 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
34 lcd.clear(); // Clear the screen before going to the next loop.
35}
The Beginner’s Guide 1st edition - Chapter 2- 9
8283
수정 -6월 5일.indd 82-832019-06-05 오후 6:19:30
Page 44
CAK Starter Code > 09_04_1602LCD_TextDirection
CAK Starter Code > 09_05_1602LCD_CustomCharacters
1/* This sketch shows that 1602 LCD uses I2C communication.
2 * Show one alphabet from a to Z.
3 * 'a through l' is written from left to right.
4 * 'm through r' is written from right to left
5 * 's through z' causes text to appear from left to right again.
6 */
7
8#include <Wire.h>
9#include <LiquidCrystal_I2C.h>
10
11LiquidCrystal_I2C lcd(0x27,16,2); // Set the LCD I2C address. Use 16 Space 2-line LCD.
12
13int thisChar ='a'; // thisChar Save
14
15voidsetup(){
16 lcd.init();
17 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
18 lcd.cursor(); // Turn on the cursor.
19}
20
21void loop(){
22 if(thisChar =='m') { // If thisChar is m, change direction.
23 lcd.rightToLeft(); // From the next letter, mark to the left.
24 }
25
26 if(thisChar =='s') { // If thisChar is s
27 lcd.leftToRight(); // From the next letter, mark to the left.
28 }
29
30if(thisChar >'z') { // When thisChar is out of z,
31 lcd.home(); // Go to (0,0)
32 thisChar ='a'; // Restart from the beginning
33 }
34
35 lcd.write(thisChar); // Indicate thisChar value on LCD.
36 delay(1000); // for a second
37 thisChar++; // increase thisChar value one by one
38}
1 /* This sketch shows that 1602 LCD uses I2C communication.
2 * Set up a special character or Figure to "I ♥ Array Kit !" and smile on the first line of the LCD.
3 * In the second row, the shape of a person who raises and lowers his or her arms is displayed.
4 * Learn how to indicate that the value of A0 variable resistance is constant.
5 */
6
7#include <Wire.h>
8#include <LiquidCrystal_I2C.h>
9
10LiquidCrystal_I2C lcd(0x27,16,2); // Set the LCD I2C address. Use 16 Space 2-line LCD.
11
12// Create special characters
13byte heart[8] ={
14 0b00000,
15 0b01010,
16 0b11111,
17 0b11111,
18 0b11111,
19 0b01110,
20 0b00100,
21 0b00000
22};
23
24byte smiley[8] ={
25 0b00000,
26 0b00000,
27 0b01010,
28 0b00000,
29 0b00000,
30 0b10001,
31 0b01110,
32 0b00000
33};
34
35byte frownie[8] ={
36 0b00000,
37 0b00000,
38 0b01010,
39 0b00000,
40 0b00000,
The Beginner’s Guide 1st edition - Chapter 2- 9
8485
수정 -6월 5일.indd 84-852019-06-05 오후 6:19:30
Page 45
41 0b00000,
42 0b01110,
43 0b10001
44};
45
46byte armsDown[8] ={
47 0b00100,
48 0b01010,
49 0b00100,
50 0b00100,
51 0b01110,
52 0b10101,
53 0b00100,
54 0b01010
55};
56
57byte armsUp[8] ={
58 0b00100,
59 0b01010,
60 0b00100,
61 0b10101,
62 0b01110,
63 0b00100,
64 0b00100,
65 0b01010
66};
67
68voidsetup(){
69 lcd.init();
70 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
71
72 // Define New Characters
73 lcd.createChar(0,heart);
74 lcd.createChar(1,smiley);
75 lcd.createChar(2,frownie);
76 lcd.createChar(3,armsDown);
77 lcd.createChar(4,armsUp);
78
79 lcd.setCursor(0,0); // first line first column
80// Write text to LCD
81 lcd.print("I ");
82 lcd.write(byte(0)); // Use a heart that is stored at 0 bytes..
83 lcd.print(" Array Kit! ");
84 lcd.write((byte)1); // Use a smiley stored in one byte..
85}
86
87voidloop(){
88int sensorReading = analogRead(A0); // Read the variable resistance value of A0.
89int delayTime = map(sensorReading,0,1023,200,1000); // Map resistance values from 200 to 1000
90 lcd.setCursor(4,1); // Set the cursor to the bottom 5th position
91 lcd.write(3); // Draw a person with his arm down on number 3.
92delay(delayTime); // Delay by variable resistance value
93 lcd.setCursor(4,1); // Set the cursor to the bottom 5th position
94 lcd.write(4); // Draw the person with the arm up stored in number 4.
95delay(delayTime); // Delay by variable resistance value
96}
byte Save the 8-bit signless number from 0 to 255
The shape of each user-defined character consists of 5×8 dots. Each row is specified
in an array of eight bytes, one by one, and each row is defined as a hexadecimal.
Assuming that you make a heart, you can set it as follows:
Special characters specified in the array are defined as lcd.createChar (number, data).
The numbers can then be defined by a total of eight characters from 0 to 7, and the
data can be named after the array. lcd to output user-defined characters to LCD.use
a number.
The Beginner’s Guide 1st edition - Chapter 2- 9
8687
수정 -6월 5일.indd 86-872019-06-05 오후 6:19:31
Page 46
9
CODING ARRAY CIRCUIT
You can adjust the rate of special character change in the second row by adjusting the variable resistance of the slide
Print out characters using the I2C interface module, which controls 1602 LCDs consisting of 2 rows wide and 16 spaces with SDA (Serial
Data, A4) and SCL (Serial Clock, A5), as well as GND, and 5 volt total..
1/* This sketch shows that 1602 LCD uses I2C communication.
2Try printing the entered characters in the serial window.
3*/
4
5#include <Wire.h>
6#include <LiquidCrystal_I2C.h>
7
8LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address. Use 16 Space 2-line LCD.
9
10voidsetup() {
11 lcd.init();
12 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
13
14
Serial.begin(9600); // Starts serial communication at 9600 speed
15
}
16
17voidloop() {
18 if (Serial.available()) { // When the text arrives on the serial communication,
19delay(100); // Wait 0.1 seconds for the entire message to arrive.
20 lcd.clear(); // Clear the screen.
21 while (Serial.available() > 0) { // while the text is coming in
22 lcd.write(Serial.read()); // Write the characters you read on the LCD.
23 }
24 }
25}
Serial.
available(); returns the number of data when received by serial communication.
Returns zero if no data has been received.
Serial.
read();to read data entering the serial by 1 byte and return it to the decimal (constant)
ASCII code value. Returns –1 if the receive buffer is empty.
View Results
Send
When you enter and transfer data in the serial window, the data is output on the first line of the LCD.
If you enter more than 16 data, only 16 will appear in the first line..
Let's find out about While Sentence.
while {execution code; }
'While' is one of the repeats used to give the same
command over and over, like 'for'. 'While statement' is a
structure that gives a certain repeat condition and repeats
the execution code while satisfying the condition. For
statement lists the multiplication table under the iterative
conditions, but in the whle statement, the multiplication
ceremony is placed in the execution code..
conditions
Truth
If execution code
Truth
Falsehood
The Beginner’s Guide 1st edition - Chapter 2- 9
lcd.write(
It is represented by converting it to a letter using lcd.write.
If you write lcd.print, the number of Aski codes will be output.
Serial
.read());data entered into the serial are passed in aske code numbers.
9091
수정 -6월 5일.indd 90-912019-06-05 오후 6:19:33
Page 48
Distance measurement with
velocity =
Distance
time
, time=
Distance
velocity
, Distance =v elocity× time
Sound speed=340+0.6×(current temperature-15)
STARTER KIT FOR ARDUINO
codingarray
10
CHAPTER 2
ultrasonic sensor
Ultrasonic Distance Module
Ultrasonic is a type of sound wave, which is the
sound wave of a frequency (>20KHz) area
that is higher than the area that a person can hear.
Ultrasonic sensors can calculate the distance using
the time it takes for sound waves to return to an
Pin D5 Pin D4
Ultrasonic sensors have two speakers that look like
speakers. One side has to produce ultrasonic waves
with digital output HIGH and then stops ultrasonic
waves with LOW. Ultrasonic sensors used in the
starter kit will use a pulse width of 10 μs and
therefore maintain the HIGH for 10 μs. The other
is the role (Echo) of detecting ultrasonic waves reflected on an object. To detect the
return of ultrasound, make sure that the reflector and the ultrasonic sensor are at right
angles
Distance
TimeSpeed
Ultrasonic waves can be generated from the trig pin of the ultrasonic sensor and obtained by
means of the reciprocating distance, reciprocating time and sound velocity reflected on the
barrier..
Distance, velocity and time form the following formular
obstacle that is close to 3-400 cm..
In Arduino, the time it takes for the ultrasound to return is in microseconds (), so the distance
can be obtained in cm after the unit conversion..
At this point, the speed of sound is about 340 m/s at 15°C, and as the temperature
rises by 1°C, the speed of 0.6 m/s increases. Therefore, it may be used with the
following corrections:.
The Beginner’s Guide 1st edition - Chapter 2- 10
Using the principles of ultrasonic sensors, one can measure a key or measure a
distance to an obstacle in front of one. It is also possible to implement a parking
system by sensing that the parking space is empty or parked, such as a parking lot in
a large shopping mall. Ultrasonic waves are also used to examine the condition of the
human organs or to identify deep undersea terrain, as the density of the medium that
transmits sound is higher. In vacuum, there is no medium, so distance measurements
using ultrasonic waves are not allowed..
9293
수정 -6월 5일.indd 92-932019-06-05 오후 6:19:34
Page 49
CAK Starter Code > 10_Ultrasonic_Distance
1/ * This sketch uses ultrasonic sensors to measure the distance.
2 * The trigger pin is connected to Arduino's number 5. The trigger pin produces ultrasonic waves.
3 * Echo pins are connected to Arduino's number 4. The echo pin detects reflected ultrasound.
4 * The measured distance should be shown in both the serial and LCD windows.
5 * If the measured distance exceeds the set value, the green LED,
6 * If the measured distance exceeds the set value, turn on the red LED.
7 */
8
9#include <Wire.h>
10#include <LiquidCrystal_I2C.h>
11
12LiquidCrystal_I2C lcd(0x27,16,2); // Set the LCD I2C address. Use 16 Space 2-line LCD
13
14int redLED = 13; // Red LED No. 13
15int greenPin=10; // Green LED No. 13
16int threshold = 15; // Set Distance Threshold Value
64delay(2000); // 2000 millisecond delay to reliably read values
65}
float Duration, Distance;
pulseIn (Pin number, Value, timeout);
if (Distance < threshold){ // If the measurement distance is less than the threshold value, turn on the
red LED.
A variable with the same type of data can be declared at once..
Measure the amount of time it takes to return after a
pulse occurs.
Pin number :
Value
timeout (optional) :
pin number to read the pulse
: Type of pulse to read. HIGH or LOW
The time (microseconds) to wait for the pulse to start, and the
length of the pulse (unshinged long) in microseconds.
Returns zero if the pulse does not start within the specified timeout.
It can operate from 10 microseconds to 3 minutes.
pulseIn (echoPin, HIGH)
; when the value of echoPin reaches HIGH, start the timer
and return the time that HIGH is maintained.
((float)(340 *Duration) /10000) /2;
Since the calculation result is a true type with a decimal
point, attach the data type as float.
The Beginner’s Guide 1st edition - Chapter 2- 10
9495
수정 -6월 5일.indd 94-952019-06-05 오후 6:19:34
Page 50
10
CODING ARRAY CIRCUIT
Once the program is uploaded, you can see that the green LED illuminates when the obstacle is more than
15cm apart in front of the ultrasonic sensor, and that the red LED turns on when the obstacle is less than
The trigger that produces ultrasonic waves is connected to digital No. 5 and the echo that detects reflected ultrasonic waves is
connected to digital No. 4. Using the principles of ultrasonic sensors, measure the distance to the obstacle in front.. .
View Results
9697
15cm away.
수정 -6월 5일.indd 96-972019-06-05 오후 6:19:35
Page 51
CAK Starter Code > 11_HallEffect
11
CHAPTER 2
Detecting Magnetics with a Hall Sensor
Magnetic Sensing Hall Sensor (Hall Effect Module)
Magnetic Field
Detection
Power LED
Hall Effect (Hall Effect) A conductor is placed
in a magnetic field, and the flow of current in
a direction perpendicular to both the magnetic
field and the electric current in the conductor
creates electromotive force in that direction,
which is published by the potential difference
in this direction, was discovered by the
American physicist Hall (E. H. Hall).
The magnetic sensing sensor can be used to check the magnetic field of the conductor to
act as a switch or to detect the rotational speed, position and current of the motor. It is
used variously in real life such as the speed measured on a car's instrument panel, the speed
measured on a treadmill, and the door switch on a washing machine or refrigerator.
Magnetic sensing hole sensor is a device that changes
internal resistance according to strength of external
magnetic field by using Hall Effect principle. The
closer and stronger the magnetic field, the higher the
output voltage. There are two types of Hall sensors:
Digital Hall sensors and Analog Hall sensors.
igital hall sensors can only detect whether or not a
magnetic field exists, and analog hall sensors can detect
the magnetic field poles as well as the strength of the
magnetic field with linear hall effects. Analog hall sensor
module is used in array kit. As the S-pole approaches
the front of the hall sensor, the voltage becomes close
to 5 V, and the N-pole can be closer to the lock0
V, indicating the strength and poles of the upcoming
magnetic field..
1 /* This sketch uses the Hall Effect module connected to Analog A2.
2 * Read the value of the analogue sensor which varies with the surrounding magnetic field
3 * Measure the strength of the magnetic field by converting it to voltage.
4 * This module has a lower output voltage as the N pole approaches and a higher output voltage as the S pole approaches.
5 * Outputs a comma-separated serial message for easy transfer of result values to Excel.
6 * Copy the message from the serial window and paste it into the memo pad.Save as CSV" extension
7 * You can create a file that can be retrieved from Excel.
8*/
9
10// set up for LCD use
11#include <Wire.h>
12#include <LiquidCrystal_I2C.h>
13LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address. Use 16 Space 2-line LCD
14
15const int hallPin = A2; //connect hall sensor to A2 pin
16int sensorReading; // Store analog sensor values
17int voltage; // Store the converted value to voltage
18
19voidsetup() {
20Serial.begin(9600); // Set communication speed to 9600
21Serial.println("sensorReading, Voltage (mv)"); // Output message for csv file in serial window
22
23 // LCD initialization
24 lcd.init();
25 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
26delay(1000);
27}
28
29voidloop() {
30 sensorReading = analogRead(hallPin); // Read and save the analog value of the sensor
31 voltage = sensorReading * (5.0 / 1024.0) * 1000; // Convert Analog Values from Voltage0 to 5000
32
33 // csv (when you want to receive data in comma-separated text format)
34Serial.print(sensorReading);
35Serial.print(",");
36Serial.println(voltage);
37
38 // Output a message in an LCD window
39 lcd.clear();
40 lcd.setCursor(0, 0); // first line first column
41 lcd.print("Anlaog_V :");
42 lcd.print(sensorReading);
43 lcd.setCursor(0, 1); // 2nd line first column
44 lcd.print(voltage);
45 lcd.print(" mV");
46delay(500);
47}
The Beginner’s Guide 1st edition - Chapter 2- 11
9899
수정 -6월 5일.indd 98-992019-06-05 오후 6:19:36
Page 52
11
After the program uploads, the LCD screen outputs
analog input values (approximately 506) and
conversion voltages (approximately 2470 mV)
when no magnetic field is detected. The closer the
N pole of the magnet is to the magnetic sensing
sensor, the smaller the analog input value, and the
closer the S-pole, the larger the analog input value..
In this example, let's move the data that appears in
the serial window to Excel. Outputs data separated
by commas, drags and copies the results shown in
the serial window..
CODING ARRAY CIRCUIT
Analog magnetic sensing sensor module is connected to A2 pin. You can check the analog output value that changes as the
N pole and S pole of the magnet approach the sensor. It also looks at moving serial output data to Excel.
Edit Format View Help
Untitled - Notepad
File
sensorReading, Voltage (mv)
508,2480.47
507,2475.59
Ctrl+S
Ctrl+N
Ctrl+O
New
Open...
Save
507,2475.59
507,2475.59
507,2475.59
508,2480.47
Save As...
Page Setup
508,2480.47
508,2480.47
506,2470.70
Ctrl+P
Print...
Exit
508,2480.47
507,2475.59
508,2480.47
508,2480.47
Attach this result value to Notepad and save it with a csv extension, such as file >Save
As>result.csv. Open the csv extension file in Excel and use it.
View Results
100101
수정 -6월 5일.indd 100-1012019-06-05 오후 6:19:38
Page 53
STARTER KIT FOR ARDUINO
codingarray
12
CHAPTER 2
Photoresistor
Learn how to use light sensing sensors to detect
light intensity and calibrate sensor values
Photoresistor
Light sensing resistance sensors are called by a
variety of names such as light sensors, light sensing
sensors, photoresistors, LDR (Light Dependent
Power LED
Resistors), Cadmium Sulfide (CdS), CdS Cells, CdS
Photoresistors, Photometric Cells and Photocorel. As
the intensity of light increases, the resistance value
decreases, and the intensity of light can be measured
by increasing the resistance value.
voltage distribution of between 0 and 5 volts between the resistance of the light
sensor and the resistance of the 10 KΩ resistance and the intensity of the light..
The other, which utilizes a large resistance of 10KΩ, is that measuring light in a
very bright area can cause the resistance value of the light sensor to be very small,
allowing over-current to flow to the analog input pin, which can also be prevented.
The resistance values vary depending on the type
of light sensor, but usually have a range of 5 KΩ
(when light) to 200 KΩ (when dark) and show
a nonlinear relationship between resistance and
intensity of light, as with the following Figure.
Light sensors can measure the change in value
due to the intensity of light at low prices, and
have various advantages, such as night lighting
or lighting sensing devices that control the speed
of the camera shutter. However, resistance may vary with temperature, and there is a
time difference between the change in intensity of light and the change in resistance. It
also has less light sensitivity than photo diode or photo transistor. Therefore, it is not
suitable for use in places where rapid changes in light or intensity of light need to be
accurately measured, and is suitable for determining only bright and dark levels..
As Arduino reads voltage values rather than resistance values,
the resistance of the light sensor must be calculated using a
Photoresistor
voltage distribution scheme. In order to calculate the voltage
entering the sensor using a voltage distribution scheme, the
circuit should be constructed with two resistors that know
the resistance and size of the sensor. The light sensor is
connected in series with a 10KΩ resistance. This causes a
Resistance
Power of Light
The Beginner’s Guide 1st edition - Chapter 2- 12
102103
수정 -6월 5일.indd 102-1032019-06-05 오후 6:19:38
Page 54
CAK Starter Code > 12_01_Photoresistor
1/ * This sketch measures the brightness of light using a light sensing sensor.
* A1 pin connected to the light sensing sensor enters an analog input value between 0 and 1023,
2
depending on the brightness of the light.
3 * Analog input values are divided into 0 - 3 4 steps through map function and used for switch-case.
4 */
5
6// Settings for LCD use
7#include <Wire.h>
8
#include <LiquidCrystal_I2C.h>
9LiquidCrystal_I2C lcd(0x27,16,2); // Set the LCD I2C address. Use 16 space 2 line LCD.
10
11const int photoresistorPin=A1; // connect the light sensor to the A1 pin
12const int sensorMin =0; // Minimum sensor value found by experiment, can be modified.
13constint sensorMax =700; // Maximum sensor value found by experiment, can be modified.
14
15voidsetup() {
16 lcd.init(); // LCD initialization
17 lcd.backlight(); // Turn on the backlight. (lcd.noBacklight() turns off the backlight.)
18 lcd.setCursor(0,0); // first line first column
19 lcd.print("Range : "); // Message Output
20
21Serial.begin(9600); // Starts serial communication at 9600 speeds
22}
23
24voidloop() {
25// Read sensor values to map ranges
26
int sensorReading =
27Serial.println(sensorReading);
28int range = map (sensorReading,sensorMin,sensorMax,0,3); // Map the sensor values from 0 to 3.
29
30// output messages according to sensor range
31switch(range) { // according to range 0-3
32case 0: // touch the sensor and when the sensor value is zero,
33Serial.println("DARK"); // Darkprint and replace lines in the serial window
34 lcd.setCursor(9,0); // the ninth column of the first line
35 lcd.print(range); // indicate brightness phase on LCD window
36 lcd.setCursor(0,1); // the first column of the second line
analogRead
(photoresistorPin);
// Read the light sensor value from the A2 pin
37 lcd.print("DARK"); // DARK Output
38break;
39
40case 1: // Put your hands close to the sensor and when the sensor value is 1,
41Serial.println("DIM"); // Dimprint and replace lines in serial window
42 lcd.setCursor(9,0); // the ninth column of the first line
43 lcd.print(range); // indicate brightness phase on LCD window
44 lcd.setCursor(0,1); // the first column of the second line
45
46break;
47
48case 2: // Keep your hands away from the sensor and when the sensor value is 2
49Serial.println("MEDIUM"); // print medium on serial window and replace lines
50 lcd.setCursor(9,0); // the ninth column of the first line
51 lcd.print(range); // indicate brightness phase on LCD window
52 lcd.setCursor(0,1); // the first column of the second line
53 lcd.print("MEDIUM"); // MEDIUM Output
54break;
55
56case 3: // When the sensor value is 3 without touching the sensor nearby,
57Serial.println("BRIGHT"); // print the lightprint on the cereal window and replace the line
58 lcd.setCursor(9,0); // the ninth column of the first line
59 lcd.print(range); // indicate brightness phase on LCD window
60 lcd.setCursor(0,1); // the first column of the second line
61 lcd.print("BRIGHT"); // BRIGHT Output
62break;
63 }
64delay(50); // 50 millisecond delay to reliably read values
65}
constrain(x, a, b);
lcd.print("DIM"); // DIM output
Measure the amount of time it takes to return after a pulse occurs.
x : number of restrictions, a : lower range, b : upper range, x, a, b are all data types
Return x value if x is a value between a and b, return a value if x is less than a,
Returns the b value if x is greater than b
constrain(sensorValue, 0, 255);
Returns 0 value if sensorValue value is less than 0; returns 255 if sensorValue
value is greater than or equal to 255.
Restrict the scope of 0 and 255.
The Beginner’s Guide 1st edition - Chapter 2- 12
104105
수정 -6월 5일.indd 104-1052019-06-05 오후 6:19:38
Page 55
12
CODING ARRAY CIRCUIT
Using a light sensing resistance sensor connected to the analogue A1 pin, control the LED output according to the intensity of
the light, and learn about the calibration of the analog sensor values.
When the program is uploaded, the light sensor detects the light and divides the amount of light into four stages to display the
results in an LCD window. Touch the light sensor and observe the results as you keep away from it..
sensorValue = constrain(sensorValue, 0, 255); // limit if sensor value is outside calibration
range
analogWrite(bluePin, sensorValue); // adjust the LED brightness with the calibrated value.
// calibrate() function setting: Reset the maximum and maximum values of the sensor according to
the ambient brightness.
The Beginner’s Guide 1st edition - Chapter 2- 12
112113
수정 -6월 5일.indd 112-1132019-06-05 오후 6:19:42
Page 59
12
Once the program is uploaded, you can start
CODING ARRAY CIRCUIT
Insert code that runs
calibrating the sensor while holding down the
button switch. When the button switch is pressed,
the "Calibration START" message appears in the
LCD window, and a correction function is invoked
when you touch the light sensing sensor and
then gradually move away. When you release the
button switch, the message "Calibration END"
appears to end the calibration. You can see that
the blue LED's brightness changes depending
on the amount of light detected by the light
sensing sensor after the calibration operation.
The calibration function can be called by pressing
the button switch to make it easier to calibrate
each time the surrounding environment changes.
It is possible to recognize the ambient brightness
and to implement a smart street lamp that
illuminates when the amount of light entering the
light sensor is below a certain value. Smart street
lamps not only reduce the effort to turn street
lights on and off, but also save electricity..
Function can be declared above or below the loop()
function and called using the function name during code
parameter is not required, leave ( ) blank.
{ Function body; return value; } :
within the actual function.
return : has the function of ending function and return
result value.
If you return the function result value, write the return
value.
If the return type is void, return ; can be written or
omitted.
}
{ digitalWrite(redLED, HIGH);
execution..
Let's learn about the use of functions..
Set as a name that represents the characteristic
: Set type to return result value of function
void calibrate( )
When you write a program, you create and write a 'function'
to organize the program by performing the same task several
times, having to be reused by another program, or creating a
View Results
114115
수정 -6월 5일.indd 114-1152019-06-05 오후 6:19:43
modular piece of code. The function is defined as follows
Return typeName(Parameter){ body }
Return type
void : indicates no return value.
Function name :
Put the factors to be used in the function. If there
of the function
(parameter) :
are multiple parameters, the order must also be observed. If the
Page 60
changes from on to off
13
CHAPTER 2
Detect flame with flame detection sensor
I2C (Inter-Integrated Circuit) is an NFC that can
connect a 1 master (Arduino) : multiple slave (sensor
modules) in one direction using a SCL (Serial Clock)
pin and SDA (Serial Data) pin with full-up resistance
connected. Arduino can use SDA, SCL pins as I2C
communication pins or analog A4, A5 pins as functions
of SDA and SCL respectively. In the starter kit, the
SDA and SCL pins of the Uno board are conveniently
placed with a slide switch in the center of the Arduino
Uno board
CAUTION!
You can not use the I2C communication interface and the A4, A5 pins at the same
time on the Arduino board. Therefore, the thermistor module and flame sensor module
cannot be used simultaneously with the I2C LCD in the starter kit. Therefore, when
using I2C LCD, define the module of use by placing the slide switch left and right as
shown in Figure below..
Flame Sensor
Infrared sensor
in photo transistor (Phototransistor) and the output voltage increases as the amount of light
detected increases . The flame detection sensor has an infrared sensing sensor unit that is
covered with a black epoxy that looks like an LED. Because of its polarity, the sensor has long
legs (+) poles and short legs (-) connected.
Infrared sensor
change in resistance. It also has less light sensitivity than photo diode or photo transistor.
Therefore, it is not suitable for use in places where rapid changes in light or intensity of light
need to be accurately measured, and is suitable for determining only bright and dark levels..
CAUTION!
Sensitivity control
variable resistance
located at the point
where the output LED
Output LED
Power LED
Pin A5
(-)
Short leg
(+)
Long leg
There are many types of flame detection sensors connected
to analog A5 such as ultraviolet flame detection, infrared
flame detection and IR3 flame detection. The infrared
flame detection sensor used in the coding array kit detects
wavelengths in the infrared LEDs in the range of 760 to
1100nm from flames or light sources within an angle of
60° and converts them into electrical signals. The sensor
is also called a collector (Collector ,+polar connection),
and a short leg is called an emitter ( -polar connection)
It is connected to A2 pin when module is combined, but can
be used as a digital sensor by
connecting D and digital pin after module is disconnected.
es that control the speed of the camera shutter. However,
resistance may vary with temperature, and there is a time
difference between the change in intensity of light and the
The Beginner’s Guide 1st edition - Chapter 2- 13
The A4, A5 analogue pins cannot be used simultaneously with the SCL and SDA pins of I2C,
●
so they must be fitted with a jumper at "A5 Jumper" to use the flame detection sensor.
When using flame sensors, it is not possible to display the output on the LCD.
●
There are many types of fire detectors, such as heat sensing, smoke detection and flame detection.
Double flame detection is installed in a space with high ceilings and external cultural properties,
which are difficult to detect heat or smoke, to detect and operate infrared or ultraviolet radiation
generated from the flame in case of fire.
In this example, if a flame is detected within 60° using a flame detection sensor,
the piezo buzzer will sound an alarm.
116117
수정 -6월 5일.indd 116-1172019-06-05 오후 6:19:43
Page 61
CAK Starter Code > 13_FlameSensor
STARTER KIT FOR ARDUINO
codingarray
1/* This sketch uses the flame sensor module connected to analogue A5.
2* Detects flame strength around (prepare lighter and bring flame near module)
3* If the threshold value set is exceeded, an audible alarm will be
9int Buzzer =6; // connect the piezo buzzer to pin 6.
10int sensorReading =0; // Variables for storing sensor output values
11
12voidsetup() {
13pinMode(Buzzer, OUTPUT); // Output settings for piezo buzzer pins
14pinMode(flameSensor, INPUT); // set flame sensor pin to input
15
Serial.begin(9600); // initiate serial communication at 9600 speed
16}
17
18voidloop() {
sensorReading = analogRead(flameSensor); // save an analogue value of the flame detection
19
sensor
Serial.println(sensorReading); // Print the value of the flame detection sensor to the serial
20
window
21 if(sensorReading <=1000) { // flame detection sensor value greater than 1000
22Serial.println("Fire !!"); // Fire! Outputs on screen
23 playTone(); // Alarm negative
24 } else { // If flame detection sensor value is less
25noTone(Buzzer); // off Peugeot Booger
26 }
27delay(500); // 0.5 second interval
28}
29
30// set alarm negative function
31void playTone() {
32float sinVal; // save the sine wave value
33int toneVal; // store value for alarm sound generation
34
35for(int i =0 ; i < 180; i++) {
36
37 toneVal = 2000+(int(sinVal * 1000)); // translate alarm to frequency
38tone(Buzzer,toneVal); // frequency generated from Peugeot speakers
39delay(10); // alarm sound frequency rate adjustment
40 }
41}
sinVal =sin(i * PI/180); // calculate the sin value by changing the angle to the radian
value
#define PI 3.141592 Define the value of the circumference π.
sin(rad) Calculate the Sin value of the radian angle. -1≤ sin(rad)≤ 1 range.
Rad :Radian angle, actual type
Loudness Method: To display angles using arc length
The Beginner’s Guide 1st edition - Chapter 2- 13
118119
수정 -6월 5일.indd 118-1192019-06-05 오후 6:19:44
Page 62
13
Send
Clear output
9600 baud
Autoscroll
CODING ARRAY CIRCUIT
After uploading the sketch, bring the lighter flame near the flame sensor (if the lighter is not available,
replace it with an infrared remote control at home). If a flame is detected within about 10cm, it indicates
an analog value of less than 1000 and the manual buzzer produces a sin-wave alert.
After module removal, digital pins can be connected to D and used as digital sensors. If the flame is not
detected, it will return "0" or "1" if the flame is detected. The sensitivity of the sensor is adjusted by rotating
If a flame is detected using a flame detection sensor connected to the analogue A5 pin, use the manual buzzer connected to
the digital No. 6 pin to sound the alarm..
View Results
120121
수정 -6월 5일.indd 120-1212019-06-05 오후 6:19:45
the variable resistance on the board.
Page 63
14
CHAPTER 2
Temperature measurement
with NTC thermistor
I2C (Inter-Integrated Circuit) is an NFC that can
connect a 1 master (Arduino) : multiple slave (sensor
modules) in one direction using a SCL (Serial Clock)
pin and SDA (Serial Data) pin with full-up resistance
connected. Arduino can use SDA, SCL pins as I2C
communication pins or analog A4, A5 pins as functions
of SDA and SCL respectively. In the starter kit, the
SDA and SCL pins of the Uno board are conveniently
placed with a slide switch in the center of the Arduino
Uno board
CAUTION!
You cannot use the I2C communication interface and the A4, A5 pins at the same time
on the Arduino board. Therefore, the thermistor module and flame sensor module
cannot be used simultaneously with the I2C LCD in the starter kit. Therefore, when
using I2C LCD, define the module of use by placing the slide switch left and right as
shown in Figure below..
NTC Thermistor (Negative Temperature Coefficient Thermistor)
There are many types of temperature sensors and they can
Thermistor
Power LED
Thermistors are divided into NTC (Negative Temperature Coefficient) using properties that
reduce resistance values as temperatures rise and PTC (Positive Temperature Efficient) using
properties that increase resistance values as temperatures rise..
Resistance
STEP 01
Thermistors indicate temperature due to changes in electrical resistance. However, the analog input
pins of the Arduino board measure voltages other than resistance. Therefore, the resistance of the
thermistor should be converted to voltage using the voltage distribution method. Series connection
between Ohm's law and resistance (current flowing to each resistor is the same. The following
expressions can be derived using the addition of two resistors). Use known resistance R=10KΩ,
Rt= thermistor to use voltage divider circuits. V0 is measured at A4..
The Relationship between
Resistance of thermistor
and Temperature
Temperature
Voltage distribution
CAUTION!
be divided into analog temperature sensors and digital
temperature sensors. The array kit used NCT thermistor
as an analogue temperature sensor for analog A4 pins.
Thermistor is a composite of Thermal + Resistor, an
electrical element with a properties in which the resistance
of a substance varies with temperature. A thermistor
thermometer is usually used at –50°C to 350°C.
Three steps are taken to indicate the temperature due to the
change in thermistor's electrical resistance.
Step1) On the analog input A4 pin to which the thermistor
is connected, measure the voltage using the voltage
distribution method.
Step2) Convert voltage to resistance.
Step3) Convert resistance to temperature
The Beginner’s Guide 1st edition - Chapter 2- 14
Vs: Full Voltage
Vo: Voltage to 10KΩ resistance
I: Total Current
R: 10KΩ resistance
Rt: thermistor resistance
122123
수정 -6월 5일.indd 122-1232019-06-05 오후 6:19:46
Page 64
STEP 02
Convert voltage to resistance.
If you organize the above expression for Rt and indicate the resistance value of the thermistor
STEP 03
Convert resistance to temperature.
There are two main ways to measure the resistance value of the thermistor and convert it to
temperature.
The first <Shenhart-Hart>
T: Kelvin temperature (absolute temperature)
R: Resistance value at temperature T
A, B, and C: Known constants derived from resistance values according to the three
temperatures
Second <B or β parameter >
NTC thermistors are inexpensive, small, responsive, and have a large coefficient of resistance to
temperature, which can be used for precise temperature measurements. It is used for industrial
equipment, home appliances, remote weather observation, and home automation system
equipment.
CAK Starter Code > > 14_01_Thermistor_SH
1/* This sketch converts the voltage distributed to the thermistor connected to the A4 into a resistor.
2 One of the ways to change the resistance value to temperature
3 Use the Steinhart-Hart formula to calculate the temperature.
4 The A4 pin and I2C LCD module cannot be used together and must be selected as a jumper.
5*/
6
7#include <math.h>
8
9const int thermistorPin = A4; // connect thermistor to A4 pin
10
11// parameters can vary the value depending on the module.
12double ParamA = 0.001129148;
13double ParamB = 0.000234125;
14double ParamC = 0.0000000876741;
15
16voidsetup() {
17Serial.begin(9600); // initiate serial communication at 9600 speeds
18}
19voidloop() {
20int readVal = analogRead(thermistorPin);
21double temp = Thermistor(readVal); // recall temperature measurement function
22double tempC = temp - 273.15; // Convert Absolute Temperature to Celsius
23double tempF = (tempC * 9.0) / 5.0 + 32.0; // Convert temperature to Fahrenheit
24
25 // Output Serial Monitor
26 //Serial.println(readVal);
27Serial.print(tempC); // display temperature
28Serial.println(" C");
29delay (500);
30}
31// set Steinhart-Hart temperature measurement function
26 // Serial.println(readVal); // output analog values read from Serial.println(readVal); A4
27Serial.print(tempC); // temperature output
28Serial.println(" C"); // output units
29
30delay(1000); //1 second delay
31}
31// set Steinhart-Hart temperature measurement function
The Beginner’s Guide 1st edition - Chapter 2- 14
When you upload a sketch, you can see the result of converting the resistance value of the
thermistor to temperature using the B parameter expression..
128129
수정 -6월 5일.indd 128-1292019-06-05 오후 6:19:49
Page 67
15
CHAPTER 2
Detect sound with microphone sensor
MIC Sensor
MIC
Sensitivity
Control
Potentiometer
Output LED
Power LED
When energized, the power lamp turns on and the output LED turns on when the
sound is detected. Turn the sensitivity controlled variable resistance to adjust it to
the moment when the output LED turns into a load
You can use sound sensors to create LED lights that
respond to the volume size of your speakers, or to turn the
lights on and off by recognizing clapping sounds.
Sound sensors are also called sound sensors,
microphone sensors, or sound sensors. This is a
device that collects sound from the surrounding area
through a microphone, enters the LM386 amplifier
and measures it in size (db, decibels) regardless of the
low (frequency) of the sound. Note, however, that
there is no linear relationship between the decibel
size of the actual sound and the analog input value.
CAK Starter Code > 15_MIC_Clap_ONOFF
1/* This sketch turns on the LED when you clap twice.
2* Shows the LED illuminates when hit twice again.
3*/
4
5#include <Wire.h>
6#include <LiquidCrystal_I2C.h>
7
8LiquidCrystal_I2C lcd(0x27, 16, 2);
9
10const int sampleWindow = 125;
11int ledPin = 13;
12
// Red LED connection to pin 13
// set LCD I2C address. 16kans2joules LCD use
// sample period milliseconds (125 mS = 8 Hz)
13int soundValue = 0;
14int clapCounter = 0;
15double threshold = 2.0;
16
17voidsetup() {
18
19 Serial.begin(9600);
20
21 lcd.init();
22 lcd.backlight();
23 lcd.clear();
24 lcd.setCursor(0, 0);
25 lcd.print("LED OFF");
26 lcd.setCursor(0, 1);
27 lcd.print("CLAP TWICE~");
28
29pinMode(ledPin, OUTPUT);
30}
31
32
33voidloop() {
34
35unsignedlong start= millis();
36unsignedint peakToPeak = 0;
37unsignedint signalMax = 0;
38unsignedint signalMin = 1024;
39
40
// collect data for 125 milliseconds.
41while (millis() - start < sampleWindow)
42{
43soundValue = analogRead(3);
44if (soundValue < 1024)
45{
// store the value of the sound sensor
// Save clap count
// set clapping sound threshold voltage value
// initiate serial communication at 9600 speeds
// Initialize LCD
// turn on the backlight (lcd.noBacklight() turns off the backlight).
// clear LCD screen
// First line first column
// message output
// Line 1st column
// output messages
// set red LED to output
// start sampling
// Amplitude Value Variables
// specify analogue pin number 3.
// Read data up to the ADC maximum (1024=10bit).
The Beginner’s Guide 1st edition - Chapter 2- 15
130131
수정 -6월 5일.indd 130-1312019-06-05 오후 6:19:50
Page 68
46if (soundValue > signalMax)
STARTER KIT FOR ARDUINO
codingarray
47{
48signalMax = soundValue;
49}
50elseif (soundValue < signalMin)
51{
52signalMin = soundValue; /
53}
54}
55}
56peakToPeak = signalMax - signalMin;
double volts = (peakToPeak * 5) / 1024;
57
5V
58
59Serial.println(volts);
60if (volts >=threshold)
61{
62clapCounter ++;
63Serial.println(soundValue);
64
Serial.println(clapCounter);
65delay(50);
66
// turn on the LED in two claps
67if(clapCounter == 2)
68{
69digitalWrite(ledPin, HIGH);
70Serial.println("LED ON" );
71
// LCD output
72lcd.clear();
73lcd.setCursor(0, 0);
74lcd.print("LED ON");
75lcd.setCursor(0, 1);
76lcd.print("CLAP TWICE ");
77}
78
// turn off the LED in four claps
// Store the maximum sound value in the signalMax variable.
/ store the sound minimum in the variable (signalMin).
// Output soundValue value to serial monitor
// Output number of applause to serial monitor
// turn on the red LED.
// Output a message to the serial monitor
// First line first column
// message output
// Line 1st column
// output message
// calculate peak-to-peak amplitude
// convert the ADC value to a voltage value. Reference Voltage
79if (clapCounter == 4)
80{
81digitalWrite(ledPin, LOW);
82Serial.println("LED OFF");
83
// LCD output
84lcd.clear();
85lcd.setCursor(0, 0);
86lcd.print("LED OFF");
87lcd.setCursor(0, 1);
88lcd.print("CLAP TWICE ");
89clapCounter = clapCounter % 2;
90}
91}
92}
// output messages to serial monitors
// First line first column
// message output
// Line 1st column
// output message
// Turn off the red LED.
// Save remaining 0 (initialize clap count)
The Beginner’s Guide 1st edition - Chapter 2- 15
132133
수정 -6월 5일.indd 132-1332019-06-05 오후 6:19:50
Page 69
After you upload the sketch, open the serial window. If
15
you clap, the serial window will often clap, and the LED
will turn on when the clapping is detected twice. If the
clapping sound is detected four times, the LED goes off
and the next clapping count goes back to 1..
CODING ARRAY CIRCUIT
Using a sound sensor connected to the analog A3 pin, the ambient sound is received as an analog input value.
View Results
134135
수정 -6월 5일.indd 134-1352019-06-05 오후 6:19:51
Page 70
Measure the temperature and humidity
Let's find out about digital output
16
CHAPTER 2
with the sensor
Humidity & Temperature Sensor
Hot-humidity sensors are sensors that can help people
understand humidity at the same time. The temperature
Power LED
Pin D12
The temperature sensor used in the eray kit is a DHT-11 model, which includes a
fractional temperature sensor whose resistance decreases as the temperature increases,
and a capacitive humidity sensor whose resistance varies with humidity. Temperature
measurements range from 0°C to 50°C, with error of ±2°C. Humidity is
represented by relative humidity and the humidity measurement range is 0 to 100%,
with ±2% of the error. Relative humidity means the ratio of the amount of water
vapor contained in the atmosphere at a given temperature and the amount of
saturated water vapor (the higher the temperature, the greater the value of saturated
water vapor) as a percentage)..
sensor has a positive temperature coefficient type in
which resistance increases with increasing temperature
and a negative temperature coefficient in which resistance
decreases with increasing temperature.
To add a library, click Sketch > Include Library > Manage Libraries to run the Library Manager.
Search the search box for "DHT" and install "DHT sensor library by Adafruit".
Install "Adafruit Unified Sensor by Adafruit" in the search box
The Beginner’s Guide 1st edition - Chapter 2- 16
The DHT11 sensor consists of four pins, but the
third pin is not used. Connects pin 1 to 5 V, pin
2 to data input/output, and pin 4 to GND (0 V),
and does not require resistance. The module has a
sampling rate of less than 1 Hz, i.e. not more than
once per second.
The hot-humidity sensor provides both temperature and humidity at the same time, so the
code is complex, but it can be used easily using a library. A DHT library is required to use the
DHT** sensor.
108 // indicate temperature and humidity results on LCD
109delay(1000); // delay of 1000 milliseconds to reliably read values
110}
The Beginner’s Guide 1st edition - Chapter 2- 16
140141
수정 -6월 5일.indd 140-1412019-06-05 오후 6:19:53
Page 73
16
CODING ARRAY CIRCUIT
When you upload a program, the DHT-11 Hot and Humidity Module measures the temperature and
Use the NTC thermistor connected to the analog A4 pin to measure the temperature. Read the voltage at the NTC according to
temperature and convert it to temperature using the Steinhart-Hart formula and the B parameter formula..
View Results
142143
humidity and shows the result values to the serial monitor and I2C LCD
수정 -6월 5일.indd 142-1432019-06-05 오후 6:19:54
Page 74
Let's learn how to add a library..
STARTER KIT FOR ARDUINO
codingarray
Using the Arduino Library
File Edit Sketch
Tools HelpFile Edit Sketch Tools Help
Include Library
Arduino Library
Servo
Search and install libraries in 'Library Manager'
File Edit Sketch
When you add a library, the example contained in the library in
Tools Help
Include Library
Manage Libraries
ADD .ZIP Library
Arduino Library
Installing the Extended Library
Search for the module keyword you want to use at
github.com/
Download the library of the ZIP file format. Add a library that you downloaded
in the following ways..
File Edit Sketch
ToolsHelp
https://www.google.com/ or https://
File > Example
Search Keywords
The Beginner’s Guide 1st edition - Chapter 2- 16
can be used..
144145
수정 -6월 5일.indd 144-1452019-06-05 오후 6:19:54
Include Library
Manage Libraries
ADD .ZIP Library
Arduino Library
Page 75
17
CHAPTER 2
Controlling servo motors
Servo Motor
Pin D3 5V GND
Angle Display
Servo Motor
motors consume significant power and, if more than one movement is required, must
be supplied with external power rather than 5V of Arduino..
To control the servo motor, the servo library makes it easy to handle the servo motor.
Using this library on the Uno Board disables the analogWrite() PWM function on
pins 9 and 10 regardless of whether the pin has a servo motor.
A servo motor larger than the servo motor used in the array kit can move the park
breaker or move the robot's hand, arm, etc..
The servo motor is a motor that can rotate the axis
at the desired angle and was used for small RC toys.
It is also the first motor connected to Arduino. The
array kit used a 9g servo motor showing the rotation
angle between 0 and 180°. The servo motor has
a line that can connect three pins, brown to GND,
red to 5 V and orange to Arduino's PWM pin. Servo
17voidloop() {
18 myservo.write(90); // position in the center of the servo motor shaft (90 degrees)
19delay (1000);
20
21 myservo.write(0); // position 0 degrees on servo motor shaft
22delay (1000);
23
24 myservo.write(180); // position 180 degrees on servo motor shaft
25delay (1000);
26
27 myservo.write(90); // located in the center of the servo motor shaft
28delay (1000);
29
30for(position = 0; position <= 180; position += 1) { // increase by 1 degree to 0 to 180 degrees.
31 myservo.write(position); // move to a specified angle
32delay(30); // wait until servo to arrive.
33 }
34
35for(position = 180; position >= 0; position -= 1) { // decrease by 1 degree to 180 degrees.
36 myservo.write(position); // move to a specified angle
37delay(30); // wait until servo to arrive.
38 }
39}
The Beginner’s Guide 1st edition - Chapter 2- 17
CAK Starter Code > 17_01_Servo_Sweep
1/* This sketch uses servo live
* Move the servo motor by 0 - > 180 degrees
2
3 * Move back to 180 - >0 degrees.
4 * Note that servo motors cannot be rotated 360 degrees.
5 */
6
7#include <Servo.h> // Include servo library
8
9Servo myservo; // create object myservo to control servo
10
11intposition =0; // store the servo's position. Initial value 0
12
13voidsetup() {
14 myservo.attach(3); // attach servo motor to pin 3
15}
16
myservo.attach(pin number, max value, max value);
recognises servo motor connected to PWM pin.
myservo :
Pin number :
Maximum value (optional) :
servo (in microseconds), default 544
Maximum value (optional) :
(180 degrees) angle of servo, default 2400
myservo.write; move the axis of the servo motor to the desired angle.
myservo :
Angle :
Position + = 1 and position = position +1 and position ++
to mean increasing position by 1 after executing function.
However,
position by one, function is executed'.
servo object
Pin number with servo attached
Pulse width corresponding to the angle of (0 degrees) of the
Pulse width in microseconds corresponding to the maximum
servo object
Value from 0 to 180 for servo to move
+ position
is a different expression from the above three: 'After increasing
.
are all the same expressions
146147
수정 -6월 5일.indd 146-1472019-06-05 오후 6:19:55
Page 76
17
CODING ARRAY CIRCUIT
Upload the sketch and you can see the axis of the servo motor moving at an angle
created by the code..
Using the DHT-11 temperature and humidity module connected to pin 12 digital, measure the temperature and display the
results.
View Results
148149
수정 -6월 5일.indd 148-1492019-06-05 오후 6:19:56
Page 77
STARTER KIT FOR ARDUINO
codingarray
CAK Starter Code > 17_02_Servo_Knob
1/* This sketch uses servo live
2* The servo motor is between 0 and 180 degrees depending on the variable resistance value
3 * Move the axis.
4 */
5
6#include <Servo.h>
7
8Servo myservo;
9
10intposition =0; /
11int potPin=A0;
12
13void setup() {
14 myservo.attach(3);
15
}
16
17
voidloop() {
18
19
int val =analogRead(potPin); /
20 int servoVal =map(val,0,1023,0,180);
21
myservo.write(servoVal);
22
delay(15);
23
24
int pitchVal=map(val, 0, 1023,120,1500);
25
tone(6, pitchVal, 10);
26
27
delay (1);
28
29
}
// Include servo library
// create object myservo to control servo; up to 12 can be created
/ store the servo's position. Initial value 0
// Connect variable resistance to A1 pin
// attach servo motor to pin 3
/ Read variable resistance value (0-1023)
// map variable resistance values to 0-180 degrees servo motor rotation angle
// position of mapped servo
// wait for the servo to arrive.
// map variable resistance values to 120 to 1500 Hz sound frequencies
// output mapped sound value to manual buzzer connected to pin 6 for 10 milliseconds
// delay of 1 millisecond for safety
The Beginner’s Guide 1st edition - Chapter 2- 17
150151
수정 -6월 5일.indd 150-1512019-06-05 오후 6:19:58
Page 78
Let's learn about the methods available
in the Servo library
Servo object name;
Form an object called Servo myservo; myservo to activate the servo site.
myservo.attach (pin number, max value, max value);
input/output pin
myservo : servo object
Pin number : Pin number with servo attached
Maximum value (optional) : Pulse corresponding to the angle of (0
degrees) of the servo (microseconds), default 544
Maximum value (optional) : Pulse width in microseconds corresponding
to the maximum (180 degrees) angle of servo, default 2400
form objects of the Servo class
connecting servo motor to
QuestionSolution
The touch sensor module turns on a
blue light when it is not pressed.
FAQ and Solution
1. Switch on due to current consumption rather than failure, remove and plug in
the USB cable.
2. Connect the 7V to 12V adaptors separately and use them.
- This is mainly caused by high current consumption during servo motor
operation.
myservo.write (angle);
set the angle to move the servo motor
myservo : servo object
Angle : The value from 0 to 180 for the servo to move, the wrong angle is
treated with microseconds.
CAUTION) When rotating using the letter(), wait for the time to rotate.
A short setting of this time will not allow rotation to the desired angle.