## Week 05
miroslav.binas@tuke.sk / [**IoT1**](http://kpi.pages.kpi.fei.tuke.sk/iot1)
#### http://kpi.pages.kpi.fei.tuke.sk/iot1
#### https://mattermost.kpi.fei.tuke.sk/iot1
[![Hack Košice 2019](img/hack.kosice.png)](https://hackkosice.com/)
[![Namakaný deň 2019](img/namakany.den.2019.png)](https://www.namakanyden.sk/)
## Microcontroller Components
* A/D converter
* analog comparator
* Brown-out detect
* 3 timers
* Watch-dog timer
## Components Management
* possible to turn on/off selectively
* macros in `avr/power.h`
```cpp
power_adc_disable();
power_adc_enable();
```
## Low-Power Library
* support for all sleep modes of _ATmega328P_,
* sleep for _15 ms_, _30 ms_, _60 ms_, _120 ms_, _250 ms_, _500 ms_, _1 s_, _2 s_, _4 s_, _8 s_ with timers,
* turn off _A/D converter_,
* turn off _Brownout Detector_ module,
* in selected sleep modes it is possible tu turn off all _timers_, _USART0_, _TWI_, and _SPI_ module
### Low-Power Usage
* `LowPower` class with methods: `idle()`, `adcNoiseReduction()`, `powerDown()`, `powerSave()`, `powerStandby()`, `powerExtStandby()`
* example:
```cpp
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
```
## Reducing Clock Frequency
![ATmega328P Frequency vs Supply Current (5V)](https://cdn.sparkfun.com/assets/learn_tutorials/5/8/3/ATmega328P_Clock_Speed-large.png)
### Impact of Reducing Clock Frequency
* direct impact to all synchronized parts
* time functions such as `delay()` or `millis()`
* speed of I/O communication
* speed of A/D converter
### Clock Prescale Register
![`CLKPR` Register](https://www.peterbeard.co/postimages/arduino-powersave/clkpr-diagram.png)
### Clock Division Factor
* combination of bits `CLKPS0` to `CLKPS3`
![Clock Division Factor - Options](img/clock.division.factor-options.png)
### Steps to Change Frequency
1. turn off interrupts (with `noInterrupts()`)
2. set `CLKPCE` to _1_ and all other bits of `CLKPR` register to _0_
3. set `CLKPS` bits to value of selected _Clock Division Factor_
4. enable interrupts (with `interrupts()`)
## Managing Energy Consumption with Hardware
* _Arduino_ is prototyping board at first
* not ideal for low-power solutions
* contains several components, which has direct affect to energy consumption
### Arduino Components
* the core (microcontroller)
* powering part
* communication part
### The Microcontroller
![ATMega328P](https://qph.fs.quoracdn.net/main-qimg-8c1cffa1171557798e3d3b8906acf127.webp)
### Power Supply
* two external ports:
* _USB port_ - direct connection to board
* _DC jack_ - protected with voltage regulator (_LM7805_)
`$$ P_{wasted} = (V_{in} - V_{out}) * I $$`
### Communication Part
* _ATMega16U2_ - convertor between _USB_ and _serial link_
* for communication with connected devices
* for microcontroller programming
![Breadboard Arduino](img/breadboard.arduino.png)