Professional Documents
Culture Documents
pinMode(pin, Mode)
• Configures the specified pin to behave either input or output.
• Parameters:
pin: the number of the pin whose mode you wish to set.
Mode: either INPUT or OUTPUT
Example:
int ledPin = 13; // LED connected to digital pin 13
Example
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
digitalWrite(pin, value)
• Sets a pin configured as OUTPUT to either a
HIGH or a LOW state at the specified pin.
• The digitalWrite() function is also used to set
pullup resistors when a pin is configured as an
INPUT.
digitalRead(pin)
• Reads the value from a specified pin, it will be either
HIGH or LOW.
Example:
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the
voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the
voltage LOW
delay(1000); // wait for a second
}
Push Button
The pushbutton is a component that connects two points in a circuit
when you press it.
When the pushbutton is open (unpressed) there is no connection
between the two legs of the pushbutton, so the pin is connected to 5
volts (through the pull-up resistor) and we read a HIGH. When the
button is closed (pressed), it makes a connection between its two legs,
connecting the pin to ground, so that we read a LOW. (The pin is still
connected to 5 volts, but the resistor in-between them means that the
pin is "closer" to ground.)
Example
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
Example
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
}
Example
• Common Anode
Using for Loop
void setup() {
// define pin modes
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop() {
// loop to turn leds od seven seg ON
for(int i=2;i<9;i++)
{
digitalWrite(i,HIGH);
delay(600);
} // loop to turn leds od seven seg OFF
for(int i=2;i<9;i++)
{
digitalWrite(i,LOW);
delay(600);
}
delay(1000);
}
void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
digitalWrite(9, 0); // start with the "dot" off
}
void loop() {
// write '9'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '8'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '7'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 0);
delay(1000);
// write '6'
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '5'
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
digitalWrite(2, 1);
digitalWrite(3, 0);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '4'
digitalWrite(2, 0);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 1);
digitalWrite(8, 1);
delay(1000);
// write '3'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 1);
delay(1000);
// write '2'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 0);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 0);
digitalWrite(8, 1);
delay(1000);
// write '1'
digitalWrite(2, 0);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 0);
digitalWrite(6, 0);
digitalWrite(7, 0);
digitalWrite(8, 0);
delay(1000);
// write '0'
digitalWrite(2, 1);
digitalWrite(3, 1);
digitalWrite(4, 1);
digitalWrite(5, 1);
digitalWrite(6, 1);
digitalWrite(7, 1);
digitalWrite(8, 0);
delay(4000);
}
Array (typeName variableName [size])
An array is a collection of variables that are accessed with an index
number. Arrays in the C programming language, on which Arduino is
based, can be complicated, but using simple arrays is relatively
straightforward.
Example:
int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";
int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = {
2, 7, 4, 6, 5, 3
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the
array)
void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
Using Switch Case
Modulo %
Remainder operation calculates the remainder when one integer is
divided by another. It is useful for keeping a variable within a particular
range (e.g. the size of an array). The % (percent) symbol is used to carry
out remainder operation.
Syntax:
remainder = dividend % divisor;
Parameters:
remainder : variable. Allowed data types: int, float, double
dividend : variable or constant. Allowed data types: int
divisor : non zero variable or constant. Allowed data types: int
Example:
• int x = 0;
• x = 7 % 5; // x now contains 2
• x = 9 % 5; // x now contains 4
• x = 5 % 5; // x now contains 0
• x = 4 % 5; // x now contains 4
• x = -4 % 5; // x now contains -4
• x = 4 % -5; // x now contains 4
Led Control using Modulo
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin1 = 3; // the number of the LED pin
const int ledPin2 = 4; // the number of the LED pin
const int ledPin3 = 5; // the number of the LED pin
const int ledPin4 = 6; // the number of the LED pin
const int ledPin5 = 7; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPressCount = 0;
int numberOfLED = 5;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (buttonPressCount % numberOfLED == 0){
digitalWrite(ledPin1, HIGH);} // turn LED1 on:
else{
digitalWrite(ledPin1, LOW);}
if (buttonPressCount % numberOfLED == 1){
digitalWrite(ledPin2, HIGH); }// turn LED2 on:
else{
digitalWrite(ledPin2, LOW)};
buttonPressCount++;
delay(300);
}
}
Modulo on 8-bit LED
void setup()
{
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
}
void loop()
{
for(byte i=0;i<255;i++)
{
byte a=i%2;
byte b=i/2 %2;
byte c=i/4 %2;
byte d=i/8 %2;
byte e=i/16 %2;
byte f=i/32 %2;
byte g=i/64 %2;
byte h=i/128 %2;
digitalWrite(2,a);
digitalWrite(3,b);
digitalWrite(4,c);
digitalWrite(5,d);
digitalWrite(6,e);
digitalWrite(7,f);
digitalWrite(8,g);
digitalWrite(9,h);
delay(200);
}
}
Array + Modulo 8bit LED Counter
int ledPins[] = {2,3,4,5,6,7,8,9}; //An array to hold the pin each LED is
connected to Arduino.
void setup () {
for (int i = 0; i<8;i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop () {
for (int i = 0; i<256;i++) {
iloveEcE(i);
delay(100);
}
}
void iloveEcE(int num) {
for (int i = 0; i<8; i++) {
If(num%2){
digitalWrite(ledPins[i], HIGH);}
else{
digitalWrite(ledPins[i], LOW);}
num/=2;
}
}
Logical Operators
LOGICAL AND (&&)
Description
Logical AND results in true only if both operands are true.
Example Code
This operator can be used inside the condition of an if statement.
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // if BOTH the
switches read HIGH
// statements
}
Logical NOT (!)
Description
Logical NOT results in a true if the operand is false and vice versa.
Example Code
This operator can be used inside the condition of an if statement.
if (!x) { // if x is not true
// statements
}
It can be used to invert the boolean value.
x = !y; // the inverted value of y is stored in x
LOGICAL OR (||)
Description
Logical OR results in a true if either of the two operands is true.
Example Code
This operator can be used inside the condition of an if statement.
if (x > 0 || y > 0) { // if either x or y is greater than zero
// statements
}
Not Equal (!=)
Description
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the two operands are not
equal.
Syntax
x != y; // is false if x is equal to y and it is true if x is not equal to y
Example Code (SSD)
int a = 2; //For displaying segment "a"
int b = 3; //For displaying segment "b"
int c = 4; //For displaying segment "c"
int d = 5; //For displaying segment "d"
int e = 6; //For displaying segment "e"
int f = 8; //For displaying segment "f"
int g = 9; //For displaying segment "g"
void setup() {
pinMode(a, OUTPUT); //A
pinMode(b, OUTPUT); //B
pinMode(c, OUTPUT); //C
pinMode(d, OUTPUT); //D
pinMode(e, OUTPUT); //E
pinMode(f, OUTPUT); //F
pinMode(g, OUTPUT); //G
}
void displayDigit(int digit)
{
//Conditions for displaying segment a
if(digit!=1 && digit != 4)
digitalWrite(a,HIGH);
{
display_tens(tens);
}
}
void display_tens(const int tens)
{
int pin1, a, ones;
for (pin1 = 0, a = 0; pin1 < 7; pin1++, a++)
{
digitalWrite(pin1, bitRead(number[tens], a));
}
for (ones = 0; ones < 10; ones++)
{
display_ones(ones);
delay(300);
}
}
void display_ones(const int x){
int pin2, b;
for (pin2 = 7, b = 0; pin2 <= 13; pin2++, b++)
{
digitalWrite(pin2, bitRead(number[x], b));
}
}
SSD using ARRAY
void Display_Segment(int);
int digit[10][7] = {{ 0,1,1,1,1,1,1}, // Digit "0"
{ 0,0,0,0,1,1,0}, // Digit "1"
{ 1,0,1,1,0,1,1}, // Digit "2"
{ 1,0,0,1,1,1,1}, // Digit "3"
{ 1,1,0,0,1,1,0}, // Digit "4"
{ 1,1,0,1,1,0,1}, // Digit "5"
{ 1,1,1,1,1,0,1}, // Digit "6"
{ 0,0,0,0,1,1,1}, // Digit "7"
{ 1,1,1,1,1,1,1}, // Digit "8"
{ 1,1,0,1,1,1,1 }}; // Digit "9"
void setup()
{
// Seven Segment Pins as Output
for(int a=0 ; a<=6; a++){
pinMode(a, OUTPUT);
}
}
void loop()
{
for (int value = 0; value<=9; value++)
{
delay(1000);
Display_Segment(value);
}
delay(2500);
}
void Display_Segment(int value)
{
for (int x=6,startPin =0; x >= 0; x--, startPin++) {
digitalWrite(startPin, digit[value][x]);
}
}
Increment & Decrement
const int a = 8; //For displaying segment "a"
const int b = 9; //For displaying segment "b"
const int c = 4; //For displaying segment "c"
const int d = 5; //For displaying segment "d"
const int e = 6; //For displaying segment "e"
const int f = 2; //For displaying segment "f"
const int g = 3; //For displaying segment "g"
bool bPress = false;
const int IncbuttonPin = 10;
const int DecbuttonPin = 11;
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button
presses
int IncbuttonState = 0; // current state of the button
int lastIncbuttonState = 0; // previous state of the button
int DecbuttonState = 0; // current state of the button
int lastDecbuttonState = 0; // previous state of the button
void setup() {
// put your setup code here, to run once:
pinMode(a, OUTPUT); //A
pinMode(b, OUTPUT); //B
pinMode(c, OUTPUT); //C
pinMode(d, OUTPUT); //D
pinMode(e, OUTPUT); //E
pinMode(f, OUTPUT); //F
pinMode(g, OUTPUT); //G
pinMode( IncbuttonPin , INPUT_PULLUP );
pinMode( DecbuttonPin , INPUT_PULLUP );
displayDigit(buttonPushCounter);
}
void loop() {
IncbuttonState = digitalRead(IncbuttonPin);
DecbuttonState = digitalRead(DecbuttonPin);
checkIncButtonPress();
checkDecButtonPress();
if( bPress ){
bPress = false;
turnOff();
displayDigit(buttonPushCounter);
}
void checkIncButtonPress()
{
// compare the IncbuttonState to its previous state
if (IncbuttonState != lastIncbuttonState) {
// if the state has changed, increment the counter
if (IncbuttonState == LOW) {
// if the current state is HIGH then the button went from off to on:
bPress = true;
buttonPushCounter++;
if( buttonPushCounter > 9){ buttonPushCounter =0 ;
} // Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastIncbuttonState = IncbuttonState;
}
void checkDecButtonPress()
{
// compare the IncbuttonState to its previous state
if (DecbuttonState != lastDecbuttonState) {
// if the state has changed, increment the counter
if (DecbuttonState == LOW) {
// if the current state is HIGH then the button went from off to on:
bPress = true;
buttonPushCounter--;
if( buttonPushCounter < 0){ buttonPushCounter =9 ;
Serial.println("on");
}}
// save the current state as the last state, for next time through the loop
lastDecbuttonState = DecbuttonState;
}
void displayDigit(int digit)
{
//Conditions for displaying segment a
if(digit!=1 && digit != 4)
digitalWrite(a,HIGH);
//Conditions for displaying segment b
if(digit != 5 && digit != 6)
digitalWrite(b,HIGH);
//Conditions for displaying segment c
if(digit !=2)
digitalWrite(c,HIGH);
if(digit != 1 && digit !=4 && digit !=7)
digitalWrite(d,HIGH);
//Conditions for displaying segment e
if(digit == 2 || digit ==6 || digit == 8 || digit==0)
digitalWrite(e,HIGH);
//Conditions for displaying segment f
if(digit != 1 && digit !=2 && digit!=3 && digit !=7)
digitalWrite(f,HIGH);
if (digit!=0 && digit!=1 && digit !=7)
digitalWrite(g,HIGH);
}
void turnOff()
{
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
}
Mini-Quiz
•Button 1 (Display
10,20,30,40,50,60,70,80,90)
•Button 2(Display 00 to 99)
•Button 3 (Increment)
•Button 4 (Decrement)
Port Registers
Port registers allow for lower-level and faster manipulation of the i/o
pins of the microcontroller on an Arduino board. The chips used on the
Arduino board (the ATmega8 and ATmega168) have three ports:
void loop()
{
for(int i = 0; i<10;i++)
{
ShowDigit(i);
delay(500);
}
}
void ShowDigit(int digit) {
if(digit == 0) PORTD = B00111111; // 0
if(digit == 1) PORTD = B00000110; // 1
if(digit == 2) PORTD = B01011011; // 2
if(digit == 3) PORTD = B01001111; // 3
if(digit == 4) PORTD = B01100110; // 4
if(digit == 5) PORTD = B01101101; // 5
if(digit == 6) PORTD = B01111101; // 6
if(digit == 7) PORTD = B00000111; // 7
if(digit == 8) PORTD = B01111111; // 8
if(digit == 9) PORTD = B01101111; // 9
}
Define
A useful C component that allows the
programmer to give a name to a constant value
before the program is compiled. Defined
constants in arduino don't take up any program
memory space on the chip. The compiler will
replace references to these constants with the
defined value at compile time.
Syntax
#define constantName value
Example
#define Karl 0
// The compiler will replace any mention of Karl with the value 0 at
compile time
Debounce
Pushbuttons often generate spurious open/close transitions when
pressed, due to mechanical and physical issues: these transitions may
be read as multiple presses in a very short time fooling the program.
This example demonstrates how to debounce an input, which means
checking twice in a short period of time to make sure the pushbutton is
definitely pressed. Without debouncing, pressing the button once may
cause unpredictable results. This sketch uses the millis() function to
keep track of the time passed since the button was pressed.
Example:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output
flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
Ultrasonic Sensor
Ultrasonic sensors measure distance by using ultrasonic
waves.
The sensor head emits an ultrasonic wave and receives
the wave reflected back from the target. Ultrasonic
Sensors measure the distance to the target by measuring
the time between the emission and reception.
HC-SR04 Ultrasonic Sensor
It emits an ultrasound at 40 000 Hz which travels through
the air and if there is an object or obstacle on its path It
will bounce back to the module. Considering the travel
time and the speed of the sound you can calculate the
distance.
HC-SR04 Specifications
• Working Voltage: DC 5V
• Working Current: 15mA
• Working Frequency: 40Hz
• Max Range: 4m
• Min Range: 2cm
• Measuring Angle: 15 degree
• Trigger Input Signal: 10µS TTL pulse
• Echo Output Signal Input TTL lever signal and the range in proportion
• Dimension 45 * 20 * 15mm
Pins
• The HC-SR04 Ultrasonic Module has 4 pins, Ground,
VCC, Trig and Echo. The Ground and the VCC pins of the
module needs to be connected to the Ground and the 5
volts pins on the Arduino Board respectively and the
trig and echo pins to any Digital I/O pin on the Arduino
Board.
Triggering
In order to generate the ultrasound you need to set the Trig on a
High State for 10 µs. That will send out an 8 cycle sonic burst which will
travel at the speed sound and it will be received in the Echo pin. The
Echo pin will output the time in microseconds the sound wave traveled.
For example, if the object is 10 cm away from the sensor, and the
speed of the sound is 340 m/s or 0.034 cm/µs the sound wave will
need to travel about 294 u seconds. But what you will get from the
Echo pin will be double that number because the sound wave needs to
travel forward and bounce backward. So in order to get the distance in
cm we need to multiply the received travel time value from the echo
pin by 0.034 and divide it by 2.
Pulsein()
• Reads a pulse (either HIGH or LOW) on a pin. For example,
if value is HIGH, pulseIn() waits for the pin to go
from LOWto HIGH, starts timing, then waits for the pin to
go LOW and stops timing. Returns the length of the pulse in
microseconds or gives up and returns 0 if no complete pulse was
received within the timeout.
• The timing of this function has been determined empirically and
will probably show errors in longer pulses. Works on pulses from
10 microseconds to 3 minutes in length.
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)
Parameters
pin: the number of the Arduino pin on which you want to read the pulse.
Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data types: int.
timeout (optional): the number of microseconds to wait for the pulse to
start; default is one second. Allowed data types: unsigned long.
Example:
int pin = 7;
unsigned long duration;
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
void loop() {
duration = pulseIn(pin, HIGH);
Serial.println(duration);
}
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
}
Seatwork:
Design the following:
When the sensor detects an object distance is equals or below 100 cm, the
first LED turn on.
When the sensor detects an object distance is equals or below 150 cm, but
not lower than 100, the first LED turn off and the second LED turn on.
When the sensor detects an object distance is equals or below 200 cm, but
not lower than 150 the first and second LED turn off and the third LED will
turn on.
When the sensor is not detecting something, the fourth LED will turn on.
analogRead(pin)
Reads the value from the specified analog pin. The Arduino
board contains a 6 channel (8 channels on the Mini and
Nano), 10-bit analog to digital converter.
Parameters:
The number of the analog input pin to read from (0 to 5 on
most boards, 0 to 7 on the Mini and Nano)
Return:
An integer value in the range of 0 to 1023.
Example:
int analogPin = 3; // potentiometer wiper (middle terminal) connected to
analog pin 3
// outside leads to ground and +5V
int val = 0;
// variable to store the value read
void setup() {
}
void loop() {
val = analogRead(analogPin); // read the input
}
analogWrite(pin, value)
Writes an analog value to a pin.
Parameters:
pin: the pin to write to.
value: the duty cycle: between 0 (always off) and 255 (always on).
Returns:
nothing
Example:
int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output }
void loop() {
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023,
analogWrite values from 0 to 255
}
Pin Mapping
The analog pins can be used identically to the digital pins, using the
aliases A0 (for analog input 0), A1, etc.
Example:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);
Note:
The analogRead command will not work correctly if a pin has been
previously set to an output, so if this is the case, set it back to an input
before using analogRead.
tone()
Generates a square wave of the specified frequency (and 50% duty
cycle) on a pin. A duration can be specified, otherwise the wave
continues until a call to noTone(). The pin can be connected to a piezo
buzzer or other speaker to play tones.
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- the duration of the tone in milliseconds (unsigned long)
Returns:
Nothing
Notes:
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.
Example:
int buzzerPin = 9;
int buttonPin = 7;
int ledPin = 6;
const int toneFreq = 523;
void setup()
{
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
int buttonState = digitalRead(buttonPin);
if (buttonState==LOW)
{
digitalWrite(ledPin, HIGH);
tone(buzzerPin, toneFreq);
}
else
{
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
}
Seatwork
Kindly write down a program in which you have a potentiometer and a
buzzer.
Scenario:
The potentiometer has a value range from (0 to 1023) and when it
reaches below 300 and above 900 the buzzer starts to produce a sound
with a frequency of 1khz, it will continue to produce sound until the
condition is true.
Serial
Used for communication between the Arduino board and a computer
or other devices. All Arduino boards have at least one serial port (also
known as a UART or USART): Serial. It communicates on digital pins 0
(RX) and 1 (TX) as well as with the computer via USB. Thus, if you use
these functions, you cannot also use pins 0 and 1 for digital input or
output.
Serial.begin()
Sets the data rate in bits per second (baud) for serial
data transmission. For communicating with the
computer, use one of these rates: 300, 600, 1200, 2400,
4800, 9600, 14400, 19200, 28800, 38400, 57600, or
115200.
Example:
For Arduino Uno:
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
}
For Arduino Mega:
void setup(){
Serial.begin(9600);
Serial1.begin(38400);
Serial2.begin(19200);
Serial3.begin(4800);
}
void loop() {
}
Serial.end()
Pauses the program for the amount of time (in milliseconds) specified
as parameter. (There are 1000 milliseconds in a second.)
Syntax
delay(ms)
delayMicroseconds()
Pauses the program for the amount of time (in microseconds) specified
as parameter. There are a thousand microseconds in a millisecond, and
a million microseconds in a second.
Syntax
delayMicroseconds(us)
micros()
Returns the number of microseconds since the Arduino board began
running the current program. This number will overflow (go back to
zero), after approximately 70 minutes.
Syntax
Time = micros();
unsigned long time;
void setup(){
Serial.begin(9600);
} void loop()
{
Serial.print("Time: ");
time = micros();
Serial.println(time); //prints time since program started
delay(1000); // wait a second so as not to send massive amounts of
data
}
millis()
Returns the number of milliseconds since the Arduino board began
running the current program. This number will overflow (go back to
zero), after approximately 50 days.
Syntax
Time = millis();
constrain()
Constrains a number to be within a range.
Syntax
constrain(x,a,b)
Parameters
X, the number to constrain
a, lower end of the range
b, upper end of the range
sensVal = constrain(sensVal, 10, 150); // limits range of sensor values to
between 10 and 150
map()
Re-maps a number from one range to another. That is, a value
of fromLow would get mapped to toLow, a value
of fromHigh to toHigh, values in-between to values in-between, etc.
value: the number to map
fromLow: the lower bound of the value's current range
fromHigh: the upper bound of the value's current range
toLow: the lower bound of the value's target range
toHigh: the upper bound of the value's target range
Example
void setup() {
}
void loop() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}
Seatwork
Given: Potentiometer Arduino UNO Buzzer
Light Dependent Resistor LED
Problem: The potentiometer will only vary from 0 to 255. When
the pot is equals or below 50, the buzzer will enable with a frequency
which is equals to the value of the potentiometer, and the LED is turn
ON. Display the ffg. “BOTH LED and BUZZER is ON”. When the pot
varies from 51 to 149 the buzzer will enable with a frequency of 1 khz
and the LED will blink continuously. Display potentiometer value. When
both conditions were false, the buzzer will enable with a frequency of
2khz, LED will turn OFF and display the ffg: “ERROR, CONDITIONS WERE
NOT MET”.
Arduino Serial Plotter
This tools gives you the ability to visualize your data in a plot that is
updated in real time.
ReadAnalogVoltage
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
Syntax:
servo.attached()
Returns
true if the servo is attached to pin; false otherwise.
detach()
Detach the Servo variable from its pin. If all Servo variables are
detached, then pins 9 and 10 can be used for PWM output with
analogWrite().
Syntax
servo.detach()
write()
Writes a value to the servo, controlling the shaft accordingly. On a
standard servo, this will set the angle of the shaft (in degrees), moving
the shaft to that orientation. On a continuous rotation servo, this will
set the speed of the servo (with 0 being full-speed in one direction, 180
being full speed in the other, and a value near 90 being no movement).
Syntax
servo.write(angle)
Parameters
angle: the value to write to the servo, from 0 to 180
Example:
#include <Servo.h>
Servo myservo;
void setup () {
myservo.attach(9);
myservo.write(90); //set servo to mid point
}
void loop () {
}
read()
Read the current angle of the servo (the value passed to the last call to
write()).
Syntax
servo.read()
Example Code:
include <Servo.h>
void setup() {
// We need to attach the servo to the used pin number
Servo1.attach(servoPin);
}
void loop(){
// Make servo go to 0 degrees
Servo1.write(0);
delay(1000);
// Make servo go to 90 degrees
Servo1.write(90);
delay(1000);
// Make servo go to 180 degrees
Servo1.write(180);
delay(1000);
}
Knob
Control the position of a RC (hobby) servo motor with your Arduino
and a potentiometer.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // reads the value of the potentiometer (value
between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between
0 and 180)
myservo.write(val); // sets the servo position according to the scaled
value
delay(15); // waits for the servo to get there
}
Sweep
Sweeps the shaft of a RC servo motor back and forth across 180
degrees.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
Mini-QUIZ
Given a potentiometer, buzzer, servo motor and LED.
Map the range of the potentiometer from 0 to 180. Display the
following data thru the serial monitor, use serial.println.
If the potentiometer varies from 0 to 90, the LED is ON and will control
the arm of the servo motor, buzzer will buzz if the pot hits 45 and 90
degrees with a frequency of 1 kHz, else noTone.
If the potentiometer varies from 91 to 180, the LED is OFF and will
control the arm of the servo motor, buzzer will buzz if the po hits 180
degress with a frequency of 500, else noTone.
Infrared Sensor
• Infrared waves are not visible to the human eye. In the
electromagnetic spectrum, infrared radiation can be found between
the visible and microwave regions. The infrared waves typically have
wavelengths between 0.75 and 1000µm.
1 Vcc Input voltage is +5V for typical applications. Can range from
4.5V- 12V
void setup () {
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(pirSensor, INPUT);
}
void loop () {
int pirSensorvalue = digitalRead(pirSensor);
if (pirSensorvalue == HIGH){
digitalWrite(LED, HIGH);
Serial.println(“THE LED IS ON”);
}
else{
digitalWrite(LED,LOW);
Serial.println(“THE LED IS OFF”);
}
}
Example:
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(9600);
}
void loop(){
val = digitalRead(inputPin); // read input value
if (val == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
}
Active Infrared
Active Infrared sensors transmit and measure the
reflection levels of infrared light. They can detect motion
and static presence, and have a high immunity to the
negative effects of external influences such as
reflections, sunlight and artificial light.
Pin Configuration
Example:
void setup() {
pinMode(7,INPUT);
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
Serial.print("IRSensorip ");
Serial.println(digitalRead(7));
if(digitalRead(7)==0)
{
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
}
Difference between IR and PIR
While PIR sensors are excellent if you want to detect
general movement, they don’t give you any more
information on your subject. To know more, you’ll need
an active IR sensor. Setting up an active IR sensor
requires both an emitter and receiver, but this sensing
method is simpler than its passive counterpart.
Sumobot Code:
#include Ultrasonic.h
Ultrasonic ultrasonic(4,3);
const int IN1=5;
const int IN2=6;
const int IN3=9;
const int IN4=10;
#define IR_sensor_front A0 // front sensor
#define IR_sensor_back A1 // rear senson
int distance ;
void setup()
{
Serial.begin(9600);
delay (5000);
}
void loop(){
int IR_front = analogRead(IR_sensor_front);
int IR_back = analogRead(IR_sensor_back);
distance = ultrasonic.read();
ROTATE(200); // start rotate
if (distance < 20){
Stop();
while (distance < 20 ) {
FORWARD(255);
distance = ultrasonic.read();
IR_front = analogRead(IR_sensor_front);
IR_back = analogRead(IR_sensor_back);
if ( IR_front > 650 || IR_back > 650 ) { break;}
delay(10); }
if (IR_front < 650 ) // < 650 means white line
{
Stop();
delay (50);
BACKWARD(255);
delay (500);
}
• 8 data pins (D0 -D7). The states of these pins (high or low) are the bits
that you're writing to a register when you write, or the values you're
reading when you read.
• There's also a display constrast pin (Vo), power supply pins (+5V and
Gnd) and LED Backlight (Bklt+ and BKlt-) pins that you can use to
power the LCD, control the display contrast, and turn on and off the
LED backlight, respectively.
LiquidCrystal()
Syntax
lcd.begin(cols, rows)
print()
Prints text to the LCD.
Syntax
lcd.print(data)
lcd.print(data, BASE)
void setup()
{
lcd.print("hello, world!");
}
void loop() {}
setCursor()
Position the LCD cursor; that is, set the location at which subsequent
text written to the LCD will be displayed.
Syntax
lcd.setCursor(col, row)
blink() and noBlink()
1. Display the blinking LCD cursor. If used in combination with
the cursor() function, the result will depend on the particular
display.
Syntax
lcd.blink()
2. Turns off the blinking LCD cursor.
Syntax
lcd.noBlink()
I2C (Inter-Integrated Circuit)
The Inter-integrated Circuit (I2C) Protocol is a protocol
intended to allow multiple “slave” digital integrated
circuits (“chips”) to communicate with one or more
“master” chips. Like the Serial Peripheral Interface
(SPI), it is only intended for short distance
communications within a single device. Like
Asynchronous Serial Interfaces (such as RS-232 or
UARTs), it only requires two signal wires to exchange
information.
Short History
The I2C bus was designed by Philips in the early ’80s to allow easy
communication between components which reside on the same circuit
board. Philips Semiconductors migrated to NXP in 2006.
The name I2C translates into “Inter IC”. Sometimes the bus is called IIC or I²C
bus.
void loop(){
}
Example:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
}
void loop(){
// when characters arrive over the serial port...
if (Serial.available()) {
// wait a bit for the entire message to arrive
delay(100);
// clear the screen
lcd.clear();
// read all the available characters
while (Serial.available() > 0) {
// display each character to the LCD
lcd.write(Serial.read());
}
}
}
Addressing
A0 A1 A2 HEX Address
1 1 1 0x27
0 1 1 0x26
1 0 1 0x25
0 0 1 0x24
1 1 0 0x23
0 1 0 0x22
1 0 0 0x21
0 0 0 0x20
Keypad
A keypad is one of the most commonly used input devices in
microprocessor applications. In a standard keypad wired as an X-Y
switch matrix, normally-open switches connect a row to a column
when pressed. If a keypad has 12 keys, it is wired as 3 columns by 4
rows. A 16 key pad would have 4 columns by 4 rows.
Keypads are used in all types of devices, including cell phones, fax
machines, microwaves, ovens, door locks, etc. They’re practically
everywhere. Tons of electronic devices use them for user input.
Pin Connections
One of the most mysterious things
about these keypads is that they
usually come with no
documentation, so a user is left to
figure out the pin configuration for
him or herself. With the keypad
facing up so that the keys are up
and facing you, from left to right,
the 1st 4 pins are the row pins and
the last 4 pins are the column pins.
Functions
Keypad(makeKeymap(userKeymap), row[], col[], rows, cols)
const byte rows = 4; //four rows
const byte cols = 3; //three columns
char keys[rows][cols] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'#','0','*'}
};
byte rowPins[rows] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[cols] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
Instantiates a Keypad object that uses pins 5, 4, 3, 2 as row pins, and 8,
7, 6 as column pins.
This keypad has 4 rows and 3 columns, resulting in 12 keys.
char waitForKey()
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key != NO_KEY){
Serial.println(key);
}
}
#include <Keypad.h>
#define ledpin 13
void setup(){
pinMode(ledpin,OUTPUT);
digitalWrite(ledpin, HIGH);
Serial.begin(9600);
}
void loop() {
char key = kpd.getKey();
if(key) // Check for a valid key.
{
switch (key)
{
case '*':
digitalWrite(ledpin, LOW);
break;
case '#':
digitalWrite(ledpin, HIGH);
break;
default:
Serial.println(key);
}
}
}
Notes on using the library
• The library is non-blocking which means you can press and hold the
key all day long and your Arduino will continue processing the rest of
your code.
• Consider, though, when you are writing your code that every delay()
you use will take processing time away from the keypad. Something
as short as delay(250) can make the keypad seem very unresponsive.
And the same thing will happen if you sprinkle a bunch of delay(10)'s
all through your code.
• The function getKey() returns a key value as soon as you press the key
but it does not repeat automatically. Also, when you release the key
you can track the key RELEASED event if you are using the
eventListener feature of the library.