Arduino 101
Arduino 101
Obakoma G. Martins
Copyright
Copyright©2020 Obakoma G. Martins
All rights reserved. No part of this book may be reproduced or used in any manner without the prior
written permission of the copyright owner, except for the use of brief quotations in a book review.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for
any errors or omissions that may be made. The publisher makes no warranty, express or implied, with
respect to the material contained herein.
Printed on acid-free paper.
- Hold on for the program to complete the installation and close it.
- Now locate the Arduino shortcut on your computer and open it. The IDE
will be opened and the code editor will be displayed.
There are numerous varieties of Arduino boards that can be utilized for
various purposes. A number of the boards appear to be different, however
most Arduinos have most of these parts in common:
- Power (USB/Barrel Jack)
Each Arduino board has to be connected to a power outlet. The Arduino
UNO can be supplied power from a USB link originating from your PC or a
wall socket that ends in a barrel jack. In the image above, the USB port is
labelled as (1) and the barrel jack is labelled as (2). In addition, it is through
the USB connection that you will input the codes into your Arduino board.
However, don't connect to a power supply that is larger than 20 Volts,
because this will overpower and damage your Arduino. The suggested
voltage for most Arduino models is somewhere in the range of 6 and 12 Volts
- Pins (5V, 3.3V, GND, Analog, Digital, PWM, AREF)
The pins on your Arduino are where you associate wires to build a circuit
(most likely in conjunction with a breadboard and some wire. Usually, they
have dark plastic 'headers' that enables you to simply plug a wire directly into
the board. The Arduino has various types of pins, each of which is marked on
the board and utilized for numerous functions.
- GND (3): abbreviated form for 'Ground'. There are numerous GND
pins on the Arduino, any of which can be utilized to ground your
circuit.
- 5V (4) and 3.3V (5): the 5V pin produces 5voltels of power, while the
3.3V pin supplies a power of 3.3volts. The vast majority of the basic
components utilized with the Arduino run on 5 or 3.3 volts.
- Analog (6): The zone of pins under the 'Analog In' name (A0 through
A5 on the UNO) are Analog In pins. These pins can analyze the signal
from an analog sensor (similar to a temperature sensor) and convert it
into a computerized value that is human readable.
- Digital (7): on the other side from the analog pins are the digital pins
(0 through 13 on the UNO). These pins can be utilized for both
computerized input (such as confirming whether a button was pushed)
and other digital outputs such as powering a LED.
- PWM (8): You may have seen the tilde (~) close to a portion of the
advanced pins (3, 5, 6, 9, 10, and 11 on the UNO). These pins function
as digital pins, however can likewise be utilized for something many
refer to as Pulse-Width Modulation (PWM). These pins can recreate
analog outputs.
- AREF (9): represents Analog Reference. Mostly, you might not use
this pin. It is employed to set an outer reference voltage (between 0 and
5 Volts) as the upper limits for analog input pins.
- Reset Button
Similar to any electronic device you know, the Arduino has a reset button
(10). Pushing it will quickly interface the reset pin with the ground and restart
any code that is present on the Arduino. This can be extremely valuable if
your code doesn't repeat, and you need to test it multiple times. However,
resetting it doesn't fix any problem.
- Power LED Indicator
Just underneath, and to the right side of "UNO" on your circuit board, there's
a small LED close to the word 'ON' (11). This LED should illuminate
anytime you connect your Arduino into a power outlet. In the event that this
light doesn't turn on, there's a decent possibility something isn't right. You
should recheck your circuit.
- TX RX LEDs
TX is an abbreviation for transmit, RX represents Receive. These markings
show up a lot in electronics to demonstrate the pins answerable for sequential
communication. There are two spots on the Arduino UNO where TX and RX
show up (once by advanced pins 0 and 1, and a second time close to the TX
and RX pointer LEDs (12)). These LEDs will provide us with some pleasant
visual signs at whatever point our Arduino is getting or sending information.
- Main IC
The black component with all the metal legs is an Integrated Circuit (13).
Consider it the brain of our Arduino. This IC on the Arduino is somewhat
different depending on the board type, yet is typically from the ATmega line
of IC's from the ATMEL organization. This can be important because you
need to know the IC type (alongside your board type) before entering a new
program from the Arduino programming. Details about this are on the top
side of the integrated circuit. If you intend to know more about the
differences between the IC's, the datasheet may help you out.
- Voltage Regulator
The voltage regulator (14) isn't really something that is friendly on the
Arduino. However, it is possibly helpful to know that it is there and what it's
for. Just like the name implies, it regulates the quantity of voltage that is
allowed into the Arduino board. It will dismiss an additional voltage that may
damage the circuit. And the regulator itself has limits, so don't power your
Arduino to anything greater than 20 volts.
Now that you’re aware of the various components of an Arduino board, let's
discuss the set up.
Step 1: Download and Install the IDE
The IDE is available for download on the official Arduino site. Since the
Arduino employs a USB to serial converter, which enables it to interact with
the host PC, the Arduino board is viable with most PCs that have a USB port.
That being said, you will require the IDE first. Fortunately, the Arduino
architects have produced numerous versions of the IDE for various operating
systems, including Windows, Mac, and Linux. So you should download the
IDE that is appropriate for the Operating System your computer has. After
downloading it, install and enable all the options.
Step 2: Get the Arduino COM Port Number
Next, you'll have to interface the Arduino Uno board to the PC. You can do
this by means of a USB connection. The USB supplies the board with 5V up
to 2A. When you connect the Arduino, the operating system ought to identify
the board as a conventional COM port. When the computer recognizes the
board, you should look for the port number assigned to it. The simplest
method to do this is to type "device manager" into Windows Search and press
Device Manager when it shows.
In the Device Manager window, search for a device under "Ports (COM and
LPT)", and the Arduino might probably be the main gadget on the list. In my
Device Manager, the Arduino appears as COM7. However, the computer
won't always identify the Arduino automatically. In case the PC doesn't
recognize the Arduino, uninstall the driver, remove the Arduino, insert the
Arduino again, locate the unrecognized device, right click "Update driver",
and afterward click "Search consequently". This should fix the issue almost
all the time.
At this point, you should inform the IDE about the COM port the Arduino is
on. To do this, go to Tools > Port > COM7. Clearly, if your Arduino is on
another port, select that port.
- Preparing an Arduino Sketch with the IDE
When you have effectively installed Arduino IDE, you can start coding. The
source code documents for Arduino are called sketches. A sketch stands for a
name that Arduino uses for a program. It's the unit of code that is uploaded to
and operated on an Arduino board. The Arduino programming language is
based on C/C++ and it is almost the same. Open the Arduino IDE and a blank
sketch will show up on your screen
The sketch is separated into two program parts: set up and loop.
In set up, you make fundamental hardware and software configurations. This
aspect of the code runs only once. For instance, if we are driving a LED, we
can program the computerized I/O pin we have our LED attached to as an
output pin.
Since we have finished setting up the Arduino, we can compose the main
body of the code. This will fall under the loop aspect and will rehash
repeatedly except it is instructed otherwise or if power is taken out from the
Arduino.
We will then input these commands if we want to flash the LED on and off
1) Turn LED On
2) Wait ½ of a second (500 milliseconds)
3) Turn LED Off
4) Wait ½ of a second
5) Repeat
Since the code we compose is inside the loop function, the Arduino will
consequently repeat the code.
Connect the Arduino board to your PC via the USB. After interfacing the
Arduino, follow these steps to upload the sketch:
1) Select the type of board you're using, that is the target board
The board you select informs the Arduino IDE which Arduino board you are
uploading to. If you have another board other than the Arduino Uno, select
that board
2) Choose the serial port the board is associated with
Now that we have informed the Arduino software about the type of board you
are interacting with and which serial port connection it is using, you can
upload the Blink sketch.
Press the Verify button. This checks whether the inputted codes fit well. This
doesn't actually imply that your code will do what you are expecting,
however it verifies that the language structure is written in a manner Arduino
can comprehend. You should notice a progress bar and the content Compiling
Sketch for a couple of seconds followed by the text Done compiling after the
concluding the process
Then, if the sketch compiled successfully, you can press the Upload button
near the verify button. A progress bar shows up, and you see numerous
activities on your board from the two LEDs marked RX and TX. These imply
that the Arduino is sending and receiving information. After a while, the RX
and TX LEDs quit blinking, and a Done Uploading message shows up at the
base of the window.
You should see the LED stamped L blinking intermittently: on for a second,
off for a second
A copy of the sketch has now been saved in your sketchbook. This implies
anytime you want to use it, you can simply open it via the File → Sketchbook
menu option.
Next, you have to press the verify button (check mark) that is situated in the
upper left of the IDE box. This will compile the sketch and search for errors.
When it shows "Done Compiling”, it can be uploaded. Press the upload
button, represented by the forward arrow, to send the program to the Arduino
board.
The implicit LEDs on the Arduino board will flash quickly for a couple of
seconds and afterward the program will execute. If it goes as expected, the
LED on the breadboard should flash intermittently.
With that, you have just successfully completed your first Arduino project.
A typical Arduino sketch comprises two functions called set up and loop.
2.2 Variables
A variable is a method of naming and putting a value for future use by the
program, for example, data obtained from a sensor or a moderate value
utilized in a computation.
Declaring Variables
You have to declare a variable before you use it. Declaring a variable implies
that you are characterizing its type and alternatively, setting an initial value(
this is called initializing the variable).
int inputVariable1;
int inputVariable2 = 0; //both are correct
You ought to consider the size of the numbers they intend to store in picking
variable types. Variables will turn over when the attached value surpasses the
space allotted to store it.
Using Variables
After declaring a variable, you can characterize them by setting the variable
equivalent to the value one intends to store with the assignment operator
(single equal sign). The program operator instructs the program to enter
whatever is on the right side of the equal sign into the variable on the left
side.
inputVariable1 = 7; // sets the variable named inputVariable1 to 7
inputVariable2 = analogRead(2); // sets the variable named inputVariable2 to
the
// (digitized) input voltage read from analog pin
#2
Examples
int lightSensVal = 1234;
char currentLetter = 'a';
unsigned long speedOfLight = 186000UL;
char errorMessage[] = "choose another option"; // see string
After setting a variable by assigning it a value, you can ascertain its value to
check whether it satisfies certain requirements, or you can utilize its value
directly. For example, these tests whether the inputVariable2 is less than 100,
afterwards set a delay based on inputVariable2 which has 100 as its minimum
Example Code
float myfloat;
float sensorCalbrate = 1.117;
int x;
int y;
float z;
x = 1;
y = x / 2; // y now contains 0, ints can't hold fractions
z = (float)x / 2.0; // z now contains .5 (you have to use 2.0, not 2)
It is important you know that when doing math with floats, you have to
include a decimal point, else it will be treated as an integer.
The float data type entails about 6-7 decimal digits of accuracy. This implies
the entire number of digits, not the number to the right side of the decimal
point. In contrast to other platforms, where you can be provided with more
precision by utilizing a double( up to 15 digits), on the Arduino, a float has a
similar size as that of a double.
Floating-point numbers are not precise, and may produce random results
when analysed. For instance 6.0/3.0 may not equal 2.0. Instead, you ought to
check the absolute value of the distinction between the number is less than
some small number.
Changing from floating point to integer may provide you with truncated
results;
If, instead, you want to round off during the conversion process, you need to
add 0.5:
float x = 2.9;
int y = x + 0.5; // 3
or use the round() function:
float x = 2.9;
int y = round(x); // 3
Also, floating-point math is less quicker than integer math in carrying out
calculations, so ought to be avoided if, for instance, a loop needs to operate at
maximum speed for a basic function.
Creating an Array
You can create (declare) an array through any of these methods:
Getting to an Array
Clusters can be zero field, that is, taking an example from the exhibit
instatement over, the principal component of the exhibit is at record, thus
mySensVals[1] == 4, etc.
It likewise implies that in an array with ten components, index nine is the last
component. Therefore;
Therefore, you should be careful when accessing arrays. Accessing beyond
the terminal of an array (utilizing a file number greater than the created array
size - 1) is perusing from memory that is being used for different purposes.
Reading from these areas won’t deliver much other than yield invalid data.
Writing in a non-sequential manner to different memory locations is not such
a good idea and might give unpleasant results such as crashes or program
malfunction. This can also be a difficult issue to troubleshoot.
In contrast to BASIC or JAVA, the C++ compiler does not verify whether the
array access is within legitimate limits of the array size that you have created.
To assign a value to an array:
Also, these examples will inform us about what a string consists of; a
character array with printable characters and 0 as the last element of the array
to indicate this is the point the string finalizes. The string will be outputted on
the Arduino IDE Serial Monitor window through the Serial.println() and
passing the name of the string.
Likewise, there are ways to write such strings in a more convenient way;
In this sketch, the compiler estimates the size of the string array and
consequently null terminates the string with a zero. An array that possesses
six letters in length and comprises of five characters followed by a zero is
created in the same way as the previous sketch.
- Manipulating String Arrays
We can adjust a string array in a sketch, for instance;
Result
I like coffee and cake
I like coffee
I like coffee and tea
The adjustment is made to the sketch in this way:
- You first create and print the string.
-Then you shorten the string probably by replacing a character in the string
with the null terminating zero.
- Changing words in the string. The words to be changed are first replaced
with a null terminating zero, then you enter the new word.
Likewise, there’s the else-if, where you can check a subsequent condition if
the first statement is false:
if (someCondition) {
// do stuff if the condition is true
} else if (anotherCondition) {
// do stuff only if the first condition is false
// and the second condition is true
}
/and the subsequent condition is valid
}
Subtraction
Multiplication
Division
Int divide;
Divide = a/ b;
Increment operation
Decrement operation
For instance;
int a = -5;
x = abs(a); x = abs(-5);
Result x is 5.
- Syntax
An alternative method is to use a library called TextFinder, which is
accessible from the Arduino Playground. The basic function of a TextFinder
is to extract information from a web stream, but it functions effectively with
serial data. This sketch utilizes a TextFinder to deliver similar functionality to
the previous sketch:
#include
TextFinder finder(Serial);
Const int NUMBER_OF_FIELDS = 3; // how many comma-separated fields we expect
Int fieldIndex = 0;
// the current field being received
Int values[NUMBER_OF_FIELDS];
// array holding values for all the fields
Void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
}
Void loop()
{
For(fieldIndex = 0; fieldIndex < 3; fieldIndex ++)
{
Values[fieldIndex] = finder.getValue(); // get a numeric value
Additionally, you need to create a link to the serial port so that the Arduino
IDE can identify it. The code below does that.
Sudo ln -s /dev/ttyAMA0 /dev/ttyUSB9
This last procedure must be carried out after every reboot.
Nevertheless, the Arduino can’t be programmed from the IDE running on the
Raspberry Pi with these changes. We have to toggle the reset pin on the
Arduino to begin programming.
Connect Pin 11 (GPIO 17) of the RPi to the DTR Pin on the Arduino Pro
Mini by using the level converter. Run thesevcommands to download and
configure avrdude-rpi:
You have to run the Arduino IDE as root from this point i.e. in LXTerminal:
Sudo Arduino
Then, reboot the Raspberry Pi to activate the earlier procedures. You will
then be able to program whatever you like on to the Arduino through the IDE
running on the Raspberry Pi.
CHAPTER FIVE
5.1 Using a Switch with the Arduino
sing a switch with the Arduino allows us to control certain functions of
U the Arduino by using a push button. For instance, with the switch, we can
switch an LED on or off when we press the push button.
The necessary materials needed to do this are:
- A push button switch
- An Arduino board
- A resistor of any value
- 2 Jumper cables (breadboard jumpers)
- 1 Breadboard
- A Light Emitting Diode
Place the switch in the breadboard and insert an LED with the longer
leg into pin 13 and shorter leg to the Gnd of the Arduino.
Next, place one end of the resistor in +5 V and then connect the other
end with one of the terminals of the switch. Attach the equivalent
terminal to Gnd of the Arduino. The terminal that is located on the
same side of the first one is the equivalent terminal.
- Afterwards, connect the terminal with the resistor to pin 2 on the Arduino
and enter the program:
Int d=2; // to store on or off value
Void setup()
{pinMode(2,INPUT);
pinMode(13,OUTPUT);
}
Void loop()
{
D=digitalRead(2);
If(d==0)
{digitalWrite(13,HIGH);}
Else
{digitalWrite(13,LOW);}
}
That is all! Just press the switch and the LED will illuminate.
- The code
Void loop(){
// Read the value of the input. It can either be 1 or 0
Int buttonValue = digitalRead(buttonPin);
If (buttonValue == LOW){
// If button pushed, turn LED on
digitalWrite(LED,HIGH);
} else {
// Otherwise, turn the LED off
digitalWrite(LED, LOW);
}
}
Perhaps the button is inserted into a different pin, change the buttonPin value
to the value of the pin that is being used.
While joining the pins to the Arduino board, they should be associated with
the advanced yield pins, D9-D2. The principal pin of the keypad must be
joined to D9, the second pin to D8, the third pin to D7, the fourth pin to D6,
the fifth pin to D5, the 6th pin to D4, the seventh pin to D3, and the eighth
pin to D2.
The table above contains the different range of values, the value to the left of
the comma is the adc value while to the right is the mapped output value.
You will observe that that input is mapped to output ranges in blocks of 4 (1
output value for a range of 4 input values). This is understandable since
1024/4 = 256. However, the final output value has only 1 input for one output
i.e. 1023 results in 255, while 1019~1022 results in 254 as output. Your aim
is to obtain an even spread of values across the entire range.
To arrive here, a few of the other outputs must have had 5 values as inputs.
- Next task is to set up the voltage divider; we first need to know the values
of resistors. We can know that though these steps:
- Identify the maximum voltage, which you intend to measure.
- Set a suitable and standard value for R1 in the kilo-ohm range.
Using formula, calculate R2.
If the value of R2 isn’t precisely the standard value, change R1 and repeat the
above steps.
Since Arduino can handle a maximum of 5V, V1 = 5V.
Let’s assume values and set the maximum voltage (Vm) to be measured by
12V and R1 = 47 kilo-ohms. Then using the formula R2 comes out to be
equal to 33k.
Now, build a voltage divider circuit integrating these resistors.
Following this set up, we are left with a maximum and minimum limit. For
Vm = 12V we get V1 = 5V and for Vm = 0V we get V1 = 0V. That is, for 0
to 12V at Vm, we will have an equivalent voltage from 0 to 5V at V1 which
can then be inputted into the Arduino as before.
A PIR Sensor
Layout the circuit as in the layout and circuit diagrams.
Set up the circuit and select File→Examples→01.Basics→DigitalReadSerial
from the Arduino menu to load the sketch.
This sketch is equivalent to a pushbutton but follows the same method
/*
DigitalReadSerial
// digital pin 2 has a pushbutton attached to it. Assign a name to it:
Int pushButton = 2;
// the setup routine runs once when you reset it:
Void setup() {
// begins the serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton’s pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
Void loop() {
// read the input pin:
Int buttonState = digitalRead(pushButton);
Serial.println(buttonState);
Delay(1); // delay in between reads for stability
}
Click on the compile button to inspect the code. This highlights and points
out any error or bug. After the compiling process, click Upload to transfer the
sketch to your board. After uploading, place the PIR sensor to a surface that
is free of movement and open the serial monitor.
The sketch will reset when you open the serial monitor, and the sensor gets
itself ready in the first 1 to 2 seconds. When it detects a movement, the
buttonState value changes from 1 (no movement) to 0 (movement). On the
other hand, if no changes occur check your wiring.
}
Else {
digitalWrite(ledPin, LOW);
}
Delay(100);
}
Compile it and run the code, your Arduino will conveniently detect changes
in light levels in the LED.
Set up the circuit from the layout and circuit diagrams. The connections for
the rangefinder are indicated beneath the PCB. The 5V and GND connections
provide power for the sensor and should be attached to the 5V and GND
supplies on your Arduino. The PW connection represents the pulse width
signal that will be read by pin 7 on your Arduino. Ensure that your distance
sensor is positioned firmly to a support in the direction that you intend to
measure.
Create a new sketch, enter these codes into it, and save it with.
Compile the code, and then upload it to your board. After uploading, you
should see the distance measured in inches and centimetres on your serial
monitor. If the value isn’t stable, try with an entity which has a larger surface.
You can even check the result with a measuring tape and make corrections to
the code if you notice irregularities.
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
Void setup()
{
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
Mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println(“Approximate your card to the reader…”);
Serial.println();
}
Void loop()
{
// Look for new cards
If ( ! mfrc522.PICC_IsNewCardPresent())
{
Return;
}
// Select a card
If ( ! mfrc522.PICC_ReadCardSerial())
{
Return;
}
//Show UID on serial monitor
Serial.print(“UID tag :”);
Approximate the card you’ve picked to give access and it will display this;
Then launch the Arduino IDE software on your computer, create a new
sketch and input these codes;
Upload the codes to your Arduino and that should be it. Move the pushbutton
and you’ll notice the changes
Only four-wire connections are needed Vcc, Gnd, SCL, and SDA pins, and
these are connected via the I2C cable.
Open the Arduino program on your computer, create a new sketch and input
these codes;
// Select data register
Upload the codes to your Arduino and run it.
CHAPTER SEVEN
7.0. Visual Output
These projects show the simplest things that can be achieved with the
Arduino to see the physical or visual output.
Connect the ground 3 pins which stand for the colors will be connected to the
cathode through 220 Ohm resistors to 3 pins on the Arduino that generates
the PWM signal. The PWM signal’s function is to set various voltage levels
to the LEDs to get the intended colors. Create a new sketch on your pc and
input these codes, afterwards, upload it on your Arduino.
7.4. Sequencing Multiple LEDs
An LED sequencer is a typical LED driving circuit that is used in running-
light rope displays to flash different lighting patterns. In a sequencer circuit, a
controller directs the sequence and timing of the flashing LEDs to exhibit
various kinds of lighting patterns. An LED sequencer is built on Arduino
UNO.
Components required:
- An Arduino board
- 7 LEDs
- Seven330 Ohms Resistor
- A Breadboard
- Male-to-Male Jumper wires
Circuit connections:
The circuit of an LED sequencer is programmed on a breadboard. LEDs are
attached to the Arduino channels to allow them to take the current from the
LEDs.
The cathodes of the LEDs are attached to the digital I/O pins 0, 1, 2,
3, 5, 6, and 7 from the Arduino UNO through the current-limiting
series resistor at the individual channel
Connect the entire LED anodes to the power supplying row of the
breadboard.
Load the sketch for the LED sequencer to the Arduino.
Utilize the 5V power pin and one of the ground pins from Arduino
to supply the 5V DC and then ground to the breadboard.
Switch on the Arduino by connecting it to a power supply.
Then input the codes for lighting an LED, insert the code such that it
encompasses the whole LEDs, for example:
Void setup() {
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
digitalWrite(0, HIGH);
delay(200);
digitalWrite(1, HIGH);
delay(200);
digitalWrite(2, HIGH);
delay(200);
digitalWrite(3, HIGH);
delay(200);
digitalWrite(5, HIGH);
delay(200);
digitalWrite(6, HIGH);
delay(200);
digitalWrite(7, HIGH);
delay(200);
…
When a logical LOW is fixed as the output from a pin, the current passes
through the attached LED and it illuminates. When a logical HIGH is fixed as
the output from a pin, the attached LED does not receive the required forward
voltage and it will stop illuminating. The LEDs are interfaced to the Arduino
in this manner;
Programming the Arduino LED grid requires controlling the ports. Utilizing
ports for programs makes it simpler to work with and it likewise spares
space. Port control isn't so difficult, look at the picture for instance. The red
specks imply the LEDs, which are ON, and the white as OFF. In the main
line of the lattice, to turn on the second and seventh LEDs, we input an order
to the Arduino port: B01000010. Here the second and seventh pieces are "1",
which thus turns the LED ON. "B" suggests that the port is a yield port. We
complete these for all the columns lastly; we will get a smiley face in the
lights it is shown in the picture. At that point, unplug the 0 and 1 pins
subsequent to transferring the program.
Attach the red wire of the servo to the 5V pin of the Arduino Uno.
Insert the black wire of the servo to the GND pin of the Arduino
Uno.
Next thing is to connect the yellow control wire of the servo to
Digital Pin 9 of the Arduino Uno. The function of this yellow wire
is to receive commands from the Arduino.
Switch on your Arduino by plugging in the USB cord to your
computer.
Launch the Arduino IDE, and in a new sketch, enter the following
code:
When you’re done, upload the code to your board. This code will
cause the shaft of the motor sweep back and forth 180 degrees.
Two outer terminals are used for power: one outer pin connects
to ground and the other connects to positive voltage. Then there’s
a central control terminal used for voltage output: turning the knob
of the potentiometer increases or decreases the resistance, which
by implication increases or decreases the voltage output.
Circuit Setup:
Unplug your Arduino, and insert the 10k Ohm potentiometer into the
breadboard. Ensure that each terminal is connected to a separate row in the
breadboard. Carry out the connections this way;
You can then plug in your Arduino. Launch the Arduino IDE, create a new
sketch, enter the following code:
Transfer the code to your Arduino. Turn the handle on your potentiometer to
move the servo, this increment or diminishes the voltage yield, the higher the
voltage yield by the potentiometer, the more prominent the servo's point of
pivot.
Associate the Potentiometer to the vcc or 5v pin of the Arduino and the
Ground. Interface the third terminal that is the variable pin to the Analog pin
A0. You can in any case control the Arduino utilizing the BEC (Battery
Eliminator Circuit) accessible in your ESC. If you need to get the BEC, just
associate the red thick wire to the Vin Pin of Arduino .It can give 5V.
Nevertheless, not all ESC’s are given a BEC, in this case you can utilize an
outside 5v power gracefully. Force on the Arduino and associate the Lipo
battery to your ESC. At that point, bit by bit pivot the Potentiometer Knob to
begin and speed up the Motor.
Create a new sketch and input this code;
Upload the code to your Arduino, and gradually rotate the knob to adjust the
motor’s speed.
Circuit connection
Bool debounce()
{
Byte count = 0;
For(byte I = 0; I < 5; i++) {
If (digitalRead(button) == 0)
Count++;
Delay(10);
}
If(count > 2) return 1;
Else return 0;
}
CHAPTER NINE
9.1. Playing Tones
his project describes how to go about the function, tone(), to generate
T notes. It plays a sound or melody when you run it
Hardware Required;
- Arduino board
- Piezo buzzer or a speaker
- Hook-up wires
Circuit setup;
When it’s time to upload the code onto Arduino, you should detach the MIDI
device, as it may disrupt the upload. After uploading the sketch, connect a
MIDI sound device to the Arduino output. A musical scale will play each
time you press the button connected to pin 2:
//these numbers specify which note
Const byte notes[8] = {60, 62, 64, 65, 67, 69, 71, 72};
//they are part of the MIDI specification
Const int length = 8;
Const int switchPin = 2;
Const int ledPin = 13;
Void setup() {
Serial.begin(31250);
pinMode(switchPin, INPUT);
digitalWrite(switchPin, HIGH);
pinMode(ledPin, OUTPUT);
}
Void loop() {
If (digitalRead(switchPin == LOW))
{
For (byte noteNumber = 0; noteNumber < 8; noteNumber++)
{
playMidiNote(1, notes[noteNumber], 127);
digitalWrite(ledPin, HIGH);
delay(70);
playMidiNote(1, notes[noteNumber], 0);
digitalWrite(ledPin, HIGH);
delay(30);
}
}
Void playMidiNote(byte channel, byte note, byte velocity)
{
Byte midiMessage= 0x90 + (channel – 1);
Serial.write(midiMessage);
Serial.write(note);
Serial.write(velocity);
}
CHAPTER TEN
10.1 Responding to an infrared remote
control
n this project, we will interface an infrared remote control with the Arduino
I and afterwards use it to control certain functions, such as controlling
LEDs. The IR sensor is a 1838B IR receiver. Whenever you press a button
on the remote, it will send an infrared signal to the IR sensor in the coded
form. The IR sensor will then receive this signal and relay it to the Arduino.
Circuit setup
To start with, connect the four LEDs to the Arduino. Attach the
positive terminals of the four LEDs to the pins 7, 6, 5, and 4. Connect
the negative terminals of the four LEDs to GND on the Arduino
through the 220-ohm resistors. The longer wires on the LEDs are
positive and the shorter wires are negative. Afterwards, connect the
IR sensor to the Arduino. The connections for the IR sensor with the
Arduino should be done this way;
Void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
Code;
#include <Wire.h>
#include <ds3231.h>
struct ts t;
void setup() {
Serial.begin(9600);
Wire.begin();
DS3231_init(DS3231_INTCN);
/*Insert these values to synchronize clock module/
t.hour=12;
t.min=30;
t.sec=0;
t.mday=25;
t.mon=12;
t.year=2019;
DS3231_set(t);
}
void loop() {
DS3231_get(&t);
Serial.print("Date : ");
Serial.print(t.mday);
Serial.print("/");
Serial.print(t.mon);
Serial.print("/");
Serial.print(t.year);
Serial.print("\t Hour : ");
Serial.print(t.hour);
Serial.print(":");
Serial.print(t.min);
Serial.print(".");
Serial.println(t.sec);
delay(1000);
}
CHAPTER ELEVEN
11.1. Connecting to an Ethernet network
onnecting an Arduino to an Ethernet network grants it online
C accessibility. We’ll use an Arduino Ethernet Shield here. The Ethernet
shield will then be stacked above the Arduino via a Shield interface.
These are the procedures to follow:
- Fix the Ethernet Shield tightly on the Arduino hardware as shown in the
image
That is all!
Required components;
- Arduino board
- Ethernet shield
- Wired LAN Connection with a speed of 10/100Mb
- An Ethernet cable
- Wi-Fi Router
- A Breadboard
- 3 Jumper Wires
- 10k Resistor
- Two 9V Adaptor
- 1 pushbutton
Circuit setup
Code:
Client.println(“<!DOCTYPE html>”); //web page is made using HTML
Client.println(“<html>”);
Client.println(“<head>”);
Client.println(“<title>Ethernet Tutorial</title>”);
Client.println(“<meta http-equiv=\”refresh\” content=\”1\”>”);
Client.println(“</head>”);
Client.println(“<body>”);
Client.println(“<h1>A Webserver Tutorial </h1>”);
Client.println(“<h2>Observing State Of Switch</h2>”);
Client.print(“<h2>Switch is: </2>”);
If (digitalRead(8))
{
Client.println(“<h3>ON</h3>”);
}
Else
{
Client.println(“<h3>OFF</h3>”);
}
Client.println(“</body>”);
Client.println(“</html>”);
This sketch will lead to a web page on a Web browser when the IP address
assigned to the Arduino is accessed.
11.3. Sending Twitter messages
The objective is to demonstrate how we can use Arduino to post automatic
and cyclical tweets to share the status of the Analog inputs on Twitter.
Required components;
- An Arduino board
- An Arduino Ethernet shield
Code;
#include <SPI.h> // needed in Arduino 0019 or later
#include <Ethernet.h>
#include <Twitter.h>
// Ethernet Shield Settings
Byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Message to post
Char msg[200];
Int a0,a1,a2,a3,a4,a5;
Int n=0;
Void setup()
{
Delay(1000);
Ethernet.begin(mac, ip);
Serial.begin(9600);
Serial.println(“connecting …”);
}
Void loop()
{
While(1){ //repeat for ever
N++; // Index to say which order of tweet is
//get some data from Aanalog inputs.
A0=analogRead(0);
A1=analogRead(1);
A2=analogRead(2);
A3=analogRead(3);
A4=analogRead(4);
A5=analogRead(5);
Serial.println(msg); //for testing
If (twitter.post(msg)) { //To post the Tweet
Int status = twitter.wait(&Serial);
If (status == 200) {
Serial.println(“OK.”);
} else {
Serial.print(“failed : code “);
Serial.println(status);
}
} else {
Serial.println(“connection failed.”);
}
Delay(70000); //
}
}
CHAPTER TWELVE
12.1. Arduino Build Process
T heVarious
processes involved when you want to build a sketch in the Arduino.
things need to occur for your Arduino code to get onto the
Arduino board. To start with, the Arduino development program plays out
some minor pre-processing to transform your sketch into a C++ program.
Next, the conditions of the sketch are found. It is at that point sent to a
compiler (Avr-GCC), which transforms the human-readable code into
machine-readable code. At that point, your code is linked against the standard
Arduino libraries that give essential functions like digitalWrite() or
Serial.print(). The outcome is a solitary Intel hex document, which contains
the particular bytes that should be written in the program memory of the chip
on the Arduino board. This file is then transferred to the board:
communicated over the USB or sequential association through the bootloader
present the chip or with outside programming hardware.
12. 2 Measuring Used RAM on Arduino
In the Arduino IDE directory where you’ll find the avr-gcc compiler, there’s
also a tool called ‘avr-size’. Move to hardware/tools/avr/bin/, you’ll find this
tool there. The IDE makes an impermanent catalog in your temp index when
assembling, and duplicates the whole C(++) documents to it.
Void setup()
{
Serial.begin(9600);
Int a = 42;
Char c = ‘m’;
Float root2 = sqrt(2.0);
Serial.println(a);
Serial.println©;
Serial.println(root2);
}
Void loop()
{
// Empty, no repeating code.
}
Next, we set the time interval. This routine appends itself onto the TIMER0
interrupt, which is set to initiate at approximately every 1 msec. Your
“interval” denotes the number of TIMER0 interrupts to process. Each interval
is approximately 1 millisecond, therefore, you’re basically setting how many
TIMER0 interrupts to count before activating your interval. IOW, inputs the
variable TIMER0_COUNT to the number of milliseconds you intend to wait.
For instance, if you want to wait for 5 seconds, use 5000
Afterwards, you enter the “TIMER0 initialization” code to your setup()
method.
// *** TIMER0 initialization ***
Cli(); // disable all interrupts
TIMSK0 = 0; // disable timer0 for lower jitter
OCR0A = 0xBB; // arbitrary interrupt count
TIMSK0 |= _BV( OCIE0A ); // append onto interrupt
Sei(); // activates interrupt
Now, you just need to include the “time check” code to your loop() method.
If ( time ) {
Time = false;
// do something here
}
The “time = false;” line is essential. If this line is absent, the “do something
here” line(s) would be executed every time the program carries out the loop()
function. Definitely, you’ll replace activities in the “do something here” line
by printing some text or flashing the LED.
Now, these frequencies are ideal for low-frequency applications like fading
an LED. However, these default frequencies are not compatible with High-
frequency circuits; hence, we need to change them.
Let’s take a look at the code for the D3 & D1
The Arduino circuit is imitated in duplicity in order to show how the changes
occur when you apply the code.
From the oscilloscope, you will see that frequency is increased to a very high
value when this line of code is inputted;
TCCR2B = TCCR2B & B11111000 | B00000001; // for PWM frequency of
31372.55 Hz
Furthermore, ensure you set the Board option in the correct manner. The
serial port selection isn’t compulsory for uploading the sketch, however, it is
still necessary if you’re doing anything that involves the serial monitor. To
upload the sketch via the programmer you chose, go to File > Upload Using
Programmer. If you’ll be doing this severally, it can easily be done by
pressing CTRL+SHIFT+U (COMMAND+SHIFT+U on Mac).
12.10. Replacing Arduino Bootloader
If you’ve uploaded a sketch via the programmer, automatically you’ve also
erased the Arduino bootloader. Hence, we have to replace the serial
bootloader on your Arduino. One of the embedded features of the Arduino
IDE is to allow users to (re-)upload a bootloader to the AVR. Here’s how:
Ensure you’ve set the Board option correctly as stated earlier. Then, move to
Tools > Burn Bootloader at the base of the menu. This process may delay a
bit because asides from writing the bootloader into the flash of your AVR,
the fuse bits (setting the clock speed, bootloader space, etc), and lock bits
(barring the bootloader from overwriting itself) will also be (re)set.
The bootloader upload process is said to be complete when the “Burning
bootloader to I/O board (this may take a minute)…” message becomes “Done
burning bootloader.”
Overall, the Arduino microcontroller is a versatile gadget, very versatile, and
it fits conveniently into our daily digital uses. Have a wonderful time
exploring this superb gadget!
About the Author
Obakoma G. Martins is a tech enthusiast with several years of experience in
the ICT industry. He is a geek and passionately follows the latest technical
and technological trends. His strength lies in figuring out the solution to
complex tech problems.
Obakoma holds a Bachelor’s Degree in Computer Science.