Arduino Programming Part2 PDF
Arduino Programming Part2 PDF
Part 2
EAS 199A
Lecture 6
Fall 2011
Overview
• Variable types
❖ int
❖ float
• Loops
❖ for loops
❖ while loops (another day)
void setup() {
start_time = millis();
Serial.begin(9600);
}
void loop() {
current_time = millis();
if ( (current_time - start_time) > wait_time ) {
Serial.println(“24 hours has passed”);
start_time = current_time;
}
}
Practical advice
❖ Use a float in formulas when fractional values are needed
❖ A float can be very large or small
❖ floating point math involves small rounding errors
a = 4;
b = 3;
c = a/b; // Value of 1 is stored in c
Convert to an integer:
a = int(x);
Practical Advice
Use explicit type conversion functions to convey your intent
Analog pin 3
10 kΩ
void loop () {
sensorVal = analogRead(sensorPin);
voltage = float(sensorVal)*input2volts;
Serial.print(“sensorVal, voltage = “);
Serial.print(sensorVal); Serial.print(“ “);
Serial.println(voltage);
}
Loops
Loops
Initial value of counter
i=0 only on first pass through the loop
Stopping test: Continue while this
condition is true
Decrement by one
for ( i=12; i>=0; i-- ) { // decrement by one
... code block goes here
}
float sensorAve; 10 kΩ
int sensorSum;
int nave=5;
Change nave
❖ Increase nave from 5 to 10, 50, 100, 500
❖ Why is the reading negative for large nave?
❖ How can you fix this by changing the variable type for sensorSum?
Add print statements inside the averaging loop
Serial.print(“\t Reading = “);
Serial.println(sensorVal);