COURSE: Microprocessors and Microcontrollers-II
CONTACT: [email protected]
Lets Discuss Arduino
Code Basics and Digital I/O
programming
ARDUINO
PROGRAM SKETCH
STRUCTURE void setup() {
// put your setup code here, to run once
//The setup section is used for assigning
TWO functions Used
input and outputs (Examples: motors, LED’s,
sensors etc) to ports on the Arduino
• void setup()
– Will be executed //setup motors, sensors etc
only when the
program begins }
(or reset button
void loop() {
is pressed)
// put your main code here, to run repeatedly
// e.g get information from sensors
• void loop()
// send commands to motors etc
– Will be executed
repeatedly }
ARDUINO COMMANDS TO CONFIGURE I/O
DIRECTION AND DATA
pinMode(pin#, mode) // command to make pin#9 of
Arduino as OUTPUT
Sets pin mode to either INPUT or OUTPUT pinMode(9, OUTPUT);
digitalWrite(pin#,value)
Writes HIGH or LOW value to a pin // command to write LOW to pin#2
digitalWrite(2, LOW);
digitalRead(pin#)
Reads HIGH or LOW from a pin
// Code to make pin#1 HIGH if pin#2 is LOW
if(digitalRead(2) == LOW)
{
digitalWrite(1, HIGH);
}
Program that toggle LED after every ½ sec
attatched with pin 13 of Arduino
const int kPinLed = 13;
void setup() //will run once in start
{
pinMode(kPinLed, OUTPUT); //make pin#13 o/p
}
void loop() //executed again and again
{
digitalWrite(kPinLed, HIGH); //make pin#13 hi
delay(500); //500ms delay, command format: delay(milliseconds)
digitalWrite(kPinLed, LOW); //make pin#13 lo
delay(500);
}
Program that switch on LEDs connected to pin2-5 from left to right
and then switch off on reverse order
const int kPinLeds[] = {2,3,4,5}; // LEDs connected to pins 2-5
void setup()
{
for(int i = 0; i<4; i++)
pinMode(kPinLeds[i], OUTPUT); // make LED pins 2-5 o/p
}
void loop()
{
for(int i = 0; i < 4; i++) // LEDs switch on from left to right
{
digitalWrite(kPinLeds[i], HIGH);
delay(100);
}
for(int i = 3; i >= 0; i--) // LED switch off from right to left
{
digitalWrite(kPinLeds[i], LOW);
delay(100);
}
}
const int kPinLed = 13;
void setup()
{
pinMode(kPinLed, OUTPUT);
}
int delayTime = 1000;
void loop()
{
if(delayTime <= 100){
delayTime = 1000; // If it is less than or equal to !!100, reset it
}
else{
delayTime = delayTime - 100;
}
digitalWrite(kPinLed, HIGH);
delay(delayTime);
digitalWrite(kPinLed, LOW);
delay(delayTime);
)
Program that switch on LEDs connected to pin9 according
to switch connected on pin2
const int kPinButton1 = 2; // button attached to pin#2
const int kPinLed = 9; // LED attached with pin#9
void setup()
{
pinMode(kPinButton1, INPUT); // make button pin i/p
digitalWrite(kPinButton1, HIGH);// enable internal pull up resistors for i/p pin
pinMode(kPinLed, OUTPUT); // make LED pins 2-5 o/p
void loop()
{
if(digitalRead(kPinButton1) == LOW) // make LED pins 2-5 o/p
digitalWrite(kPinLed, HIGH); // make LED pins 2-5 o/p
else
digitalWrite(kPinLed, LOW);
}
boolean data type is used
to store state of a pin.