4 Functions(1)
4 Functions(1)
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:
̶ 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
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
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);
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 */
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
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 */
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 */
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
̶ 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
• 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
• 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
• 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.
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)");
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);
Start libraries
Set pinModes void setup()
One-time code