0% found this document useful (0 votes)
2 views

4. Intro to the Arduino (1)

The document provides an introduction to microcontroller boards, focusing on various types including Arduino, Raspberry Pi, and BeagleBone, highlighting their features and specifications. It details the Arduino Uno's specifications and programming environment, including how to write and upload sketches, as well as examples of controlling LEDs and using interrupts. The document serves as a guide for beginners to understand microcontrollers and start programming with Arduino.

Uploaded by

Ibrahem Masoud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

4. Intro to the Arduino (1)

The document provides an introduction to microcontroller boards, focusing on various types including Arduino, Raspberry Pi, and BeagleBone, highlighting their features and specifications. It details the Arduino Uno's specifications and programming environment, including how to write and upload sketches, as well as examples of controlling LEDs and using interrupts. The document serves as a guide for beginners to understand microcontrollers and start programming with Arduino.

Uploaded by

Ibrahem Masoud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Intro to the Microcontroller

Boards and Arduino


Microcontroller Boards
• Microcontroller Boards are boards with integrated microprocessors,
memory, chipset and on-board peripherals like LCD, Keypad, USB,
serial port, ADC, RTC, Motor Driver ICs, SD card slot, Ethernet, etc. ,
and input - output pins to get information from the environment and
to control attached devices.
• There are many alternatives to choose from.
• We will use Arduino Microcontroller Boards because of their low cost
and simplicity on coding.
Microcontroller Boards
Raspberry Pi 4 Development Board BeagleBone Black Development Board

Released in 2019 Raspberry Pi 4 is the fastest


BeagleBone Black consists of 512MB RAM with 4GB FLASH
microcontroller board available today. It’s available in
storage. It has 46 × 2 number of header pins, Ethernet, 2 USB
different RAM choices, ranging from 2GB up to 8GB. More
ports. The higher number of I/O pins makes it more suitable
features include onboard wireless LAN, Bluetooth 5.0, two
for electronics projects. It also has reduced consumption of
USB 2.0 and USB 3.0 ports, two Micro HDMI ports, and a
power with no requirement of heat sinks. It also has to be
Gigabit Ethernet port. Up to 64GB SD card can be used for
used with an Operating System.
storage. It has to be used with an Operating System.
Microcontroller Boards (Cont.)
AdaFruit Flora Development Board Teensy 4.0

Teensy 4.0 microcontroller board (600MHz processor) is of


small size as compared to other boards and can be used to
make various types of DIY projects. All the commands are given
Small, round module with microcontroller AVR via two USB ports to the board. Teensy 4.0 can be programmed
Atmega 32u4 (Flash memory: 8 KB, SRAM: 512 B) is by Arduino IDE with a little Add-on.
designed to support smart clothes. Thanks to the
miniUSB connector, as well as uploaded bootloader,
the module can be programmed directly from the
Arduino IDE environment.
Microcontroller Boards
MBED LPC1768 Intel Quark D2000

MBED LPC1768 microcontroller board includes


a built-in USB FLASH programmer. The board is
based on the NXP LPC1768, 32-bit ARM M3
core. The RAM is 32K with 512K FLASH. It Quark D2000 microcontroller is one of the most robust
consists of I/O peripherals, a USB port, and microcontrollers. It is based on ×86 intel Microcontroller family.
built-in Ethernet. It is a 32-bit microcontroller running at 32MHz with 8K SRAM
and 32K FLASH. It is tremendously flexible as it requires only up
to 3.3 volts DC supply. They only support embedded operating
systems.
Meet Arduino Uno
Arduino UNO Board Specifications
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limit) 6-20V

Digital I/O Pins 14 (of which 6 provide PWM output)

PWM Digital I/O Pins 6


Analog Input Pins 6
DC Current per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
32 KB (ATmega328P) of which 0.5 KB
Flash Memory
used by bootloader
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
Clock Speed 16 MHz
LED_BUILTIN 13
Length 68.6 mm
Width 53.4 mm
Weight 25 g
Arduino Boards
LilyPad Mega

LilyPad is a wearable e-textile technology that was


creatively designed with large connecting pads and a flat
back to allow them to be sewn into clothing with
conductive thread. The LilyPad also has its own family of The Arduino Mega is like the UNO's big brother. It
input, output, power, and sensor boards that are also has lots (54!) of digital input/output pins (14 can be
built specifically for e-textiles. They're even washable! used as PWM outputs), 16 analog inputs, a USB
connection, a power jack, and a reset button.
Arduino Boards
Due
Leonardo

The Leonardo is Arduino's first development board to use one


microcontroller with built-in USB. This means that it can be The Due is Arduino's first ARM-based Arduino
cheaper and simpler. Also, because the board is handling USB development board. This board is based on a
directly, code libraries are available which allow the board to powerful 32bit CortexM3 ARM microcontroller made
emulate a computer keyboard, mouse, and more! programmable through the familiar Arduino IDE. It
increases the computing power available to Arduino
users.
Types of Arduino Boards

Arduino Board Processor Memory Digital I/O Analogue I/O

2KB SRAM, 32KB


Arduino Uno 16Mhz ATmega328 14 6 input, 0 output
flash

84MHz 96KB SRAM, 512KB


Arduino Due 54 12 input, 2 output
AT91SAM3X8E flash

8KB SRAM, 256KB


Arduino Mega 16MHz ATmega2560 54 16 input, 0 output
flash

2.5KB SRAM, 32KB


Arduino Leonardo 16MHz ATmega32u4 20 12 input, 0 output
flash
Other Arduino Boards

https://www.arduino.cc/en/Products/Compare

https://www.arrow.com/en/research-and-
events/articles/choose-the-perfect-arduino-board-for-your-
next-project
Getting Started
• Check out: http://arduino.cc/en/Guide/HomePage
• Arduino microcontrollers are programmed using the Arduino
IDE (Integrated Development Environment)
• Can be downloaded for free from
http://arduino.cc/en/Main/Software
1. Download & install the Arduino environment (IDE)
2. Connect the Arduino board to your computer via the USB cable
3. If needed, install the drivers
4. Launch the Arduino IDE
5. Select your board
6. Select your serial port
7. Open the sketch (program)
8. Upload the program
Select Serial Port and Board
Parts of the IDE main screen
Name of current sketch
Main menus
Action buttons/icons

Verify (AKA compile)


Upload (send to Arduino)
Text area for
writing/editing Start a new sketch
sketches.
Open a sketch (from a file)
Save current sketch (to a file)
Open Serial Monitor window

Error messages and other


feedback show up here.

See: http://arduino.cc/en/Guide/Environment for more information


BareMinimum – sketch organization
• Arduino programs, called “sketches”, are written in a programming language
similar to C and C++
• Every sketch must have a setup() function (executed just once) followed by a
loop() function (potentially executed many times);
setup(): It is called only when the Arduino is powered on or reset. It is used to initialize
variables and pin modes
loop(): The loop functions runs continuously till the device is powered off. The main logic
of the code goes here. Similar to while (1) for micro-controller programming.
• add “comments” to code to make it easier to read (technically optional, but
actually required (by me))
• Many sensors and other hardware devices come with prewritten software – look
on-line for sample code, libraries (of functions), and tutorials
BareMinimum – sketch organization
todbot.com/blog/bionicarduino
Input/Output

Image from Theory and Practice of Tangible User Interfaces at UC Berkley


Digital Input/Output

1
• Digital IO is binary valued—
it’s either on or off, 1 or 0
• Internally, all 0

microprocessors are digital.


Arduino Digital I/0

www.mikroe.com/chapters/view/1

pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
PinMode
• A pin on arduino can be set as input or output by using pinMode
function.

• pinMode(13, OUTPUT); // sets pin 13 as output pin

• pinMode(13, INPUT); // sets pin 13 as input pin


Reading/writing digital values
• digitalWrite(13, LOW); // Makes the output voltage on pin 13 , 0V

• digitalWrite(13, HIGH); // Makes the output voltage on pin 13 , 5V

• int buttonState = digitalRead(2); // reads the value of pin 2 in


buttonState
Our First Program
Place an LED on the breadboard (don’t put both legs into a
single (connected) column)
Wire the LED’s negative (shorter) lead to a 560 Ohm “safety
resistor” then wire the other end of the resistor to ground
(GND)
Wire the LED’s positive (longer) lead to digital Pin 13 on the
Arduino
Plug in the Arduino with the USB cable and run the Arduino IDE
software on the computer
Write the code.
Note: delay(T) waits T millisec
Verify (AKA Compile) the code, then Upload it to the Uno –
notice that it runs immediately (and will re-run if you power
cycle) – the sketch will stay in the Uno memory until
overwritten or erased
Discuss how the sketch works (in general terms: setup(),
loop(), liberal use of comments); digital HIGH is 5V and LOW
is 0V (ground)
This is an example of “control (output) using digital pin 13”
Controlling LED by a pushbutton
• If we wish an LED to be turned on when a pushbutton is pressed then we should first find the
pushbutton we will use.
• A 4 pin pushbutton is usually used which is cheap and flexible.

pin
5V source
10kΩ

• The pushbutton has a simple internal structure as shown above.


• Pins 2 and 3 are connected to a single node as pins 1 and 4.
• We can use any two diagonal pins on the button to control conduction with the button (on or off).
• When used with Arduino, one of the diagonal pins is connected to a 5V source while the other
diagonal pin is connected to an Arduino pin.
• So when the button is pressed there will be 5V on the Arduino pin which can be detected as HIGH by
the controller. Otherwise the pin will be detected as LOW by the controller.
• In order not to leave the pin floating, we should place a pulldown resistor which has a high resistance
(i.e. 10kΩ) between the ground and pin. The circuit is shown above.
Controlling LED by a pushbutton

for safety of LED


and Arduino

560Ω
10kΩ
Pulldown resistor
Controlling LED by pushbutton
• void setup()
• {
• pinMode(12, OUTPUT);
• pinMode(7,INPUT);
• }

• void loop()
• {
/*When the BUTTON is pressed, x will
• int x=digitalRead(7); //read pin 7 as HIGH or LOW
have a value 1; and when not pressed

value will be 0. */
• if(x==HIGH)
• digitalWrite(12,HIGH); /*When x is 1, pin 12 will be given 5V.
• else When x is 0, pin 12 will be given 0V.
• digitalWrite(12,LOW); */
• }
Controlling LED by pushbutton (Alternative)
• int ButtonState; //When the LED is ON its state will be 1 otherwise 0.
• void setup()
• {
• pinMode(12, OUTPUT);
/*When a BUTTON is pressed, the LED will
• pinMode(7,INPUT); be turned on. When another press is
• ButtonState=0; //initialize state to be 0 detected it will be turned off.
• }

• void loop()
• {
• int x=digitalRead(7); //read pin 7 as HIGH or LOW

• if(x==HIGH && ButtonState==0 ) // If the button is pressed and it is at OFF position turn it ON
• { digitalWrite(12,HIGH); delay(100); ButtonState=1; }
• else if (x==HIGH && ButtonState==1)
• {digitalWrite(12,LOW); delay(100); ButtonState=0; }
• }
Controlling Multiple LEDs
Controlling Multiple LEDs (pushbutton to start)
int x; void loop()
int ledArray[]={10,11,12,13};//keep led pin names in an array {
x=digitalRead(8);
void setup()
{ if(x==HIGH)
pinMode(8, INPUT); {
pinMode(ledArray[0], OUTPUT); while(1)
pinMode(ledArray[1], OUTPUT); {
pinMode(ledArray[2], OUTPUT); for(int i=0;i<4;i++)
pinMode(ledArray[3], OUTPUT); {
x=0; digitalWrite(ledArray[i], HIGH);
} delay(100);
}
for(int i=3;i>=0;i--)
{
digitalWrite(ledArray[i], LOW);
delay(100);
}
}
}
}
Controlling Multiple LEDs (pushbutton to start and stop)
int LEDarray[]={9, 10, 11, 12}; void loop()
int i; {
int Bstate=0; int x=digitalRead(8);
void setup() if(x==HIGH && Bstate==0)
{ {
Bstate=1;
while(1)
pinMode(8, INPUT); {
for( i=0;i<4;i++) for(i=0;i<4;i++)
{ { digitalWrite(LEDarray[i], HIGH); delay(100); }
pinMode(LEDarray[i], OUTPUT); for(i=3;i>=0;i--)
} { digitalWrite(LEDarray[i], LOW); delay(100); }
if(digitalRead(8)==HIGH )
} {
Bstate=0;delay(100);break;
}
}
}

}
Arduino Interrupts
• In some cases like the example shown on the previous slide, because
of the delays, information that should be received from some sensors
are missed on real time events.
• In order to prevent this (missing real time sensory information),
Arduino boards can give priority to some pins. This is called
interruption, which pauses all other operations when information
comes to the prioritized pins, and continues to the paused process
after completing the prioritized action.
Arduino Interrupts
• Instead of just watching that pin all the time (by reading the pin at
each iteration), Arduino can farm the work of monitoring that pin to
an Interrupt, and free up loop() to do whatever is necessary to be
done in the meantime!
• The function attachInterrupt() employs the interruption process on
Arduino with three arguments:
• 1. The interrupt number,
• 2. The function name of the interrupt service routine,
• 3. The interrupt mode
Arduino Interrupts
attachInterrupt(The interrupt number, The function name , The interrupt mode)
• 1. The interrupt number, determines what pin can generate an interrupt. This isn't the number of the pin itself, but it's
actually a reference to where in memory the Arduino processor has to look to see if an interrupt occurs. A given space in
that vector corresponds to a specific external pin, and not all pins can generate an interrupt! On the Arduino Uno, pins 2
and 3 are capable of generating interrupts, and they correspond to interrupt vectors 0 and 1, respectively. You can see a
list of what pins are available as interrupt pins, on different Arduino boards.
BOARD DIGITAL PINS USABLE FOR INTERRUPTS
Uno, Nano, Mini, other 328-based 2, 3
Uno WiFi Rev.2, Nano Every all digital pins
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
Zero all digital pins, except 4
MKR Family boards 0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Nano 33 IoT 2, 3, 9, 10, 11, 13, 15, A5, A7
Nano 33 BLE, Nano 33 BLE Sense all pins
Due all digital pins
all digital pins (Only pins 2, 5, 7, 8, 10,
101
11, 12, 13 work with CHANGE)
Arduino Interrupts
attachInterrupt(The interrupt number, The function name , The interrupt mode)

• The function digitalPinToInterrupt(pin) is used translate the actual


digital pin to the specific interrupt number. For example, if you
connect to pin 3, use “digitalPinToInterrupt(3)” as the first parameter
to attachInterrupt().
Arduino Interrupts
attachInterrupt(The interrupt vector, The function name , The interrupt mode)
• 2. The function name of the interrupt service routine - this function determines the code that gets run when
the interrupt condition is met. This function should be defined before or after the loop function. This
function must take no parameters and return nothing. The function should neither do complex operations
nor use “delay()” function.
• 3. The interrupt mode, which determines what pin action triggers an interrupt. The Arduino Uno supports
four interrupt modes:
• LOW to trigger the interrupt whenever the pin is low,

• CHANGE to trigger the interrupt whenever the pin changes value

• RISING to trigger when the pin goes from low to high,

• FALLING for when the pin goes from high to low.

• The Due, Zero and MKR1000 boards allow also:

• HIGH to trigger the interrupt whenever the pin is high.


Arduino Interrupt Example

We want the LED to blink (turn on and off


frequently) if the pushbutton is pushed once. It
should stop blinking on the next push. The
connections should be as shown on the left. The
sketch is on the next slide.
Arduino Interrupt Example
int ledPin = 13;
int interruptPin = 2; //pushbutton is connected to the pin 2.
volatile is a C keyword applied to variables. It means
volatile int state = LOW;
void setup()
that the value of that variable is not entirely within
{ a program's control. It reflects that the value of
pinMode(ledPin, OUTPUT); state could change, and change on something that
pinMode(interruptPin, INPUT); the program itself can't predict.
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, RISING );
// Interrupt takes place when button changes its state from low to high One more useful thing that the volatile keyword
// and blink function is called does is protect us from any accidental compiler
}
optimization. Compilers, as it turns out, have a few
void loop()
{
purposes in addition to turning your source code
while(state) into a machine executable. One of their tasks is to
{ trim unused source code variables out of machine
digitalWrite(ledPin, HIGH); code. Since the variable state is not used or called
delay(200); directly in the loop() or setup() functions, there is a
digitalWrite(ledPin, LOW); risk that the compiler might remove it as an unused
delay(200); variable. Obviously, this is wrong - we need that
}
variable! The volatile keyword has the side effect of
}
void blink() {
telling the compiler to cool its jets and hang on to
state = !state; that variable - it's not a fat finger error!
}
About Interrupt Service Routines (Functions)
• ISRs are special kinds of functions that have some unique limitations most
other functions do not have. An ISR cannot have any parameters, and they
shouldn’t return anything.
• Generally, an ISR should be as short and fast as possible. If your sketch uses
multiple ISRs, only one can run at a time, other interrupts will be executed
after the current one finishes in an order that depends on the priority they
have. millis() relies on interrupts to count, so it will never increment inside
an ISR. Since delay() requires interrupts to work, it will not work if called
inside an ISR. micros() works initially but will start behaving erratically after
1-2 ms. delayMicroseconds() does not use any counter, so it will work as
normal.
• Typically global variables are used to pass data between an ISR and the
main program. To make sure variables shared between an ISR and the main
program are updated correctly, declare them as volatile.
Controlling Multiple LEDs
Controlling Multiple LEDs (pushbutton to start and stop) (with interrupt)
int LEDarray[]={9, 10, 11, 12, 13}; void loop()
int i; {
volatile int Bstate=0; while(Bstate)
void setup()
{
{
pinMode(2,INPUT); //pushbutton is connected to the pin 2.
for( i=0;i<5;i++) for(i=0;i<5;i++)
{ { digitalWrite(LEDarray[i], HIGH); delay(100); }
pinMode(LEDarray[i], OUTPUT); for(i=4;i>=0;i--)
} { digitalWrite(LEDarray[i], LOW); delay(100); }
attachInterrupt(digitalPinToInterrupt(2), ChangeState, RISING );
// Interrupt takes place when button changes its state from low to high }
// and ChangeState function is called
}
}

void ChangeState() {
Bstate = !Bstate;
}
 What is analog ?
 It is continuous range of voltage values (not just 0 or 5V)

 Why convert to digital ?


 Because our microcontroller only understands digital.
Converting Analog Value to Digital
Quantanization the signal
ADC in Arduino
• The Arduino Uno board contains 6 pins for ADC/DAC

• For Analog INPUT: 10-bit analog to digital converter


• This means that it will map input voltages between 0 and 5 volts into integer
values between 0 and 1023
• For Analog OUTPUT: 8-bit digital to analog converter
• This means that it will map output voltages between 0 and 5 volts into integer
values between 0 and 255
 analogRead(A0); // used to read the analog value from the pin A0

 analogWrite(2,128); // used to write the analog value 128 on the


pin 2
int val = analogRead(A0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);

 This reads the voltage on pin A0 and puts it into a variable called val.
val can range from 0 to 1023. If you need a different value, like for an LED
(which takes values from 0 to 255.):
map takes the value of val and converts to the new range of values from 0
to 255.
Pulse-Width Modulation (PWM)
• The Fading example demonstrates the use of analog output (PWM) to fade
an LED. It is available in the File->Sketchbook->Examples->Analog menu of
the Arduino software.
• Pulse Width Modulation, or PWM, is a technique for getting analog results
with digital means.
• Digital control is used to create a square wave, a signal switched between on
and off. This on-off pattern can simulate voltages in between full on (5 Volts)
and off (0 Volts) by changing the portion of the time the signal spends on
versus the time that the signal spends off.
Pulse-Width Modulation (PWM)(Cont.)
• The duration of "on time" is called the pulse width. To get varying
analog values, you change, or modulate, that pulse width. If you
repeat this on-off pattern fast enough with an LED for example, the
result is as if the signal is a steady voltage between 0 and 5v
controlling the brightness of the LED.
Pulse-Width Modulation (PWM)(Cont.)
• In the graphic in next slide, the green lines represent a regular time
period. This duration or period is the inverse of the PWM frequency.
In other words, with Arduino's PWM frequency at about 500Hz, the
green lines would measure 2 milliseconds each.
• A call to analogWrite() is on a scale of 0 - 255, such that
analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
Pulse-Width Modulation (PWM)(Cont.)
PWM instruction example
Sets the output to the LED proportional to the value read
from the potentiometer.

void setup()
{
pinMode(ledPin,OUTPUT);
pinMode(analogPin,INPUT);
}

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
Sample Arduino Code

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
SERIAL MONITOR
• Adding the facility to control any device from
your computer using the Arduino Serial
Monitor.

• The serial monitor is the 'tether' between the


computer and your Arduino - it lets you send
and receive text messages, handy for
debugging and also controlling the Arduino
from a keyboard!
Serial
• All Arduino boards have at least one serial port (also known as a UART
or USART), and some have several.

BOARD USB CDC NAME SERIAL PINS SERIAL1 PINS SERIAL2 PINS SERIAL3 PINS

Uno, Nano, Mini 0(RX), 1(TX)

Mega 0(RX), 1(TX) 19(RX), 18(TX) 17(RX), 16(TX) 15(RX), 14(TX)

Leonardo, Micro,
Serial 0(RX), 1(TX)
Yún

Uno WiFi Rev.2 Connected to USB 0(RX), 1(TX) Connected to NINA

MKR boards Serial 13(RX), 14(TX)

SerialUSB (Native Connected to


Zero 0(RX), 1(TX)
USB Port only) Programming Port

SerialUSB (Native
Due 0(RX), 1(TX) 19(RX), 18(TX) 17(RX), 16(TX) 15(RX), 14(TX)
USB Port only)

101 Serial 0(RX), 1(TX)


Serial (Cont.)
• On Uno, Nano, Mini, and Mega, pins 0 and 1 are used for communication with the computer. Connecting
anything to these pins can interfere with that communication, including causing failed uploads to the board.

• You can use the Arduino environment’s built-in serial monitor to communicate with an Arduino board. Click
the serial monitor button in the toolbar and select the same baud rate used in the call to begin().

• Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on the board). Don’t
connect these pins directly to an RS232 serial port; they operate at +/- 12V and can damage your Arduino
board.

• To use these extra serial ports to communicate with your personal computer, you will need an additional
USB-to-serial adaptor, as they are not connected to the Mega’s USB-to-serial adaptor. To use them to
communicate with an external TTL serial device, connect the TX pin to your device’s RX pin, the RX to your
device’s TX pin, and the ground of your Mega to your device’s ground.
Some of the Serial Functions (Serial.function_name)
• if(Serial): • findUntil(): • println():
• Indicates if the specified Serial port is ready. • Reads data from the serial buffer until a • Prints data to the serial port as human-readable ASCII text
target string of given length or followed by a carriage return character and a newline character
• available(): terminator string is found. The function
returns true if the target string is found, • read():
• Get the number of bytes (characters) available false if it times out. • Reads incoming serial data.
for reading from the serial port. This is data
that’s already arrived and stored in the serial • flush(): • readBytes():
receive buffer (which holds 64 bytes). • Waits for the transmission of • Returns the number of characters placed in the buffer. A 0
means no valid data was found.
outgoing serial data to
• begin(): complete. • Syntax: Serial.readBytes(buffer, length)
• Sets the data rate in bits per second (baud) for • readBytesUntil():
serial data transmission. • parseFloat(): • Reads characters from the serial buffer into an array.
• Returns the first valid floating • Syntax: Serial.readBytesUntil(character, buffer, length)
• end(): point number from the Serial
• Disables serial communication, allowing the RX and buffer. • readString():
TX pins to be used for general input and output. • Reads characters from the serial buffer into a String.
• parseInt():
• find(): • Looks for the next valid integer • setTimeout():
in the incoming serial. • Sets the maximum milliseconds to wait for serial data. It
• Serial.find() reads data from the serial buffer until defaults to 1000 milliseconds.
the target is found. The function returns true if target
is found, false if it times out.
• print(): • Syntax: Serial.setTimeout(time)
• Prints data to the serial port as • write():
• Syntax: human-readable ASCII text. This
• Serial.find(target) OR command can take many forms. • Writes binary data to the serial port. This data is sent as a byte
or series of bytes; to send the characters representing the digits
• Serial.find(target, length) Numbers are printed using an ASCII of a number use the print() function instead.
character for each digit. Floats are
similarly printed as ASCII digits,
defaulting to two decimal places.
Bytes are sent as a single character.
Characters and strings are sent as is.
Serial Monitoring Example
(Brightness of the LED is entered by user)
const int ledPin = 3; // the pin that the LED is attached to
void setup() {
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
int brightness=0;

void loop() {

if (Serial) //check if the Serial port is ready


{

Serial.println("Enter the brightness level as a percentage");


delay(2000);
if(Serial.available())// Get the number of bytes (characters)
//available for reading from the serial port.
//if it is zero we haven't entered any value: DO NOTHING
{

brightness = Serial.parseInt(); // set the brightness of the LED:


brightness=map(brightness,0,100,0,255);// convert percentage to 8 bit
Serial.print("Brightness = ");
Serial.println(brightness);
analogWrite(ledPin, (int)(brightness));
delay(2000);
}
}
}
//Program to turn on the chosen one of 4 LEDs for 2 seconds
int dataPin[4]={43,44,45,46};
int LEDon=0;
void setup()
{

for(int i=0;i<4;i++)
pinMode(dataPin[i], OUTPUT);

Serial.begin(9600); // initialize serial communications at 9600 bps


while (! Serial); // Wait until Serial is ready
Serial.print("Enter LED Number 0 to 3\n "); // Display message on Serial Monitor
}
void loop()
{
if (Serial.available())
{
char ch = Serial.read(); // Read input from user and assign it to the character variable ch
if (ch >= '0' && ch <= '3')
{
int LEDon= ch - '0'; // Convert the type of input from char to int
Serial.print("\nTurned on LED ");
Serial.print(LEDon);
digitalWrite(dataPin[LEDon],HIGH);
delay(2000);
digitalWrite(dataPin[LEDon],LOW);
}
else
Serial.print("\nRe-enter value between 0 and 3\n");
}
}
User-defined Function
• Segmenting code into functions allows a programmer
to create modular pieces of code that perform a
defined task and then return to the area of code from
which the function was "called".
• The typical case for creating a function is when one
needs to perform the same action multiple times in a
program.

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
Advantages of User-defined Function
• Functions help the programmer stay organized. Often
this helps to conceptualize the program.
• Functions codify one action in one place so that the
function only has to be thought out and debugged
once.
• This also reduces chances for errors in modification, if
the code needs to be changed.

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
Advantages of User-defined Function
• Functions make the whole sketch smaller and more
compact because sections of code are reused many
times.
• They make it easier to reuse code in other programs by
making it more modular, and as a nice side effect, using
functions also often makes the code more readable.

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
User-defined Function

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
Pre-defined Function
void setup()
{
//put your settings here
}
void loop()
{
//put your actions here
}

Getting Started with Arduino, Massimo Banzi, 2nd Edition:


www.it-ebooks.info
About Motors
•There are several different types
– Standard DC motor - input current for full continuous rotation. No
special pins or wiring.
– Standard servomotor (AKA servos) - Motor capable of limited
rotation (generally 180°) in precise degree increments. Uses Servo
library in Arduino. Have 3+ pins. Controlled by pulse-width
modulation (PWM) (“~” pins)
– Continuous rotation servo – can go all the way around
continuously. Interprets PWM value as speed & dir.
–Stepper Motors - Servo capable of full rotation in small steps.
Uses Stepper library in Arduino. Have 3+ pins
Servo

Note that the servo has a plug attached to its ribbon cable. This is so that we can more
easily extend the cable using plugs and more ribbon cable. It also allows it to plug into
specific plugs built into some shields. Several companies make a few different Motor
Shields, which are shields specifically designed to drive servos, motors, and stepper
motors. These usually support 2 to 4 motors, although Adafruit has one that will
control 16. They generally have plugs built into the shield for the motors and often
drive them through some sort of a serial connection (I2C or SPI is common).

Right: Adafruit Motor Shield


http://www.adafruit.com/products/1411
Note about Libraries:
• Libraries take large amounts of code and refine it into a few
simple commands we can use. Ex: datalog.print will print
something to a file.
• This actually takes a lot of code, but by putting it in a library we
can ignore the basic code and focus on the useful commands
and functions
• Usually ends in a .h (header file)
• Used in our programs by the #include command: #include
"SD.h"
• Almost everything that is not analog (digital sensors, servos, etc)
use a library of some sorts (Many use the same library-ie. Wire)
• You can install more libraries into your IDE. Look under
Sketch:Import Library to see which ones you have.
• Ex: “SD.h”, SoftwareSerial.h, Wire.h, OneWire.h,
“RTClib.h”

You might also like