Computing for Engineers
B57AS
Lecture 02
This week:
• Using the serial monitor
• Serial communication functions
• Defining Variables and Variable Scope
• More Control Structures or Flow Control
• Assignment & Arithmetic Operators
• Operator Precedence and Associativity
• Problem solving case study
• Common programming problems
Serial communication with Arduino
• Serial communication is the process of sending data elements
over a channel, often named a bus
• In serial communication, data is sent sequentially, one after
the previous one
• This involves a clock initializing serial communication at a
particular speed in baud, also called baud rate
• Each Arduino board has at least one serial port. It can be used
by using digital pins 0 and 1, or directly using the USB
connection to communicate with your computer
Serial communication with Arduino
• On the Arduino board, you can read RX and TX on both digital
pins 0 and 1 respectively
• TX means transmit and RX means receive; indeed, the most
basic serial communication requires two wires
Serial communication with Arduino
const int kPinLed = 13;
void setup()
{
pinMode(kPinLed, OUTPUT);
serial.begin(9600); // Set the baud rate for serial communication
}
int delayTime = 1000;
void loop()
{
delayTime = delayTime – 100;
if (delayTime <= 0)
delayTime = 1000; // reset if less than equal to zero
serial.print(“delayTime =”); // prints whatever is between “ ”
serial.println(delayTime); // prints with a carriage return
digitalWrite(kPinLed, HIGH);
delay(delayTime);
digitalWrite(kPinLed, LOW);
delay(delayTime);
}
Serial monitor
Serial monitor: Can use this to issue commands
to the board and read outputs from the board.
The serial monitor GUI:
This is where you can print
your outputs and view its
values
Using the Serial Monitor
/*
For Loop Sketch demonstrating output to
serial monitor
*/
Output:
void setup()
{ for(int i = 0; i < 4; i++)
0
// set baud rate to transmit data
1
Serial.begin(9600); 2
} 3
What’s this dot?
void loop()
{ The dot (.) operator is used for direct member
selection viaserial
// print to object monitor
name. Here,
with begin()
carriageis return
a member
and new line
function of the object Serial.
Serial.println(“for(int i = 0; i < 4; i++)”);
for(int i = 0; i < 4; i++)
Serial.println(i); // print out each i value
}
Serial communication functions
Commonly used
Serial.begin() –
Sets the data rate in bits per second (baud) for serial data
transmission. 9600 is the default.
Serial.println() –
Prints data to the serial port, followed by an automatic
carriage return and new line. Same as Serial.print(), but is
easier for reading data on the Serial Monitor.
Useful for debugging!
Defining variables
Defining variables
Defining variables
Variables Variations Program
The scope context
• The scope of a variable where the variable is visible and usable
• A global variable is visible and usable everywhere in the source code
• A local variable is visible only inside a particular function
int value; // ‘value’ is visible to any function
void setup()
{
// no setup needed
}
void loop()
{
for(int i = 0; i < 20;) // ‘i’ is only visible
{ // inside for-loop
value = i++;
}
float f; // ‘f’ is only visible inside
loop()
Control Structures or Flow Control
• A while statement repeats a code block (code
within the curly braces { } ) as long as the
condition is true
Syntax:
while( expression )
{
doDomething; // statements
}
Control Structures or Flow Control
• A do-while statement is similar to the while, but
makes its expression evaluation at the end of the
loop, which means after the statements execution.
Syntax:
do
{
doDomething; // statements
} while( expression );
Do-while loop
int counter = 0; // global counter
void setup() {
Serial.begin(9600); // set baud rate
}
void loop() {
do
{ // prints the value of i
Serial.println(counter);
counter++; // increments counter
// terminates when counter is greater than 100
} while( counter < 100 );
}
Built-in Data types
Assignment & Arithmetic Operators
Assignment & Arithmetic Operations
Examples:
Multiplication
String concatenation
Operator precedence
Precedence Operator Associativity
1 Parentheses: ( ) Innermost first
Unary operators;
2 Right to left
+- ++ -- (type)
Binary operators:
3 Left to right
* / %
Binary operators: Left to right
4
+ -
Assignment operators:
5 Right to left
= += -= *= /= %=
Don’t cram…
Binary multiple
operators assignment
also have “left” or statements are difficult to interpret!!
“right” associativity.
• +e.g.
is left
a =associative
b += c + d;and thus 1 + 2 + 3 is read as (1 + 2) + 3.
• - is left associative and thus 9 - 4 - 2 is read as (9 - 4) - 2.
Better b = b + (c + d);
This isa =not
b; the same as 9 - (4 - 2).
While – Conditional example
Using a while loop to calibrate the value of an
analogue sensor
Hardware Required
Arduino Board
Pushbutton or switch
Photoresistor or another analogue sensor
2 10k ohm resistors
Breadboard
While – Conditional example
Circuit
Connect analogue sensor (e.g.
potentiometer, light sensor) on
analogue input 2 with a 10K
ohm resistor to ground.
Connect button to digital pin,
with a 10K ohm resistor to
ground.
Connect LED to digital pin 9,
with a 220 ohm resistor in
series.
While – Conditional example
In the main loop, the sketch reads the value of a photoresistor on analogue pin
0 and uses it to fade an LED on pin 9. But while a button attached to digital pin
2 is pressed, the program runs a method called calibrate() that looks for the
highest and lowest values of the analogue sensor. When the button is released,
the sketch continues with the main loop.
This technique updates the maximum and minimum values for the photoresistor
when the lighting conditions change.
While – Conditional example
/*
This example demonstrates the while() statements. While the pushbutton is
pressed, the sketch runs the calibration routine. The sensor readings
during the while loop define the minimum and maximum of expected values
from the photoresistor. http://www.arduino.cc/en/Tutorial/WhileLoop
*/
// These constants won't change:
const int sensorPin = A0; // sensor pin
const int ledPin = 9; // LED pin
const int indicatorLedPin = 13; // built-in LED pin
const int buttonPin = 2; // button pin
// These variables will change:
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
int sensorValue = 0; // the sensor value
void setup() {
// set the LED pins as outputs and the switch pin as input:
pinMode(indicatorLedPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
While – Conditional example
void loop() {
// while the button is pressed, take calibration readings:
while (digitalRead(buttonPin) == HIGH) {
calibrate(); // call calibration function
}
// signal the end of the calibration period
digitalWrite(indicatorLedPin, LOW);
Use the Arduino map function to
// read the sensor: scale values to the range you want
sensorValue = analogRead(sensorPin);
// apply the calibration to the sensor reading
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
// in case the sensor value is outside the range seen during calibration
sensorValue = constrain(sensorValue, 0, 255);
// fade the LED using the calibrated value:
analogWrite(ledPin, sensorValue); Returns a value between
} the bounds of min and max
While – Conditional example
void calibrate() {
// turn on the indicator LED to indicate that calibration is happening:
digitalWrite(indicatorLedPin, HIGH);
// read the sensor:
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax)
sensorMax = sensorValue;
// record the minimum sensor value
if (sensorValue < sensorMin)
sensorMin = sensorValue;
The next lecture will cover extending functions.
A Case Study: Radar Speed Traps
The speed of an approaching car, or one speeding away, can
be found from the change in frequency of microwaves
reflected from it.
The following relation is used to calculate v the velocity of
an approaching/receding car:
f f
v 6.685 x 10 8
f
r e
mph
r f e
Where,
fe : frequency of microwave beam emitted
fr : frequency of microwaves beam reflected
Suppose fe = 2 x 1010 sec-1
Determine the speed of the car if fr is 2.0000004 x 1010 sec-1
A Case Study: Radar Speed Traps
• Step 1: Analyze the Problem
– Understand the desired outputs
– Determine the required inputs
• Step 2: Develop a Solution
– Determine the algorithms to be used
– Use top-down approach to design
• Step 3: Code the Solution
• Step 4: Test and Correct the Program
Code the Solution – C++ example
Can you spot
any errors?
Correct the Program
f f
v 6.685 x 10 8
f
r e
mph
r f e
Recall operator precedence?
≠
Run the solution
Arduino challenge
Suppose you want to replicate the case study
with using the Arduino.
What sensor might you use? And how would
you code that up?
Common Programming Errors
• Missing { and } that signifies the start and end of a function body
• Misspelling the name of an object or function
• Missing a semicolon at end of statements
• Substituting letter O for zero and vice versa
• Failing to declare all variables
• Storing an incorrect data type into a variable
• Attempting to use a variable with no value
• Dividing integer values incorrectly
• Mixing data types in the same expression
In lab this week:
• Try the exercises
• Explore Arduino CC projects