0% found this document useful (0 votes)
10 views27 pages

B57as L03

This lecture covers various programming concepts including operators, time functions, and mathematical library functions, with a focus on assignment operations and coercion of data types. It also discusses increment and decrement operators, relational and logical operators, and the importance of timing in electronics projects. Additionally, a case study on acid rain is presented, requiring students to develop an Arduino sketch to calculate pH levels based on hydronium ion concentration.

Uploaded by

grokking Stuff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views27 pages

B57as L03

This lecture covers various programming concepts including operators, time functions, and mathematical library functions, with a focus on assignment operations and coercion of data types. It also discusses increment and decrement operators, relational and logical operators, and the importance of timing in electronics projects. Additionally, a case study on acid rain is presented, requiring students to develop an Arduino sketch to calculate pH levels based on hydronium ion concentration.

Uploaded by

grokking Stuff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 27

Computing for Engineers

B57AS
Lecture 03
This week:
• More on Operators
• Time functions
• Using mathematical library functions
• Symbolic constants
• A case study involving acid rain
• Common programming errors
Assignment Operations – Part 2
• Coercion: Forcing a data value to another data type

• Value of the expression on the right side of an assignment


statement will be coerced (converted) to the data type of the
variable on the left side during evaluation

double x = 2.3;
double y = 3.2;

• Variable on the left side may also be used on the right side of
an assignment statement
int sum = x + y; // output is 5
Assignment Operations – Part 2
Accumulation statement: Has the effect of accumulating, or
totaling

Syntax:
variable = variable + newValue;

Additional assignment operators provide short cuts:


+=, -=, *=, /=, %=
Example:
sum = sum + 10;
is equivalent to: sum += 10;
price *= rate +1;
is equivalent to:
price = price * (rate + 1);
Assignment Operators
Increment operator
• Increment operator ++: Unary operator for the special
case when a variable is increased by 1

• Prefix increment operator appears before the variable


– Example: ++i;

• Postfix increment operator appears after the variable


– Example: i++;
Decrement operator
• Decrement operator --: Unary operator for the special
case when a variable is decreased by 1

• Prefix decrement operator appears before the variable


– Example: --i;

• Postfix decrement operator appears after the variable


– Example: i--;
Increment/Decrement example
• Example: k = ++n; //prefix increment
is equivalent to:
n = n + 1; //increment n first
k = n; //assign n’s value to k

• Example: k = n--; //postfix decrement


is equivalent to
k = n; //assign n’s value to k
n = n - 1; //and then decrement n
Relational operators
• Relational expressions are evaluated to a numerical value of 1 or 0
only:
– If the value is 1, the expression is true
– If the value is 0, the expression is false
• char values are automatically coerced to int values for
comparison purposes
• Strings are compared on a character by character basis
– The string with the first lower character is considered smaller
Performing Logical Comparisons
• Logical operators evaluate the logical relationship between
two or more expressions
• Logical operators return true or false values depending on
the logical relationship

AND (&&): Condition is true only if both expressions are true

OR (||): Condition is true if either one or both of the


expressions is true

NOT (!): Changes an expression to its opposite state; true


becomes false, false becomes true
Logical Operators
Operator Precedence and Associativity
Practice! - evaluate
 (-6<0)&&(12>=10)
true && true
results in true

 (3.0 >= 2.0) || (3.0 >= 4.0)


true || false
results in true
 (3.0 >= 2.0) && (3.0 >= 4.0)
true && false
results in false
Logical AND Example
//declare variables to store pin number
int pressureSensor = 10; // pressure pin
int led = 7; // LED pin
void setup() {
//declare pin as an output
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
//read the input on analogue pin 12:
int pressureValue = analogRead(pressureSensor);
//as long as the value is in between 500 and 700 keep on looping
while(pressureValue > 500 && pressureValue < 700){
//turn the led on
digitalWrite(led, HIGH);
//check so that the value
pressureValue = analogRead(pressureSensor);
}
//turn the led off
digitalWrite(led,LOW);
}
Time functions
• Timing is important in electronics projects
• Electronics are not instantaneous, and most sensor
components require some time before they can be
accessed
• A typical one-wire humidity sensor requires 100 ms of time
between the command to acquire a reading and returning
the result
• You’ve already used a timer function delay() to get the
Arduino to patiently wait for a specified amount of time
• When an Arduino is powered on (or reset), two counters
begins counting: the number of microseconds that the
system has been running and the number of milliseconds.
Time functions
Time functions
unsigned long time;
unsigned long timeBefore;
unsigned long timeAfter;

void setup(){
Serial.begin(9600);
}

void loop() {

timeBefore = millis(); //Get the time before running a function


aLongFunction(); //Run a function that could take some time
timeAfter = millis(); //And now get the time after running the function

Serial.print(“Time: “);
time = micros();
//prints time since program started
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000); // in milliseconds
delayMicroseconds(500); // waits for 500 microseconds
}
Mathematical Functions
Math.h contains the trigonometry function's prototype.

double sin(double x); //returns sine of x radians


double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x

float deg = 30; // angle in degrees


float rad = deg * PI / 180; // convert to radians
Serial.println(rad); // print the radians
Serial.println(sin(rad)); // print the sine
Serial.println(cos(rad)); // print the cosine
Mathematical Functions

• Function calls can be nested


– Example: sqrt(sin(abs(theta)))
Using Floating-Point Numbers
• Floating point math is not exact, and values
returned can have small approximation error
• Always test if the values are within a range of
tolerance rather than exactly equal
Using Floating-Point Numbers
/*
* Floating-point example.
* This sketch initialized a float value to 1.1
* It repeatedly reduces the value by 0.1 until
* the value is 0
*/

float value = 1.1;

void setup()
{
Serial.begin(9600);
}
Using Floating-Point Numbers
void loop()
{
// reduce value by 0.1 each time through the loop
value = value - 0.1;

if( value == 0)
Serial.println("The value is exactly zero");
else if(almostEqual(value, 0)) // call custom function
{
Serial.print("The value ");
Serial.print(value,7); // print to 7 decimal places
Serial.println(" is almost equal to zero");
}
else
Serial.println(value);

delay(100);
}
Using Floating-Point Numbers

// returns true if the difference between a and b is small


// set value of DELTA to the maximum difference considered
// to be equal
boolean almostEqual(float a, float b)
{
// max difference to be almost equal
const float DELTA = .00001;
if (a == 0) return fabs(b) <= DELTA;
if (b == 0) return fabs(a) <= DELTA;

return fabs((a - b) / max(fabs(a), fabs(b))) <= DELTA ;


}
Symbolic Constants
• Symbolic constant: Constant value that is
declared with an identifier using the const
keyword
• A constant’s value may not be changed
Example:
const int MAXNUM = 100;

Good programming places statements in appropriate order


Exercise: Acid Rain
Coal is still a major power source. When it is
burned, sulphur and carbon dioxide is released
into the atmosphere.

When mixed with air and water, sulphuric acid is


formed, which transforms into separate hydronium
ions and sulphates.

Acid rain contains hydronium ions and can be


measured on a pH scale using this formula

pH = log10 (hydronium concentration)

Hydronium ions is measured in units of


moles/litre.
Exercise: Acid Rain
• Develop an Arduino sketch to sense and
calculate the pH level of a substance based on
user input of the concentration of hydronium
ions

pH level Acidity
7 Neutral
<7 Acidic
>7 Alkaline
Code the Solution

Something to code up during your lab session.


In lab this week:
• Work the tutorials

You might also like