0% found this document useful (0 votes)
0 views

Lect 2 Arduino Programming

The document provides an overview of Arduino programming, focusing on serial communication, data types, and basic programming concepts such as variables, loops, and functions. It includes examples of how to control LEDs and read button states, as well as using a potentiometer for brightness control. Key commands and structures like conditional statements and loops are also discussed to facilitate effective programming in Arduino.

Uploaded by

Amiell O. Reyes
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lect 2 Arduino Programming

The document provides an overview of Arduino programming, focusing on serial communication, data types, and basic programming concepts such as variables, loops, and functions. It includes examples of how to control LEDs and read button states, as well as using a potentiometer for brightness control. Key commands and structures like conditional statements and loops are also discussed to facilitate effective programming in Arduino.

Uploaded by

Amiell O. Reyes
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

ARDUINO

PROGRAMMING
Serial Communication
Serial Communication
• Compiling turns your program into binary
data (ones and zeros)
• Uploading sends the bits through USB cable
to the Arduino
• The two LEDs near the USB connector blink
when data is transmitted
• RX blinks when the Arduino is receiving
data
• TX blinks when the Arduino is
transmitting data
ASCII Table
Variables

 You can use variables in a similar way


as they are used in math or physics
 All variables have to be declared
before they are used , and optionally,
 set an initial value (initializing the
variable).
char
 A data type that takes up 1 byte of memory that
stores a character value. Character literals are
written in single quotes, like this: 'A' (for multiple
characters - strings - use double quotes: "ABC").

 Characters are stored as numbers however. You


can see the specific encoding in the ASCII chart.
char
 The char datatype is a signed type,
meaning that it encodes numbers from -
128 to 127. For an unsigned, one-byte (8
bit) data type, use the byte data type.

 Example
 char myChar = 'A';
 char myChar = 65; // both are equivalent
char

 It is possible to do arithmetic on characters, in which


the ASCII value of the character is used (e.g. 'A' + 1
has the value 66, since the ASCII value of the
capital letter A is 65). See Serial.println reference for
more on how characters are translated to numbers.
byte
A byte stores an 8-bit unsigned
number, from 0 to 255.
Example
 byte b = B10010; // "B" is the binary
formatter (B10010 = 18 decimal)
int
 Integers are your primary datatype for number storage, and
store a 2 byte value. This yields a range of -32,768 to
32,767 (minimum value of -215 and a maximum value of
(2^15) - 1).
 Int's store negative numbers with a technique called 2's
complement math. The highest bit, sometimes refered to as
the "sign" bit, flags the number as a negative number. The
rest of the bits are inverted and 1 is added.
int

 Syntax
 int var = val;

Example
 int ledPin = 13;
unsigned int

 Unsigned ints (unsigned integers) are the same as


ints in that they store a 2 byte value. Instead of
storing negative numbers however they only store
positive values, yielding a useful range of 0 to
65,535 (2^16) - 1).
unsigned int
 Syntax
 unsigned int var = val;
 var - your unsigned int variable name
 val - the value you assign to that
variable

 Example
 unsigned int ledPin = 13;
long
 long – long variables are extended size variables
for number storage, and store 32 bits (4 bytes),
from −2,147,483,648 to 2,147,483,647.
 unsigned long – unsigned long variables are
extended size variables for number storage, and
store 32 bits (4 bytes). Unlike standard longs
unsigned longs won't store negative numbers,
making their range from 0 to 4,294,967,295
float / double
 float – datatype for floating-point numbers, a number
that has a decimal point. They are often used to
approximate analog and continuous values because they
have greater resolution than integers. Floating-point
numbers can be as large as 3.4028235E+38 and as low as
−3.4028235E+38. They are stored as 32 bits (4 bytes) of
information.
 double – double precision floating point number.
Occupies 4 bytes. The double implementation on the
Arduino is currently exactly the same as the float, with
no gain in precision.
Arithmetic Operators
 Arithmetic operators include addition,
subtraction, multiplication, and division. They
return the sum, difference, product, or quotient
of two operands.
y = y + 3;
x = x - 7;
i = j * 6;
r = r / 5;
Comparison Operators
 x < y (x is less than y)
 x > y (x is greater than y)
 x <= y (x is less than or equal to y)
 x >= y (x is greater than or equal to y)
 x == y (x is equal to y)
 x != y (x is not equal to y)
First Program
/*
* Hello World!
* From www.ladyada.net
* It shows how to send data to the computer
*/
void setup() // run once, when the sketch starts
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Hello world!"); // prints hello with a line break
}
void loop() // run over and over again
{ // do nothing!
}
Open the Serial Monitor and
Upload the Program
Example – Printing a message repeatedly
The previous program was modified. The Serial.print(“Hello!”) instruction was moved into the loop function. Now it
will be written to the output screen repeatedly.

Notes:
•The following instruction causes a delay of
1000 ms or 1 second.
delay(1000);
•Hello! is now printed to the display window
once per second.
•If we want each Hello! statement printed on a
new line, we can used the following
command:
•Serial.println(“Hello!”)
Basic Programming
 The pinMode() function configures a pin as
either an input or an output. To use it:
 You pass it the number of the pin to configure and the
constant INPUT or OUTPUT.
 pinMode(11, INPUT);
 pinMode(13, OUTPUT);
 When configured as an input, a pin can detect the state of
a sensor like a pushbutton.
 As an output, it can drive an actuator like an LED.
Basic Programming
 The delay() causes the Arduino to wait
for the specified number of
milliseconds before continuing on to
the next line.
 There are 1000 milliseconds in a
second, so the line:
 delay(1000); //creates a delay of one second.
Basic Programming
 The digitalWrite() functions outputs a value on
a pin.
 Possible values are:
 LOW (0 V)or
 HIGH (5 V)
 For example:
 digitalWrite(13, HIGH);
 digitalWrite(11, LOW);
Common Commands
• Serial.begin()
- e.g., Serial.begin(9600)
• Serial.print() or Serial.println()
- e.g., Serial.print(value)
• Serial.read()
• Serial.available()
• Serial.write()
• Serial.parseInt()
Useful Functions
 Lots of useful functions
 pinMode() – set a pin as input or output
 digitalWrite() – set a digital pin high/low
 digitalRead() – read a digital pin’s state
 analogRead() – read an analog pin
 analogWrite() – write an “analog” PWM value
 delay() – wait an amount of time (ms)
 millis() – get the current time
Conditional Statement

if (someCondition) {
// do stuff if the condition is true
} else {
// do stuff if the condition is false
}
Conditional Statement
int printMessage = 1;
int printMessage = 1;
void setup()
void setup()
{ Serial.begin(9600);
{ Serial.begin(9600);
}
}
void loop()
{
void loop() if (printMessage == 1) {
{ Serial.println("Message");
if (printMessage == 1) { printMessage= 0;
Serial.println("Message"); }
else {
printMessage= 0; Serial.println("NO Message");
} printMessage= 1;
}
} }
while Loop

while(expression){
statement(s);
}
Example
int var = 0;
while (var < 200) {
// do something repetitive 200 times
var = var + 1;
}
while Loop
void setup()
{ Serial.begin(9600);
int count = 0;
while (count < 5) {
Serial.println("Hello world!");
count = count +1;
}
}

void loop()
{
}
for loop in C++:
Several types of looping structures can be used in C++. The for loop is
especially useful when you want to execute instructions in the loop a specific
number of times. See the example below.
Form: for (initialization; condition; increment)
{
// body of loop
}

Note:
C++ sometimes uses shortcut
operators to increment, decrement,
or change variables in loops.

i++ means add one to i


j-- means to subtract one from j
k+=2 means add 2 to k
for loop
for Loop
void setup()
{
Serial.begin(9600);
for (int count = 0; count < 5; count++) {
Serial.println("Hello world!");
}
}

void loop()
{
}
Functions
 loop() and setup() are procedures
 You can create you own functions
void setup() {
}
void loop() {
}

Both setup() and loop()


have no parameters and
return no values
Functions: Example 1
Functions: Example 2
Blink
 The boards are designed to make it easy to blink an LED using
digital pin 13. Some (like the Diecimila and LilyPad) have the LED
built-in to the board. On most others (like the Mini and BT), there is
a 1 KB resistor on the pin, allowing you to connect an LED directly.
EXAMPLE PROGRAM
int ledPin = 13; // LED connected to digital pin 13

// The setup() method runs once, when the sketch starts

void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
}

// the loop() method runs over and over again,


// as long as the Arduino has power

void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // set the LED off
delay(1000); // wait for a second
}
Button
 Pushbuttons or
switches connect
two points in a circuit
when you press
them. This example
turns on the built-in
LED on pin 13 when
you press the button.
int buttonPin = 2; // the number of the pushbutton pin
int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop(){
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:

if (buttonState == HIGH) { // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
digitalWrite(ledPin, HIGH); // turn LED on:
}
else {
digitalWrite(ledPin, LOW); // turn LED off:
}
}
Button

 The problem with the last program is that the


switch has to remain pressed in order for the LED
to turn on
 We want the LED to change state when we press
the button and to stay in the new state when the
button is released
int buttonPin = 2; // the pin that the pushbutton is attached to
int ledPin = 13; // the pin that the LED is attached to
int buttonState = 0; // current state of the button
int lastLEDState = 0; // previous state of the button

void setup() {
pinMode(buttonPin, INPUT); // initialize the button pin as a input:
pinMode(ledPin, OUTPUT); // initialize the LED as an output:
}

void loop() {
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:

if (buttonState == HIGH) { // Determine if button State is HIGH


if (lastLEDState == HIGH) { // if the current state is HIGH then turn LED off
digitalWrite(ledPin, LOW);
lastLEDState = LOW;
}
else {// if the current state is LOW then turn LED on
digitalWrite(ledPin, HIGH);
lastLEDState = HIGH;
}
while(buttonState == HIGH){
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:
};
delay(250);
}
}
int buttonPin = 2; // the pin that the pushbutton is attached to
int ledPin = 13; // the pin that the LED is attached to
int buttonState = 0; // current state of the button
int lastLEDState = 0; // previous state of the button

void setup() {
pinMode(buttonPin, INPUT); // initialize the button pin as a input:
pinMode(ledPin, OUTPUT); // initialize the LED as an output:
}

void loop() {
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:

if (buttonState == HIGH) { // Determine if button State is HIGH


if (lastLEDState == HIGH) { // if the current state is HIGH then turn LED off
digitalWrite(ledPin, LOW);
lastLEDState = LOW;
}
else {// if the current state is LOW then turn LED on
digitalWrite(ledPin, HIGH);
lastLEDState = HIGH;
}
while(buttonState == HIGH){
buttonState = digitalRead(buttonPin); // read the pushbutton input pin:
};
delay(250);
}
}
Potentiometer Example
const int ledPin = 9; // PWM pin for LED
const int potPin = A0; // Analog input pin for potentiometer

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
int sensorValue = analogRead(potPin); // Read potentiometer value
int brightness = map(sensorValue, 0, 1023, 0, 255); // Map to PWM range

analogWrite(ledPin, brightness); // Set LED brightness


delay(30); // Small delay for smooth transition
}
LED Brightness Control with PWM
const int ledPin = 9; // PWM pin for LED

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness); // Set LED brightness
delay(20); // Small delay for smooth transition
}

for (int brightness = 255; brightness >= 0; brightness--) {


analogWrite(ledPin, brightness); // Set LED brightness
delay(20); // Small delay for smooth transition
}
}

You might also like