AURDINO CODES AND USES
1)Serial.println(value); Used to print value/data on computer/MAC from aurdino. It
prints text and moves the cursor to next line.
2)pinMode(pin,mode); Configures a digital pin to read(INPUT) or write(OUTPUT)
3)digitalRead(pin); Reads a digital value HIGH or LOW on a pin configured for
input.
4)digitalWrite(pin,value); Writes a digital value HIGH or LOW on a pin configured
for output.
5)delay(ms); Used to stop the execution of a program for a given milliseconds.
6)Serial.begin(baudrate); It is used to setup communication between aurdino and
another device .SYNTAX-> Serial.begin(baudrate); 9600,115200,57600 are standard
baudrates.
7)int myInt=8; Declares 16-bit signed integer
8)short myShort=200; Declares 16-bit signed integer
9)long myLong=125; Declares 32-bit signed integer
10)byte myByte=42; 8-bit unsigned integer
11)float myFloat=3.14; 32-bit floating number
12)double myDouble=3.141592; 32-bit floating number
13)char myChar='A'; declares single character
14)char myString[]='Hello'; declares string
15)int val; Used to read digital input from sensors, digital/analog inputs. Eg->
int val=digitalRead(sensorPin);
16)int inputPins[]={2,3,4,5}; Create an array of pins for switch inputs/outputs.
17)Serial.print(value); Used to print value/data on computer/MAC from aurdino.It
prints text without moving the cursor to next line.
18)const int Ledpin=2;The declaration const int Ledpin means that the Ledpin is a
constant integer and 2 is the value of the input pin assigned to it.Eg->const int
motorpin=13;
19)int inputPins[] = {2, 3, 4, 5};
void setup() {
for (int i = 0; i < 4; i++) {
pinMode(inputPins[i], INPUT);
}
}
Assigns all the pins in the array 2,3,4,5 as input pins.Similarly->
int outputpins[]={7,8,9};
void setup(){
for(int index=0,index<3;index++){
pinMode(outputpins[index],OUTPUT);
}
}
Assigns all the pins in the array as OUTPUT PINS.
20)text1.length(); depicts the number of characters in the string text1.
21)text1.concat(text2);It is used to concatenate 2 strings text1 and text2.
Eg->
String text1="Hello";
String text2="How are you";
void setup()
{
Serial.begin(9600);
Serial.print(text1);
Serial.println(text2);
Serial.print("I am in Delhi");
Serial.println(text1.length());
Serial.print(text2.length());
text1.concat(text2);
Serial.print(text1);
}
void loop()
{
}
OUTPUT of the above code is :
HelloHow are you!
I am in Delhi5
12HelloHow are you!
22)char Stringname[ ];char Stringname[num];char Stringname[num]="string"; They are
used to initialize char[] charcater arrays.Stringname is the name of the string,
num is the number of characters in the string.
23)strcpy(destination,source); It is used to copy a string to a destination, here
source is the string to be copied. All characters are copied from source to
destination.
24)strlen(stringname); It is used to find the number of characters in the
string ,where stringname is the name of the string.
25)strncpy(destination,source,num); It limits the number of characters that are
copied from source to destination, here source is the string to be copied. num is
the number
of characters that are copied from source to destination.
26)strcat(destination,source); It appends the source string at the end of the
destination string.
void setup(){
Serial.begin(9600);
char stringA[8]="";
char stringB[8]="aurdino";
char stringC[16]="aurdino";
char stringD[ ]="aurdino";
char stringE[40];
strcat(stringE,stringB);
strcat(stringE,stringC);
char stringF[35];
strcpy(stringF,stringC);
strcpy(stringF,stringB);
char stringG[35];
strcpy(stringG,stringC);
strncpy(stringG,stringB,3);
int num1=strlen(stringA);
int num2=strlen(stringB);
int num3=strlen(stringC);
int num4=strlen(stringD);
Serial.print(num1);
Serial.print(num2);
Serial.print(num3);
Serial.println(num4);
Serial.println(stringE);
Serial.println(stringF);
Serial.println(stringG);
}
void loop()
{
}
OUTPUT of the above code is :-
0777
aurdinoaurdino
aurdino
aurdino
27)stringname.substring(start,end); it is used to split a string into various
parts. stringname is the of the string to be split. start is the start Index. end
is the end Index. Explicit indexing is used. NOTE->It can be used only with Aurdino
string class.
28)stringname.indexOf('character'); it is used to search a single character,
substring within a string. stringname is the name of the string. character is
character to be searched. If the character is present it returns its index, else it
returns -1indictaing it absence.
29)strkok_r(char *str,const char *delim, char *savepter);It is used to split the
string and tokenize string into smaller parts based on a delimiter. str is the
string to be
tokenized,delim is the delimiter charcters,savepter is the pointer to keep track of
the next token.
void setup()
{
Serial.beign(9600);
char str[]="Orange,Apple,Kiwi";
char *token;
char *saveptr;
token=strok_r(str,",",&saveptr);
Serial.printIn(token);
token=strok_r(NULL,",",&saveptr);
Serial.printIn(token);
token=strok_r(NULL,",",&saveptr);
Serial.print(token);
}
void loop()
{
}
OUTPUT of the code is->
Orange
Apple
Kiwi
30)strcmp(string1,string2);It used to compare 2 strings (string1 and
string2).Returns 0 if string 1=string2, 0< if string1 is less than string2,0> if
string1 is greater than string2).
31)itoa(num,buffer,base); It is used to convert integer to string where num is the
integer, buffer is the string ,base is the base of the integer.
void setup()
{
Serial.begin(9600);
int num=255;
char buffer[10];
itoa(num,buffer,10);
Serial.print(buffer);
}
void loop()
{
}
32)int num=atoi(string); Used to convert string to integer, string is the name of
the string and num is the name of the integer.
33)float num=atof(string);Used to convert string to float value, string is the name
of the string and num is the name of the float value.
void setup()
{
Serial.begin(9600);
int num1;
float num2;
char str2[]="12.34";
char str1[]="567";
int num1=atoi(str1);
float num2=atof(str2);
Serial.printIn(num1);
Serial.print(num2);
}
void loop()
{
}
34)random(min,max); generates pseudo random number between min and max-1(if min
absent, generates numbers between 0 and max-1).
35)&&;Logical AND ,evaluates to True if conditions on both sides are True else
False
36)||;Logical OR, evaluates to True if condition on at least one side is True.
37)!;NOT, gives False if expression is True and vice-versa
38)&; Sets bits in each place to 1 if both bits are 1; otherwise, bits are set to
0.Similar to AND. 3 & 1 equals 1 (11 & 01 equals 01)
39)|; Sets bits in each place to 1 if either bit is 1.Similar to OR. 3 | 1 equals 3
(11 | 01 equals 11)
40)~; Inverts the value of each bit. Similar to NOT. ~1 equals 254 (~00000001
equals 11111110)
41)^; Sets bits in each place to 1 only if one of the two bits is 1.Similar to XOR.
3 ^ 1 equals 2 (11 ^ 01 equals 10)
42)Value=Value>>n; It moves the bits of integer Value to right by n positions.
43)Value=Value<<n; It moves the bits of integer Value to left by n positions.
44)%; Modulus Operator
45)abs(x); It provides the absolute value of the number.
46)constrain(x,min,max); If x<min it returns min, if x>max it returns max, else it
returns x.
47)min(x,y); It returns the smaller of two values.
48)max(x,y); It returns the larger of two values.
49)pow(x,y); It provides the value of x^y;
50)sqrt(x); It returns the square root of x.
51)floor(x); It returns the largest integer that is not greater than x.
52)ceil(x); It returns the smallest integer value that is just greater than x.
53)sin(x),cos(x),tan(x); Return Sine, Cosine, Tangent value of x.
54)Serial.available(); used to check how many bytes of data are available to read
from the serial buffer.
55)lowByte(x); It extracts the lower 8 bits (least significant byte) from a larger
number, such as a 16-bit (int) or 32-bit (long) value. [Last 8 bits in Binary form]
56)highByte(x); It is used to extract the most significant byte (MSB) from a 16-bit
number. [First 8 bits in Binary form]
int intValue = 258; // 258 in hexadecimal notation is 0x102
void setup()
{
Serial.begin(9600);
}
void loop()
{
int loWord,hiWord; #Binary form of 258 is 0000 0001 0000 0010
byte loByte, hiByte; #loByte is 0000 0010 #hiByte is 0000 0001
hiByte = highByte(intValue);
loByte = lowByte(intValue);
Serial.println(intValue,DEC); #258
Serial.println(intValue,HEX); #102
Serial.println(loByte,DEC); #2
Serial.println(hiByte,DEC); #1
}
57)word(h,l); It is used to form 16 bit value using two bit values h,l where h is
the MSB and l is the LSB of the 16 bit value.
58)Serial.printIn(x,DEC); Presents the value in DECIMAL form
59)Serial.printIn(x,HEX); Presents the value in HEXADECMAL form
60)Serial.printIn(x,OCT); Presents the value in OCTAL form
61)Serial.printIn(x,BIN); Presents the value in BINARY form
char chrValue = 65;
int intValue = 65;
float floatValue = 65.0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println("chrValue: ");
Serial.println(chrValue);
Serial.println(chrValue,DEC);
Serial.println("intValue: ");
Serial.println(intValue);
Serial.println(intValue,DEC);
Serial.println(intValue,HEX);
Serial.println(intValue,OCT);
Serial.println(intValue,BIN);
Serial.println("floatValue: ");
Serial.println(floatValue);
delay(1000);
chrValue++;
intValue++;
}
EXAMPLE->
chrValue: A 65
intValue: 65 65 41 101 1000001
floatValue: 65.00
chrValue: B 66
intValue: 66 66 42 102 1000010
62)Serial.read(); It is used to read incoming data from the buffer. If no data is
available -1 is read.[Used with Serial.available(); to avoid reading empty data]
const int ledPin = 13;
int blinkRate=0;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
if ( Serial.avialable()) // Check to see if at least one character is available
{
char ch = Serial.read();
if(ch >= '0' && ch <= '9')
{
blinkRate = (ch - '0');
blinkRate = blinkRate * 100;
digit
}
}
blink();
}
//defining blink function
void blink()
{
digitalWrite(ledPin,HIGH);
delay(blinkRate);
digitalWrite(ledPin,LOW);
delay(blinkRate);
}
63)serial_lcd.begin(9600); It is used to communicate to LCD and PC at the same
time.
EXAMPLE 1->
#include <NewSoftSerial.h>
const int rxpin = 2; // pin used to receive from LCD
const int txpin = 3; // pin used to send to LCD
NewSoftSerial serial_lcd(txpin, rxpin); // new serial port on pins 2 and 3
void setup()
{
Serial.begin(9600); // 9600 baud for the built-in serial port
serial_lcd.begin(9600); //initialize the software serial port also for 9600
}
int number = 0;
void loop()
{
serial_lcd.print("The number is "); // send text to the LCD
serial_lcd.println(number); // print the number on the LCD
Serial.print("The number is "); // send text to the PC
Serial.println(number); // print the number on the PC console
delay(500); // delay half second between numbers
number++; // to the next number
}
EXAMPLE 2->
Receiving data from gps
#include <NewSoftSerial.h>
const int rxpin = 2; // pin used to receive from GPS
const int txpin = 3; // pin used to send to GPS
NewSoftSerial serial_gps(txpin, rxpin); // new serial port on pins 2 and 3
void setup()
{
Serial.begin(9600); // 9600 baud for the built-in serial port
serial_gps.begin(4800); // initialize the port, most GPS devices use 4800 baud
}
void loop()
{
if (serial_gps.available() > 0) // any character arrived yet?
{
char c = serial_gps.read(); // if so, read it from the GPS
Serial.print(c, BYTE); // and echo it to the serial console
}
}
EXAMPLE 3->
#include <NewSoftSerial.h>
const int rxpin1 = 2;
const int txpin1 = 3;
const int rxpin2 = 4;
const int txpin2 = 5;
NewSoftSerial gps(txpin1, rxpin1); // gps device connected to pins 2 and 3
NewSoftSerial xbee(txpin2, rxpin2); // gps device connected to pins 2 and 3
void setup()
{
gps.begin(4800);
xbee.begin(9600);
}
void loop()
{
if (xbee.available() > 0) // xbee is active. Any characters available?
{
if (xbee.read() == 'y') // if xbee received a 'y' character
{
unsigned long start = millis(); // begin listening to the GPS
while (start + 100000 > millis())
// listen for 10 seconds
{
if (gps.available() > 0) // now gps device is active
{
char c = gps.read();
// *** process gps data here
}
}
}
}
}
64)int val(); It is used to store the value of the input/output.
65)millis(); It returns the number of milliseconds since the board was powered on
or reset.
EXAMPLE-1) Creating Timer
unsigned long startTime;
const long duration = 5000; // 5 seconds
void setup() {
Serial.begin(9600);
startTime = millis(); // Start the timer
}
void loop() {
unsigned long elapsedTime = millis() - startTime;
if (elapsedTime >= duration) {
Serial.println("5 seconds have passed!");
startTime = millis(); // Restart timer //When 5 seconds pass it prints
the meassge 5 seconds have passed !
}
EXAMPLE-2) Controlling 2 LED using millis() function
const int led1 = 13;
const int led2 = 12;
unsigned long previousMillis1 = 0;
unsigned long previousMillis2 = 0;
const long interval1 = 1000; // 1 sec
const long interval2 = 500; // 0.5 sec
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
// Blink LED1 every 1 second
if (currentMillis - previousMillis1 >= interval1) {
previousMillis1 = currentMillis;
digitalWrite(led1, !digitalRead(led1)); //thus at every 1 second led1
blinks.
}
// Blink LED2 every 0.5 seconds
if (currentMillis - previousMillis2 >= interval2) {
previousMillis2 = currentMillis;
digitalWrite(led2, !digitalRead(led2)); //thus at every 0.5 second led2
blinks.
}
}
66)switchTime(); It is used to measure how long a button has been continuously
pressed.It returns the duration in milliseconds that the button has been held down.
EXAMPLE->Using Aurdino as Switch
const int ledPin = 13; // choose the pin for the LED
const int inputPin = 2; // choose the input pin (for a pushbutton)
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare pushbutton as input
}
void loop(){
int val = digitalRead(inputPin); // read input value
if (val == HIGH) // check if the input is HIGH
{
digitalWrite(ledPin, HIGH); // turn LED on if switch is pressed
}
else
{
digitalWrite(ledPin, LOW); // turn LED off
}
}
EXAMPLE->Using the millis() and startTime() function to control LED and measure
press time of switch.
const int ledPin = 13; // the number of the output pin
const int inPin = 2; // the number of the input pin
const int debounceTime = 20; // Min. press time to be valid
const int fastIncrement = 1000; // If switch held >1sec,incraese count fast
const int veryFastIncrement = 4000; //If switch held >4sec,incraese count faster
int count = 0; // Initial value of count is 0
void setup()
{
pinMode(inPin, INPUT); //assigning INPUT pin
digitalWrite(inPin, HIGH); // INPUT pin is HIGH
pinMode(ledPin, OUTPUT); //assigning OUTPUT pin
Serial.begin(9600);
}
void loop()
{
int duration = switchTime(); //duration measures the time for which the switch
is held
if( duration > veryFastIncrement)
count = count + 10; //if switch held >4 sec count
increases by 10
else if ( duration > fastIncrement)
count = count + 4; //if switch held >1 sec count
increases by 4
else if ( duration > debounceTime)
count = count + 1; //if switch held >0.02 sec count
increases by 4
else
{
if( count == 0)
digitalWrite(ledPin, HIGH); // turn the LED on if the count is 0 and switch
pressed for less than 20msec.
else
{
digitalWrite(ledPin, LOW); // turn the LED off if the count is not 0 and switch
not pressed and decrement the count.
count = count - 1;
}
}
Serial.println(count); //print the value of count
delay(100);
}
long switchTime()
{
static unsigned long startTime = 0;
static boolean state; // the current state of the switch
if(digitalRead(inPin) != state) // check to see if the switch has changed state
{
state = ! state; // yes, invert the state
startTime = millis(); // store the time
}
if( state == LOW)
return millis() - startTime; // switch pushed, return time in milliseconds
else
return 0; // return 0 if the switch is not pushed (in the HIGH state);
}
67)READING A KEYPAD
const int numRows = 4; // number of rows in the keypad
const int numCols = 3; // number of columns
const int debounceTime = 20; // number of milliseconds for switch to be stable
const char keymap[numRows][numCols] = {
{ '1', '2', '3' } ,
{ '4', '5', '6' } , // this array determines the pins used for rows and columns
{ '7', '8', '9' } ,
{ '*', '0', '#' }
};
const int rowPins[numRows] = { 7, 2, 3, 6 }; // Rows 0 through 3
const int colPins[numCols] = { 5, 8, 4 }; // Columns 0 through 2
void setup()
{
Serial.begin(9600);
for (int row = 0; row < numRows; row++)
{
pinMode(rowPins[row],INPUT); // Set row pins as input
digitalWrite(rowPins[row],HIGH); // turn on Pull-ups
}
for (int column = 0; column < numCols; column++)
{
pinMode(colPins[column],OUTPUT); // Set column pins as outputs for writing
digitalWrite(colPins[column],HIGH); // Make all columns inactive
}
}
void loop()
{
char key = getKey();
if( key != 0) { // if the character is not 0 then it's a valid key press
Serial.print("Got key ");
Serial.println(key);
}
}
// returns with the key pressed, or 0 if no key is pressed
char getKey()
{
char key = 0; // 0 indicates no key pressed
for(int column = 0; column < numCols; column++)
{
digitalWrite(colPins[column],LOW); // Activate the current column.
for(int row = 0; row < numRows; row++) // Scan all rows for a key press.
{
if(digitalRead(rowPins[row]) == LOW) // Is a key pressed?
{
delay(debounceTime); // debounce
while(digitalRead(rowPins[row]) == LOW)
; // wait for key to be released
key = keymap[row][column]; // Remember which key was pressed.
}
}
64)analogRead()->The analogRead() function in Arduino is used to read the value
from an analog input pin (A0 to A5 on Arduino Uno). It returns a value between 0
and 1023, representing the voltage level from 0V to 5V (for 10 bit ADC resolution)
EXAMPLE ->Read an analog pin and flash an led in proportional to the value returned
from the analogRead function.
const int Ledpin=13;
const int potpin=0;
int val=0;
void setup()
{
pinMode(Ledpin,OUTPUT);
}
void loop() {
val = analogRead(potPin); // read the voltage on the pot
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(val); // blink rate set by pot value (in milliseconds)
digitalWrite(ledPin, LOW); // turn the ledPin off
delay(val); // turn led off for same period as it was turned on
}
65)map(value,fromLow,fromHigh,toLow,toHigh)->The map() function in Arduino is used
to scale a number from one range to another.
value :it is the number to be mapped, fromLow :The lower bound of the input
range ,fromHigh :The upper bound of the input range.
toLow :The lower bound of the output range, toHigh :The higher bound of the output
range.(it works only with numbers)
EXAMPLE-> We want to display the position of the potentiometer knob as a percenet
from 0% to 100%.
const int potPin=0;
const int Ledpin=13;
void setup()
{
pinMode(ledPin,OUTPUT);
Serial.begin(9600);
}
void loop()
{
int val; //voltage at potentiometer
int percent; //mapped value
val=analogRead(potPin); //Reading value from potPin(val ranges from 0 to 1023)
percent=map(val,0,1023,0,100); //pecent will rangefrom 0 to 100
digitalWrite(Ledpin,HIGH); //turn Ledpin ON
delay(percent); //Led HIGH time give by percent, program
delays for percent ms.
digitalWrite(Ledpin,LOW); //turn Ledpin LOW
delay(100-percent); // Led LOW time give by (100-percent)
Serial.println(percent); //prints the value of percent, program delays for
(100-percent) ms.
}
EXAMPLE ->Displaying Voltages up to 5V
const int referenceVolts=5;
const int batteryPin=0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
int val=analogRead(batteryPin);
float volts=(val/1023)*(referenceVolts);
Serial.println(volts);
}
66)WORKING WITH SENSORS
a)DETECTING WHEN SOMEONE IS MOVING,SHAKEN OR TILTED
const int tiltSensorPin=2;
const int firstLedPin=11;
const int secondLedPin=12;
void setup()
{
pinMode(tiltSensorPin,INPUT);
pinMode(firstLedPin,OUTPUT);
pinMode(secondLedPin,OUTPUT);
}
void loop()
{
if(digitalRead(tiltSensorPin)){ //if the sensor is triggerd firstLed is
HIGH,secondLED is LOW
digitalWrite(firstLedPin,HIGH);
digitalWrite(secondLedPin,LOW);
}
else{ //if the sensor is not triggered
firstLed is LOW, secondLed is HIGH
digitalWrite(firstLedPin,LOW);
digitalWrite(secondLedPin,HIGH);
}
}
b)Lighting an LED if the tilt sensor is shaken
const int tiltSensorPin=2;
const int Ledpin=13;
const int tiltSensorCurrentvalue=0;
const int tiltSensorPreviousvalue=0;
const int shaketime=50;
void setup()
{
pinMode(tiltSensorPin,INPUT);
digitalWrite(tiltSensorPin,HIGH);
pinMode(Ledpin,OUTPUT);
}
void loop()
{
tiltSensorCurrentvalue =digitalRead(tiltSensorPin);
if
(tiltSensorCurrentvalue !=tiltSensorPreviousvalue) //if the
digitalRead(tiltSensorPin) is not equal to 0
{
lastTimeMoved=millis(); //lastTimeMoved=time for which the board has been
powered{ lastTimeMoved=millis(); }
tiltSensorPreviousvalue=tiltSensorCurrentvalue; //tiltSensorPreviousvalue is equal
to tiltSensorCurrentvalue
}
if(millis()-lastTimeMoved<shaketime)
{
digitalWrite(Ledpin,HIGH); //if millis()-lastTimeMoved<50ms Led turns ON
}
else
{
digitalWrite(Ledpin,LOW); //if millis()-lastTimeMoved>50ms Led turns OFF
}
}
c)Measure the distance of something moving towards the aurdino using the PIR
sensor.
const int pingPin=5;
const int Ledpin=13;
void setup()
{
Serial.begin(9600);
pinMode(Ledpin,OUTPUT);
pinMode(pingPin,INPUT);
}
void loop()
{
int cm=ping(pingPin);
Serial.println(cm);
digitalWrite(Ledpin,HIGH);
delay(cm*10);
digitalWrite(Ledpin,LOW);
delay(cm*10);
}
d)RESPONDING to VIBRATION : Light up the LED when vibration is produced on the
piezo sensor.
const int Piezopin=0;
const int Ledpin=13;
const int THRESHOLD=100;
void setup()
{
pinMode(Piezopin,INPUT);
pinMode(Ledpin,OUTPUT);
digitalWrite(Ledpin,LOW);
}
void loop()
{
int val=analogRead(Piezopin);
if(val>THRESHOLD)
{
digitalWrite(Ledpin,HIGH);
delay(50);
}
else
{
digitalWrite(Ledpin,LOW);
}
}
e)Detect Temperature using LM35 Heat detection Sensor.
const int inPin=0; //AnalogPin
void setup()
{
Serial.begin(9600);
}
void loop()
{
int value=analogRead(inPin);
Serial.println(value);
float millivolts=(value/1024.0)*5000;
float celsius=millivolts*10;
Serial.println(celsius);
float fahrenheit=(celsius*9)/5+32;
Serial.print(fahrenheit);
delay(1000);
}
f)Detecting Sound :You want to detect sounds like clapping, talking, shouting.
const int Ledpin=13;
const int middlevalue=512;
const int numberofSamples=128;
int sample;
long signal;
long averageReading;
long runningAverage;
const int averagedOver=16;
const int threshold=400;
void setup()
{
pinMode(Ledpin,OUTPUT);
Serial.begin(9600);
}
void loop()
{
long sumOfsquares=0;
for(int i=0;i<numberofSamples;i++)
{
sample=analogRead(0);
signal=(sample-middlevalue);
signal*=signal;
sumOfsquares+=signal;
}
averageReading=sumOfsquares/numberofSamples;
runningAverage=(((averagedOver-1)*runningAverage)+averageReading)/averagedOver;
if(runningAverage>threshold)
{digitalWrite(Ledpin,HIGH);}
else
{digitalWrite(Ledpin,LOW);}
Serial.println(runningAverage);
}
g)Track the movement and direction of a dial using a rotatory encoder.
const int encoderpinA=4;
const int encoderpinB=2;
const int encoderStepsPerRevolution=16;
int angle;
int val;
int encoderPos=0;
boolean encoderALast=LOW; //encoderALast stores the previous states of pinA
void setup()
{
pinMode(encoderpinA,INPUT);
pinMode(encoderpinB,INPUT);
digitalWrite(encoderpinA,HIGH);
digitalWrite(encoderpinB,HIGH);
Serial.begin(9600);
}
void loop()
{
boolean encoderA=digitalRead(encoderpinA);
if ((encoderALast == HIGH) && (encoderA == LOW)) //encoderA=LOW,encoderALast==HIGH
means HIGH to LOW transition takes place on pinA
{
if (digitalRead(encoderPinB) == LOW)
{encoderPos--;} //If pinB is low encoder rotates in anticlockwise
direction
else
{encoderPos++;} //If pinB is low encoder rotates in clockwise direction
angle=(encoderPos % encoderStepsPerRevolution)*360/encoderStepsPerRevolution;
Serial.print (encoderPos);
Serial.print (" ");
Serial.println (angle);
}
encoderALast=encoderA;
}
h)Tracking the movement using rotatory encoder by using interrupts in aurdino
const int encoderPinA = 2;
const int encoderPinB = 4;
int Pos, oldPos;
volatile int encoderPos = 0; // variables changed within interrupts are volatile
void setup()
{
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
digitalWrite(encoderPinA, HIGH);
digitalWrite(encoderPinB, HIGH);
Serial.begin(9600);
attachInterrupt(0, doEncoder, FALLING); // encoder pin on interrupt 0 (pin 2)
}
void loop()
{
uint8_t oldSREG = SREG; //Save Interrupt Status
cli(); //Disable Interrupts
Pos = encoderPos; //Copy shared variable safely
SREG = oldSREG; //Restore Interrupt Status
if(Pos != oldPos) //If Pos is not equal to oldPos, position changed
{
Serial.println(Pos,DEC); //Print new Position in the DECIMAL form
oldPos = Pos; //Restore the old position
}
delay(1000);
}
#include "TinyGPS.h"
#include "NewSoftSerial.h"
#define HEMISPHERE_PIN 13
#define GPS_RX_PIN 2
#define GPS_TX_PIN 3
TinyGPS gps; // create a TinyGPS object
NewSoftSerial nss(GPS_RX_PIN, GPS_TX_PIN); // create soft serial object
void setup()
{
Serial.begin(9600); // for debugging
nss.begin(4800); // Use NewSoftSerial object to talk to GPS
pinMode(HEMISPHERE_PIN, OUTPUT);
digitalWrite(HEMISPHERE_PIN, LOW); // turn off LED to start
}
void loop()
{
while (nss.available())
{
int c = nss.read();
Serial.print(c, BYTE); // display NMEA data for debug
// Send each byte to encode()
// Check for new position if encode() returns "True"
if (gps.encode(c))
{
long lat, lon;
gps.get_position(&lat, &lon);
// Display new lat/lon on debug console
Serial.print("Lat: "); Serial.print(lat);
Serial.print(" Lon: "); Serial.println(lon);
if (lat < 0) // Southern Hemisphere?
digitalWrite(HEMISPHERE_PIN, HIGH);
else
digitalWrite(HEMISPHERE_PIN, LOW);
}
}
}
void doEncoder()
{
if (digitalRead(encoderPinA) == digitalRead(encoderPinB))
encoderPos++; // count up if both encoder pins are the same //if A==B rotate
encoder in clockwise direction
else
encoderPos--; //count down if pins are different //if Ais not equal to B rotate
encoder in anticlockwise direction
}
i)Determine the location using a GPS module
General way to using a GPS is :
1)Physically connect the GPS device to the aurdino
2)Read Serial NMEA data from the GPS device
3)Process data to determine location
Using Tiny GPS use may do the following:
1)Physically connect the GPS device to the aurdino
2)Create a Tiny GPS object
3)Read Serial NMEA data from the GPS device
4)Process each byte from the TinyGPS's encode() method.
5)Periodically query TinyGPS's get_position() method to determine location.
#include "TinyGPS.h"
TinyGPS gps; // create a TinyGPS object
#define HEMISPHERE_PIN 13
void setup()
{
Serial.begin(4800); // GPS devices frequently operate at 4800 baud
pinMode(HEMISPHERE_PIN, OUTPUT);
digitalWrite(HEMISPHERE_PIN, LOW); // turn off LED to start
}
void loop()
{
while (Serial.available())
{
int c = Serial.read();
// Encode() each byte
// Check for new position if encode() returns "True"
if (gps.encode(c))
{
long lat, lon;
gps.get_position(&lat, &lon);
if (lat < 0) // Southern Hemisphere?
digitalWrite(HEMISPHERE_PIN, HIGH);
else
digitalWrite(HEMISPHERE_PIN, LOW);
}
}
}
67)lat ->It represents the latitude(north-south position)
68)lon ->It represents the longitude(east-west position)
69)long ->A data type in C/C+ used for storing large integer values.
70)Serial.read() ->It is used to read sensors/GSM module,reads the incoming data
from the serial port.
71)gps.encode() ->A gps module sends data in the NMEA format over Serial
Connection,the gps.encode() is used inside the loop to process each character
received.
EXAMPLE using NewSoftSerail.h to read location using gps module(GPS MODULE : EM-
406A)
#include "TinyGPS.h"
#include "NewSoftSerial.h"
#define HEMISPHERE_PIN 13
#define GPS_RX_PIN 2
#define GPS_TX_PIN 3
TinyGPS gps; // create a TinyGPS object
NewSoftSerial nss(GPS_RX_PIN, GPS_TX_PIN); // create soft serial object
void setup()
{
Serial.begin(9600); // for debugging
nss.begin(4800); // Use NewSoftSerial object to talk to GPS
pinMode(HEMISPHERE_PIN, OUTPUT);
digitalWrite(HEMISPHERE_PIN, LOW); // turn off LED to start
}
void loop()
{
while (nss.available())
{
int c = nss.read();
Serial.print(c, BYTE); // display NMEA data for debug
// Send each byte to encode()
// Check for new position if encode() returns "True"
if (gps.encode(c))
{
long lat, lon;
gps.get_position(&lat, &lon);
// Display new lat/lon on debug console
Serial.print("Lat: ");
Serial.printIn(lat);
Serial.print(" Lon: ");
Serial.println(lon);
if (lat < 0) // Southern Hemisphere?
digitalWrite(HEMISPHERE_PIN, HIGH);
else
digitalWrite(HEMISPHERE_PIN, LOW);
}
}
}
j)Detecting Rotation using Gyroscope
const int inputPin=0;
const int powerDownPin=15;
int rotationRate=0;
void setup()
{
Serial begin(9600);
pinMode(powerDownPin,OUTPUT);
digitalWrite(powerDownPin,LOW);
}
void loop()
{
rotationRate=analogRead(inputPin);
Serial.print("Rotation rate is ");
Serial.print(rotationRate );
delay(500);
}
VISUAL OUTPUTS
a)Control intensity of one of more LEDs(3 LEDs)
const int firstLed = 3; // specify the pin for each of the LEDs
const int secondLed = 5;
const int thirdLed = 6;
int brightness = 0;
int increment = 1;
void setup()
{
// pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
if(brightness > 255)
{
increment = -1; // count down after reaching 255
}
else if(brightness < 1)
{
increment = 1; // count up after dropping back down to 0
brightness = brightness + increment; // increment (or decrement sign is minus)
// write the brightness value to the LEDs
analogWrite(firstLed, brightness);
analogWrite(secondLed, brightness);
analogWrite(thirdLed, brightness );
delay(10); // 10ms for each step change means 2.55 secs to fade up or down
}
b)Adjust the color of an RGB LED under a control program.
int const redPin=3;
int const greenPin=5;
int const bluePin=6;
const boolean invert = true; // set true if common anode, false if common cathode
int color = 0; // a value from 0 to 255 representing the hue
int R, G, B; // the Red Green and Blue color components
void setup()
{
// pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
int brightness = 255; // 255 is maximum brightness
hueToRGB( color, brightness); // call function to convert hue to RGB
// write the RGB values to the pins
analogWrite(redPin, R);
analogWrite(greenPin, G);
analogWrite(bluePin, B );
color++; // increment the color
if(color > 255) //
color = 0;
delay(10);
}
void hueToRGB( int hue, int brightness)
{
unsigned int scaledHue = (hue * 6);
unsigned int segment = scaledHue / 256; // segment 0 to 5 around the color
wheel
unsigned int segmentOffset = scaledHue - (segment * 256); // position within
the segment
unsigned int complement = 0;
unsigned int prev = (brightness * ( 255 - segmentOffset)) / 256;
unsigned int next = (brightness * segmentOffset) / 256;
if(invert)
{
brightness = 255-brightness;
complement = 255;
prev = 255-prev;
next = 255-next;
}
switch(segment ) {
case 0: // red
R = brightness;
G = next;
B = complement;
break;
case 1: // yellow
R = prev;
G = brightness;
B = complement;
break;
case 2: // green
R = complement;
G = brightness;
B = next;
break;
case 3: // cyan
R = complement;
G = prev;
B = brightness;
break;
case 4: // blue
R = next;
G = complement;
B = brightness;
break;
case 5: // magenta
default:
R = brightness;
G = complement;
B = prev;
break;
}
}
c)Create a LED bar graph that lights up various LED in proportion to the value.
const int NbrLEDs=6;
const int LEDpins[]={2,3,4,5,6,7};
const int analogInPin=0;
const int wait=30;
const boolean LED_ON=LOW;
const boolean LED_OFF=HIGH;
int SensorValue=0; //value read from the sensor
int Ledlevel=0; //sensor value converted into LED 'bars'
void setup()
{
for(int led=0;led<NbrLEDs;led++)
{pinMode(LEDpins[led],OUTPUT);} //all LEDs give OUTPUT.
}
void loop()
{
SensorValue=analogRead(analogInPin); //read the value of analogInPin and store it
in Sensor Value
Ledlevel=map(SensorValue,0,1023,0,NbrLEDs);
for(int led=0;led<NbrLeds;led++)
{
if(led<Ledlevel)
{digtalWrite(LEDpins[],LED_ON);}
else
{digitalWrite(LEDpins[],LED_OFF);}
}
}
d)Create an LED chase sequence
const int NbrLeds=6;
const int LEDpins[]={2,3,4,5,6,7};
const int wait=30;
void setup()
{
for(int led=0;led<NbrLeds;led++)
{pinMode(LEDpins[led],OUTPUT);}
}
void loop()
{
for(int led=0;led<NbrLeds-1;led++)
{
digitalWrite(LEDpins[led], HIGH);
delay(wait);
digitalWrite(LEDpins[led + 1], HIGH);
delay(wait);
digitalWrite(LEDpins[led], LOW);
delay(wait*2);
}
for(int led=NbrLeds-1;led>0;led--)
{
digitalWrite(LEDpins[led], HIGH);
delay(wait);
digitalWrite(LEDpins[led - 1], HIGH);
delay(wait);
digitalWrite(LEDpins[led], LOW);
delay(wait*2);
}
}
e)Display images using an LED matrix
//each bit corresponds to an LED, a 0 indicates that the LED is OFF,1 indicates LED
is ON
byte bigHeart[] = {
B01100110,
B11111111,
B11111111,
B11111111,
B01111110,
B00111100,
B00011000,
B00000000};
byte smallHeart[] = {
B00000000,
B00000000,
B00010100,
B00111110,
B00111110,
B00011100,
B00001000,
B00000000};
const int columnPins[]={2,3,4,5,6,7,8,9};
const int rowPins[]={10,11,12,15,16,17,18,19};
void setup()
{
for(int i=0;i<8;i++)
{
pinMode(rowPins[i],OUTPUT);
pinMode(columnPins[i],OUTPUT);
digitalWrite(columnPins[i],HIGH);
}
}
void loop()
{
int pulseDelay=800;
show(smallHeart,80);
show(bigHeart,160);
delay(pulseDelay);
}
// routine to show a frame of an image stored in the array pointed to by the
image parameter.
// the frame is repeated for the given duration in milliseconds
void show( byte * image, unsigned long duration)
{
unsigned long start = millis(); // begin timing the animation
while (start + duration > millis()) // loop until the duration period
has passed
{
for(int row = 0; row < 8; row++)
{
digitalWrite(rowPins[row], HIGH); // connect row to +5 volts
for(int column = 0; column < 8; column++)
{
boolean pixel = bitRead(image[row],column);
if(pixel == 1)
{
digitalWrite(columnPins[column], LOW); // connect column to Gnd
}
delayMicroseconds(300); // a small delay for each LED
digitalWrite(columnPins[column], HIGH); // disconnect column from Gnd
}
digitalWrite(rowPins[row], LOW); // disconnect LEDs
}
}
}
f)You have a number of LEDs and you wantto minimize the number of pins needed to
turn them ON and OFF.
byte pins[]={2,3,4}; //We are using 3 pins
const int NUMBER_OF_PINS=sizeof(pins)/sizof(pins[0]);
const int NUMBER_OF_LEDS=NUMBER_OF_PINS*(NUMBER_OF_PINS-1); //the number of LEDS
are 3*(3-1)=6
byte pairs[NUMBER_OF_LEDS/2][2]={{0,1},{1,2},{0,2}}; //maps pins to LEDS each
pair can control 2 LED by switching polarity
void setup()
{
}
void loop()
{
for(int i=0;i<NUMBER_OF_LEDS;i++)
{
lightLed(i); //Turns one LED at a time with a delay of 1 second
delay(1000);
}
}
void lightLed(int led) //LightLed function is used to light the correct LED
{
int indexA=pairs[led/2][0]; //convert the LED number to the pin number
int indexB=pairs[led/2][1];
int pinA=pins[indexA];
int pinB=pins[indexB];
for(int i=0;i<NUMBER_OF_PINS;i++)
if(pins[i]!=pinA && pins[i]!=pinB)
{
pinMode(pins[i],INPUT);
digitalWrite(pins[i],LOW);
}
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
if( led % 2 == 0)
{
digitalWrite(pinA,LOW);
digitalWrite(pinB,HIGH);
}
else
{
digitalWrite(pinB,LOW);
digitalWrite(pinA,HIGH);
}
}
g)Display numerals using a seven segment display
const byte numeral[10] = {
//ABCDEFG /dp
B11111100, // 0
B01100000, // 1
B11011010, // 2
B11110010, // 3
B01100110, // 4
B10110110, // 5
B00111110, // 6
B11100000, // 7
B11111110, // 8
B11100110, // 9
};
// pins for decimal point and each segment
// dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};
void setup()
{
for(int i=0; i < 8; i++)
{
pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
}
}
void loop()
{
for(int i=0; i <= 10; i++)
{
showDigit(i);
delay(1000);
}
// the last value if i is 10 and this will turn the display off
delay(2000); // pause two seconds with the display off
}
// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
boolean isBitSet;
for(int segment = 1; segment < 8; segment++)
{
if( number < 0 || number > 9){
isBitSet = 0; // turn off all segments
}
else{
isBitSet = bitRead(numeral[number], segment);
}
isBitSet = ! isBitSet; // remove this line if common cathode display
digitalWrite( segmentPins[segment], isBitSet);
}
}
h)Drive a multidigit seven segment display
const int numeral[10] = {
//ABCDEFG /dp
B11111100, // 0
B01100000, // 1
B11011010, // 2
B11110010, // 3
B01100110, // 4
B10110110, // 5
B00111110, // 6
B11100000, // 7
B11111110, // 8
B11100110, // 9
};
// pins for decimal point and each segment
// dp,G,F,E,D,C,B,A
const int segmentPins[] = { 4,7,8,6,5,3,2,9};
const int nbrDigits= 4; // the number of digits in the LED display
//dig 1 2 3 4
const int digitPins[nbrDigits] = { 10,11,12,13};
void setup()
{
for(int i=0; i < 8; i++)
pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
for(int i=0; i < nbrDigits; i++)
pinMode(digitPins[i], OUTPUT);
}
void loop()
{
int value = analogRead(0); //Reads the value at A0
showNumber(value); //Displays the value at A0 on the seven segment display eg->if
value=758 7,5,8 is displayed.
}
void showNumber( int number)
{
if(number == 0)
showDigit( 0, nbrDigits-1) ; // display 0 in the rightmost digit
else
{
// display the value corresponding to each digit
// leftmost digit is 0, rightmost is one less than the number of places
for( int digit = nbrDigits-1; digit >= 0; digit--)
{
if(number > 0)
{
showDigit( number % 10, digit) ;
number = number / 10;
}
}
}
}
// Displays given number on a 7-segment display at the given digit position
void showDigit( int number, int digit)
{
digitalWrite( digitPins[digit], HIGH );
for(int segment = 1; segment < 8; segment++)
{
boolean isBitSet = bitRead(numeral[number], segment);
// isBitSet will be true if given bit is 1
isBitSet = ! isBitSet; // remove this line if common cathode display
digitalWrite( segmentPins[segment], isBitSet);
}
delay(5);
digitalWrite( digitPins[digit], LOW );
}
i)Controlling an array of LEDS using MAX72xx SHIFT REGISTER
#include <Sprite.h> //Used for Drawing 2D graphics
#include <Matrix.h> //Provides Functions to control an 8*8 LED Matrix
// Hello Matrix
// by Nicholas Zambetti <http://www.zambetti.com>
// Demonstrates the use of the Matrix library
// For MAX7219 LED Matrix Controllers
// Blinks welcoming face on screen
const int loadPin = 2;
const int clockPin = 3;
const int dataPin = 4;
Matrix myMatrix = Matrix(dataPin, clockPin, loadPin); // create a new Matrix object
for communication
instance
void setup()
{
myMatrix.begin();
}
void loop()
{
myMatrix.clear(); // clear display
delay(1000);
myMatrix.write(1, 5, HIGH);
myMatrix.write(2, 2, HIGH);
myMatrix.write(2, 6, HIGH);
myMatrix.write(3, 6, HIGH);
myMatrix.write(4, 6, HIGH);
myMatrix.write(5, 2, HIGH);
myMatrix.write(5, 6, HIGH);
myMatrix.write(6, 5, HIGH);
delay(1000);
}
f)Use an Analog Panel Meter as a Display ->Control the pointer of an analog Panel
meter
const int analogPin=0;
const int analogmeterPin=9;
int SensorValue=0;
int OutputValue=0;
void setup()
{
}
void loop()
{
SensorValue=analogRead(analogPin);
OutputValue=map(SensorValue,0,1023,0,255);
analogWrite(analogmeterPin,OutputValue);
}