NSWI170 Computer Systems
3rd practicals
Agenda
- Arduino LEDs review (constants, labels, timing)
- Working with buttons (problem with oscillation)
- Code quality: Reducing the code redundancy
- Communication with a computer for debugging
- New assignment: Arduino Buttons
The idea behind 2nd hw
The input parameters / configuration is:
// Program parameters
constexpr int animationDurationMs = 300;
constexpr int ledsPins = {led1_pin, led2_pin, led3_pin, led4_pin};
The rest is calculated:
// Leds count
constexpr int ledsCount = sizeof(ledsPins) / sizeof(ledsPins[0])
// Last LED
ledsPins[ledsCount - 1]
// Total animation duration
(ledsCount * 2 - 2) * animationDurationMs
The program should not break if we change or add new values.
The size should not be hard-coded.
Problems with delay() and while(millis() < ...)
Example scenario: Extend 2nd homework with playing twinkle twinkle little star on speaker
void setup() {
setupLedAnimation();
setupMusicPlayer();
}
void loop() {
updateLedAnimation();
updateMusicPlayer();
}
unsigned long animationDelayMs = 300;
unsigned long lastTimestamp = 0;
void setup() {
lastTimestamp = millis();
}
void loop() {
auto currentTimestamp = millis();
if (currentTimestamp >= lastTimestamp + animationDelayMs) {
// Do something
lastTimestamp = currentTimestamp;
}
}
Task: Bit encoder
Write a function that takes an integer and changes the LED states according to its lower 4 bits.
- Bitwise operators: & (AND), | (OR), ~ (negation)
- Bit shifts <<, >>
Create a clock that increments every second. Do not use delay().
Buttons
#include "funshield.h"
void setup() {
pinMode(button1_pin, INPUT);
}
void loop() {
bool isPressed = !digitalRead(button1_pin);
...
}
Task: Bit encoder
Increment if the button is pressed.
What does it mean to press the button?
What if you hold it?
Increment as soon as the button is pressed and then in regular intervals.
Instead of repeating, use:
- for loops
- functions
Do not repeat yourself
Repeated code is hard to maintain because you must fix all its copies. It is difficult to read.
Debugging
See the ASCII Table example for inspiration.
File > Examples > 04. Communication
Find out how many times per second the loop function is called. Then try to insert some computationally demanding code and recheck the loops per second.
New assignment
(Classes)
class Button {
private:
bool down;
int pin;
public:
bool isDown() {
return down;
}
Button(int _pin) {
pin = _pin;
}
};
Button button(10);
button.isDown()
NSWI170 - 3rd practicals
By Štěpán Stenchlák
NSWI170 - 3rd practicals
- 268