[go: up one dir, main page]

0% found this document useful (0 votes)
36 views91 pages

4 Functions(1)

Uploaded by

thembelihle.mng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views91 pages

4 Functions(1)

Uploaded by

thembelihle.mng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Arduino

Arduino Uno ATmega328 Arduino Mega ATmega2560

Functions
Created by: Dr. Daniel van Niekerk
Digital I/O: pinMode() function
• Description
̶ Configures a specified pin to behave either as an INPUT or an OUTPUT.
̶ It is also possible to enable the internal pull-up resistors with mode INPUT_PULLUP.
̶ Additionally, the INPUT mode explicitly disables internal pull-ups.
• Syntax
̶ pinMode(pin, mode)
• Parameters
̶ pin: the number of the microcontroller pin to set its mode (0, 1, 2, …,13, A0, A1, …A5).
̶ mode: INPUT, OUTPUT, or INPUT_PULLUP.
• Returns
̶ Nothing
• Note
̶ The analog input pins can also be used as digital pins, referred to as A0, A1, A2,…A5.
Digital I/O: digitalWrite() function
• Description
̶ Writes a HIGH or a LOW value to a digital pin.
̶ If pin is configured as an OUTPUT, its voltage will be 5V for HIGH and 0V for LOW.
̶ If pin is configured as an INPUT using pinMode(),
> digitalWrite(pin, HIGH) enables the internal pull-up resistor.
> digitalWrite(pin, LOW) disables the internal pull-up resistor.
̶ Rather use INPUT_PULLUP with pinMode() to enable the internal pull-up resistor.
• Syntax
̶ digitalWrite(pin, value)
• Parameters
̶ pin: the number of the digital pin (0, 1, 2, …,13, A0, A1, …A5).
̶ value: HIGH or LOW
• Returns
̶ Nothing
Example: digitalWrite() function
// constant text “pinLED” makes code more readable
const int pinLED = 10; // anode of LED connected to digital
// pin 10 and GND through 220R resistor

void setup()
{
pinMode(pinLED, OUTPUT); // sets the digital pin as output
}

void loop()
{
digitalWrite(pinLED, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(pinLED, LOW); // sets the LED off
delay(1000); // waits for a second
}
Digital I/O: digitalRead() function
• Description
̶ Reads the value from a specified digital input pin, either as HIGH (5 V) or LOW (0 V).
• Syntax
̶ digitalRead(pin)
• Parameters
̶ pin: the number of the digital pin to read (0, 1, 2, …,13, A0, A1, …A5).
• Returns
̶ HIGH or LOW
• Note
̶ If the pin isn't connected to anything (floating pin) then digitalRead() can return either
HIGH or LOW that randomly changes every time the pin is read.
Example: digitalRead() function
const int pinPB = 7; // pushbutton connected pin 7 and ground
boolean boolVal = false; // variable to store the read value

void setup()
{
// sets built-in led connected to digital pin 13 as an output
pinMode(LED_BUILTIN, OUTPUT);
// sets the digital pin 7 as input with pull-up resistor enabled
pinMode(pinPB, INPUT_PULLUP);
}

void loop()
{
// note: (true == HIGH == 1 == 5V) and (false == LOW == 0 == 0V)
boolVal = digitalRead(pinPB); // read the input pin
digitalWrite(LED_BUILTIN, boolVal); // sets LED to button's value
delay(10); // pushbutton de-bounce delay
}
Analog I/O: analogReference() function
• Description
̶ Configures the reference voltage or the top voltage level of analog input range, for the
analog input pins.
̶ Reference voltage options are:

̶ DEFAULT: the default analog reference of 5 Volts (on 5 V Arduino boards)


or 3.3 Volts (on 3.3 V Arduino boards)

̶ INTERNAL: a built-in reference, equal to 1.1 volts on the ATmega328 or


ATmega168 and 2.56 volts on the ATmega8
(This option is not available on the Arduino Mega)

̶ INTERNAL1V1: a built-in 1.1 volt reference (Arduino Mega only)

̶ INTERNAL2V56: a built-in 2.56 volt reference (Arduino Mega only)

̶ EXTERNAL: the voltage applied to the AREF pin (0 to 5 V only) is used as the
reference voltage.
Analog I/O: analogReference() function
• Syntax
̶ analogReference(type)
• Parameters
̶ type: which type of reference to use:
> DEFAULT, // On Arduino 5 V or 3.3 V boards
> INTERNAL, // 1.1 V on ATmega328 or ATmega168 and 2.56 V on ATmega8
> INTERNAL1V1, // 1.1 V only on Arduino Mega board
> INTERNAL2V56 or // 2.56 V only on Arduino Mega board
> EXTERNAL. // Voltage level between 0 V and 5 V, on AREF pin
• Returns
̶ Nothing
• Note
̶ After changing the analog reference, the first few readings from analogRead() may not
be accurate.
Analog I/O: analogReference() function
• Warning
̶ Don't use anything < 0 V or > 5 V, for external reference voltage on the AREF pin!
̶ As soon as analogRead() called in code, AREF pin = 5 V (DEFAULT) or 1.1 V (INTERNAL).
̶ If using an external reference voltage on AREF pin, set analog reference to EXTERNAL
before calling analogRead().
̶ Otherwise, the active internally generated reference and AREF pin voltage, will be
shorted together, damaging the microcontroller on the Arduino board.
̶ Alternatively, connect external reference voltage to AREF pin through a 5 K resistor, this
allows switching between external and internal reference voltages without damage.
̶ Note that the resistor will alter the voltage that gets used as the reference because
there is an internal 32 K resistor to ground on the AREF pin.
̶ The two act as a voltage divider, so for 2.5V applied through the 5K resistor, voltage at
AREF pin will be: (2.5 V * 32 K / (32 K + 5 K)) = 2.2 V at the AREF pin.
Arduino Microcontroller 2.5 V
2.2 V AREF Pin
Internal Ref
5K
32 K
Analog I/O: analogRead() function
• Description
̶ Reads digitized value of an analog voltage connected to a specified analog input pin.
̶ The Arduino board contains a 10-bit analog to digital converter (ADC).
̶ This means that it will map input voltages between 0 to 5 volts, into integer values
between 0 and 1023.
̶ This yields a resolution of: (5 V / 1023) volts/bit or 0.00488 V per bit.
̶ The input range and resolution can be changed using analogReference().
̶ It takes about 100 microseconds (0.0001 s) to read an analog input.
̶ So the maximum sampling rate is approximately 10,000 times a second (1/100 us).
• Note
̶ For a 10-bit ADC, the range will be from 0 to (2^10-1) = 1023 bit changes.
̶ There are 6 ADC channels on the UNO, 8 ADC channels on the Mini & Nano and 16 ADC
channels on the Mega Arduino boards.
Analog I/O: analogRead() function
• Syntax
̶ analogRead(pin)
• Parameters
̶ pin: the number of the analog input pin to read from (A0, A1, …A5).
• Returns
̶ int (0 to 1023)
• Note
̶ ADC pins are: A0 to A5 on the UNO, A0 to A7 on the Mini & Nano and A0 to A15 on the
Arduino Mega boards.
̶ If the analog input pin is not connected to anything, value returned by analogRead()
will fluctuate based on a number of factors.
̶ Such as the values of the other analog inputs or how close your hand is to the board,
static electricity, etc...
Example: analogRead() function
const int pinAnalogPot = A3; // potentiometer wiper (middle terminal)
// connected to analog pin A3
// outside leads to ground and +5 volts

int iVal = 0; // variable to store the value read

void setup()
{
Serial.begin(9600); // setup serial to 9600 bits per second
}

void loop()
{
iVal = analogRead(pinAnalogPot); // read digitized analog input pin
Serial.println(iVal); // serially send value to debug
delay(1000); // one second delay between reads
}
Example: Moving Average Analog to Digital Filter
const int AVG_BY = 5; // average 5 ADC values
char cInd = 0; // array index pointer
int iArr[AVG_BY]; // used to log ADC data
int iTotal = 0; // running total
int iAvg = 0; // moving average
int iVal = 0; // used in loop()
int AvgFil(int iADC){
iTotal = iTotal - iArr[cInd]; // subtract last ADC data
iArr[cInd] = iADC; // update with new data
iTotal = iTotal + iADC; // add new data to total
cInd++; // next array position
if(cInd == AVG_BY) cInd = 0; // wrap to beginning
iAvg = iTotal / AVG_BY; // calculate average
return(iAvg);
}
void setup(){
Serial.begin(9600); // setup serial to 9600 bps
}
void loop(){
iVal = AvgFil(analogRead(A0)); // read analog input pin and average
Serial.println(iVal); // serially send average value
delay(1000); // one second delay between reads
}
Analog I/O: analogWrite() function
• Description
̶ The analogWrite() function outputs Pulse Width Modulation (PWM) to a given pin.
̶ After a call to analogWrite() function, the specified pin will generate a steady square
wave with specified duty cycle until the next call to analogWrite() function.
̶ The pinMode() function doesn't need to be call, to set the pin as an output before
calling analogWrite() function.
̶ The analogWrite() function has nothing to do with the analog pins or analogRead()
function.
• Note
̶ The PWM can be used to vary the brightness of an LED, used to drive a DC motor at
various speeds etc...
̶ On most Arduino Uno boards (with ATmega168 or ATmega328), the PWM function
works on pins 3, 5, 6, 9, 10, and 11.
̶ The frequency of the PWM signal on pins 3, 9, 10 and 11 is approximately 490 Hz.
̶ On the Arduino Uno, pins 5 and 6 have a frequency of approximately 980 Hz.
̶ Pins 3 and 11 on the Arduino Leonardo board, also run at 980 Hz.
̶ On the Arduino Mega, PWM is available on pins 2 - 13 and 44 - 46.
Analog I/O: analogWrite() function
• Syntax
̶ analogWrite(pin, value)
• Parameters
̶ pin: the pin to write to (Arduino Uno pins: 3, 5, 6, 9, 10 & 11).
̶ value: the duty cycle, between 0 (always off) and 255 (always on).
• Returns
̶ Nothing
• Known Issues
̶ On pins 5 and 6 the PWM outputs generated will have higher-than-expected duty
cycles when using the millis() and delay() functions.
̶ This is because the internal timer used to generate those PWM outputs, is shared with
the millis() and delay() functions.
̶ This will be noticed mostly on low duty-cycle settings (0 - 10) and may result in a value
setting of 0, not fully turning off the output on pins 5 and 6.
Example: analogWrite() function
/* Output PWM, controlled by voltage divider potentiometer input */

const int pinLED = 9; // LED connected to pin 9 and GND via 220R
const int pinAnalogPot = A3; // potentiometer connected to pin A3
int iVal = 0; // variable to store the ADC read value

void setup(){
// “pinMode(pinLED, OUTPUT)” not required, to set PWM pin as output pin
}

void loop()
{
iVal = analogRead(pinAnalogPot); // get ADC result on analog A3 pin
analogWrite(pinLED, iVal / 4); // result range is from 0 to 1023
// PWM range is from 0 to 255
} // Note: 1023/4 = 255.75 ≈ 255
Analog I/O: analogWrite() function
• Pulse Width Modulation
̶ PWM, is a technique for getting analog results by digital means.
̶ Digital control is used to create a square wave signal, switched between on and off.
̶ This on-off pattern can simulate voltages in-between fully on (5 V) and fully off (0 V) by
changing the portion of time the signal spends “on” versus the time that the signal
spends “off”.
̶ The duration of "on time" is called the pulse width or the Duty Cycle.
̶ By changing or modulating the pulse width while the period remains fixed, it generates
a varying average analog output value.
̶ If this on-off pattern is repeated fast enough on an LED, the result is the same as
varying a steady voltage between 0 V & 5 V thereby, controlling the LED brightness.
Analog I/O: analogWrite() function

̶ In the graphic the green lines represent the


fixed PWM time period.
̶ This duration or period is the inverse of the
PWM frequency.
̶ On Arduino Uno PWM pins 3, 9, 10 and 11
the frequency is about 490 Hz therefore, the
period of the PWM is approximately 2 ms
(T=1/f).
̶ On Arduino Uno PWM pins 5 and 6 the
frequency is about 980 Hz therefore, the
period of the PWM is approximately 1 ms
(T=1/f).
̶ The analogWrite() has a range of 0 - 255,
such that analogWrite(255) results in a
100% duty cycle (always on).
̶ For analogWrite(127), approximately 50%
duty cycle is set which means that the pin is
set HIGH half of the period time.
Advanced I/O: tone() function
• Description
̶ Generates a square wave of the specified frequency, at 50% duty cycle on a pin.
̶ Duration can be specified or the wave continues until a call to noTone() function.
̶ Only one tone can be generated at a time, on a given pin.
̶ If a tone is already playing, a call to tone() on a different pin will have no effect.
̶ If a tone is playing on a given pin, a call to tone() on this pin will set its frequency again.
̶ It is not possible to generate tones lower than 31Hz.
• Note
̶ The digital pin can be connected to a piezo buzzer or a speaker, to play tones.
̶ Use of tone() function will interfere with PWM output on pins 3 and 11 on Arduino Uno
boards except the Arduino Mega board.
̶ If you want to play different pitches on multiple pins, you need to call noTone() on one
pin before calling tone() on the next pin.
̶ After calling the tone() function, normal code execution continues.
Advanced I/O: tone() function
• Syntax
̶ tone(pin, frequency)
̶ tone(pin, frequency, duration)
• Parameters
̶ pin: the pin on which to generate the tone.
̶ frequency: the frequency of the tone in hertz (unsigned int).
̶ duration: is “optional”, the duration of the tone in milliseconds (unsigned long).
• Returns
̶ Nothing
Advanced I/O: noTone() function
• Description
̶ Stops the generation of a square wave on the specified pin that was triggered by tone().
̶ Has no effect, if no tone is being generated on the specified pin.
• Note
̶ If you want to play different pitches on multiple pins, call noTone() on one pin before
calling tone() on the next pin.
• Syntax
̶ noTone(pin)
• Parameters
̶ pin: the pin on which to stop generating the tone.
• Returns
̶ Nothing
Advanced I/O: shiftOut() function
• Description
̶ Shifts-out a byte, one bit at a time, from either leftmost (MSB) or rightmost (LSB) bit.
̶ Each data bit is written to a pin, after which a clock pin is pulsed (taken high then low).
̶ If the device is clocked by rising edges, the clock pin must first be set LOW using
digitalWrite(), before a call to shiftOut() function.
• Syntax
̶ shiftOut(dataPin, clockPin, bitOrder, value)
• Parameters
̶ dataPin: the pin on which to output each data bit (byte).
̶ clockPin: the pin to toggle once the dataPin has been set to the correct data bit (byte).
̶ bitOrder: which order to shift out the bits, either MSBFIRST or LSBFIRST.
̶ value: the data byte to shift out (byte).
• Returns
̶ Nothing
• Note
̶ This is a software implementation, the SPI library provides a hardware implementation
that is faster but works only on specific pins.
Advanced I/O: shiftOut() function
• Note
̶ The dataPin and clockPin must be configured as outputs by a call to pinMode().
̶ shiftOut() outputs only one byte (8-bits), so it requires a two step operation to output
date values larger than 255.
• For 16-bit shift
// Do this for “Most significant Bit” serial out
int iData = 500;
// shift out highbyte
shiftOut(pinData, pinClock, MSBFIRST,(iData >> 8));
// shift out lowbyte
shiftOut(pinData, pinClock, MSBFIRST, iData);

// Or do this for “Least significant Bit” serial out


iData = 1024;
// shift out lowbyte
shiftOut(pinData, pinClock, LSBFIRST, iData);
// shift out highbyte
shiftOut(pinData, pinClock, LSBFIRST, (iData >> 8));
74HC595: 8-bit Shift Register with output latches
̶ The 74HC595 has a serial-in 8-stage shift
register and a D-type parallel-out 8-bit
storage register that feeds eight output
3-state buffers.
̶ 8-bits of data is clocked in a serial fashion
into the shift register and then the output
drivers are activated to make the data
available at the output.
̶ Received data is latched out only after the
8-bit data is shifted in, otherwise the
output will change as the data is clocked
into the shift register.
̶ Separate clocks are provided for the shift
register (SCK) and storage register (RCK).
̶ The shift register can be cleared (SCLR)
and a serial output pin (QH’) can be used
for cascading.
̶ When gate pin (G) is low the eight buffers
are in output mode.
74HC595: 8-bit Shift Register with output latches
̶ The 74HC595 device can be connected to
5V
the Arduino as follows:
74HC595
̶ SCLR pin is connected high to prevent Arduino
SCLR QA Bit 0
shifted data from being cleared. Clock
Pin 10 SCK Bit 1
̶ G pin is connected low to output the 8-bit
storage register data to QA-QH. Pin 11
Latch
RCK
̶ A high or low input at Data-in (Pin 12) is Data in
shifted in when a low to high or positive Pin 12 SI QH Bit 7
edge trigger occurs on the Clock (Pin 10). G QH’ Data out

̶ When all 8-bits of data is serially shifted in,


the Latch (Pin 11) must be set high and
then low to latch the serially received data Old_74HC595 New_SN74HC595
to the output pins (QA to QH) of the
74HC595 device.
̶ The advantage of this system is that only
three digital pins are require to serially
shift and output 8-bits of data.
̶ Three pull-down 10K resistors on pins 10,
11 & 12 will ensure that the 74HC595 pins
do not float during power-ups or resets.
Example: shiftOut() function
/* using shiftOut() to send 8-bit data to 74HC595 serially */

const int pinClock = 10; // connected to Clock (Pin 10 to SCK)


const int pinLatch = 11; // connected to Latch (Pin 11 to RCK)
const int pinData = 12; // connected to Data-in (Pin 12 to SI)

void setup()
{
pinMode(pinLatch, OUTPUT);
pinMode(pinClock, OUTPUT);
pinMode(pinData, OUTPUT);
}

void loop()
{
for(int iData = 0; iData < 256; iData++)
{
digitalWrite(pinLatch, LOW); // latch pin to initial state
digitalWrite(pinClock, LOW); // to ensure rising edge clock
shiftOut(pinData, pinClock, MSBFIRST, iData);
digitalWrite(pinLatch, HIGH); // set high to output data
delay(500); // 0.5s delay between writes
}
}
Advanced I/O: shiftIn() function
• Description
̶ Shifts-in a byte of data, one bit at a time from either the leftmost (MSB) or rightmost
(LSB) bit.
̶ For each data bit, the clock pin is pulled high, the data bit is read from the data pin,
then the clock pin is taken low.
̶ If the device is clocked by rising edges, then clock pin must first be set LOW using
digitalWrite(), before a call to shiftIn() function.
• Syntax
̶ byte bytComingIn = shiftIn(dataPin, clockPin, bitOrder);
• Parameters
̶ dataPin: the pin on which to input each data bit (int).
̶ clockPin: the pin to toggle before reading data bit at the dataPin.
̶ bitOrder: which order to shift in data bits, either MSBFIRST or LSBFIRST.
• Returns
̶ The value read (byte).
• Note
̶ This is a software implementation, the SPI library provides a hardware implementation
that is faster but works only on specific pins.
74HC165: 8-bit parallel-in/serial-out shift register
̶ Parallel input port expansion can be
implemented using a 74HC165, 8-bit
parallel-in and serial-out shift register.
̶ Data is loaded into a shift register and
then shifted out into the Arduino serially.
̶ This is the reverse process of shifting data
to a parallel output expansion port.
̶ First strobe the PL pin (set low then high)
to store the parallel data on “D0 to D7”
into the 8-bit shift register of the 74HC165
device. 5V
̶ When PL pin is pulled high, the 8-bit input 74HC165
data can then be serially read out of Q7 Arduino
D0 Bit 0
pin into the Arduino, by shifting left. Pin 10
Clock
CP Bit 1
̶ The data at Q7 pin is clocked in with each
Load
positive-edge, low to high transition on Pin 11 PL
the CP pin.
Data out
Pin 12 Q7 D7 Bit 7
̶ One pull-up and two pull-down 10K
CE Ds Data in
resistors on pins 10, 11 & 12, ensures that
the 74HC165 pins do not float during
power-ups or resets.
Example: shiftIn() function
/* using shiftIn(), serially read in 8-bit data from 74HC165 device */
const int pinClock = 10; // connected to Clock (Pin 10 to CP)
const int pinLoad = 11; // connected to Load (Pin 11 to PL)
const int pinData = 12; // connected to Data-out (Pin 12 to Q7)
unsigned char ucData[256]; // Data array to store data bytes read

void setup(){
pinMode(pinClock, OUTPUT);
pinMode(pinLoad, OUTPUT);
pinMode(pinData, INPUT);

for(int iCnt = 0; iCnt < 256; iCnt++)


{
digitalWrite(pinClock, HIGH); // set clock high before L-H on PL
digitalWrite(pinLoad, LOW); // load new data into 74HC165
digitalWrite(pinLoad, HIGH); // to allow data to leave 74HC165
ucData[iCnt] = shiftIn(pinData, pinClock, LSBFIRST);
delay(500); // 0.5s delay between reads
}
}

void loop(){
//....
}
Advanced I/O: pulseIn() function
• Description
̶ Measures pulse width length for either high or low square wave pulse input, on a pin.
̶ If it’s a high pulse, pulseIn() waits for the pin to go high to start timing and then waits
for the pin to go low to stop timing.
̶ It returns pulse length value in microseconds or gives up and returns 0, if no pulse
starts within a specified timeout.
̶ Works on pulses ranging from 10 microseconds to 3 minutes in length.
• Syntax
̶ pulseIn(pin, value)
̶ pulseIn(pin, value, timeout)
• Parameters
̶ pin: the number of the pin on which to read the pulse width (byte).
̶ value: the type of pulse to read: either HIGH or LOW (byte).
̶ Timeout: is optional, number of us to wait for pulse to start, 1s default (unsigned long).
• Returns
̶ Pulse length in microseconds or 0 if no pulse started after timeout (unsigned long).
• Note
̶ This function will probably show errors with longer pulse widths.
Example : pulseIn() function
/* If input pulse width every 20 ms is >= 1.5 ms, switch on a relay */
/* If input pulse width every 20 ms is < 1.5 ms, switch off a relay */

const int pinPulse = 7; // for input pulse width signal


const int pinRelay = 2; // for controlling relay coil energization
unsigned long ulDuration;

void setup()
{
pinMode(pinPulse, INPUT); // used to measure pulse width of signal
pinMode(pinRelay, OUTPUT); // used to switch on relay when set HIGH
}

void loop()
{
ulDuration = pulseIn(pinPulse, HIGH); // get pulse width duration

if(ulDuration >= 1500) // duration in microseconds


digitalWrite(pinRelay, HIGH); // switch on relay coil
else
digitalWrite(pinRelay, LOW); // switch off relay coil
}
Time: millis() function
• Description
̶ This function returns the number of milliseconds since the Arduino board began
executing its current program.
̶ Return value of millis() function is an unsigned long number.
̶ This number will overflow back to zero, after approximately 50 days.
• Syntax
̶ millis()
• Parameters
̶ None
• Returns
̶ Number of milliseconds since the program started (unsigned long).
• Note
̶ Errors may occur if the millis() return value math with data types other than an
unsigned long, is executed.
̶ (232-1)= 4294967295 ms/1000 = 4294967 s/60 = 71582 min/60 = 1193 hr/24 = 49.7 Days
Example: millis() function
/* serially sends time in “ms” since program start after PB press */

const int pinPB = 2; // push-button connected to pin 2 and GND


unsigned long ulTime;

void setup()
{
Serial.begin(9600);
pinMode(pinPB, INPUT_PULLUP);
}

void loop()
{
if(digitalRead(pinPB)== LOW)
{
Serial.print("Time: ");
ulTime = millis();
// prints time in milliseconds since program started
Serial.print(ulTime);
Serial.println(" ms");
delay(10); // for push button switch de-bouncing
}
}
Time: micros() function
• Description
̶ This function returns the number of microseconds since the Arduino board began
executing its current program.
̶ Return value of micros() function is an unsigned long number.
̶ This number will overflow back to zero, after approximately 70 minutes.
• Syntax
̶ micros()
• Parameters
̶ None
• Returns
̶ Number of microseconds since the program started (unsigned long).
• Note
̶ On a 16 MHz Arduino board, this function has a resolution of four microseconds
(i.e. the value returned is always a multiple of four).
̶ Note that there are 1,000 us in 1ms and 1,000,000 us in 1 s.
̶ (232-1) = 4294967295 us/1000000 = 4294 s/60 = 71.58 min
Example: micros() function
/* serially sends time in “us” since program start and every second
thereafter */

unsigned long ulTime;

void setup()
{
Serial.begin(9600);
}

void loop()
{
Serial.print("Time: ");
ulTime = micros();
//prints time since program started and every second thereafter
Serial.print(ulTime);
Serial.println(" us");
// wait a second so as not to send massive amounts of data
delay(1000);
}
Time: delay() function
• Description
̶ Pauses program execution for the amount of time specified by the parameter, in
milliseconds (ms).
• Syntax
̶ delay(ms)
• Parameters
̶ ms: the number of milliseconds to pause (unsigned long).
• Returns
̶ Nothing
• Note
̶ Note that there are 1000 milliseconds in one second.
Example: delay() function
/* continually switch an LED on for 1s and then off for 500ms */

const int pinLED = 4; // LED connected to pin4 & GND via 220R

void setup()
{
pinMode(pinLED, OUTPUT); // sets the digital pin as output
}

void loop()
{
digitalWrite(pinLED, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(pinLED, LOW); // sets the LED off
delay(500); // waits for 1/2 a second
}
Time: delay() function
• Known Issues
̶ While it is easy to create a blinking LED or switch de-bouncing with the delay() function,
the use of delay() in a sketch has significant drawbacks.
̶ No other reading of sensors, mathematical calculations or pin manipulation can go on
during the delay function, so in effect it brings most other activity to a halt.

̶ However, certain things do go on while the delay() function pauses program execution
because the delay() function does not disable interrupts and it still works as it should.
̶ Serial communication that appears at the RX pin is recorded, analogWrite() PWM
outputs and pin states are maintained.

̶ Use and poll the millis() function instead, for an alternative approach to control timing.
̶ More knowledgeable programmers usually avoid the use of delay() for timing of events
longer than 10's of milliseconds.
̶ If the Arduino sketch code is simple then there is no problem in generating longer delays
with the delay() function.
Time: delayMicroseconds() function
• Description
̶ Pauses program execution for the amount of time specified by the parameter, in
microseconds (us).
̶ Currently the largest value that will produce an accurate delay, is: 16383 us.
̶ Note that this could change in future Arduino releases.
̶ For delays longer than a few thousand microseconds, use delay() function instead.
• Syntax
̶ delayMicroseconds(us)
• Parameters
̶ us: the number of microseconds to pause (unsigned int).
• Returns
̶ Nothing
• Note
̶ Note that there are 1000 microseconds in one millisecond and there is 1000 000
microseconds in one second.
̶ The delayMicroseconds(us) does not make use of interrupts to tie the delay and
therefore, in can be used inside an Interrupt Service Routine (ISR).
Example: delayMicroseconds() function
/* generates a 50 us high by 100 us low pulse train */

const int pinPT = 8; // digital pin to generate pulse train

void setup()
{
pinMode(pinPT, OUTPUT); // sets the digital pin as output
}

void loop()
{
digitalWrite(pinPT, HIGH); // set PW pin high
delayMicroseconds(50); // pauses for 50 microseconds
digitalWrite(pinPT, LOW); // sets the pin off
delayMicroseconds(100); // pauses for 100 microseconds
}

• Known Issues
̶ This function works very accurately in the range of 3 to 16383 microseconds.
̶ The delayMicroseconds() may not perform precisely for smaller delay times.
̶ The delayMicroseconds() no longer disables interrupts.
Math: min() function
• Description
̶ Calculates the minimum of two numbers.
• Syntax
̶ min(x, y)
• Parameters
̶ x: the first number, any data type.
̶ y: the second number, any data type.
• Returns
̶ The smaller of the two parameter number values.
• Example
sensVal = min(sensVal, 100); // assigns sensVal to smaller of
// either sensVal or 100, ensures that
// sensVal never gets above 100.
Math: min() function
• Note
̶ Perhaps counter-intuitively, min() is used to constrain the upper end of a variable's
range, while max() is often used to constrain the lower end of a variable's range.
• Warning
̶ Because of the way the min() function is implemented, avoid using other functions
inside the brackets, it may lead to incorrect results.
• Example
iVal = min(sensVal++, 100); // avoid this - yields incorrect result

iVal = min(sensVal, 100); // keep other math outside function


sensVal++; // yields the correct expected result
• Macro
#define min(a,b) ((a)<(b)?(a):(b))
Math: max() function
• Description
̶ Calculates the maximum of two numbers.
• Syntax
̶ max(x, y)
• Parameters
̶ x: the first number, any data type.
̶ y: the second number, any data type.
• Returns
̶ The larger of the two parameter number values.
• Example
sensVal = max(sensVal, 20); // assigns sensVal to the larger of
// either sensVal or 20, ensures that
// sensVal never gets below 20
Math: max() function
• Note
̶ Perhaps counter-intuitively, max() is often used to constrain the lower end of a
variable's range, while min() is used to constrain the upper end of a variable's range.
• Warning
̶ Because of the way the max() function is implemented, avoid using other functions
inside the brackets, it may lead to incorrect results
• Example
iVal = max(sensVal--, 100); // avoid this - yields incorrect result

iVal = max(sensVal, 100); // keep other math outside function


sensVal--; // yields the correct expected result
• Macro
#define max(a,b) ((a)>(b)?(a):(b))
Math: abs() function
• Description
̶ Computes the absolute value of a number.
• Syntax
̶ abs(x)
• Parameters
̶ x: the number, signed data type.
• Returns
̶ x: if x is greater than or equal to 0.
̶ -x: if x is less than 0 (converts negative number to a positive number).
• Warning
̶ Because of the way the abs() function is implemented, avoid using other functions
inside the brackets, it may lead to incorrect results.
• Example
iVal = abs(a++); // avoid this - yields incorrect result
iVal = abs(a); // use this - keep other math outside function
a++; // yields the correct expected result
• Macro
#define abs(x) ((x)>0?(x):-(x))
Math: constrain() function
• Description
̶ Constrains a number to be within a min and max range.
• Syntax
̶ constrain(num, min, max)
• Parameters
̶ num: the number to constrain, any data type.
̶ min: the lower end of the range, any data type.
̶ max: the upper end of the range, any data type.
• Returns
̶ num: if num is between min and max.
̶ min: if num is less than min.
̶ max: if num is greater than max.
• Example
sensVal = constrain(sensVal, 10, 150); // limits range of sensor to
// between 10 and 150
• Macro
#define constrain(a,l,h) ((a)<(l)?(l):((a)>(h)?(h):(a)))
Math: round() function
• Description
̶ Rounds a floating-point number to the nearest integer.
̶ If the fractional part is exactly 0.5, the function rounds to the nearest integer.
• Syntax
̶ round(x)
• Parameters
̶ x: the number, float data type.
• Returns
̶ x: rounded to the nearest integer as a long data type.
• Example
float fnum1 = 3.4, fnum2 = 4.5, fnum3 = -1.4, fnum4 = -2.6;
...
Serial.println(round(fnum1)); // prints integer: 3
Serial.println(round(fnum2)); // prints integer: 5
Serial.println(round(fnum3)); // prints integer: -1
Serial.println(round(fnum4)); // prints integer: -3
• Macro
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
Math: map() function
• Description
̶ Re-maps a given number, Xin from one range to another.
̶ Xmin maps to Ymin, Xmax maps to Ymax and in-between values are also mapped.
̶ The map() function does not constrain the Xin value to within a range.
̶ If range limits are required, use the constrain() function either before the use of map()
function or after the map() function.

̶ The lower bounds may be larger or smaller than the upper bounds of either range, so
the map() function may be used to reverse a range of numbers.
̶ For example: y = map(x, 1, 50, 50, 1);
̶ The map() function also handles negative numbers.
̶ For example: y = map(x, 1, 50, 50, -100);

̶ The map() function uses integer long math and will not generate fractions.
̶ Fractional remainders are truncated and are not rounded or averaged.
• Syntax
̶ map(Xin, Xmin, Xmax, Ymin, Ymax)
Math: map() function
• Parameters
̶ Xin: number to map (long).
̶ Xmin: lower bound of Xin number value, current range.
̶ Xmax: upper bound of Xin number value, current range.
̶ Ymin: new lower bound of Xin number value, target range.
̶ Ymax: new upper bound of Xin number value, target range.
• Returns
̶ The mapped target number value (long).
• Example
/* Map an analog 10-bit value to 8-bits for PWM output */
void setup(){
}

void loop(){
int iVal = analogRead(A0);
iVal = map(iVal, 0, 1023, 0, 255);
analogWrite(9, iVal);
delay(1000);
}
Math: map() function
• Note
∆𝒀 𝐘𝐦𝐚𝐱−𝒀𝒎𝒊𝒏 Y axis
̶ 𝐒𝐥𝐨𝐩 = 𝐦 = = output Constant
∆𝑿 𝐗𝐦𝐚𝐱−𝑿𝒎𝒊𝒏
Linear slope
̶ ∴ 𝐁𝐞𝐜𝐚𝐮𝐬𝐞 𝐨𝐟 𝐚 𝐜𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐥𝐢𝐧𝐞𝐚𝐫 𝐬𝐥𝐨𝐩𝐞 Ymax
𝐘𝐨𝐮𝐭−𝒀𝒎𝒊𝒏 𝐘𝐦𝐚𝐱−𝒀𝒎𝒊𝒏 ∆𝒀
̶ 𝐦= = =
𝐗𝐢𝐧−𝑿𝒎𝒊𝒏 𝐗𝐦𝐚𝐱−𝑿𝒎𝒊𝒏 ∆𝑿
Yout
𝐘𝐦𝐚𝐱−𝒀𝒎𝒊𝒏
̶ ∴ 𝐘𝐨𝐮𝐭 − 𝐘𝐦𝐢𝐧 = 𝐗𝐢𝐧 − 𝑿𝒎𝒊𝒏
𝐗𝐦𝐚𝐱−𝑿𝒎𝒊𝒏

∆𝒀 Ymin
̶ ∴ 𝐘𝐨𝐮𝐭 = 𝐗𝐢𝐧 − 𝑿𝒎𝒊𝒏 + 𝐘𝐦𝐢𝐧
∆𝑿 X axis
input
̶ ∴ 𝐘𝐨𝐮𝐭 = 𝐦 𝐗𝐢𝐧 − 𝑿𝒎𝒊𝒏 + 𝐂 … (𝐋𝐢𝐧𝐞 𝐄𝐪𝐮) Xmin Xin Xmax

• Function code
long map(long Xin, long Xmin, long Xmax, long Ymin, long Ymax)
{
return(((Ymax - Ymin)/(Xmax - Xmin))*(Xin - Xmin) + Ymin);
}
Math: pow() Function
• Description
̶ Calculates the value of a number raised to a given power (eg: 2.0^10.0 = 1024.0).
̶ The pow() function can be used to raise a number to a fractional power.
̶ This is useful for generating exponential mapping of values or curves.
• Syntax
̶ pow(base, exponent)
• Parameters
̶ base: the number (float).
̶ exponent: the power to which the base is raised (float).
• Returns
̶ The result of the exponentiation (float/double).
• Example
// for 2.0 raised to the power of 3.0
float fBase = 2.0;
float fExponent = 3.0;
float fResult = pow(fBase, fExponent); // result = 2.0^3.0 = 8.0
Math: sqrt() Function
• Description
̶ Calculates the square root of a given number.
• Syntax
̶ sqrt(num)
• Parameters
̶ num: the number, any data type.
• Returns
̶ The given number's square root (float/double).
• Example
float fNum = 25.0;
float sqrt_fNum = sqrt(fNum);
...
Serial.print("Square root of ");
Serial.print(fNum);
Serial.print(" is ");
Serial.println(sqrt_fNum); // prints: Square root of 25.00 is 5.00
Math: sq() Function
• Description
̶ Calculates the square of a given number.
• Syntax
̶ sq(num)
• Parameters
̶ num: the number, any data type.
• Returns
̶ The given number's square.
• Example
int iNum = 5;
int sq_iNum = sq(iNum);
...
Serial.print("Square of ");
Serial.print(iNum);
Serial.print(" is ");
Serial.println(sq_iNum); // prints: Square of 5 is 25
• Macro
#define sq(x) ((x)*(x))
Trigonometry: radians()
• Description
̶ Converts a value from degrees to radians.
• Syntax
̶ radians(angleDeg)
• Parameters
̶ angleDeg: the angle (0.0 to 360.0) in degrees (float).
• Returns
̶ The equivalent angle in radians (float).

Trigonometry: degrees()
• Description
̶ Converts a value from radians to degrees.
• Syntax
̶ degrees(angleRad);
• Parameters
̶ angleRad: the angle (0.0 to 6.28 or 2π) in radians (float).
• Returns
̶ The equivalent angle in degrees (float).
Trigonometry: sin() Function
• Description +1
̶ Calculates the sine of an angle in radians.
̶ The result will be between -1 and 1.
r
• Syntax y
θ
̶ sin(angleRad) -1
x
+1

• Parameters
̶ angleRad: the angle in radians (float).
• Returns -1

̶ The sine of the angle (float/double).


Hypotenuse
• Note (r) Opposite
̶ sin(angleRad) = Opp(y)/Hyp(r) (y)

• Example θ
Adjacent
float fHyp = 1.0; (x)
float fDeg = 45.0;
...
float fRad = radians(fDeg);
float fOpp = fHyp * sin(fRad);
Serial.println(fOpp,3); // prints: 0.707
Trigonometry: cos() Function
• Description +1
̶ Calculates the cosine of an angle in radians.
̶ The result will be between -1 and 1.
r
• Syntax y
θ
̶ cos(angleRad) -1
x
+1

• Parameters
̶ angleRad: the angle in radians (float).
• Returns -1

̶ The cosine of the angle (float/double).


Hypotenuse
• Note (r) Opposite
̶ cos(angleRad) = Adj(x)/Hyp(r) (y)

• Example θ
Adjacent
float fHyp = 1.0; (x)
float fDeg = 60.0;
...
float fRad = radians(fDeg);
float fAdj = fHyp * cos(fRad);
Serial.println(fAdj,2); // prints: 0.50
Trigonometry: tan() Function
• Description +1
̶ Calculates the tangent of an angle in radians.
̶ The result will be between -∞ and +∞.
r
• Syntax y
θ
̶ tan(angleRad) -1
x
+1

• Parameters
̶ angleRad: the angle in radians (float).
• Returns -1

̶ The tangent of the angle (float/double)


Hypotenuse
• Note (r) Opposite
̶ tan(angleRad) = Opp(y)/Adj(x) (y)

• Example θ
Adjacent
float fAdj = 0.5; (x)
float fDeg = 70.0;
...
float fRad = radians(fDeg);
float fOpp = fAdj * tan(fRad);
Serial.println(fOpp,1); // prints: 1.4
Characters: isAlphaNumeric() Function
• Description
̶ Analyze if a char is alphanumeric.
• Syntax
̶ isAlphaNumeric(thisChar) // does char variable contain either a letter or number
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.

Characters: isAlpha() Function


• Description
̶ Analyze if a char is alpha.
• Syntax
̶ isAlpha(thisChar) // does char variable contain only a letter
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isAscii() Function
• Description
̶ Analyze if a char is ASCII.
• Syntax
̶ isAscii(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.

Characters: isWhitespace() Function


• Description
̶ Analyze if a char is white space.
• Syntax
̶ isWhitespace(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isControl() Function
• Description
̶ Analyze if a char is a control character.
• Syntax
̶ isControl(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.

Characters: isDigit() Function


• Description
̶ Analyze if a char is a digit.
• Syntax
̶ isDigit(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isGraph() Function
• Description
̶ Analyze if a char is a printable character that's not whitespace.
• Syntax
̶ isGraph(thisChar)
• Parameters
̶ thisChar: the char to be analyzed
• Returns
̶ true or false.

Characters: isLowerCase() Function


• Description
̶ Analyze if a char is a lower case character.
• Syntax
̶ isLowerCase(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isPrintable() Function
• Description
̶ Analyze if a char is a printable character.
• Syntax
̶ isPrintable(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.

Characters: isPunct() Function


• Description
̶ Analyze if a char is punctuation character.
• Syntax
̶ isPunct(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isSpace() Function
• Description
̶ Analyze if a char is a space character.
• Syntax
̶ isSpace(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.

Characters: isUpperCase() Function


• Description
̶ Analyze if a char is an upper case character.
• Syntax
̶ isUpperCase(thisChar)
• Parameters
̶ thisChar: the char to be analyzed.
• Returns
̶ true or false.
Characters: isHexadecimalDigit() Function
• Description
̶ Analyze if a char is a valid hexadecimal digit.
• Syntax
̶ isHexadecimalDigit(thisChar)
• Parameters
̶ thisChar: the char to be analyzed
• Returns
̶ true or false.
Example: Character functions
/* Examples using the character analysis operators. */

Void setup()
{
// Open serial communications
Serial.begin(9600);
// send an introduction
Serial.println("Send a byte and I'll tell you everything about it");
Serial.println(); // print extra line space
}

void loop()
{
// get any incoming bytes
if(Serial.available() > 0)
{
unsigned char ucChar = Serial.read(); // get & say what is received
Serial.print("You sent me: \'");
Serial.write(ucChar); // prints ASCII character text
Serial.print("\' ASCII Value: ");
Serial.println(ucChar); // print as an ASCII-encoded decimal
// for example prints: “You sent me ‘A’ ASCII Value: 65”
// analyze what was received
if(isAlphaNumeric(ucChar)) Serial.println("it's alphanumeric");
if(isAlpha(ucChar)) Serial.println("it's alphabetic");
if(isAscii(ucChar)) Serial.println("it's ASCII");
if(isWhitespace(ucChar)) Serial.println("it's whitespace");
if(isControl(ucChar)) Serial.println("it's a control character");
if(isDigit(ucChar)) Serial.println("it's a numeric digit");
if(isGraph(ucChar))
Serial.println("it's printable character that's not whitespace");
if(isLowerCase(ucChar)) Serial.println("it's lower case");
if(isPrintable(ucChar)) Serial.println("it's printable");
if(isPunct(ucChar)) Serial.println("it's punctuation");
if(isSpace(ucChar)) Serial.println("it's a space character");
if(isUpperCase(ucChar)) Serial.println("it's upper case");
if(isHexadecimalDigit(ucChar))
Serial.println("it's hexadecimaldigit (0-9, a-F or A-F)");

// add some space and ask for another byte


Serial.println();
Serial.println("Give me another byte:");
}
}
Random Numbers: randomSeed() Function
• Description
̶ The randomSeed() initializes the pseudo-random number generator, causes it to start at
an arbitrary point in its random sequence.
̶ If it is important for a sequence of values generated by the random() function to differ,
on subsequent executions use randomSeed() to initialize random number generator
again with a fairly random input, such as analogRead() on an unconnected pin.
̶ It can occasionally be useful to use pseudo-random sequences that always repeats
exactly the same.
̶ This can be accomplished by calling randomSeed() with a fixed number, before starting
the random sequence.
• Syntax
̶ randomSeed(seed)
• Parameters
̶ seed: pass a number to generate (long or int).
• Returns
̶ Nothing
Example: randomSeed() Function
/*Sequence of different random values generated by random() function
for two dice separate results that is used in games of chance.*/

const int pinPB = 2; // pushbutton connected to pin 2 and GND


long lRandomNum;

void setup()
{
Serial.begin(9600);
pinMode(pinPB, INPUT_PULLUP);
randomSeed(analogRead(A0)); // initializes random number generator
// to start at an arbitrary point
}

void loop()
{
if(digitalRead(pinPB) == LOW)
{
Serial.print("Two dice result: ");
lRandomNum = random(1, 7); // get random number between 1 & 6
Serial.println(lRandomNum);
lRandomNum = random(1, 7); // get random number between 1 & 6
Serial.println(lRandomNum);
delay(250); // short de-bounce delay
}
}
Random Numbers: random() Function
• Description
̶ The random() function generates pseudo-random numbers.
• Syntax
̶ random(max)
̶ random(min, max)
• Parameters
̶ min - lower bound of the random value (zero or an optional value).
̶ max - upper bound of the random value.
• Returns
̶ A random number between min and max - 1 (long).
• Note:
̶ If it is important for a sequence of values generated by random() function to differ, on
subsequent executions, use randomSeed() to initialize random number generator again
with a fairly random input, such as analogRead() on an unconnected pin.
̶ It can occasionally be useful to use pseudo-random sequences that always repeat
exactly the same.
̶ This can be accomplished by calling randomSeed() with a fixed number, before starting
the random sequence.
Example: random() Function
long lRandomNum;

void setup()
{
Serial.begin(9600);
// if analog input pin A0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(A0));
}

void loop()
{
// print a random number from 0 to 299
lRandomNum = random(300);
Serial.println(lRandomNum);
// print a random number from 10 to 19
lRandomNum = random(10, 20);
Serial.println(lRandomNum);

randomSeed(analogRead(A0)); //shuffle random number generator again


delay(250); // short delay
}
Bits and Bytes: lowByte() Function
• Description
̶ Extracts the low-order rightmost byte of a word.
• Syntax
̶ lowByte(Var)
• Parameters
̶ Var: a value of any data type.
• Returns
̶ byte
• Macro
#define lowByte(Var) ((uint8_t) ((Var) & 0xff))
Bits and Bytes: highByte() Function
• Description
̶ Extracts the high-order leftmost byte of a word.
̶ Or the second lowest byte of a larger data type.
• Syntax
̶ highByte(Var)
• Parameters
̶ Var: a value of any data type.
• Returns
̶ byte
• Macro
#define highByte(Var) ((uint8_t) ((Var) >> 8))
Bits and Bytes: bitRead() Function
• Description
̶ Reads a bit of a numeric variable.
• Syntax
̶ bitRead(Var, Bit)
• Parameters
̶ Var: the numeric variable from which to read a bit.
̶ Bit: which bit to read, starting at 0 the least-significant rightmost bit of Var.
• Returns
̶ The value of bit read (0 or 1).
• Macro
#define bitRead(Var, Bit) (((Var) >> (Bit)) & 0x01)
Bits and Bytes: bitSet() Function
• Description
̶ Sets or writes a 1 to a bit of a numeric variable.
• Syntax
̶ bitSet(Var, Bit)
• Parameters
̶ Var: the numeric variable whose bit to set.
̶ Bit: which bit to set starting at 0, the least-significant rightmost bit of Var.
• Returns
̶ Nothing
• Macro
#define bitSet(Var, Bit) ((Var) |= (1UL << (Bit)))
Bits and Bytes: bitClear() Function
• Description
̶ Clears or writes a 0 to a bit of a numeric variable.
• Syntax
̶ bitClear(Var, Bit)
• Parameters
̶ Var: the numeric variable whose bit to clear.
̶ Bit: which bit to clear starting at 0, the least-significant rightmost bit of Var.
• Returns
̶ Nothing
• Macro
#define bitClear(Var, bit) ((Var) &= ~(1UL << (Bit)))
Bits and Bytes: bitWrite() Function
• Description
̶ Writes to a bit of a numeric variable.
• Syntax
̶ bitWrite(Var, Bit, bVal)
• Parameters
̶ Var: the numeric variable to write a bit too.
̶ Bit: which bit to write too, starting at 0 the least-significant rightmost bit of Var.
̶ bVal: the value (0 or 1) to write too the specified bit.
• Returns
̶ Nothing
• Macro
#define bitWrite(Var, Bit, bVal) ((bVal)?bitSet(Var, Bit):bitClear(Val, Bit))
Bits and Bytes: bitToggle() Function
• Description
̶ Used to toggle the value of a single bit at the specified position within a given byte,
without affecting the other bits.
• Syntax
̶ bitToggle(Var, Bit)
• Parameters
̶ Var: value of a byte variable
̶ Bit: bit position to toggle.
• Returns
̶ Nothing
• Example
byte myByte = B10001111;
...
Serial.println(myByte, BIN); // prints: 10001111
bitToggle(myByte, 2);
bitToggle(myByte, 5);
Serial.println(myByte, BIN) // prints: 10101011
• Macro
#define bitToggle(Var, Bit) ((Var)^=(1UL << (Bit))
Bits and Bytes: bit() Function
• Description
̶ Computes the value of the specified bit (bit-0 is 1, bit-1 is 2, bit-2 is 4, etc…).
• Syntax
̶ bit(Bit)
• Parameters
̶ Bit: the bit whose value to compute (20, 21, 22, etc…).
• Returns
̶ The value of the bit.
Interrupts
• Purpose of using Interrupts
̶ For the loop code to always catch an input, it will need to constantly poll an input.
̶ However, an interrupt will catch an input, when an input change occurs.
̶ An interrupt frees the microcontroller to do other tasks, while not missing an input.
̶ Tasks that an interrupt may be use for are:
> Reading a motor shaft rotary encoder signal change,
> Trying to catch a coin drop using an infrared slot sensor (photo-interrupter),
> Monitoring a user push-button, switch or keypad press inputs, etc…
̶ While loop code is continually executed, an random interrupt can occur.
̶ Loop code is paused and its data is saved so that it can resume with correct data later.
̶ An Interrupt Service Routine (ISR) is then executed containing interrupt related code.
̶ When the interrupt code has finished, the loop code resumes where it left off.
Include libraries
Declare variables Start
Define functions

Start libraries
Set pinModes void setup()
One-time code

Run code in sequence Interrupt code


void loop() ISR
Continuously repeat Execute Quickly
Interrupts
• Interrupt Service Routines (ISR)
̶ ISR’s are special kinds of functions that have some unique limitations, that most other
functions do not have.
̶ An ISR can not take any parameters and they don't return anything.
̶ Declare global variables to be used in an ISR, to ensure that they are updated correctly.
̶ Must used global volatile variables to pass data between an ISR and the loop code.
̶ If not declared volatile, the Arduino IDE compiler may try and over-optimize the code
and remove the variable because it is not changed by the main loop code.
̶ If multiple ISR’s are used, only one can run at a time and other interrupts will be
ignored (or turned off) until the current one is finished.
̶ An ISR should be short and as fast as possible, to allow other tasks in the loop code to
operate on time.
• Note
̶ The serial() functions will not work in the ISR, thus no printing to the serial monitor.
̶ The delay() and millis() functions will not work while an ISR is running because both
rely on timer interrupts to function.
̶ However, delayMicroseconds() does not rely on timer interrupts and will work as
expected inside the ISR.
External Interrupts: attachInterrupt() Function
• Description
̶ Specifies an Interrupt Service Routine (ISR) function, to call when an interrupt occurs.
̶ Replaces any previous ISR function that was attached to the interrupt.
• Note
̶ Any variables modified within the attached ISR function, must be declare as volatile.
̶ Inside the attached ISR function, the delay() function won't work and the value
returned by millis() function will not be increment.
̶ Received serial data may be lost, if too long inside the attached ISR function.
̶ Most Arduino boards have two external interrupts, int.0 on digital pin 2 and int.1 on
digital pin 3, available external interrupt pins on various boards is shown in the table.
Board int.0 int.1 int.2 int.3 int.4 int.5
Uno 2 3
Mega2560 2 3 21 20 19 18
Leonardo 3 2 0 1 7
̶ The Arduino Due board has powerful interrupt capabilities that allows attaching an
interrupt function on all available digital pins.
̶ Directly specify the required interrupt number in the attachInterrupt() function or use
the digitalPinToInterrupt() to map a digital pin to the corresponding interrupt number.
External Interrupts: attachInterrupt() Function
• Syntax
̶ attachInterrupt(interrupt, ISR, mode)
̶ attachInterrupt(pin, ISR, mode) -> only for Arduino Due
• Parameters
̶ interrupt: the number of the interrupt (int) -> 0 or 1 for Arduino UNO.
̶ pin: the pin number -> only for Arduino Due.
̶ ISR: the Interrupt Service Routine name to call when the interrupt occurs.
> This function takes no parameters and returns nothing.
̶ mode: there are four modes that can trigger an interrupt, use the following constants:
> LOW: continually trigger the interrupt as long as a pin is low.
> CHANGE: trigger the interrupt whenever a pin changes value.
> RISING: trigger the interrupt whenever a pin goes from low to high (rising edge).
> FALLING: trigger the interrupt whenever a pin goes from high to low (falling edge).
̶ The Arduino Due board also allows:
> HIGH: continually trigger the interrupt as long as a pin is high.
• Returns
̶ none
Example: attachInterrupt() Function
const int pinPB = 2; // push-button connected to pin 2 and GND
volatile byte vbCnt = 0;
void INC_ISR(){
if(digitalRead(pinPB) == LOW){
delayMicroseconds(10000); // delay 10ms to debounce
if(digitalRead(pinPB) == LOW){
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
vbCnt++;
}
}
}
void setup(){
Serial.begin(9600);
pinMode(pinPB, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
//attachInterrupt(0, INC_ISR, FALLING); // using int.0 on pin 2
attachInterrupt(digitalPinToInterrupt(pinPB), INC_ISR, FALLING);
}
void loop(){
Serial.println(vbCnt); // prints: 0,0,1...255,0,1,1 INC when pressed
delay(250); // short delay between vbCnt prints
}
External Interrupts: detachInterrupt() Function
• Description
̶ Turns off or detaches the ISR function that was attached to the interrupt number of
either 0 or 1 for the Arduino Uno.
• Syntax
̶ detachInterrupt(interrupt) -> 0 or 1 for Arduino UNO
̶ detachInterrupt(pin) -> only for Arduino Due
• Parameters
̶ interrupt: the number of the interrupt to disable.
̶ pin: the pin number of the interrupt to disable -> only for Arduino Due.
Interrupts: noInterrupts() Function
• Description
̶ Disables interrupts and can be re-enable with interrupts() function again.
• Parameters
̶ None
• Returns
̶ Nothing
• Note
̶ Interrupts allow certain important tasks to happen in the background while sketch code
is executing and are enabled by default.
̶ These interrupts can disrupt critical or time-sensitive code sections and may therefore,
be disabled using noInterrupts() function.
̶ However, some Arduino functions will not work while interrupts are disabled and
incoming serial (RX) communication may be ignored.
̶ Therefore, after critical or time-sensitive code has executed re-enable interrupts with
interrupts() function.
Interrupts: interrupts() Function
• Description
̶ Re-enables interrupts after they've been disabled by noInterrupts().
• Parameters
̶ None
• Returns
̶ Nothing
• Example
void loop()
{
noInterrupts();
// critical or time-sensitive code executes
//...
interrupts();
// code continues executing with interrupts re-enabled
//...
}
EXERCISE
1. Elaborate on the functionality of the Arduino “pinMode()” function?
2. Elaborate on the functionality of the Arduino “digitalWrite()” function?
3. Write an Arduino C program without comments to continuously switch the LED connected
to pin 13, on for half a second and then off for one second.
4. Describe the functionality of the Arduino “digitalRead()” function and discuss what can
occur if the digital pin is floating (not connected to anything)?
5. Develop an Arduino C program without comments that continually reads the state of a
normally open pushbutton connected to digital pin 2 and ground. The internal pull-up on
pin 2 must be enabled and the state of the pushbutton must be continually written to the
built-in LED connected to pin 13.
6. Elaborate on the functionality of the Arduino “analogReference()” function and describe
the associated reference options?
7. Elaborate on the functionality of the Arduino “analogRead()” function including the
resolution and sampling time?
8. Design an Arduino C program without comments that reads the digitized analog value on
A2 pin and then serially transmits at 9600 board rate the ASCII analog value every half
second. A 10k potentiometer wiper is connected to A2 pin and outside leads are
connected to ground and 5V.
9. Describe the operation of the Arduino “analogWrite()” function, including any relation to
the “pinMode()” and “analogRead()” functions?
EXERCISE
10. Create an Arduino C program without comments that reads the digitized analog value on
A3 pin and uses this value to control the PWM duty cycle on pin 9, that is connected to an
LED. A 10k potentiometer wiper is connected to A3 pin and outside leads are connected
to ground and 5V.
11. Elaborate on how Pulse Width Modulation (PWM) works and explain how it can be used
to control the brightness of a LED?
12. Create an Arduino C program without comments that can control the brightness of an LED
connected to pin 9 and ground by using PWM. When the normally open pushbutton
connected to pin 2 and ground is continually pressed, LED brightness must increase every
30 milliseconds, until maximum brightness level is reached. If the pushbutton is still
continually pressed the LED brightness must switch off and then start increasing again
every 30 millisecond, until maximum brightness level is reached. When the pushbutton is
released the LED must remain at the adjusted set brightness level.
13. Describe the operation of the Arduino “tone()” function and discuss its limitations?
14. Explain the purpose for the Arduino “noTone()” function and discuss how it can be used to
play different pitches on multiple digital pins?
15. Describe and explain the operation of the Arduino “shiftOut()” function?
16. Sketch the Arduino connected to a 74HC595, 8-bit shift register device. Show the clock pin
(SCK) connected to pin 10, the Latch pin (RCK) connected to pin 11 and the Data-in (SI)
connected to pin 12 on the Arduino. State the values of the pull-down resistors and
explain why are they required?
EXERCISE
17. Design an Arduino C program without comments that serially shifts out, 8-bits of data to a
74HC595 device using the Arduino “shiftOut()” function. The clock (SCK) is connected to
pin 10, the Latch (RCK) is connected to pin 11 and the Data-in (SI) is connected to pin 12.
The data send continually every half a second, must increment from 0 to 255 and then
back to 0 again.
18. Describe and explain the operation of the Arduino “shiftIn()” function?
19. Sketch the Arduino connected to a 74HC165, 8-bit parallel-in/serial-out shift register
device. Show the clock pin (CP) connected to pin 10, the parallel load pin (PL) connected
to pin 11 and the Data-out (Q7) connected to pin 12 on the Arduino. State the values of
the pull-up/pull-down resistors and explain why are they required?
20. Design an Arduino C program without comments that serially shifts in 8-bits of data from
a 74HC165 device using the Arduino “shiftIn()” function. The clock (CP) is connected to pin
10, the Load (PL) is connected to pin 11 and the Data-Out (Q7) is connected to pin 12.
Initially at start-up the data be shifted in continually every half second and stored into a
255 data array.
21. Elaborate on the operation of the Arduino “pulseIn()” function including its range?
22. Create an Arduino C program without comments using the “pulseIn()” function to switch
on a relay driven by digital pin 4. If a low pulse width on input pin 3 (with an external pull-
up resistor) is greater than one millisecond, switch on the relay using a high digital output.
The Arduino must wait for at least five seconds in order to detect the low pulse width. If
the generated pulse width becomes less than or equal to one millisecond or is not
detected, the relay must be switch off.
EXERCISE
23. Describe the operation of the Arduino “millis()” function including its return data type and
approximately when will it overflow?
24. Develop an Arduino C program without comments that uses the “millis()” function to
serially send at 9600 bit/s, the time in milliseconds since the program started after every
pushbutton press. Transmit a serial string as “Time: xxxx ms” on each new line, every time
a pushbutton connected to pin 2 and ground without an external pull-up, goes low. Wait
for the pushbutton to go high again before checking for the next low pushbutton press.
25. Describe the operation of the Arduino “micros()” function including its return data type
and approximately when it will overflow?
26. Develop an Arduino C program without comments using the “micros()” function to serially
send at 9600 bits/s, the time in microseconds since the program started after every
second. Transmit a serial ASCII string as “Time: xxxxxx us” on each new line every second.
27. Describe the operation of the Arduino “delay()” function including its drawbacks and
discuss what is unaffected by this function call?
28. Write an Arduino C program without comments using the “delay()” function to continually
switch the built-in LED on for a second and a half, and then off for three seconds.
29. Explain the operation of the Arduino “constrain(num, min, max)” function and discuss
what can possibly be returned?
30. Elaborate on how the Arduino “map(Xin, Xmin, Xmax, Ymin, Ymax)” function works
including range limits and discuss what can possibly be done using this function?
EXERCISE
31. Reproduce the Arduino C program “map(Xin, Xmin, Xmax, Ymin, Ymax)” function code.
32. Describe the operation of the Arduino “randomSeed()” and “random()” functions by
discussing how random sequences can be cause to differ or always repeat exactly the
same sequence of numbers?
33. Design an Arduino C program that uses the “randomSeed()” and “random()” function to
serially send at 9600 bits/s, a random number between 10 and 90, every half second.
Ensure on subsequent executions that the “randomSeed()” function is initialize with
random noise.
34. Perceive and discuss the purpose of using an interrupt and provide two task examples
where an interrupt should be used?
35. Explain what makes an Interrupt Service Routine (ISR) different to other functions and
discuss what should be considered when using an ISR?
36. Discuss the purpose of the Arduino “attachInterrupt()” function and describe the four
possible modes that can trigger an interrupt?
37. Design an Arduino C program without comments that uses “attachInterrupt()” function to
changes the output state of a LED connected to pin 10, when a normally open pushbutton
(with external pull-up) connected to interrupt pin 0 changes state. Make use of a global
variable to change the LED output state in the main “loop()” function.
38. Explain the purpose for the Arduino “onInterrupts()” and “interrupts()” functions?

You might also like