Full text
Universidade do Minho Escola de Engenharia Sofia Arriscado Terramoto de Paiva Software/Hardware Co-Design for NB-IoT Low-Power Applications: Consumption and Performance Analysis novembro de 2020 UMinho | 2020 Sofia Paiva Software/Hardware Co-Design for NB-IoT Low-Power Applications: Consumption and Performance Analysis
Sofia Arriscado Terramoto de Paiva Software/Hardware Co-Design for NB-IoT Low-Power Applications: Consumption and Performance Analysis Dissertação de Mestrado Engenharia Eletrónica Industrial e Computadores Sistemas Embebidos e Computadores Trabalho efetuado sob a orientação do Professor Doutor Jorge Cabral Universidade do Minho Escola de Engenharia novembro de 2020
DIREITOS DE AUTOR E CONDIÇÕES DE UTILIZAÇÃO DO TRABALHO POR TERCEIROS Este é um trabalho académico que pode ser utilizado por terceiros desde que respeitadas as regras e boas práticas internacionalmente aceites, no que concerne aos direitos de autor e direitos conexos. Assim, o presente trabalho pode ser utilizado nos termos previstos na licença abaixo indicada. Caso o utilizador necessite de permissão para poder fazer um uso do trabalho em condições não previstas no licenciamento indicado, deverá contactar o autor, através do RepositóriUM da Universidade do Minho. Licença concedida aos utilizadores deste trabalho Atribuição-NãoComercial CC BY-NC https://creativecommons.org/licenses/by-nc/4.0/ ii
Acknowledgements I would like to thank Professor Jorge Cabral for convincing me into developing this project and challenging me in some other academic and professional adventures, while still guiding me throughout the development of this work. An extended thanks to both ESRG and DTx groups for taking me in with such sympathy. A special thanks to Rui Ferreira from DTx for assisting me with the hardware development and to Marcelo Borges from ESRG for helping me conclude one software module. I gratefully acknowledge the assistance of NOS IoT team during the first steps of implementation, whose support made possible to keep working during the confinement period and overcome initial difficulties. A huge thanks to my family, for always supporting me in my decisions. To my mom, who always showed me to accept yourself as you are and be grateful for what you have accomplished, never accepting less than you deserve. To my dad, a man of wise words, who always inspired me to think critically and whose sarcasm can not be matched. To my sister, whose patience and help does not go unnoticed. A big thanks to my long lasting friends, Bia and Cátia, for being there for me all these years. To the rest of the club for being amazing friends. To Diogo, Bruno and Rui for partnering with me these last few years, it was as insightful as it was fun. Thanks also to the named and unnamed people that crossed my path and contributed in some way to get me where I am today. This work has been supported by NORTE-06-3559-FSE-000018, integrated in the invitation NORTE-59- 2018-41, aiming the Hiring of Highly Qualified Human Resources, co-financed by the Regional Operational Programme of the North 2020, thematic area of Competitiveness and Employment, through the European Social Fund (ESF). iii
STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. iv
Resumo Software/Hardware Co-Design para Aplicações NB-IoT de Baixo Consumo Energético: Análise de Consumo e de Desempenho Com o número de ”coisas” conectadas a aumentar a um ritmo acelerante, o ecossistema da Internet das Coisas (IoT em inglês) expande e já cobre um vasto número de domínios de aplicação, fornecendo um amplo portefólio de soluções baseadas num sistema em contínua evolução, desde os sensores físicos ( end devices ) até à cloud . Quando se projeta end devices alimentados a bateria, estudos têm identificado vários desafios como a conectividade wireless , o tempo de vida da bateria, inteligência embebida, preocupações de segurança e privacidade e, claro, custos (desenvolvimento, manutenção, modem, entre outros). O uso de software/hardware co-design é posto à prova nesta dissertação para se conceber um end device de baixo consumo que atinja uma autonomia de 10 anos com uma única bateria. Para comunicação de baixo consumo, o NarrowBand Internet of Things (NB-IoT) é a mais recente tecnologia que utiliza a infraestrutura da rede móvel para trazer conectividade a dispositivos IoT. A sua extensa cobertura traz flexibilidade de implementação e suporta vários cenários que requerem dispositivos alimentados a bateria, como é o caso do metering de utilidade. Uma seleção cuidada do hardware e uma implementação pensada do software complementam-se para alcançar o consumo energético desejado. Uma análise ao consumo e desempenho do dispositivo é feita numa perspetiva comparativa dentro dos diferentes estágios de implementação. Existem seis destes estágios nesta dissertação: três relativos ao hardware e os outros três relativos ao software . No que diz respeito ao hardware , foi feita uma benchmark a partir de uma placa de desenvolvimento existente como primeiro estágio. Depois, duas placas customizadas foram desenvolvidas num processo iterativo. Quanto ao software, duas aplicações foram desenvolvidas e duas versões do código foram testadas. A primeira aplicação foi desenvolvida em baremetal e com freeRTOS, representando o primeiro e segundo estágio de implementação neste âmbito. O terceiro estágio foi o desenvolvimento da segunda aplicação, mais complexa, apenas em bare-metal . Com base nos resultados obtidos foi possível determinar alguns fatores chave para alcançar um dispositivo de baixo consumo. Adicionalmente, mais caminhos de investigação são propostos para que se consiga perceber melhor os perfis de consumo energético observados e melhorar o sistema no geral, tanto em termos de consumos como de longevidade. palavras-chave: baixo consumo, co-design , NB-IoT v
Abstract Software/Hardware Co-Design for NB-IoT Low-Power Applications: Consumption and Performance Analysis As the number of connected ”things” increases at a very fast pace, the Internet of Things (IoT) ecosystem expands and nowadays covers a vast number of application domains, providing a broad portfolio of solutions that are based on an evolving system, from the physical sensors (end devices) to the cloud. When designing battery-powered end devices, previous research has identified several challenges such as wireless connectivity, battery lifetime, embedded intelligence, security and privacy concerns, and costs (development, maintenance, modem, among others). The use of software/hardware co-design is put to the test throughout this dissertation to conceive a low-power end device that can achieve an autonomy of up to 10 years with a single battery charge. For low-power communications, NarrowBand Internet of Things (NB-IoT) is the novel communication technology that uses the existent cellular infrastructure to bring connectivity to IoT-focused devices. Its great coverage brings implementation flexibility and supports many battery-powered requirement scenarios, such as remote utility metering. Careful hardware selection and thoughtful software implementation complement each other to achieve the desired power consumption. A consumption and performance analysis is made in a comparative perspective within the different stages of implementation accomplished. There are six different implementation stages in this dissertation: three concerning the hardware and the other three concerning the software implementation. Regarding the hardware, a benchmark was taken from an existing development board, setting the first stage. After, two other custom boards were designed using an iterative process. As for the software, two similar applications were developed, and two coding approaches were tested. With the first stage application, both baremetal and freeRTOS versions were developed, marking implementation stages one and two in this scope. The third stage was the second, more complex application, which was only developed with a bare-metal approach. Based on the results obtained, it was possible to pinpoint some key factors in accomplishing a lowpower device. Additionally, further investigation paths are proposed to better understand the power consumption profiles observed and improve the overall system from a consumption and longevity perspectives. keywords: co-design, low-power, NB-IoT vi
Contents Resumo v Abstract vi 1 Introduction 1 1.1 Contextualization ................................... 1 1.2 Motivation ...................................... 2 1.3 Objectives ...................................... 3 1.4 Methodology ..................................... 4 1.5 DissertationStructure................................. 5 2 State of the Art 7 2.1 IoT and Wireless Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.2 LPWANTechnologies ................................. 8 2.2.1 NB-IoT.................................... 10 2.3 Security ....................................... 19 2.3.1 Cryptography................................. 19 2.3.2 Serialization ................................. 23 2.4 Low-PowerApplications................................ 24 2.5 Processing Unit Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.5.1 Arm®Cortex®-M0+.............................. 34 2.6 ExistentSolutions................................... 36 3 System Specification 38 3.1 Hardware....................................... 41 3.1.1 MCU..................................... 43 3.1.2 NB-IoTModem................................ 46 3.1.3 Sensors ................................... 47 3.1.4 PowerSupply ................................ 49 3.1.5 Capacitors.................................. 50 vii
3.1.6 Security ................................... 51 3.2 Software ....................................... 51 3.2.1 Low Level Portable Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 3.2.2 System ................................... 57 3.2.3 Modem ................................... 58 3.2.4 Transmission................................. 59 3.2.5 Sensors ................................... 60 3.2.6 Security ................................... 62 3.2.7 Bare-Metal versus RTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4 Implementation 68 4.1 Hardware....................................... 68 4.1.1 NOS Board Sensors Shield . . . . . . . . . . . . . . . . . . . . . . . . . . 69 4.1.2 CustomBoardv1 .............................. 70 4.1.3 CustomBoardv2 .............................. 72 4.2 Software ....................................... 76 4.2.1 Read&Send ................................. 81 4.2.2 Read&Store ................................. 95 4.2.3 Security ...................................104 5 Tests and Results 106 5.1 ExperimentalSetup..................................106 5.1.1 BenchPowerSupply.............................106 5.1.2 Bench Digital Multimeter . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 5.1.3 Oscilloscope.................................108 5.2 Current Consumption Measurements . . . . . . . . . . . . . . . . . . . . . . . . . 109 5.2.1 NOS Board versus Custom Board v1 . . . . . . . . . . . . . . . . . . . . . 110 5.2.2 Understanding the Current Consumption Profile for Read&Send Application . . 111 5.2.3 MCU Clock Frequency Selection . . . . . . . . . . . . . . . . . . . . . . . 112 5.2.4 Bare-Metal versus RTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.2.5 Impact of Low-Power Features . . . . . . . . . . . . . . . . . . . . . . . . 116 5.2.6 Verification of Low Power Modes Consumption . . . . . . . . . . . . . . . . 118 5.2.7 LSIversusLSE................................120 viii
Code Snippets 4.1 enterStopMode() ................................... 78 4.2 clockConfigAfterStop()................................. 79 4.3 Execution flow before infinite loop of bare-metal main function . . . . . . . . . . . . . 82 4.4 Infinite loop of bare-metal main function . . . . . . . . . . . . . . . . . . . . . . . . 85 4.5 Initialization process on FreeRTOS main function . . . . . . . . . . . . . . . . . . . . 86 4.6 Wait for received message in bare-metal version . . . . . . . . . . . . . . . . . . . . 88 4.7 Wait for received message in FreeRTOS version . . . . . . . . . . . . . . . . . . . . 88 4.8 openSocket() (bare-metal version) . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 4.9 openSocket() (FreeRTOS version) . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.10 initializeTransmission() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 4.11 initializeSensors()................................... 91 4.12 UART modem receive callback detail (FreeRTOS version) . . . . . . . . . . . . . . . . 93 4.13 UART modem receive callback detail (bare-metal version) . . . . . . . . . . . . . . . 93 4.14 writeSensor() (bare-metal version) . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.15 writeSensor() (FreeRTOS version) . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 4.16 Auxiliary structures for Read&Send application . . . . . . . . . . . . . . . . . . . . . 95 4.17 Sensors structure of Read&Send application . . . . . . . . . . . . . . . . . . . . . . 96 4.18 Sensors structure of Read&Store application . . . . . . . . . . . . . . . . . . . . . . 97 4.19 Accelerometer initialization of Read&Send application . . . . . . . . . . . . . . . . . 97 4.20 Accelerometer initialization of Read&Store application . . . . . . . . . . . . . . . . . 98 4.21 initSimpleSensorData() method of Read&Store application . . . . . . . . . . . . . . . 99 4.22 initMeanSensorData() method of Read&Store application . . . . . . . . . . . . . . . . 99 4.23 Datagram structures of Read&Store application . . . . . . . . . . . . . . . . . . . . 101 4.24 Modem configuration string msgpack serialization of Read&Send application . . . . . . 101 4.25 Modem configuration string msgpack serialization of Read&Store application . . . . . . 102 4.26 Initial datagram transmission of Read&Send application . . . . . . . . . . . . . . . . 103 4.27 Initial datagram transmission of Read&Store application . . . . . . . . . . . . . . . . 103 xv
List of Abbreviations 3D Three-Dimensional. 3DES Triple Data Encryption Standard. 3GPP Third Generation Partnership Project. ADC Analog to Digital Converter. AES Advanced Encryption Standard. API Application Programming Interface. ARP Address Resolution Protocol. BoM Bill of Materials. CE Coverage Enhancement. CH4Methane. CMSIS-CORE Cortex Microcontroller Software Interface Standard. CoAP Constrained Application Protocol. COTS Comercial Off-The-Shelf. CPS Cyber-Physical System. CPU Central Processing Unit. DAC Digital to Analog Converter. DES Data Encryption Standard. DL Downlink. DMM Digital Multimeter. DNS Domain Name System. DSP Digital Signal Processor. DUT device under test. EC-GSM-IoT Extended Coverage GSM IoT. ECC Elliptic Curve Cryptography. eDRX extended idle-mode discontinuous reception. xvi
EEMBC Embedded Microprocessor Benchmark Consortium. FDD Frequency Division Duplex. FRAM Ferroelectric RAM. GPIO General Purpose Input/Output. GSA Global mobile Suppliers Association. GSM Global System for Mobile Communications. GSMA GSM Association. GUI Graphical User Interface. HAL Hardware Abstraction Layer. HSI High-Speed Internal. HTTP HyperText Transfer Protocol. IQquiescent current. I2C Inter-Integrated Circuit. IC Integrated Circuit. IDE Integrated Development Environment. IMSI International Mobile Subscriber Identity. IoT Internet of Things. IP Internet Protocol. IP Intelectual Propriety. IR Infrared. ISA Instruction Set Architecture. ISR Interrupt Service Routine. JSON JavaScript Object Notation. LAN Local Area Network. LDO low-dropout. LL Low Level. LoRa Long Range. LPUART Low-Power UART. LPWAN Low Power Wide Area Network. xvii
LSE Low-Speed External. LSI Low-Speed Internal. LTE Long Term Evolution. LTE-M LTE for Machine-Type Communication. LwM2M LightweightM2M. MCU Microcontroller Unit. MQTT Message Queuing Telemetry Transport. msgpack MessagePack. MSI Multispeed Internal. NB-IoT NarrowBand Internet of Things. NFC Near Field Communication. NVM Non-Volatile Memory. OFDMA Orthogonal Frequency-Division Multiple Access. OS Operating System. PAN Personal Area Network. PCB Printed Circuit Board. PLL Phase Lock Loop. Protobuf Protocol Buffers. PSM Power Saving Mode. PULP Parallel Ultra-Low-Power. RAM Random Access Memory. RC Rivest Cipher. RFID Radio Frequency Identification. RO Read-Only. ROM Read-Only Memory. RSA Rivest-Shamir-Adleman. RSRP Reference Signal Received Power. RSRQ Reference Signal Received Quality. RSSI Received Signal Strength Indicator. RTC Real Time Clock. xviii
RTOS Real-Time Operating System. RW Read-Write. SC-FDMA Single-Carrier Frequency-Division Multiple Access. SHA Secure Hash Algorithm. SIM Subscriber Identification Module. SIP System-in-Package. SoC System on Chip. SPI Serial Peripheral Interface. SRAM Static RAM. TAU Tracking Area Update. TCP Transmission Control Protocol. UART Universal Asynchronous Receiver/Transmitter. UDP User Datagram Protocol. UEXT Universal EXTension. UL Uplink. ULPBench Ultra-Low-Power Benchmark. ULPMark-CP ULPMark-CoreProfile. UNB Ultra NarrowBand. VPS Virtual Private Server. WAN Wide Area Network. ZI Zero-Initialized. xix
Chapter 1: Introduction In this chapter the contextualization, motivation, and objectives of this dissertation are presented. The contextualization frames the work presented in the reality of IoT development and power consumption. Based on this mindset, the motivations for the elaboration of this work are presented, sustaining the author’s choice for this theme and highlighting its relevance to current paradigms. In order to achieve valid results, objectives are defined and described, so that the research can be structured and carried on until the last milestone, followed by a brief description of the methodology adopted to deliver each one of the stated objectives. This chapter concludes with the dissertation structure, which aims to guide the reader throughout the whole text. 1.1 Contextualization Nowadays Internet of Things (IoT) is becoming a well known concept and is even being associated with specific fields of actuation such as Industrial IoT (IIoT), Cellular IoT (CIoT), Internet of Medical Things (IoMT), among others. Each one of these applications is based on the concept of connected ”things”. From an embedded system’s perspective, these ”things” are just devices with communication capabilities, sometimes with actuation capabilities too. Nowadays, there is another concept that is arising from the scientific community, the Cyber-Physical System (CPS). The CPS concept builds over the IoT concept: there are end devices or motes (sensor/actuator nodes) at the bottom – end of the network, interfacing the real/physical world, – and a server or cloud at the top – cyber end of the stack. This cyber end has microservices which gather the information from the end devices and perform a large variety of tasks, such as storing it in a non-relational database, fuel machine learning algorithms so it can process the data, and feeding the relevant information to web and mobile apps. In between ends, some transmissions layers differ from application to application, depending on the communication technology chosen. In terms of applications, some allow the end device to be wired to a power line so that it can send information uninterruptedly, such as machine monitoring, and smart home applications. However, there are others that, due to its limited access or safety restrictions, require a battery-powered solution, such as remote utility metering, and agriculture monitoring. The devices conceived to be used in battery-powered applications of this kind require special attention 1
1.2. Motivation to power consumption. There are cases where a few days autonomy is acceptable, for example, fitness smart bands or other wearables, where it is expected from the user to have access to a power source quite frequently. In other cases, this is not possible, for example, in an utility metering situation on a remote location, it might not be feasible for the user to frequently go up to the device and switch the battery or recharge it. Even worse, if there is not just one device but tenths or hundreds of them, low autonomy would mean high maintenance costs. With the energy consumption in mind, a novel communication technology was developed by the Third Generation Partnership Project (3GPP): the NarrowBand Internet of Things (NB-IoT). Since the data communication link is where most of the energy is spent on an end device, the NB-IoT communication standard brings a reduced physical layer and the capability of using the mobile communication infrastructures (LTE) to diminish the power consumption of this process while reducing production and maintenance costs, and ensuring the security, scalability and link reliability of the Long Term Evolution (LTE) network. However, communications’ power consumption should not be the only concern when designing a lowpower device. All the hard work put into implementing a lower power communication technology can go to waste if the hardware used is not adequate or even if the coded software does not have power consumption concerns. This dissertation explores the symbiosis between hardware and software, allied with the novel communication technology, NB-IoT, to bring considerations about design references for low-power end devices and their application in modern CPS solutions. 1.2 Motivation In a world eager to get everything connected, miniaturization and low-power connectivity are some of the must-have characteristics of an end device. Facing the new technologies that are emerging either from hardware components perspective or communication technologies perspective, it is compelling to study how can different reference low-power designs influence the actual power consumption of an application. The primary motivation to explore low-power applications is due to the (LINK4S)ustainability project, from the Link4S consortium. The consortium Link4S is committed to work together in the generation of new scientific knowledge to design, develop, construct and test a novel generation of Smart Embedded Connected Devices and associated software platforms, aiming at the integration of networks of objects and social networks in the context of mobility and energy ecosystems. The (LINK4S)ustainability project comprises the implementation of 7 use cases concerning energy and mobility. The use case in which this dissertation focus is intrusion and risk assessment in capillary 2
Chapter 1. Introduction assets with IoT, which is related to the energy theme, more precisely with the distribution of natural gas. Intrusion and risk assessment in capillary natural gas assets is a costly and high maintenance activity that can not be performed with the regularity that it should for the safety of the gas supply chain. By remotely monitor and detect CH4emissions by leakage, detect unauthorized accesses, and monitor temperature and relative humidity, it is possible to improve natural gas supply safety and security levels. Given the remote places where the end devices are to be installed and the extreme conditions that they must endure, a battery-powered, ATEX certified device with as longer autonomy as possible is required. Supported by this real use case, this dissertation intends to introduce yet another possible application for the recently deployed NB-IoT. This technology promises a battery life of 10 years and, with careful hardware design and software implementation, it is of most interest to this dissertation to ascertain the feasibility of such commitment. 1.3 Objectives The goal is to develop an end device based on software/hardware co-design applicable to a real monitoring use case with low-power consumption, targeting 10-years battery autonomy by using the NB- IoT communication standard. In order to achieve this, there are a few clear objectives to pursuit: •Development of benchmark software This objective is done by exploring Comercial Off-The-Shelf (COTS) development board and programming it with a monitoring application software. By exploring different methods of coding (such as bare-metal and RTOS), this objective allows establishing a power-consumption thought benchmark. •Identification of the most power demanding modules Aligned with the first objective, a performance and power consumption analysis of such a benchmark in a COTS solution allows the identification of modules (being it hardware or software modules) that have a significant impact on power consumption. •Improvement of the overall system Based on the results of the previous objective, can the system be further improved? These improvements are supported by a better choice of hardware and more careful software implementation, resulting in a custom solution that meets the use case adopted. •Confirmation of suitability for the real use case presented The end device is desired to be deployed in a real-life scenario. Therefore, it is necessary to ensure 3
1.4. Methodology that the structural and functional optimizations do not compromise its usability in such scenarios. It includes testing connectivity, autonomy, fault-handling, and required certification. 1.4 Methodology Since there is a lot that can be done when it comes to reducing power consumption, it is essential to define a detailed methodology on how to approach this vast thematic. Since it is intended to develop a benchmark based on a COTS development board, the first step is choosing one that meets almost every requirement. Over this, software is developed so the NB-IoT functionality can be studied and also assess the RTOS suitability in a system like this. After identifying the several components that comprise a system like this, a custom solution could be assembled with COTS components. It is necessary to choose a suitable NB-IoT modem, a powerefficient Microcontroller Unit (MCU), efficient power management components, such as low-dropout (LDO) voltage regulators or buck-boost converters, adequate sensors with preference for digital communication interfaces, such as SPI or I2C, and high-efficiency support components, such as transistors or capacitors. On a complementary note, the choice of a digital communication interface for the sensors is due to the high energy cost that MCU’s ADCs have. This choice is the first step towards reducing the power consumption of the system, but a comparative study was not made. After the assembling of the hardware platform, the software is developed with consideration of the hardware chosen in order to take advantage of its possible power efficiency features. For example, MCUs usually have different power modes that can be used to save energy when they are waiting for a response/event. Even some sensors can have this type of mechanism to reduce their power consumption when they are not being used (measurement request). Besides these considerations, other factors influence power consumption, namely the processor’s clock frequency. Is executing fast sleep more better than execute slow sleep less in a periodic wake-up scenario? By executing faster, the power consumption of the processing involved is higher, but it allows entering sleep mode again faster, thus sleeping for longer. When executing slower, the power consumption is lower, but it does take more time to finish computations and enter sleep again; can this be significant? Another factor to consider is the classic battle bare-metal approach versus RTOS approach . From one side, the bare-metal approach gives more control over the hardware and the timings of the program, on the other side, the RTOS gives application flexibility and introduces a concept of pseudo-parallelism that can help improve overall timings performance. While the former can be slower and have more restrictions 4
Chapter 1. Introduction from an application point of view, the latter brings a lot more overhead and results in a bigger size code image. The memory footprint is also important for power consumption, the bigger the RAM/Flash memory usage, the higher the consumption. In order to get to the bottom of this discussion, the same software application was implemented using both approaches, one bare-metal and another with an RTOS, and tests to both were made. For the baremetal approach timings and power consumption were measured in different parts of the system. This way is possible to identify bottlenecks in performance and consumption. For the RTOS approach, similar timings and power consumption were measured in order to better compare it with the bare-metal one. That way, even knowing that the tasks’ execution is not precisely known, a better assessment of the impact the RTOS approach has can be made. After getting these results for both approaches, the processor clock was reduced and increased to verify which is the optimum clock frequency. With all these results there are two research paths to follow: try and optimize the code of the most promising approach; identify the most consuming modules and try and optimize them resorting to other hardware components. Ideally, both paths cross in a more advanced stage and bring together the most optimum solution possible. Finally, and because it is required for the resulting system to perform in a real-life scenario, it is crucial to perform the ultimate performance tests, by inducing expected and unexpected conditions into the environment so that the final application can be improved and certified for use. The ultimate step is an estimation of the expected autonomy of the functional end device, by averaging its consumptions in a day and matching with the battery capacity. 1.5 Dissertation Structure After this introductory chapter, a brief research on the state of the art for some of the topics involved in the implementation is presented, allowing not only to get the knowledge needed about the subjects but also understand where they stand in the application domain. Then, the system developed is specified, emphasizing both hardware components and software implementation. This includes not only the choices made initially, but also the improvements that were verified necessary. Following the design exposed, the implementation chapter exposes the hardware conceived in the different stages of development. For the software, code snippets are shown for the most important parts developed for each application. 5
2.2. LPWAN Technologies Note that, in these studies, technology is regarded as deployed when it has been installed in the operator’s commercial network, and it is intended to remain in use (a trial or pilot installation might be discontinued, so it does not enter the statistics). A network is considered to be commercially launched once it is available, at least on a limited basis, for the use of commercial customers. Also in this latest study, but related to IoT Ecosystem equipment, GSA states that has identified, among others: • 210 devices supporting either LTE-M or NB-IoT. – Of these, 142 devices support the Cat NB1 and other variants →Where 76 devices only support the version Cat NB1 of the NB-IoT technology • 29 commercially available chipsets supporting either NB-IoT or LTE-M. In figure 2.5 is shown the types of devices that support these technologies in percentage. The modules section takes the most substantial part, as it is generic and later integrated into more specific devices. A considerable amount of devices are asset trackers, showing the utility of this technology for mobility too. Figure 2.5: IoT devices types (from (GSA, 2019b)) In terms of global shipment of NB-IoT devices, data from Berg Insight (2019) show that it reached 53 million units shipped per year in 2018 and is expected to almost triple in 2019, as it is depicted in figure 2.6. It is also expected that the NB-IoT devices’ shipment increases rapidly on the European and North American markets in the next 18 months. 12
Chapter 2. State of the Art Figure 2.6: Global NB-IoT device shipments (adapted from (I-Scoop, 2019)) Technical Overview NB-IoT is optimized for IoT communications and therefore designed to coexist with the existent 2G/3G/ 4G cellular networks (Grant, 2016). There is already confirmation of coexistence in the 5G cellular network (GSMA, 2018). The main goals are to achieve a high system capacity and a low minimum system bandwidth. NB-IoT offers three operation modes (see figure 2.8): • in-band operation mode - using resource blocks within a standard LTE carrier • guard-band operation mode - using blocks within an LTE carrier’s guard-band • standalone - using any available spectrum, for example, GSM frequency bands Figure 2.7 depicts the LTE bandwidth, stating the difference between the effective LTE transmission bandwidth and the guard-band of the carrier. Each rectangle represents a resource block and is a mere illustration. Figure 2.7: LTE bandwidth (adapted from (Lee and Lee, 2017)) 13
2.2. LPWAN Technologies (a) (b) (c) Figure 2.8: NB-IoT operation modes: a) In-band mode b) Guard-band mode c) Standalone mode (adapted from (Kabalci and Ali, 2019)) These three operation modes give NB-IoT applications flexibility according to available spectrum and use cases. In in-band mode, one or more LTE resource blocks are reserved for NB-IoT (figure 2.8 a)). However, its signals must not be transmitted in time-frequency resources reserved for LTE, having a reduced number of symbols and subcarriers in a subframe to allow for the legacy control channel and the common reference signal (Ratasuk et al., 2017). The shared use of resource blocks allows more efficiency in the spectrum use (Ratasuk et al., 2016), but this can be undesirable as it diverts some of the LTE capacity (Durand et al., 2019). In guard-band mode, NB-IoT uses new resources blocks within the guard bandwidth of the LTE carrier (as shown in figure 2.8 b)). This mode presents more performance advantages than the previous, because it has available all symbols in a subframe (Ratasuk et al., 2017). Lastly, in standalone mode, NB-IoT can be used as a replacement of one or more GSM carriers (figure 2.8 c)), this is useful where LTE coverage is scarce. The mode used is determined by the service provider based on the cell site and base station that supports the device. For the Downlink (DL) transmission, it uses Orthogonal Frequency-Division Multiple Access (OFDMA) technology with 15 kHz subcarrier spacing. While for the Uplink (UL) transmission, it uses Single-Carrier Frequency-Division Multiple Access (SC-FDMA) with 15 kHz spacing for single-tone transmission and 3.75 kHz spacing for multi-tone transmission. NB-IoT technology adopts FDD technology with half-duplex transmission to separate DL and UL transmissions (Huang et al., 2019) (see figure 2.9). 14
Chapter 2. State of the Art Figure 2.9: Half-Duplex FDD transmissions (adapted from (IS-Wireless, 2013)) Multiple NB-IoT carriers can be defined for both DL and UL transmissions, facilitating efficient system scalability with an increase in the number of IoT devices (Grant, 2016). Initially, it was stated that the NB-IoT was designed to carry 100k-200k devices per 200 kHz carrier on a cell (Vodafone, 2017). Later simulations rounded this number to at least 72k supported devices within a cell site sector (Ratasuk et al., 2016). This number eventually dropped to 50k – 55k devices per cell with further system-level simulations (Durand et al., 2019; Sinha et al., 2017). In El Soussi et al. (2018), with a network-level simulation limited to a maximum of 600 devices, it was verified a maximum of 400 – 500 successful devices’ connections simultaneously depending on devices’ location. However, due to wide cellular coverage, great interest from service providers, and easy integration of NB-IoT into existent cellular infrastructures, scalability is not foreseen to be an issue. Since NB-IoT is a 3GPP standard closely related to LTE, it inherits all of the security techniques associated with it, by using a secret key built into the NB-IoT SIM (Vodafone, 2017). In Nair et al. (2019) a summary of these security features is presented. Although it is all supported by the NB-IoT technology, the security implementations are non-trivial (Nair et al., 2019) and can compromise the overall power consumption of the device. However, security can not be left out of an IoT application, and additional ”over the top” layers of security can be applied to the device, communications and application to increase the level of protection (Vodafone, 2017). NB-IoT reuses LTE functionality with some simplifications and optimizations, so there are three procedures for application data transmission available: • Legacy LTE service requests • Control plan optimization • User plan optimization 15
2.2. LPWAN Technologies The first is native of the LTE technology. The former two procedures were specifically developed for NB-IoT use cases, because, for small data transmissions, it is possible to reduce the required signaling. In Andres-Maldonado et al. (2017), it is proven the energy efficiency brought by these procedures, compared to the conventional LTE one, resulting in a battery lifetime extension of 8 years in certain conditions. In fact, these optimized procedures are part of one of the features that allows a longer battery lifetime in NB-IoT devices. Another feature is the Power Saving Mode (PSM), which is a sleep mode that puts the device into a very low-energy consumption state while sending occasional Tracking Area Update (TAU) messages to keep it registered at the network so that there is no need for re-registration upon wake-up (Deutsche Telekom AG, 2017). Alongside this feature, there is the Long Periodic TAU, which enables the extension of the messages’ periodicity up to several weeks, allowing the device to stay in PSM for even longer time. Another important feature that contributes to the device’s power-saving is the extended idle-mode discontinuous reception (eDRX). It offers a more extended low-power paging mode that allows receiving Downlink data from the server, while no Uplink data is being sent by the device (Deutsche Telekom AG, 2017). Besides the higher battery lifetime, NB-IoT also promises better indoor coverage, being this achieved by a higher power density, since its transmissions are concentrated in a narrower carrier bandwidth of 180 kHz. Another feature that helps to justify this benefit is the use of Coverage Enhancement (CE) in transmissions. CE allows repeating a message’s transmission, if needed, in poor coverage conditions. There are three CE levels according to coverage condition (0, 1 and 2), each being suited for different application conditions (outdoor, indoor, deep indoor), by changing the maximum number of repetitions (Deutsche Telekom AG, 2017). In Deutsche Telekom AG (2019b), this characteristic was demonstrated by using a setup with multiple NB-IoT devices in different coverage conditions on a building, transmitting User Datagram Protocol (UDP) packets and receiving them back, while analyzing the signal strength and interference levels. This study proved a 100% network attach rate for ground floor/higher floors and 95% for basements. When attached, the data transmission was successful in 99.75% of the transmissions. At last, the low-cost module is achieved due to one of the features that allows the reduction of power consumption: the removal of unnecessary LTE features. These characteristics were further analyzed in Ratasuk et al. (2016), right before it was even deployed. The conclusion was that the targets could be achieved in all deployment scenarios. Other studies involved a performance analysis on battery consumption for DL transmission (Oh et al., 2017); a real-world indoor application performance analysis (Wan et al., 2019); a performance analysis in terms of throughput and power consumption of NB-IoT in heterogeneous network environment (Malik et al., 2019); a performance 16
Chapter 2. State of the Art analysis on LTE interference and throughput in different operations modes (Ratasuk et al., 2017). All of these studies, in their application area, supported the specifications presented by the 3GPP for the NB-IoT technology, some even presented the combination of different methods to achieve even higher performance and minimal power consumption ((Malik et al., 2019; Oh et al., 2017)). When it comes to security, in Coman et al. (2019), the vulnerability of infiltrating the NB-IoT network was explored. Using a cellphone with a NB-IoT SIM, the authors were able to connect to a private NB- IoT network and by granting access to a computer through the connection established by the phone, the authors were able to identify all IP NB-IoT devices and could then proceed with classical IP attacking techniques such as port scanning, and Address Resolution Protocol (ARP) and Domain Name System (DNS) spoofing. In Cao et al. (2019), a fast mutual authentication and data transfer scheme was proposed in order to reduce communication and storage overhead. By taking advantage of the certificateless aggregate signcryption technique, the authors assure security in data transmission, and identity privacy protection and nonrepudiation. In Liu et al. (2019), an end-to-end security authentication protocol based on physical unclonable function and state secret algorithm SM3 was proposed in order to improve high security of power network data transmission. This is was accomplished by introducing the domestic cryptographic algorithm, extending the existing key derivation structure of LTE, and combining the physical unclonable function to ensure the generation of encryption keys between NB-IoT terminals and power grid business platforms. Application Considerations When conceiving an application with a NB-IoT device, there are three factors to be kept in mind when it comes to its performance: battery lifetime, traffic profile and coverage condition (Deutsche Telekom AG, 2017). These factors are interdependent, and balancing them dictates the overall performance of the device. According to the application requirements, trade-offs are needed for these metrics. For example, for a poor coverage condition (e.g., basement) and a high rate traffic profile is unfeasible to achieve a 10-year battery life (Deutsche Telekom AG, 2017). Most of the applications already implemented using NB-IoT technology make use of the ”plug and play” feature that its modules bring, therefore explicit concern on how it was configured was not given. In Duangsuwan et al. (2018), an air pollution detection sensor was reported, that joins four different gas sensors with two microcontrollers and a non-specified NB-IoT module, having a website as cloud support, where data can be viewed remotely. In this case, there are only concerns about reducing the cost of the system, taking advantage of the capabilities of NB-IoT technology. 17
2.2. LPWAN Technologies In Praveen and Harini (2019), a smart parking system was reported, that can give real-time parking information to the user through a smartphone’s app. The NB-IoT module is used to transmit parking lot sensor’s information to the central server, which then updates the information accessible by the user. In Yang et al. (2019), a buoy for ocean acoustic tomography with low power consumption, high precision acquisition, mass storage, and fast data transmission requirements was discussed. As it is a critical system, it was combined NB-IoT and ZigBee for the networking, allowing buoys to establish a connection between each other (with ZigBee) and, at the same time, establishing a connection with the host (with NB-IoT) if there is a cellular network available. In Wang et al. (2019), a novel smoke sense system was designed using a Quectel NB-IoT module. Some of the most interesting features presented are the use of the three states available (link, idle (eDRX), and sleep(PSM)) for low power consumption, the possibility of selecting the reporting cycle of the sensor remotely, and the 5-year battery life expected, all possible due to the use of a NB-IoT module. In Xiong et al. (2019), a system for reporting power failure events was presented. Since it has to report a power outage event with supply from a supercapacitor in about 60 seconds, it makes use of NB-IoT technology for fast and reliable transmission as well as its low power consumption operation. In Manatarinat et al. (2019), an elderly healthcare system that uses NB-IoT technology to transmit information of a possible fall was presented. This system explores the extents of the capabilities of the NB-IoT in terms of real-time response, since it is even proposed a direct connection with hospital centers for faster actuation upon a fall event of an elder. The preferred transmission protocol in these researches is the UDP, but NB-IoT technology also supports Transmission Control Protocol (TCP) and non-IP protocols. However, according to a technical report from Deutsche Telekom, UDP is the recommended protocol for NB-IoT (Deutsche Telekom AG, 2019a). UDP is the preferred choice because of its lightweight packet when compared to full TCP/IP packets, but it can not guarantee the message delivery. In Nair et al. (2019) it is suggested the use of Constrained Application Protocol (CoAP) standard to better handle real-time application limitations. According to (T-Mobile, 2019), CoAP is the leading UDP- based protocol in terms of popularity, being better suited for resource-constrained IoT applications and devices, where the payloads are very small. In Stusek et al. (2019) it is pointed out the minimum extra overhead of this protocol when compared to UDP alone, and its extra functionalities such as flow control and fragmentation handling layers. In fact, some Quectel modules already implement protocols such as Message Queuing Telemetry Transport (MQTT), CoAP and LightweightM2M (LwM2M), in addition to UDP and TCP (Li et al., 2018). 18
Chapter 2. State of the Art As seen, the practicality, reliability, and low cost of the NB-IoT technology are the key motivators for its use, alongside with low power consumption. However, in some works, the overall system is not designed with minimum energy consumption concerns, wasting one of the most promising features introduced in LPWAN technologies. For that reason, further analysis of low-power applications is going to be described in this chapter. 2.3 Security The goals of security are (Charbathia and Sharma, 2014): • Authentication – proof of identity • Confidentiality – only the intended receiver can read the message • Integrity – certificate that the message has been received unaltered • Non-repudiation – there is no denial of having sent the message from the sender nor of having received the message from the receiver On an IoT network, one of the most concerning security features is the data security. Since a network of this nature is composed by several different end devices, which gather and send information through the internet, there is always a risk of exposure and consequence malicious attacks. Considering this, two techniques that can be applied in order to increase the communications’ security are going to be discussed with further depth. 2.3.1 Cryptography Cryptography is the most common technique used to ensure data security, it not only protects the data from alterations and theft (integrity and confidentiality), but also provides user authentication (Charbathia and Sharma, 2014). Nowadays, there are several recognized cryptographic algorithms to use, as illustrated in figure 2.10, but one can even create or modify its own algorithm. Overall, cryptographic algorithms can be divided into two main categories: key-based and keyless ciphers. Keyless ciphers like the Caesar Cipher are generally less secure than key-based systems, because once someone knows the encryption algorithm, it is easy do decrypt every message which used such algorithm (Faheem et al., 2017). 19
2.3. Security Cryptographic hash functions such as the Secure Hash Algorithm (SHA) family, are not considered an encryption mechanism as it cannot be decrypted back, but can provide additional integrity to the message sent, by providing an almost-unique signature for a given text. The key-based algorithms can be further categorized into asymmetric and symmetric key-based, depending on the type of security keys utilized for the encryption or decryption process. With asymmetric key encryption, different keys are employed for the encryption and decryption, being the Rivest-Shamir- Adleman (RSA) algorithm the most known of this kind. For symmetric key encryption, the same key is used in both encryption and decryption and the cipher can be applied by blocks – encrypting blocks of the message at a time – or streaming – each character is encrypted individually (Faheem et al., 2017). In figure 2.10 are presented some symmetric key block ciphers examples, such as Data Encryption Standard (DES), Triple Data Encryption Standard (3DES), Blowfish and Advanced Encryption Standard (AES). As for symmetric key stream ciphers is presented the RC6 of the Rivest Cipher (RC) family as an example. Figure 2.10: Cryptographic encryption algorithms overview (adapted from (Faheem et al., 2017)) However, in Hameed and Alomary (2019) is stated that neither of these algorithms is suitable to work with IoT based on the power consumption they have while operating. Due to this reality, there is many research work about lightweight implementations of cryptographic algorithms, a fair share using hardware accelerators, some presented in Hameed and Alomary (2019). The problem with designing custom optimized security/encryption algorithms is that it implies a custom design for the cloud service as well. When it is intended to simply integrate the end device with an existing cloud service, this process may not be that simple, and the use of known standards might be advisable when adding security to the data communication. Because the cloud service planned to be used with this dissertation project plans to implement RSA 20
Chapter 2. State of the Art and AES algorithms for providing authentication, confidentiality and integrity of the messages, these two algorithms are going to be further explained. Rivest-Shamir-Adleman Algorithm RSA implements a public-key cryptosystem as well as digital signatures. For the purpose of this dissertation, only the public-key cryptosystem is going to be further explored. As an asymmetric key algorithm, it uses a public key, which can be given to every stakeholder that is intended to send the messages, and a private key, which only the respectful receiver has (Milanov, 2009). The encryption algorithm is given by equation (2.1) (Goshwe, 2013). C=Mod(Me, n)(2.1) where Crepresents the cipher-text, Mis the plaintext wanted to encrypt, e, the public exponent, and n, the modulus, constitute the public key, and Mod(a, b)is a function that calculates the remainder of the division a/b. The decryption algorithm is given by equation (2.2). M=Mod(Cd, n)(2.2) Similar to equation (2.1), where dis the private exponent, and nis the same modulus, constituting the private key. The keys are calculated based on two prime numbers pand q. From these numbers it is calculated the modulus, nas represented in equation (2.3). n=p∗q(2.3) The public exponent can be then selected from equation (2.4), having to be relatively prime to the product. (p−1)(q−1) (2.4) Lastly, the private exponent, dis an integer resulting from the quotient in equation (2.5). (e∗d−1) (p−1)(q−1) (2.5) 21
2.4. Low-Power Applications event-driven system. Besides the choice of a low-power sensor (piezoelectric MEMS type), the authors also applied the technique of using standby mode whenever possible, short message communication, and low operating frequency (by using only a 1 kHz RC oscillator). In Hayashikoshi et al. (2017), two low-power techniques are presented. The first consists of task scheduling technology that counteracts the usual task scheduling of performing tasks as soon as possible when they are ready. It is then proposed two energy-efficient algorithms: one that allows execution timing management and another for dynamic active-core selection (in case it is not a single core device). Both are based on waiting for more tasks to be ready, and then executing them consecutively, respecting each deadline constraints. The second technique explores autonomous standby mode transition technology. The algorithm dynamically weights the hardware constraints (energy breakeven time (EBT) (Xu et al., 2008)) and the software constraints (waiting time depending on the application) and chooses when to enter in standby and which standby mode to use. When applied to an intruder detection monitor system, these techniques reported a decrease of 91% of power consumption. NB-IoT Special Case Aside from all the techniques seen, NB-IoT technology itself offers a low-power communication protocol to be used in conjunction with all the others aforementioned. This low-power feature is mainly achieved by the mechanisms introduced in 3GPP’s Release 13: PSM and eDRX, previously mentioned. The shortening of communications as a low-power technique was already referred and is motivated by its high-energy consumption. Figure 2.13 exemplifies the power consumption in the three possible states of an NB-IoT module: active (and consequently transmitting), idle (eDRX), and sleep (PSM). Figure 2.13: Power consumption’s illustration of NB-IoT power saving features (adapted from (Wu et al., 2018)) 28
Chapter 2. State of the Art At the module’s power-up, an attach procedure is needed so that it can be registered in the network. This communication process takes its time and energy (even if by a small amount), thus having to reattach every time the module wakes up from sleep mode would have a significant impact on a battery lifetime (GSMA, 2017b). In order to avoid this reattachment, a negotiation with the network takes place. This negotiation allows establishing a period in which the module can power down without being forgotten by the network. This way, as long as the module wakes up and sends data within the arranged time, a reattach procedure is not required (GSMA, 2017b). In figure 2.13, the data transfer does not necessarily mean there is useful data to transmit. It can be just the Tracking Area Update (TAU) that keeps the module registered with the network. After this transfer, the module may or may not enter in an idle state, that can use the eDRX time. In this state, the module is reachable by the network for short periods of time, if there is a Downlink (DL) transmission pendent. However, this is not the most power-saving method. To achieve higher saving rates, the use of PSM is necessary. In this mode, the device is in such a deep sleep state that it is not reachable by the network, meaning it is not possible to receive any DL transmissions. There are two possible interruptions of this mode: timed and internally triggered. The former is related to the period agreed with the network, which forces the device to establish a connection in order to maintain its registration (TAU). The latter happens when an anomaly is detected and needs to be communicated, so it is necessary to perform a UL transmission, and the PSM is interrupted. The utilization of both mechanisms represents a trade-off between power saving and DL communication latency. In Sultania et al. (2019), an energy consumption analysis for different PSM timers and eDRX cycles is performed. Three different scenarios of operation are considered: • Idle →Connected →Idle • Idle →PSM →Connected →Idle • Idle →PSM →Idle For each scenario the probability of happening, its execution time, and correspondent energy consumption was determined in order to calculate the total average energy consumption. Based on the simulation, it was concluded that as UL data interval increases, the average energy consumption decreases. This decrease is all the more significant, the more prolonged the PSM’s period. This study emphasizes the importance of configuring these parameters accordingly with the application characteristics. For UL-only scenarios is recommended higher PSM periods for maximum power-saving at the expense of having higher 29
2.4. Low-Power Applications DL latency. For latency-sensitive DL data applications, the use of eDRX is advisable, knowingly that it will have higher consumptions. On experimental evaluations of the power consumption of an NB-IoT device, Baltaci et al. (2019); Duhovnikov et al. (2019); Yeoh et al. (2018) demonstrated the importance of these techniques on enhancing the battery lifetime. In Yeoh et al. (2018), two Comercial Off-The-Shelf (COTS) NB-IoT modules were analyzed in terms of power consumption, with a PSM period of 54 min and IP packet transmission every 2 hours. With this data rate, it was concluded that a 1000 mAh battery would only last for 409 days. However, if the transmission only happened once per day, the same battery could last up to 12.6 years. Another consideration is the use of an IP packet. As mentioned before, the shorter the message, the shorter the communication, the lesser the energy consumption. An IP packet has at least 28 bytes of header, which can be unnecessary if a custom packet was made (as seen in Itoh (2016)). In Duhovnikov et al. (2019) and Baltaci et al. (2019), the applicability of NB-IoT technology for aircraft applications was studied. The main concern in Duhovnikov et al. (2019) is the power consumption of the module. Experimentally, the communication was tested in three different networks (two commercial and one private (local)) with the same message rate: 1 message every 30 seconds for 30 minutes. The conclusion was that commercial networks have higher energy demand and do not allow the module to enter in PSM in comparison with a private network. In these conditions, the expected battery lifetime was around 10 days, explained by the periodicity of the messages and the consumption of the peripherals. Theoretically, it was proven that by extending the transmission periodicity and optimizing the peripherals (enter sleep mode when the module is in PSM), it is possible to achieve almost 11 years of expected battery lifetime in a private network. In Baltaci et al. (2019) a further experimental study on the feasibility of implementing NB-IoT in aircraft was developed. It was evaluated its performance not only on power consumption but also on latency, transmission reliability, and data rate. From both scenarios explored – inside the cabin or outside the cabin – the NB-IoT technology only proved suitable for applications inside the cabin, with low rate communications. In conclusion, the 10-year battery lifetime expectancy is an essential motivator for considering NB-IoT in non-mission-critical applications of an aircraft. Most of these studies reflected only on the NB-IoT modem’s consumption, and the one that considered the whole device used a commercially available shield for Arduino. For this dissertation is proposed to explore further optimizations for a custom device and consequent power consumption improvement, so further emphasis is going to be given to the processing unit architecture and existent solutions available for benchmarking. 30
Chapter 2. State of the Art 2.5 Processing Unit Architecture Knowing the processing unit architecture of a microcontroller can help with the development of a lowpower application, as it allows using the resources available in a more efficient way. A microcontroller can have many different components, but the essentials are depicted in figure 2.14. The CPU is the core of the MCU, and it is connected to the remaining components by buses. Typically there is a different bus infrastructure to interact with memory-related components and with the peripherals. There are three possible types of memories in an MCU: flash memory, SRAM, and a boot ROM. As for the peripherals there can be many, between timers, Universal Asynchronous Receiver/Transmitter (UART), General Purpose Input/Output (GPIO), Inter-Integrated Circuit (I2C) and other communication protocols interfaces, Real Time Clock (RTC), Digital to Analog Converter (DAC), and Analog to Digital Converter (ADC). The last three are analog/mixed-signal peripherals, as for the rest are digital peripherals. Usually, most of these peripherals are connected to I/O pads, which are their physical interface with the world. The system analog components include the crystal oscillators, Phase Lock Loop (PLL), and voltage regulators. Figure 2.14: Simple MCU structure (adapted from (Yiu, 2015a)) In order to obtain the most power efficiency, it is advisable to choose the best suitable MCU for the application. This choice not only reflects on the peripherals needed but also on the processor used. There are several processors available on the market for microcontrollers nowadays, and one set of the most expressive is the Arm®Cortex®-M family of microprocessors, claiming 70% of market share in 32-bit MCU in 2014 (York, 2015). In an overall perspective – and more recent – Arm®processors detain 25% of market share in the embedded area specific to microcontrollers and SIM cards, and a stunning 90% market share on controllers in IoT devices (Thornton, 2019). Other processors commonly used in microcontrollers are 8-bit AVR Core (Microchip, 1996), 16-bit PIC24 (Microchip, 2006), 16-bit RL78 (Renesas, 2014) and 16-bit 31
2.5. Processing Unit Architecture MSP430 (Texas Instruments Incorporated, 1994). As it was mentioned before, one way to evaluate a microcontroller’s power efficiency is by using an Ultra-Low-Power Benchmark instead of just relying on values from the datasheets. Some of the processors mentioned above were already submitted to the ULPBench workgroup’s ULPMark-CoreProfile (ULPMark- CP) benchmark, and a summary of the results can be consulted in tables 2.2, 2.3, and 2.4. The ULPMark-CP focus on the MCU’s core, analyzing the energy cost in sleep mode, and the transition to and from the active mode. To accomplish this are needed three parts: • A workload set (in C language) portable across 8-, 16- and 32-bit microcontrollers. • A reference energy measurement hardware denominated as Energy Monitor. • A Windows-based GUI to access the Energy Monitor hardware and control the test process, and to display and compute the results. The workload set runs once every second. When all computations finish, the microcontroller enters into sleep mode, in order to mimic an IoT node application where it must save as much power as possible. The score is calculated by dividing 1000 by the median of 5 runs of the benchmark for 10 seconds. In each run is calculated the average of the energy measured per second. The bigger the result, the lower the consumption (EEMBC, 2014). Table 2.2: ULPMark-CP summary results 1 MCU APOLLO512-KBR ADuCM302x ATXMEGA32E5 PIC24FJ128GA202 Vendor Ambiq Micro Analog Devices Microchip Technology Microchip Technology Core Cortex®-M4 Cortex®-M3 8-bit AVR PIC24 ULPMark-CP (3V) 377.5 245.5 80 68.76 ULPMark-CP (Other) - - - - Table 2.3: ULPMark-CP summary results 2 MCU SAML21J18A-UES STM32L011 STM32L053R6 STM32L433 Vendor Microchip Technology STMicroelectronics STMicroelectronics STMicroelectronics Core Cortex®-M0+ Cortex®-M0+ Cortex®-M0+ Cortex®-M4 ULPMark-CP (3V) 185.8 138 120 253.2 ULPMark-CP (Other) - 244 (1.8 V) 207 (1.8 V) - 32
Chapter 2. State of the Art Table 2.4: ULPMark-CP summary results 3 MCU STM32L452 CC2650F128RGZ MSP430FR6972 MSP432P401R Vendor STMicroelectronics Texas Instruments Texas Instruments Texas Instruments Core Cortex®-M4 Cortex®-M3 MSP430 Cortex®-M4 ULPMark-CP (3V) 176 143.6 123.8 192.3 ULPMark-CP (Other) 335 (1.8 V) - - - By observing the results of the tables above, it is possible to conclude that even with MCUs with the same processor cores, the scores can have significant variations. However, it is not advisable to trust blindly in these results, due to different conditions of execution, starting in code compilation and ending in clock settings. Another intriguing conclusion from this data is the fact that the majority of the cores tested are from the Cortex®-M family, highlighting its dominance in low-power microcontrollers. Although it has not yet an evaluation with this benchmark, there is an alternative to all these propriety processors-based MCUs: the use of MCUs with an open Instruction Set Architecture (ISA). When using an open ISA, one can design a custom processor suited to the project needs and with no licensing attached. In this domain emerge two notable names: OpenRISC (OpenRISC Community, 2019) and RISC-V (RISC-V Foundation, 2020). Both rely upon extensive community support, but the latter is the one that is gaining more interest not only in the academic environment but also in big companies and industry, resulting in much more broader support than the former. RISC-V is a free and open Instruction Set Architecture born at the University of California, Berkley, enabling processor innovation through open standard collaboration. The RISC-V ISA does not restrict the implementation of the processor, leaving its organization and structure flexible for the designers to customize it according to the needs (Ishimaru et al., 2018). Additionally, there are already many implementations of RISC-V based cores, ISA extensions, and even System on Chip (SoC) and evaluation boards available. Besides the academic development of cores and extensions, there are also published works targeting RISC-V based processors for real applications, some even under the subject of IoT. The most relevant work for the context of this dissertation is presented in Eggimann et al. (2019). Here a heterogeneous quad-core Parallel Ultra-Low-Power (PULP) processor based on RISC-V is presented as part of a fully programmable ultra-low-power embedded platform. This platform hosts ”electronic skin” arrays of tactile sensors, ECG/EMG sensors, inertial sensors, and a Bluetooth Low Energy module, for an always-on wearable application. The relevance of this work is due to the comparison methods adopted since a test board 33
2.5. Processing Unit Architecture was developed and tested with custom code for various scenarios and even on other MCU. Ultimately, the tests opposed single-core vs. multi-core on the developed board and Arm®Cortex®-M4F vs. RV32ICM. The former proved results favoring the multi-core parallelized operation, even though it consumed more power, by executing faster, the total energy consumed was about 1.4 times less than the single-core operation. The latter took power consumption and execution time of the Cortex®-M4F as the baseline for comparing with the power consumption and execution time at different clock frequencies of the RV32ICMs used. The results are conclusive, at 1/4 of the frequency for the Cortex®-M4F, the RV32ICM would have a 16.13 times higher energy efficiency while having the same execution time. At maximum clock frequency (625 MHz), the RV32ICM board would save up to 23 times more energy and run 15.8 times faster with the same core voltage. It was also exposed that with a lower core voltage, RV32ICM could reach a 38.3 times better energy efficiency and still running 2.1 times faster than the Cortex®-M4F at its maximum clock frequency (168 MHz). In Pullini et al. (2019), a PULP SoC for IoT edge processing was presented, where the lack of performance of cores like the Cortex®-M0+ for applications that require larger computational power but still need to respect low-power constraints is pointed as a disadvantage. A zero-RISCY with an RV32IMC RISC-V ISA core and eight fully programmable RISC-V based cores with DSP extensions was presented as a solution. Benchmarks were performed and compared with other MCUs, DSPs, and Parallel Ultra-Low-Power (PULP) SoCs. The overall results show that the solution presented can be better than almost all the tested devices excepting the PULPv2 (Rossi et al., 2017). However, it is said that the PULPv2 lacks internal power management, not making it suitable for duty-cycled applications such as IoT. Considering the high expression RISC-V community has reached, it can not be ignored when considering a custom, optimized solution, especially when cost structure is so crucial as in massive IoT devices. However, COTS boards with RISC-V are still scarce and there is a lack of documentation, examples, and development supporting tools. For a custom board design, fabrication of the RISC-V core is almost mandatory, increasing the implementation time and jeopardizing the testing phase. For these reasons, an Arm®Cortex®-M based microcontroller is going to be used as the platform for analyzing power consumption and performance of a NB-IoT application. 2.5.1 Arm®Cortex®-M0+ Even though the Cortex®-M4 processor proves to be the more power-efficient from the benchmark scores observed, usually for low-power and ultra-low-power applications, the Cortex®-M0 and Cortex®- M0+ are used (Yiu, 2015a). Arm developed these processors exclusively with low-power consumption 34
Chapter 2. State of the Art in mind, by reducing its size and increasing its efficiency. Besides its low-power and energy efficiency characteristics, the Arm®Cortex®-M0+ brings other advantages such as (Yiu, 2015b): • High Code Density - most of the instructions are 16-bit in size, enabling an application to be squeezed into a smaller flash memory; • Low Interrupt Latency and Deterministic Behavior - by having a fixed latency of 15 cycles, the Cortex®-M0+ assures a determinist behavior when responding to interruptions, useful for real-time applications; • Ease of Use - besides the simple instruction set implemented (only 56 instructions), Arm also has an open Application Programming Interface (API) to facilitate the peripherals interface, being part of the Cortex Microcontroller Software Interface Standard (CMSIS-CORE) software framework; • System-level Features and OS Support Features - the system-level features, such as low-power support and flexible interrupt management, and the Operating System (OS) support features, such as system tick timer and banked stack pointer, make the Cortex®-M0+ suitable for a wide range of applications; • Comprehensive Debug Features - essential during the development phase, the presence of debugging features such as halting, single stepping, reset, breakpoints, and watchpoints make the Cortex®-M0+ very user-friendly; • Wide Range of Product Choice - reflecting the market share of the Arm®Cortex®-M processors, there is a large number of microcontroller devices based on these processors available. Due to this popularity, there is also a wide range of support software such as compiler toolchains, debug tools, embedded OSs, and middleware. Thinking on which processor to use in the selected MCU and corresponding evaluation board is helpful when preparing the long course of action for a custom designed chip. Only then it is possible to compare a Comercial Off-The-Shelf (COTS) solution with a custom designed one. One drawback of using Arm® processors for commercial production is the costs that are inherent to it. In order to acquire the Intelectual Propriety (IP) for the development of custom chips with the mentioned processor, it may be necessary one of the licenses that have not only upfront costs but also product license fees, not to mention the royalties (Arm Limited, 2019) However, it is relevant to have in consideration that these licenses and packages come with all the ecosystem’s benefits and personalized support in some cases. Being Arm a leading company with much 35
2.6. Existent Solutions influence on its partners, this can be perceived as an added value, but for applications with a low-cost target, these production costs cannot be neglected. 2.6 Existent Solutions When it comes to conceive a custom design, it is necessary to first analyze the options already in the market. For a NB-IoT design there are two ways to consider: • Using only the NB-IoT modem, programming its embedded application processor to establish the sensor’s interface (see figure 2.15 a)) • Using the NB-IoT modem exclusively for communication and add a Microcontroller Unit (MCU) to run the application and establish interface with other sensors (see figure 2.15 b)) (a) (b) Figure 2.15: Possible NB-IoT designs: a) NB-IoT modem with internal application CPU; b) NB-IoT modem with external MCU (adapted from (Naik, 2018)) Not all NB-IoT modems available in the market grant access to their internal processor, so the choice of the modem for the application already implies a decision on the design. While using only the NB-IoT modem for a given application (by programming its application processor) can save extra resources and minimize overall power consumption, it is surely more restricted in terms of interfaces and peripherals, and can limit applications’ implementation. In Naik (2018) is presented the Qualcomm solution for this method, the MDM9206, which is supported by two chips manufacturers (Quectel (Quectel, 2017) and SIMCom (SIMCom, 2017)) and has integrated cloud device agents. It has a Cortex®-A7 application processor and runs ThreadX RTOS. Besides Qualcomm, Quectel also employs NB-IoT modems from other manufacturers in its chips, and much like the MDM9206, Quectel offers access to the application processor of the other modems through the same development tool: QuecOpen®(Quectel, 2017). 36
Chapter 2. State of the Art Nordic Semiconductor presents its System-in-Package (SIP) nRF9160 as the integrated modem solution. It has a Cortex®-M33 application processor and has its own development kit from Nordic to allow an easy and fast contact with it (Nordic Semiconductor, 2018). The second possibility of implementation is more trivial, by making use of a simple MCU with easy programmability and extensive APIs support, reducing implementation time. For this method, any NB-IoT modem available can be used, thus allowing for a wider choice range. The internal processor is only used to deal with the interface and the connectivity, so it can be put into sleep for longer periods of time, while the acquisition and processing can be done in a less power consuming processor, from the external MCU. Besides mere shields to use with existent popular boards such as Arduino or Raspberry, there are already complete development kits which include a microcontroller, a NB-IoT modem, and other hardware components such as LEDs and buttons. The SODAQ SARA SFF is one of this development boards (SODAQ, 2019). It can have three possible NB-IoT modem from u-blox and has a ATSAMD21G18, 32-Bit Arm®Cortex®-M0+ MCU to control not only the modem but also a RGB LED, a GPS module and a accelerometer/magnetometer. It can be powered by 5 V USB or by a 3.7 V LiPo battery, rechargeable by solar power. It has a size of 50 mm ×25.4 mm, which makes it one of the smallest development boards of this kind on the market. From u-blox, there is also their own development board, C030, to use with different NB-IoT modems (u blox, 2019). It has a STM32F437VG Arm®Cortex®-M4 MCU, a RGB LED, two push buttons, a GPS module and possibility of using ethernet connection. It can be powered by 5 V USB or by a LiPo battery, rechargeable by USB power on board. It is one of the largest development boards on the market, with a size of 50 mm ×130 mm. Then, there is the STARTER KIT from NOS, developed in partnership with THINKDIGITAL®, which uses a BC68 Quectel modem. It has a STM32L073RZ Arm®Cortex®-M0+ MCU, a RGB LED, an accelerometer, a temperature sensor and three different interfaces that allow the connection of other modules (GPIO, RS485, and UEXT) (NOS Comunicações, 2019). It can also be powered by a 5 V USB or by an external battery. It has a size of 59 mm ×38 mm not considering the connectors, but it is not available on the market. However, due to affiliation to the project this dissertation is included in, samples of this board were kindly given and it was used as a benchmark for comparison with the custom board developed. 37
3.1. Hardware Besides all the peripherals it offers, it also has three internal clock sources and the possibility to add an external one for low-speed. For the system clock, two internal clock sources can be used – Multispeed Internal (MSI) or High-Speed Internal (HSI) – or the PLL. The MSI can generate 7 different frequencies, from 65 kHz up to 4.2 MHz. The default value for this MCU is 2.1 MHz. The HSI is a fixed 16 MHz RC oscillator that supplies the PLL if desired. The PLL allows generating a maximum 32 MHz clock signal from the 16 MHz HSI. As for auxiliary clock sources it can use the Low-Speed Internal (LSI) or the Low-Speed External (LSE). This clock source is usually used for peripherals like RTC and watchdog timers, since they keep running even when the MCU is put into low power modes. This is important for evaluating consumption on different clock sources, as suggested in Yiu (2015c), especially for the low-speed clock source of the RTC, that remains running even when the MCU is in deep sleep waiting to wake up and process sensors’ information. The system clock frequency is limited by the voltage at the core (VCORE), which in turn is limited by the external power supply (VDD). Figure 3.6 depicts this relation, highlighting that in order to run the MCU’s core at maximum frequency (32 MHz), a necessary Range 1 VCORE is needed (1.8 V). On the other hand, if a lower frequency is chosen (below 4.2 MHz), the VCORE can be dropped to 1.2 V, Range 3, allowing for less power consumption at the expense of less performance. Figure 3.6: Performance vs. VDD and VCORE range (from (STMicroelectronics, 2017)) 44
Chapter 3. System Specification Allied with the different voltage ranges of VCORE, this MCU features five low-power modes, presented in decrescent order of consumption (STMicroelectronics, 2016a): •Sleep mode: only CPU is stopped, all peripherals continue to operate and can wake up the CPU. Consumption in this mode can be down to 37 µA/MHz. •Low-power run mode: the clock frequency and the number of enabled peripherals are limited – maximum of 131 kHz –, and I2C and ADC not available. Consumption in this mode can be down to 8 µA. •Low-power sleep mode: CPU is stopped and peripherals are limited (much like in low-power run mode). The consumption in this mode can be down to 4.5 µA. •Stop mode: If RTC wakeup is desired, all clocks are disabled excepting the RTC source clock (LSE or LSI). Though any external interrupt line can wakeup the CPU. This is the mode with lowest power consumption with state retention (RAM and registers), with consumptions down to 0.4 µA without RTC and 0.8 µA with it. •Standby mode: Similarly to stop mode, if RTC wakeup is desired, all clocks are disabled except for the RTC source clock. However, RAM and registers contents are lost. This is the lowest power consuming mode, achieving consumptions down to 0.28 µA without RTC and 0.65 µA with it. Since gathering sensor information and sending it to a cloud server is a cyclic task, the use of RTC is indispensable for the use case. In order to resume program execution between every break, state retention is necessary, thus stop mode was used as the lowest power consumption mode. However, if something went wrong with the normal execution of the program, the end device should wait some time to retry connecting or for maintenance, allowing the use of the standby mode, which also performs a system reset. In figure 3.7 are illustrated the connections needed for the system presented in figure 3.5. Similarly to figure 3.5, connections marked with a ’*’ mean that suffered alterations from version 1 to version 2 of the custom board. It is visible that there are not many pins left available, making this chip almost custom made for applications like this one. This also reinforces the choice for sensors with digital interface, as it makes it possible to have multiple different sensors attached in the same line, being it I2C or SPI. 45
3.1. Hardware Figure 3.7: MCU connection diagram 3.1.2 NB-IoT Modem For the NB-IoT modem, the key features that influenced its selection were power consumption and power supply, technical support, and availability. Since this is a growing market and the key players chips’ manufacturers are still exploring the consumer’s needs, there are different market choices available, from single chipsets to full development kits. For the proposed custom system, a single chipset was selected, the BC66 from Quectel. This modem has one of the lowest power supply range, allowing it to be powered directly by the battery, simplifying the board design and removing the quiescent current from a booster that is not needed in these conditions. Allied with this, the BC66 also has some of the lowest power consumption in its different operation modes. Highlighting its consumption of only 3.5 µA when in Power Saving Mode and 110 mA when transmitting with LTE Cat NB1 at 23 dBm and single-tone. Table 3.2 gathers more hardware specification for this modem. 46
Chapter 3. System Specification Table 3.2: Modem hardware specification Modem Core Power Supply Consumption Size Output Power Cat Quectel BC66 MediaTek MT2625 2.1 V – 3.63 V 3.5 µA @ PSM 350 µA @ Idle (DRX = 2.56 s) 110 mA @ LTE Cat NB1 (23 dBm, single-tone) 17.7 x 15.8 (mm2)23 dBm LTE Cat NB1 The communication with the modem is done using AT commands over UART. This modem supports the 3GPP Rel.13 Compliant AT Commands and the Quectel Enhanced AT Commands, offering many device related functionalities as well as network related. It is also already integrated with different protocol stacks such as UDP, TCP, LwM2M, and MQTT, facilitating the use of such protocols from the MCU side. From a longevity perspective, the BC66 has a build-in eSIM reserved for future use, which will allow the removal of the SIM external interface, reducing the Bill of Materials (BoM) and power consumption of future devices. 3.1.3 Sensors The sensors’ choice also has to be well studied since it is desired that they keep supplied even during the stop mode of the MCU. This allows using an interrupt system if some anomaly is detected during the idle time of the system. Therefore, it is important to choose sensors with low current consumption when in standby. With this concern in mind four different sensors were selected based on three features: low power supply (ideally 1.8 V), low power consumption when in standby, and digital interface. For the accelerometer, the BMA400 from Bosch was chosen. It is a 2 mm ×2 mm, 12 bit, digital, triaxial acceleration sensor with many interrupt features related to movement and position, and variable oversampling rate (OSR) which controls the data accuracy. It consumes only 160 nA in sleep mode and 850 nA, if running in low-power mode. The CH4sensor chosen was an ePY12221 from Pyreos. It is a 5.65 mm ×3.7 mm, pyroelectric IR sensor with embedded interrupt mechanisms and low-power mode. It consumes about 3.5 µA either in sleep mode or operating at 166 Hz sample rate (sps), with 1 channel active in low-power mode. The OPT3002 from Texas Instruments (TI) was the chosen light sensor for this design. It is a 2 47
3.1. Hardware mm ×2 mm, 23 bit, light-to-digital sensor with interrupt capability. It consumes a maximum of 3.7 µA when actively converting values. Finally, the BME280 from Bosch was the chosen sensor to collect data about temperature and relative humidity. It is a 2.5 mm ×2.5 mm, temperature, humidity and pressure sensor which allows the independent enable/disable of each variable. It consumes only 100 nA when in sleep mode. Due to its lack of interrupt mechanism, the HDC2080 from Texas Instruments (TI) was the chosen temperature and relative humidity sensor for the second version of the board. It is a 3 mm ×3 mm sensor with interrupt capability that only consumes 50 nA when in sleep mode. Table 3.3 summarizes the primary features for these sensors. Table 3.3: Sensors hardware specification Sensor Power Supply Consumption Size Interface Low Power Modes BMA400 Bosch 1.72 V – 3.6 V 3.5 µA @ OSR=0 Normal Mode 850 nA @ OSR=0 Low-Power Mode 160 nA @ Sleep Mode 2 x 2 (mm2) SPI, I2C, 2 INT pins Sleep Low-Power Normal ePY12221 Pyreos 1.75 V – 3.6 V 22 µA @ 1 ksps 1 CH Normal Mode 3.5 µA @ 166 sps 1 CH Low-Power Mode 3.5 µA @ Sleep Mode 5.65 x 3.7 (mm2)I2C, 1 INT pin Sleep Low-Power Normal OPT3002 TI 1.6 V – 3.6 V 3.7 µA @ Full-Scale Active 1.8 µA @ Dark Active 0.4 µA @ Shutdown 2 x 2 (mm2)I2C, 1 INT pin Shutdown Single-shot Continuous BME280* Bosch 1.71 V – 3.6 V 340 µA @ Humidity Measurement 350 µA @ Temperature Measurement 0.1 µA @ Sleep 2.5 x 2.5 (mm2)SPI, I2C Sleep Forced Normal HDC2080* TI 1.62 V – 3.6 V 650 µA @ Humidity Measurement 550 µA @ Temperature Measurement 0.05 µA @ Sleep 3 x 3 (mm2)I2C, 1 INT pin Sleep Triggered Auto The use of I2C allows connecting the four sensors in two shared lines, one for clock and the other for 48
Chapter 3. System Specification data. This is useful because it allows reducing the number of pull-up resistors necessary on each line and reduces the number of peripherals needed by the MCU to communicate with the four sensors. 3.1.4 Power Supply For portable solutions like the one presented, batteries are the most common energy source used (Shirvanimoghaddam et al., 2019). The battery size needed for a given application is estimated from the average power consumption of the system and the expected lifetime (Amicucci, 2018). For a first iteration and since the purpose is to measure the power consumption of the system, a 3.6 Ah battery was selected. Ideally, the choice would be the LM17500 from Saft, which is a 3 V, 3 Ah battery with ATEX certification and the size of an AA battery. However, due to restrictions on transportation and unavailability in residence’s country, the choice was divided between the LS17500 and LSH14 Saft batteries. The former has a nominal voltage of 3.6 V and a capacity of 3.6 Ah, however it has a pulse capability of only 250 mA, which is insufficient to powerup the modem successfully. The latter has same nominal voltage, but capacity of 5.8 Ah and pulse capability up to 2 A. The downside is its size, being almost 1 cm larger than the LS17500. When considering battery-powered applications like the one presented in this dissertation, the current drawn from the battery in a standby condition is very important for its longevity (Glaser and Texas Instruments, 2011). Normally, in this state, there’s only a light load from the supplied system and the quiescent current (IQ) from power management components can have an important role on the overall current consumption. In order to reduce as much as possible the complementary hardware components, which in turn removes unnecessary IQ, the modem is directly supplied from the battery. However, in order to save as much power consumption as possible, the voltage supplied to the MCU and to the sensors should be the minimum possible, being 1.8 V a common standard. For converting the 3.6 V from the battery into 1.8 V a low-dropout regulator was used. On the first iteration, the LDO chosen was the TLV75101 from Texas Instruments (TI). It is a 2 mm ×2 mm, dual, adjustable, 500 mA LDO regulator. The typical IQis 25 µA, and it only needs two small capacitors as extra components for its design. Later on development and after performing the first measurements, it was concluded that the LDO chosen was not suitable for the standby period of the application, so a new LDO was selected for the board’s second version. The TPS7A02 from Texas Instruments is a 2.9 mm ×1.6 mm, 200 mA LDO 49
3.1. Hardware regulator. It has a 25 nA IQand an efficiency above 90% even with an output current of less than 10 µA. Table 3.4 gathers the hardware specification of the components involved in the power supply module of the system. Table 3.4: Power supply hardware specification Battery Nominal Voltage Nominal Capacity Pulse Capability Max Continuous Current Size LM17500 Saft 3 V 3 Ah up to 2 A 1.5 A 17.5 x 51.5 (mm2) LS17500 Saft 3.6 V 3.6 Ah up to 0.25 A 0.13 A 17 x 50.9 (mm2) LSH14 Saft 3.6 V 5.8 Ah up to 2 A 1.3 A 26 x 50.4 (mm2) Component Input Voltage Output Voltage Output Current Quiescent Current Size TLV75101* TI 1.5 V – 6 V Adjustable between 0.55 V to 5 V 500 mA 25 µA (typ.) 2 x 2 (mm2) TPS7A02* TI 1.5 V – 6 V Fixed between 0.8 V to 5 V 200 mA 25 nA (typ.) 2.9 x 1.6 (mm2) Since it was possible to design and integrate both solutions, comparative tests could be done in order to better expose the difference in current consumption. 3.1.5 Capacitors Special attention was given to the capacitors’ choice, especially for the modem power supply. There was an immediate trade off when considering the batteries available. Using higher capacitance capacitors with the smaller battery; or getting a larger battery and prescind of additional capacitors. When looking for long life operation, low leakage current and high capacitance values there is not one capacitor, at commercial reasonable price, that fits. For long life and low leakage, C0G ceramic capacitors are the best suited choice, and most of the decoupling capacitors chosen are ceramic types. However, C0G type capacitors do not have high capacitances available, and to start up the modem from the capacitors instead of the battery, high capacitance is needed. For this, tantalum type capacitors are the best and with great longevity too, but they have much more leakage current, resulting in an extra load for the battery (Horowitz and Hill, 2020). With further analysis it was assessed that two 330 µF capacitors were required to start up the modem 50
Chapter 3. System Specification with the 3.6 Ah battery. Only tantalum capacitors were found with this capacity, so it was expected to add an extra current consumption on the overall device. This addition was only made in the second version of the custom board. 3.1.6 Security Since security in an IoT application can not be put aside, an hardware solution was selected to provide it, by seamlessly adding an encryption engine to the whole system. This solution also has in mind the low-power restrictions that the application requires. It was chosen the ATECC608A from Microchip, which offers AES-128, SHA-256 and multiple SHA derivatives. It has a power consumption of 3 mA when active and during ECC command execution, but also has two power saving modes: idle and sleep. In sleep mode it has a consumption as low as 30 nA, which makes it an exceptional choice for adding another layer of security. Table 3.5 presents more hardware specification for this chip. Table 3.5: Security chip hardware specification Component Power Supply Consumption Size Interface Low Power Modes ATECC608A Microchip 2 V – 5.5 V 3 mA @ active or executing ECC command 800 µA @ Idle Mode 30 nA @ Sleep Mode 2 x 3 (mm2)I2C Sleep Idle Active 3.2 Software Having excellent hardware components with minimum power consumption just by their own does not make a low-power application. Most of the low-power consumption announced by the hardware manufacturers are features that need to be selected, as it can have much more power consumption in normal operation mode. Thus it is of extreme importance to design a low-power conscious software application, which not only applies a power consumption saving flow of execution, but also takes advantage of these low-power features of the hardware selected. Figure 3.8 presents a simplified system flowchart for both applications developed. Since it has a simple monitoring purpose, the process is cyclic, depending only on the success of the operations. 51
3.2. Software Figure 3.8: System flowchart 52
Chapter 3. System Specification It starts with the system initialization, where the MCU is configured to run at the best suitable voltage range and clock frequency, allowing to save power during the program execution from the beginning. Then, the other components are initialized and configured. This step is critical to take advantage of the low-power modes of the sensors, by configuring them into suitable operation modes. Not only the sensors, but also the modem, as it is necessary to make sure it is turned on and communicating with the MCU, as well as with the network. If any of this fails multiple times, the system must enter into standby for some time (minutes) before trying to reconnect with the base station again. This mode also allows a system reset, which can be beneficial for the success of the operations. On the Cloud side, the lack of communications from given end device can be identified and reported, so that proper attention and perhaps maintenance can be provided. Verified the initialization and connection of the modem, an initial packet is sent, to acknowledge the presence of the end device in the network. From here, each application developed performs differently within the cycle. There are two entry points (denoted by the [In] notation) and two exit points (denoted by the [Out] notation). The First entry point happens every time the initial information is sent, be it by being the first execution or by recovering from some problem. The Wake Up entry point is the repeated entry point while in normal operation cycle, happening every time the MCU wakes up from stop mode. The Success exit point is used when the task specific to each application is executed successfully, allowing the MCU to enter stop mode immediately after. On the contrary, the Problem exit point is used when some problem occurs within the execution, resulting in the exit of the normal operation cycle. The two applications already mentioned are the Read&Send and the Read&Store. The specific flow of execution is presented in figures 3.9 and 3.10, respectively. 53
3.2. Software • sendDatagram() – for sending any type of datagram (replaces both methods above); • repairConnection() – for restoring the server connection if something goes wrong with the socket handling. 3.2.5 Sensors The sensors module encapsulates the individual specific sensor files, abstracting the other application’s modules from the specific implementation of each sensor. As shown in figure 3.16, the sensors module is dependent of individual sensor modules that must have the showed API. This way, it is easy to replace a sensor on the hardware with minimal implications on the rest of the application, it is only needed to change the driver file for the specific sensor on the sensors module, and adjust its identification. Here, the main difference from the Read&Send application to the Read&Store one is the extra methods and structures needed so it is possible to sample the sensors periodically and store its data. The sensor structure is also modified so it can be better used for this scenario. Figure 3.16: Class diagram of sensors module: a) Read&Send specific; b) Read&Store specific 60
Chapter 3. System Specification Regarding the sensor driver API, the methods to employ are: • initType() – where type refers to the type of sensor, e.g. an accelerometer driver would have a initAcc() method. It is used to confirm that the sensor is responding well to queries through its protocol line (in this case, I2C); • configType() – for specific configuration of the sensor; • readType() – for reading sensor values, depending on the type of sensors it can have more than one argument; • interruptTypeHandler() – for dealing with the interrupt mechanism of the sensor. On the high level sensor module, an array of sensor structures is initialized and complemented with the following methods: • initializeSensors() – for initializing the available sensors using their APIs. If initialization is successful, the sensor structure is included in the active sensors array, otherwise it will be consider as inactive; • configSensors() – for configuring each active sensor available, using their respective APIs and saving their configuration in the individual structure; • getSensorsEnable() – for returning the number of sensors enabled at initialization, the active sensors in Read&Send app. It returns a string and its length with the type of sensors enabled in Read&Store app; • getSensorsConfig() – for getting the configuration of given sensor; • readSensors() – for performing readings using the sensors APIs. In Read&Send app it stores the values within the respective sensor structure, in Read&Store app it is used only to read the values when an interrupt is triggered and saves them in the read_data array; • getSensorsData() – for getting the sensor values available on a single string in Read&Send app. In Read&Store it returns the pointer to read_data and how many values there are available; • interruptHandlerSensors() – general sensors interrupt handler that deals with each individual sensor interrupt handler; 61
3.2. Software • configSensorsPeriods() – for tuning the sample periods of the sensors, so they can be multiples of the minimum period verified (only in Read&Store app); • sampleSensors() – for sampling the sensors according to its period (only in Read&Store app); • getSensorsSamples() – for getting the variable_data array. It also returns how many variables there are available to read (only in Read&Store app). 3.2.6 Security One of the perks of using a STMicroelectronics’ device is the ecosystem it has. By using tools from the STM32Cube ecosystem provided by STMicroelectronics, it is possible to add some pre-built and pre-tested middleware with ease, allowing for a faster project development. One available library is the STM32 crypto library (STMicroelectronics, 2020). The STM32 crypto firmware library is distributed by STMicroelectronics as an object code library linked to STM32 products. There are two object code libraries for each family of STM32 microcontrollers, one optimized for size and the other optimized for speed. There is also firmware for MCUs which have hardware acceleration for encryption methods. This crypto library offers APIs for several encryption algorithms, being the most relevant for this application the AES and the RSA. In MCUs with no hardware accelerated encryption algorithms such as the one chosen, this firmware executes the encryption and decryption exclusively by software, which can consume much more power or take too much time. Nevertheless, some level of security must be employed at the application level to ensure data reliability, so it is a necessary tradeoff to make. By co-designing the security feature with software and hardware modules, it is possible to minimize this extra power consuming/time demanding task. Of both algorithms planned to use in this application – RSA and AES –, the AES algorithm is the most computational intensive one. That is why it is preferable to have some specialized hardware to offload the processor on this task. Since the security chip chosen can not resolve RSA encryption algorithm, the STM32 crypto library presented is going to be used with this purpose. Since the RSA algorithm is only used at UL transmissions, only the following function is used: • RSA_PKCS1v15_Encrypt() – for performing an RSA-PKCS#1 v1.5 encryption using the public key 62
Chapter 3. System Specification 3.2.7 Bare-Metal versus RTOS In terms of power consumption analysis regarding the software application, besides the selection of clock frequency, one of the most interesting comparisons to make is an analysis between bare-metal and RTOS-based applications. On one side, the sequential execution of the bare-metal program makes it reliable, but with many waiting periods. On the other side, the introduction of pseudo-parallelism brings flexibility and better management of waiting periods, at a cost of more complexity and overhead. Bare-Metal The bare-metal firmware runs on a simple main respecting the flow of execution presented in figure 3.8. As seen earlier in this chapter, the bare-metal approach comprises the two applications developed. Figures 3.17 and 3.18 show the relation between the analyzed modules in both application scenarios. Figure 3.17: Bare-metal relation diagram for Read&Send application 63
3.2. Software Figure 3.18: Bare-metal relation diagram for Read&Store application With these figures the differences explained earlier become more evident. While in figure 3.17 the main interacts only with APIs to get access to the structures and data inside the modules, in figure 3.18 it has direct access to the transmission structures used for the different types of datagrams (configuration, emergency, and regular). In both applications the low level is the portable layer which directly uses the HAL API given by STMicroelectronics. RTOS There are several RTOSes available for IoT applications,open-source or propriety. After analyzing some of the most known RTOSes, such as ThreadX and embOS (proprietary), and µC/OS-III, mbedOS and FreeRTOS (open-source), the selected RTOS was FreeRTOS. According to (Belleza and De Freitas, 2018), FreeRTOS is not the fastest RTOS in most benchmarked parameters, but its performance is comparable with the other open-source RTOSes analyzed. The choice of FreeRTOS is justified by its community support, previous development experience and seamless porting to the selected MCU using the ST Cube tool. The FreeRTOS application developed respects the same layers depicted in figure 3.11, except that it introduces a new layer, close to the hardware, representative of the FreeRTOS kernel, that manages scheduling and context switching of tasks. A graphic tasks abstraction of the implementation in the RTOS context is provided in figure 3.19. 64
Chapter 3. System Specification Figure 3.19: FreeRTOS graphic tasks abstraction There are tasks and functions responsible for configuring and collect data from the sensors (left side of figure), which in turn are accessed by a manager using synchronization mechanisms such as semaphores. On the communication scope (right side of figure) there are also tasks responsible for initializing and configuring the NB-IoT connection to the base station and Cloud server, allowing the manager task to request configuration information and sending datagrams with respect to the appropriate synchronization mechanisms (semaphores and queues in this case). Figure 3.20 presents the task diagram of their relation with synchronization mechanisms and Interrupt Service Routine (ISR). In this application there is not a clear separation between the different modules, as it would only add a lot more overhead. Instead, each task has a purpose in the overall flowchart and has access to what it needs to execute: • vModemReceiver – task responsible for dealing with the incoming messages from the modem. It reads from the xModemRxQueue , parses the message, updates the nb_iot modem structure using the nb_iotMutex , and sets the mRcvSemaphore to let other tasks know the modem has responded; • vModemTransmitter – task responsible for preparing the message in the xModemTxQueue to send to the modem; • vModemInit – task responsible for initializing the modem; • vModemManager – task responsible for configuring the modem and checking connection with the network. It also checks on the mRcvSemaphore and nb_iotMutex to handle responses; 65
3.2. Software • vDataManager – task responsible for managing the data acquisition, and datagram construction and sending. It waits on dataSemaphore to get the sensor readings, using the sTxSemaphore and sRxSemaphore for that. Then, it also makes use of the xModemTxQueue to communicate with the modem. If something goes wrong with any of these steps, it notifies the vModemManager so it can reconfigure the modem and restore the network connection; • vSendInitInfo – task responsible for sending the initial information about the end device, gathering both modem and sensors configurations; • vSensorsInit – task responsible for initializing the sensors. It can run in parallel with vModemInit task and sets the sensorReadySemaphore when done. Figure 3.20: FreeRTOS tasks relation diagram 66
Chapter 3. System Specification Due to the timeline followed during the project (please check figure 3.3), the RTOS-based approach only implements the Read&Send application, very similarly to the bare-metal approach. This allowed the comparison in performance and power consumption of both approaches with the first version of the custom board. In this chapter a general specification of the system was presented, exposing the network architecture scheme in which the device is inserted, as well as the requirements and timeline adopted for a more detailed specification. Then, both hardware and software design were explained, setting the foundations for the next chapter: Implementation, which is going to reflect on how all of these constituents were assembled together to originate the end device proposed. 67
Chapter 4: Implementation The implementation phase takes the system specifications and brings them to life within the limits encountered. In this chapter, a comprehensive description of what was made in terms of hardware and software is presented. On the hardware side, some of the most important aspects of the boards designed are explained, and each BoM is discussed to highlight the low-cost aspect of developing a solution like such, even from a prototype perspective. The software part focuses on the configurations adopted for each board and application, proceeding to highlight the main differences between the bare-metal and RTOS approach for the Read&Send application and the differences between the Read&Send and Read&Store applications for the bare-metal approach. 4.1 Hardware At the hardware level there were designed and fabricated four different Printed Circuit Board (PCB). Each PCB was a result of the iterative process to achieve a low-power, low-cost end device with NB-IoT capabilities. As seen in the previous chapter, the first stage of development used a development board from NOS – NOS Board –, but in order to study the working mechanisms of the NB-IoT within the use case proposed, a sensors shield was developed. Then, after identifying the ”must have” components for an application like such, a brand new board was developed from scratch – Custom Board v1 –, with many circuitry test points so that different solutions could be compared. After identifying possible design flaws and selecting the best solutions for the application in hands, a second version of this board was developed – Custom Board v2 – with a modular approach for better suitability to the use case. This introduced the design of another sensors shield, allowing the separation of these modules so that the modem and the MCU do not have to be close to the environment being monitored. All of these boards are going to be further described taking into consideration their Bill of Materials (BoM), so that a prototyping cost could be estimated. 68
Chapter 4. Implementation 4.1.1 NOS Board Sensors Shield This shield was developed so that initial market research could be performed on the available sensors for the targeted environmental variables. It then accommodates three different types of sensors: methane gas, luminosity/light, and temperature and relative humidity. The NOS Board already had an on-board accelerometer, thus it was not included one of those in this shield. All these sensors were selected for their low-power consumption and digital interface. The fact that they use I2C as their communication protocol simplified the board design, being only necessary to share the two communication lines (SDA and SCL) with respective pull-up resistors. Additionally, a load switch was placed on the power line of the shield, this allowed to disable all sensors at once if necessary, via software. It was also included in the design a physical switch, using a 1x2 header, disabling the sensors power line by hardware too. Some extra lines were used to get the interrupt lines to the MCU, repurposing the Universal EXTension (UEXT) connector present on the NOS Board. Figure 4.1 shows the 3D model of the sensors shield designed. The extra components such as some resistors and capacitors are recommendations from each sensor datasheet: resistors for pull-up on interrupt lines and decoupling capacitors for stabilizing the input voltage in each IC. (a) (b) Figure 4.1: NOS Board sensors shield 3D model: a) Top view; b) Bottom view The design of the shield was such that it could just be connected on top of the NOS Board without compromising the accessibility to the main components as well as the connection of the programmer. In figure 4.2 there is a picture of the assembled PCB already connected to the NOS Board. 69
4.2. Software On the other hand, the estimation cost for producing one sensors shield is 81.93 e. Here the prototype production scales the price once again, plus the expensive methane sensor. However, adding both expenses, the estimated cost for the proposed end device is 118.60 e, having reduced not only the cost but also the power consumption comparing to the first version. Additionally, this end device allows the deployment in situations different from the one studied, by changing the sensors in the sensors shield. 4.2 Software The software implementation throughout the whole dissertation comprises five different STM32CubeMX projects. For each board there are two STM32CubeMX projects, one for the bare-metal approach and other for the RTOS approach, except for the Custom Board v2, which only has a bare-metal approach. Figure 4.10 presents the pins configuration for the three boards, which is influenced by the hardware each board has, but is not altered depending on the approach. (a) (b) (c) Figure 4.10: STM32CubeMX MCU pins configuration: a) NOS Board; b) Custom Board v1; c) Custom Board v2 The NOS Board pins configuration has into account every peripheral available on the board, even if it is not used for the purpose of the application. It is also notorious the difference from the MCU chosen for the Custom Boards, having a significantly reduced number of pins available for configuration (from 51 down to 23). The difference between both custom boards rely on the hardware available to configure, the most significant changes from version 1 (b) to version 2 (c) are: • Absence of a SENSORS_ENABLE control pin, as it is not possible anymore to turn off the sensors’ 76
Chapter 4. Implementation power supply; • Absence of DEBUG_TX/RX UART related pins, as it is not possible anymore to use the second UART to debug the system; • Additional interrupt pin for the new temperature and relative humidity sensor. Since the FreeRTOS was chosen for developing the RTOS-based approach, a middleware configuration in STM32CubeMX was used to save some troubles with portability and implementation (figure 4.11). Although it already generates the necessary code to have the FreeRTOS kernel up and running, further modifications can be made on the source code of the FreeRTOS implementation, as predicted by the FreeRTOS open-source license. Then, the STM32CubeMX tool facilitates the FreeRTOS initialization and utilization, without limiting its potential of being further optimized after code generation. Figure 4.11: STM32CubeMX FreeRTOS configuration panel 77
4.2. Software In order to facilitate the code update, the clock tree given by the STM32CubeMX tool was used to change the operating clock frequency when needed. Figure 4.12 shows the options available for the MCU chosen. Highlighted in red are the different clock sources for the system clock and the two multiplexers (mux) that allow the choice of the source clock for the RTC and the system clock, from top to bottom respectively. This panel is the same for all boards. Figure 4.12: STM32CubeMX clock tree panel After all configurations are set, the C code project for Keil is generated. Although STM32CubeMX allows generating C code projects for other IDEs, Keil µVision was chosen due to previous working experience of the author and comprehensive debug tools for STMicroelectronics MCUs. The modules exposed in figure 3.11 were then developed one by one, first for accomplishing the Read&Send application, then were adapted to the Read&Store application. Due to its dimension, common code of both applications is not going to be discussed in great depth. However, the enterStopMode() method from the system module is worth mentioning. Present on code 4.1, this method is rather simple: one just needs to request the use of the stop mode through the low level API and when the MCU wakes up again it has to reconfigure the clocks and the low power configuration. 1void enterStopMode (void){ 2 3/*Request Stop Mode */ 78
Chapter 4. Implementation 4requestStopMode(); 5 6/*Return from Stop Mode*/ 7clockConfigAfterStop(); 8 9lowPowerConfig(); 10 11 return; 12 } Code 4.1: enterStopMode() The particularity worth mentioning is on the clockConfigAfterStop() method from the low level portable layer. Code 4.2 shows the code necessary to reconfigure the MCU clocks. Commented are the other configuration possibilities, as several were tested and compared. 1void clockConfigAfterStop(void){ 2 3RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; 4RCC_OscInitTypeDef RCC_OscInitStruct = {0}; 5RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; 6 7/* Enable MSI Oscillator */ 8RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; 9RCC_OscInitStruct.MSIState = RCC_MSI_ON; 10 RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_3; 11 RCC_OscInitStruct.MSICalibrationValue=0x00; 12 RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; 13 if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) 14 { 15 /* Initialization Error */ 16 Error_Handler(); 17 } 18 19 /* Enable HSI Oscillator or PLL*/ 20 // __HAL_RCC_PWR_CLK_DISABLE(); 21 // 22 // /* Enable MSI Oscillator */ 23 // RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; 24 // RCC_OscInitStruct.HSIState = RCC_HSI_ON; 79
4.2. Software 25 // RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; 26 // RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; //ON 27 //// RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; 28 //// RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_4; 29 //// RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2; 30 // if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) 31 // { 32 // /* Initialization Error */ 33 // Error_Handler(); 34 // } 35 // __HAL_RCC_SYSCLK_CONFIG(RCC_SYSCLKSOURCE_HSI); //PLLCLK 36 // 37 // RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; 38 // RCC_OscInitStruct.MSIState = RCC_MSI_OFF; 39 //// RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; 40 // if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) 41 // { 42 // /* Initialization Error */ 43 // Error_Handler(); 44 // } 45 46 /* Initializes the CPU, AHB and APB busses clocks */ 47 RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK 48 |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; 49 RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; 50 RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; 51 RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; 52 RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; 53 54 if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct , FLASH_LATENCY_0) != HAL_OK) 55 { 56 Error_Handler(); 57 } 58 59 PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1| RCC_PERIPHCLK_USART2 60 |RCC_PERIPHCLK_I2C1; 61 PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; 62 PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_SYSCLK; 80
Chapter 4. Implementation 63 PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1; 64 if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) 65 { 66 Error_Handler(); 67 } 68 69 /* Enable Power Control clock */ 70 __HAL_RCC_PWR_CLK_ENABLE(); 71 } Code 4.2: clockConfigAfterStop() This is needed because when the MCU wakes up from stop mode, it defaults to use the MSI source, and this way it is ensured it maintains the clock source and frequency set at the beginning. Although this specificity is common to either application or even coding approach, other methods in the presented modules vary from application to application and from bare-metal approach to RTOS-based approach. Next it is presented the main differences in some of these methods, using the Read&Send application to expose the differences between the bare-metal and the RTOS-based approach, and the Read&Store application to expose the differences between both applications in the bare-metal approach. In order to have different applications for each coding approach without having to create another STM32CubeMX project a git repository was used. This way, not only it was possible to keep versions of each application, but by branching the source code, it was possible to have different source codes linked to the same STM32CubeMX project, since the configurations would be identical. 4.2.1 Read&Send This is the simplest and with the least resource usage application so it is ideal to start exploring the NB-IoT technology. Once a bare-metal version was implemented, it was possible to migrate it to FreeRTOS. Next, the main differences between both versions applied on Custom Board v1 are described. Code for the NOS Board will not be disclosed, because it was made having in mind the specific hardware characteristics of the board, which were not explored with such depth. However, the versions of the Read&Send application here presented reutilize most of the code from that first stage of implementation, only adapting to the hardware characteristics of the Custom Board v1. Each module has its particularity since implementing a FreeRTOS version from a bare-metal modular application has its challenges. The focus was to reuse as much code as possible between the two approaches. 81
4.2. Software Main In a bare-metal application, the while(1) loop in the main function is where all the action happens. Code 4.3 exposes the process before entering this loop, as it is necessary to prepare the end device for the repetitive task ahead. 1/* MCU Configuration --------------------------------------------------------*/ 2 3/* Reset of all peripherals , Initializes the Flash interface and the Systick. */ 4HAL_Init(); 5 6/* USER CODE BEGIN Init */ 7 8/* USER CODE END Init */ 9 10 /* Configure the system clock */ 11 SystemClock_Config(); 12 13 /* USER CODE BEGIN SysInit */ 14 initializeSystem(); 15 /* USER CODE END SysInit */ 16 17 /* Initialize all configured peripherals */ 18 MX_GPIO_Init(); 19 MX_I2C1_Init(); 20 MX_LPTIM1_Init(); 21 MX_RTC_Init(); 22 MX_TIM6_Init(); 23 MX_USART2_UART_Init(); 24 MX_USART1_UART_Init(); 25 /* USER CODE BEGIN 2 */ 26 27 #ifdef DEBUG_EN 28 initializeDebug(); 29 transmitInfo("Debug Enable"); 30 #else 31 HAL_GPIO_TogglePin(GPIOA , GPIO_PIN_9); //startup - init 82
Chapter 4. Implementation 32 #endif 33 34 initializeSensors(); 35 if (getSensorsEnabled()>0){ 36 configSensors(); 37 } 38 #ifdef DEBUG_EN 39 else { 40 transmitInfo("Sensors: error initializing"); 41 } 42 #else 43 HAL_GPIO_TogglePin(GPIOA , GPIO_PIN_9); //init - config 44 #endif 45 46 initializeModem(); 47 48 if (configModem() != SUCCESS){ //couldn't configure modem 49 50 #ifdef DEBUG_EN 51 transmitInfo("Modem: configuration error"); 52 transmitInfo("System: enter standby"); 53 #endif 54 powerOffModem(); //turn off modem 55 enterStandby(); 56 } 57 58 #ifdef DEBUG_EN 59 transmitInfo("Modem: checking connection..."); 60 #else 61 HAL_GPIO_TogglePin(GPIOA , GPIO_PIN_9); //config - checking connection 62 #endif 63 if(checkConnectionStatus() != C_STATUS_RHN){ //couldn't connect in given time 64 powerOffModem(); //turn off modem 65 enterStandby(); //enter standby mode to save energy 66 } 67 68 if(setPowerSavingConfigs() != SUCCESS){ //couldn't configure PSM settings 69 powerOffModem(); //turn off modem 83
4.2. Software 70 enterStandby(); //enter standby mode to save energy 71 } 72 73 // tries = 5; 74 // while(checkServerConnection(SERVER) != SUCCESS && tries >0){ 75 // tries --; 76 // startTimer(); 77 // while (!timeout_flag); //wait for timeout 78 // } 79 // if (tries == 0){ //couldn't connect in given tries 80 // powerOffModem(); //turn off modem 81 // enterStandby(); //enter standby mode to save energy 82 // } 83 // 84 #ifndef DEBUG_EN 85 HAL_GPIO_TogglePin(GPIOA , GPIO_PIN_9); //checking connection - connected 86 #endif 87 tries = 5; 88 while(sendInitInfo()==FAILURE && tries >0){ 89 repairServerConnection(); 90 tries --; 91 } 92 if (tries == 0){ //couldn't connect in given tries 93 powerOffModem(); //turn off modem 94 enterStandby(); //enter standby mode to save energy 95 } 96 97 data_go=1; 98 99 #ifdef DEBUG_EN 100 transmitInfo("Entering while"); 101 #endif 102 status=msg_rcv; 103 /* USER CODE END 2 */ Code 4.3: Execution flow before infinite loop of bare-metal main function The execution flow presented respects the flowchart already seen in the previous chapter. It starts with the system initialization, where most of the peripheral and low level initializations are generated by the STM32CubeMX tool, leaving the initializeSystem() on line 14 for the low power specific initialization, 84
Chapter 4. Implementation that is not performed by STM32CubeMX. Next it initializes the debug interface, but only if debug is enabled, using the DEBUG_EN macro. The advantage of using a macro for a functionality like such is that this code is not compiled and present at the object file if it is not defined, thus reducing the code size when this functionality is not needed. Going back to the application flow, the sensors are initialized and configured, followed by the modem (lines 34 through 56). After all configurations are done it is necessary to check if the modem could connect to the network and, if affirmative, set the given power saving configurations. Commented out is a procedure to check if the server connection is established, which for test purposes was not performed. If all goes right, it is then time to send the initial information right before preparing to enter the infinite loop. This loop is presented in code 4.4, where four if clauses dictate the execution flow of the end device. 1/* Infinite loop */ 2/* USER CODE BEGIN WHILE */ 3while (1) 4{ 5if (msg_rcv != status){ 6status++; 7parseMessage(); 8} 9#ifdef DEBUG_EN 10 if (dmsg_rcv){ 11 dmsg_rcv = 0; 12 processDebugMessage(); 13 status=msg_rcv; 14 } 15 #endif 16 if ( data_go){ 17 data_go = 0; 18 19 sendDataInfo(); 20 21 #ifndef DEBUG_EN 22 HAL_GPIO_TogglePin(GPIOA , GPIO_PIN_9); //connected - transmit all packets / wake -up - transmit data packects 23 #endif 24 status=msg_rcv; 25 } 26 if (incoming_flag){ 85
4.2. Software 10 11 xTaskCreate(vSensorsInit ,"Sensors Init",64,NULL ,SENSORS_PRIORITY ,& sensorInit_h); 12 13 return; 14 } Code 4.11: initializeSensors() In order to maintain the compatibility with the sensors drivers, no further alterations were made on this module from one version to the other. As it will be explained shortly, the other changes needed to ensure the sensors-related FreeRTOS functionality were made in the low level module. System The system module is responsible for managing the RTC and the power. In the bare-metal version, controlling the power of the system is straightforward, being the functions enterStopMode and enterStandby enough to do exactly what their name says. When using FreeRTOS, this power management is not that simple, since it is necessary to have into account the scheduler operations. Fortunately, FreeRTOS source code already offers methods to use low power features through macros and weak defined functions. These weak defined functions were redefined in the system module, so that the stop mode could used. Then, comparing to the bare-metal version, three more functions were added to this module: • PreSleepProcessing – which in this case only makes sure the stop mode is entered; • PostSleepProcessing – which performs the post sleep operations seen earlier in this subsection; • vPortSuppressTicksAndSleep – which performs all the necessary steps to safely stop the scheduler and put the MCU into sleep mode. The latter is intrinsically called from the FreeRTOS idle task when the expected idle time (time for the next task to be ready for execution) is greater than an user defined threshold. All these mechanisms are generated by STM32CubeMX, but the redefinition of these functions ensure that the FreeRTOS response is as intended by the application developed, since the weak defined code is rewritten whenever a new code generation is solicited on the STM32CubeMX tool. 92
Chapter 4. Implementation In this case, to ensure the desired response of the system, some of the initial code from the weak defined vPortSuppressTicksAndSleep function was commented out, since it is prepared to enter other shallow sleep modes as well, which are not wanted. Low Level In the low level module, the changes from the bare-metal to the FreeRTOS version are mostly related to the interrupt callbacks. For instance, the UART receive callback is simplified with the use of the modem receive queue (FreeRTOS version), instead of the modem receive buffer (bare-metal version) (check code snippet 4.12 for FreeRTOS version and code snippet 4.13 for bare-metal version). 1��� 2if(mRx_buffer[mRx_index]=='\n' && mRx_index >=2) { //last '\n' indicating end of response 3mRx_buffer[mRx_index] = '\0'; 4xQueueSendToBackFromISR(xModemRxQueue ,mRx_buffer ,NULL); 5mRx_index=0; 6} Code 4.12: UART modem receive callback detail (FreeRTOS version) 1��� 2if(mRx_buffer[msg_index][mRx_index]=='\n' && mRx_index >=2) { //last '\ n' indicating end of response 3mRx_buffer[msg_index][mRx_index] = '\0'; 4msg_index++; //change index 5msg_index &=0xF; //keep message index inside limits 6mRx_index=0; 7msg_rcv++; 8} Code 4.13: UART modem receive callback detail (bare-metal version) As mentioned before, some of the functions that have great impact in the sensors module are read- Sensor and writeSensor . These functions suffered the most changes on this low level module, as they would only call for the HAL I2C specific functions in the bare-metal version, but in the FreeRTOS version they have to manage the sensors receive and transmit semaphores because it cannot wait blocking for a response. Codes 4.14 and 4.15 expose the writeSensor function in bare-metal and FreeRTOS version, respectively. 93
4.2. Software 1����� 2void writeSensor(uint8_t peripheral ,uint16_t address , uint8_t* data, uint8_t size){ 3 4HAL_I2C_Master_Transmit(&hi2c1 ,address ,data ,size ,1000); 5} Code 4.14: writeSensor() (bare-metal version) 1����� 2uint8_t writeSensor(uint8_t protocol , uint16_t address , uint8_t* data , uint8_t size){ 3 4uint8_t tries=0; 5 6do{ 7HAL_I2C_Master_Transmit_IT(&hi2c1 ,address ,data ,size); 8 9if (xSemaphoreTake(sTxSemaphore ,TIMEOUT_U) == pdFAIL){ //waits ( blocking calling task) for end of transmission. 10 tries++; //If it takes too long, count it as a failed try 11 } 12 else{ 13 return SUCCESS; 14 } 15 }while (tries < TRIES); 16 17 return FAILURE; 18 } Code 4.15: writeSensor() (FreeRTOS version) Other interrupt callbacks such as the sensors GPIO and RTC only have to change from setting a flag (bare-metal version) to giving a semaphore or task notification. When comparing both versions in a measurable manner, the code size and memory allocation are the metrics to use. When compiling with Keil µVision, information about these metrics are given by four different components (Arm Limited, 2007): • Code – code size and inline data, such as short strings. It goes into the flash ROM; • Read-Only (RO) – read-only data. It goes into the flash ROM; 94
Chapter 4. Implementation • Read-Write (RW) – read-write data. It goes into the flash ROM, but is later copied into RAM. • Zero-Initialized (ZI) – zero-initialized data. It is allocated in RAM Then the total used flash space is calculated by adding up the code, RO-data and RW-data. For the MCU chosen for the Custom Boards, this limit is 64 kB. To calculate the RAM space needed it is necessary to add both RW-data and ZI-data, which cannot surpass 20 kB. Table 4.1 presents the values for the four components explained, comparing the two versions of the application Read&Send without debug functionality. The code overhead introduced by the FreeRTOS can be easily observed, having a difference of almost 9000 Bytes on the code size. Also the memory allocation needed to run the application with FreeRTOS is much more expressive than with the simple bare-metal version, due to stack allocation. This is a potential problem for further development, as it is closer to reach the limit for the chosen MCU. Table 4.1: Code size and memory allocation in bytes for each version of Read&Send application Code RO RW ZI Total ROM Total RAM Bare-Metal 31444 324 28 4324 31796 4352 FreeRTOS 40000 364 216 14832 40580 15048 4.2.2 Read&Store The Read&Store application is a bit more complex and allowed to restructure some modules implemented for the Read&Send application. Since many modules remained unchanged, only the main differences are going to be examined next. In order to compare both applications, only a bare-metal version was implemented. In general, two big changes were made: the sensors structure was extended so it could store more data in between sending time, and the transmission module was totally remolded and specific datagrams were created. This last change could also be applied to the Read&Send application with minor changes, as it only makes the transmission management more flexible and clean. Some structures created to extend the general sensors structure become common to both sensors and transmission module, because of the specific datagrams created. Therefore, they were include in a common file named ”aux_type.h” and can be seen in code 4.16. 1typedef enum ValueType{UINT8_T , UINT16_T , UINT32_T , UINT64_T , INT8_T , INT16_T , INT32_T , INT64_T , VOID_T} valuetype_t; 2 95
4.2. Software 3typedef struct unit{ 4int32_t value; 5valuetype_t type; 6}unit_t; 7 8typedef struct datavalue{ 9unit_t min; 10 unit_t max; 11 unit_t avg; 12 }datavalue_t; 13 14 typedef struct sensordata{ 15 char sensor_name[5]; 16 datavalue_t samples[MAX_N_SAMPLES]; 17 uint8_t n_sample; 18 }sensordata_t; Code 4.16: Auxiliary structures for Read&Send application Besides being developed to add extra functionality to the sensors, these structures also consider the data processing needed to serialize a datagram with msgpack . Thus the introduction of the structure typedef unit_t, which can fit up to a 32-bit value (232 −1positive value, or 231 −1positive or negative value), but it is the valuetype_t field that dictates how the value will be interpreted when serializing it. Sensors As it would be expected, this module suffered the most changes and additions. Starting with the sensors structure, code 4.17 and code 4.18 allow to observe some of the changes between the Read&Send implementation and the Read&Store implementation respectively. 1typedef struct sensor{ 2uint8_t config[64]; 3uint8_t name[32]; 4int16_t data[8]; 5uint8_t units[8]; 6uint8_t address; 7uint8_t protocol; 8uint8_t status; 9uint8_t data_status; 96
Chapter 4. Implementation 10 }sensor_t; Code 4.17: Sensors structure of Read&Send application 1typedef struct sensor{ 2uint8_t config[64]; 3uint8_t model[16]; 4uint8_t type[9]; 5 6void* data[4]; 7uint8_t units[8]; 8 9uint8_t protocol; 10 uint8_t status; 11 12 uint16_t period; 13 uint8_t counter; 14 uint8_t counts; 15 }sensor_t; Code 4.18: Sensors structure of Read&Store application Besides cleaning some of its fields and changing the data field so it could support a structure of type sensordata_t, some other fields were added related to the sampling period. The period field saves the sampling period in seconds of the sensor. Since there can be different sampling periods among the sensors, and in order to normalize the sampling process, all periods are calculated as multiples of the minimum sampling period, thus the use of two additional fields counter and counts . The former saves the current count of the minimum period and the latter is the desired number of counts to achieve the sampling period of given sensor. When it comes to the common implementation, the initialization changes a little bit, since it is necessary to fill all these new fields. This way, an implementation like the one presented in code 4.19 becomes something like the one presented in code 4.20. 1#ifdef ACC_EN 2 3strcpy((char*)acc.name , "acc - bma400"); 4 5strcpy((char*)acc.units , "mg"); 6 7acc.address = BMA400_ADDRESS; 97
4.2. Software 8 9acc.protocol = I2C_1; 10 11 acc.data_status = OLD_DATA; 12 13 if (initAcc(acc.protocol) != OK) acc.status = INACTIVE; 14 else { 15 sensors[n_sensors] = &acc; 16 n_sensors++; 17 acc.status = ACTIVE; 18 } 19 20 #endif Code 4.19: Accelerometer initialization of Read&Send application 1#ifdef ACC_EN 2strcpy((char*)acc.model , ACC_MODEL); 3strcpy((char*)acc.type , ACC_TYPE); 4strcpy((char*)acc.units , "mg"); 5 6acc.protocol = I2C_1; 7 8if (initAcc(acc.protocol) != OK){ 9acc.status = INACTIVE; 10 } 11 else{ 12 sensors[n_sensors] = &acc; 13 14 sensors[n_sensors]->data[ACCX] = initSimpleSensorData(ACCX_STRING); 15 sensors[n_sensors]->data[ACCY] = initSimpleSensorData(ACCY_STRING); 16 sensors[n_sensors]->data[ACCZ] = initSimpleSensorData(ACCZ_STRING); 17 18 n_sensors++; 19 acc.status = ACTIVE; 20 } 21 #endif Code 4.20: Accelerometer initialization of Read&Store application The initSimpleSensorData is an inline function to initialize each data field of the sensor structure. Its 98
Chapter 4. Implementation implementation can be seen in code 4.21 below. Considering that the accelerometer has three variables to read, three sensordata_t positions of the variables_data array are taken. The datavalue_t samples min and max are initialized with type VOID_T, since those fields are not going to be used in simple samples manipulation. 1static inline sensordata_t* initSimpleSensorData(char *sensor_name){ 2uint8_t i; 3 4/*Set the min and max type in samples array*/ 5for(i=0; i<MAX_N_SAMPLES; i++){ 6variables_data[variable_index].samples[i].min.type = VOID_T; 7variables_data[variable_index].samples[i].max.type = VOID_T; 8} 9 10 /*Set sensor name string*/ 11 strcpy(variables_data[variable_index].sensor_name , sensor_name); 12 13 /*Return the variables_data index modified*/ 14 return &variables_data[variable_index++]; 15 } Code 4.21: initSimpleSensorData() method of Read&Store application Other inline function was implemented for initializing sensor data on which a average calculation is going to be performed, initMeanSensorData (see code 4.22). It is used for sensors that need to control the number of samples taken in order to periodically calculate their average, while saving the maximum and minimum value observed. 1static inline sensordata_t* initMeanSensorData(char *sensor_name , uint8_t mean_limit , 2int32_t init_min_value , uint32_t init_max_value){ 3 4 5/*Set the type of the control data to VOID_T*/ 6variables_data[variable_index].samples[MEAN_CONTROL_INDEX].min.type = VOID_T; 7variables_data[variable_index].samples[MEAN_CONTROL_INDEX].max.type = VOID_T; 8variables_data[variable_index].samples[MEAN_CONTROL_INDEX].avg.type = 99
4.2. Software VOID_T; 9 10 /*Clean control variables sum and counts and set counts limit*/ 11 variables_data[variable_index].samples[MEAN_CONTROL_INDEX].min.value = 0; //used to store the samples count 12 variables_data[variable_index].samples[MEAN_CONTROL_INDEX].max.value = mean_limit; //used to store the limit for samples count 13 variables_data[variable_index].samples[MEAN_CONTROL_INDEX].avg.value = 0; //used to store the samples sum 14 15 /*Reset the min and max values of the samples array first position*/ 16 variables_data[variable_index].samples[0].min.value = init_min_value; 17 variables_data[variable_index].samples[0].max.value = init_max_value; 18 19 /*Set sensor name string*/ 20 strcpy(variables_data[variable_index].sensor_name , sensor_name); 21 22 /*Return the variables_data index modified*/ 23 return &variables_data[variable_index++]; 24 } Code 4.22: initMeanSensorData() method of Read&Store application On other common functions such as getSensorsEnabled , readSensors , and getSensorsData their purpose was slightly altered. getSensorsEnabled besides returning the number of sensors enabled like in the Read&Send application, it also returns a string and its length with the type of the sensors enabled, depending if the destination string provided is valid (not null) or not, respectively. readSensors is still used to read all sensors at once, but in Read&Store application this is only used when there is a sensor interrupt. getSensorsData returns the last read data using the readSensors function. In Read&Send application, the data is stored in the array inside each sensor structure and is returned in a single string. However, in Read&Store application the data is stored in the read_data array, which pointer is returned along with the number of datavalues available. Transmission The biggest change in the transmission module was the change of concept regarding the datagrams. In Read&Send application, there was only two types of datagrams: configurations and data, both strings. Each datagram was created and sent by their specific functions. When updating to Read&Store application, 100
Chapter 4. Implementation an additional datagram was added: emergency. Instead of creating another function, the solution was to merge the datagrams creation into one single function. The datagrams creation also suffered modifications, taking more advantage of the msgpack serialization and becoming an array of values. This allowed to better organize the datagram information and save some payload size, but it still has to be transformed into hexadecimal characters in order to be sent over the modem. To simplify the information acquisition and datagram construction, three structures were created and can be seen in code 4.23. 1struct config{ 2id_t dev_id; 3timestamp_t msg_timestamp; 4string_t sensors_enabled; 5string_t modem_config; 6uint16_t sensors_periods[MAX_SENSORS]; //up to 8 sensors 7}; 8 9struct emergency{ 10 id_t dev_id; 11 timestamp_t msg_timestamp; 12 uint8_t emergency_flag; 13 datavalue_t *values; 14 uint8_t n_values; 15 }; 16 17 struct regular{ 18 id_t dev_id; 19 timestamp_t msg_timestamp; 20 datavalue_t signal_condition; 21 sensordata_t *sensors_data; 22 uint8_t n_sensors; 23 }; Code 4.23: Datagram structures of Read&Store application The msgpack serialization was implemented by hand in both applications in order to save some code overhead. Codes 4.24 and 4.25 oppose the process of serializing the modem configuration string into datagram for the Read&Send and Read&Store applications, respectively. 1/*Construct datagram for modem configuration*/ 2datagram[MSGPACK_DATA]='\0'; 101
5.1. Experimental Setup The main difference resides on the temporal resolution achieved, but reducing the integration time also reduces the sample resolution, from 0.7 ppm of range to 3 ppm of range (Keysight Technologies, 2016). Figure 5.2: Keysight 34410A 61 /2-digit high performance DMM In order to measure the current consumption of the device under test the power supply was directly connected to the positive input of the DMM and its ground output connects to the power supply pin of the DUT with a crocodile clip. 5.1.3 Oscilloscope The oscilloscope model chosen from the available ones at the laboratory was the Tektronix MDO3012 Mixed Domain Oscilloscope (figure 5.3). It has two analog channels with 100 MHz bandwidth and possibility to sixteen digital channels. Its sample rate can reach up to 2.5 GS/s with a record length of 10 Million samples (Tektronix, 2012). Figure 5.3: Tektronix MDO3012 mixed domain oscilloscope 108
Chapter 5. Tests and Results Since it was only used to register the software timings of the execution, outputted on an accessible GPIO, one simple test probe was enough to acquire the data. The samples and time of acquisition were matched with the ones capable by the DMM so that it could be easier to process and match the execution time. Figure 5.4 shows a picture of the experimental setup assembled in the laboratory. All measurements were performed under the same conditions. Because it is relevant for the signal condition, the laboratory is located below ground level, away from windows and with many other instruments working nearby. This experimental setup is also useful to prove the indoor coverage promised by the NB-IoT standard. Figure 5.4: Experimental setup assembled 5.2 Current Consumption Measurements Current consumption measurements were performed throughout almost every stage of the development. It was used not only as a debug tool for the hardware and software, but also for comparing the solutions designed and choices made. Because of that, the results here presented mostly oppose different implementations phases or design choices, highlighting their effect on the current consumption and consequent power consumption. 109
5.2. Current Consumption Measurements 5.2.1 NOS Board versus Custom Board v1 As mentioned before, the starting point of the implementation was on a development board from NOS, allowing to understand how to use NB-IoT and how to apply it with a simple monitoring application. After understanding both hardware and software necessary to make it work, a custom board was designed to meet the specificities of the use case in hands. In order to check the improvement achieved in terms of current consumption on this step, measurements were made with the NOS Board and with the Custom Board v1 running the same application (adapted to each hardware, as co-design demands). It simply runs an early stage Read&Send application, were the sleep phase is not executed by the modem, as it wasn’t possible to make the BC68 in the NOS Board enter PSM. The results can be seen in figure 5.5. They were obtained with the 10000 samples settings with a range of 1 A so it could catch the peaks of current caused by the communication link. Both boards ran the application at 1.048 MHz, with a ten seconds interval between messages sending, where the MCU enters stop mode, but both sensors and modem are functioning normally. The red line represents the average current consumption of the whole 40 seconds of measurement. Figure 5.5: Current consumption graphics – NOS Board and Custom Board v1 The difference in current consumption can be directly observed from the graphics, highlighting two major behaviors: on one side, the NOS Board’s current consumption seems to have a fixed value around the 25 mA, which can be due to all the electronic components it has including the voltage regulators; on the other side, the Custom Board v1’s current consumption presents peaks with higher amplitude at the 110
Chapter 5. Tests and Results transmission phase. Table 5.1 presents the average values calculated over the 40 seconds execution, as represented by the red line in the graphics above. It also presents the difference from one solution to the other. This means that implementing the same application in the first custom hardware designed already saves, on average, 25 mA. Table 5.1: Average current consumption related to the graphics in figure 5.5 NOS Board Custom Board v1 Difference Average Current (mA) 35.283 9.785 25.498 Worth mentioning that this was a comparison made at an early stage of implementation, and many design choices weren’t even applied, so it was possible to reduce even more the current consumption from here. It was, however, a good indicator for what was being developed. 5.2.2 Understanding the Current Consumption Profile for Read&Send Application Before analyzing the current consumption of the various design choices made, first it is best to better understand the current consumption profile of the Read&Send application. This was the application used to validate most of the design choices made within the Custom Board v1. Figure 5.6 shows the current consumption profile for this application, when running at 1.048 MHz with a ten seconds interval between messages’ transmission. This measurement was taken from circuitry test point 2, presented in figure 4.4. The colored vertical lines are traced based on the timings obtained with the oscilloscope, marking the different parts of the application. From the beginning up until the first dashed line it is the system initialization. It does not take all that time to initialize, it is just that the DMM start measuring some time before the DUT starts running. Between this vertical dashed line and the dark blue one it is initializing both modem and sensors, checking if everything is responsive and working properly. Then it configures the modem before it connects to the network, delimited by the two blue vertical dashed lines. From the light blue line until the green one, the device is waiting for the modem to connect to the network. This time can vary on each attempt, from a few seconds to some minutes, depending on signal quality and network availability. After connected, the device prepares and sends the initial configurations datagrams and the first 111
5.2. Current Consumption Measurements Figure 5.6: Read&Send current consumption graphic - Custom Board v1 @ 1.048 MHz sensors’ data datagram before entering stop mode. This is limited by the green and first yellow line, marking the end of the initialization of the system. From here, the device is up and running its cyclic task of sleeping and waking up to read and send the sensors’ data. For these run tests, the sleep time was only ten seconds. After, only three available sensors are read and the datagram is prepared and sent, making it possible to put the device to sleep right after. 5.2.3 MCU Clock Frequency Selection One of the first and most important comparisons made was the impact of the system’s clock frequency on the overall performance and current consumption. For this, the same application was run with the same configurations, except for the system’s clock frequency. The timings remained the same, it still slept for ten seconds between each message’s transmission. Already preparing the next major comparison, both bare-metal and RTOS approach were used to measure the current consumption with different clock frequencies. Figure 5.7 presents the current consumption graphics of four different clock frequencies measured. From slower to faster, these measurements were also taken from circuitry test point 2 with the 10000 samples DMM settings. For the 1.048 MHz run, the range used was 1 mA, for the others a 10 mA range was needed to accurately measure the current consumption. 112
Chapter 5. Tests and Results Figure 5.7: Current consumption graphics – Bare-Metal MCU clock frequencies Table 5.2 gathers the results for the average current consumption and execution time calculated from the cyclic task. Since the initial tasks can have different timings (due to the establishment of connection with the network) and do not repeat themselves as frequently, their consumption was not considered for these calculations. Only the repetitive task of reading and sending the sensors’ data is considered because of its high impact on the long run operation of the device. Table 5.2: Average current consumption and execution time related to the graphics in figure 5.7 1.048 MHz 4.194 MHz 16 MHz 32 MHz Average Current (mA) 0.27506 1.0537 4.9571 8.3573 Average Execution Time (s) 2.2427 2.1110 2.0711 2.0691 From the graphics in figure 5.7 it was already visible the difference in current consumption, but the timings were a little imperceptible to grasp the real impact. The values on table 5.2 allow better understanding the performance increase that a faster clock frequency gives. Between running the application at 1.048 MHz or at 32 MHz, the latter improves execution time by almost 10% of the former, but the current consumption is increased by 30 times. Even considering the lowest clock frequencies measured in this test, running the system at 4.194 MHz only improves execution time by 6% compared to running at 1.048 MHz for an increase of 3.8 times in current consumption. Later on this section the impact these small differences have in the battery lifetime will be detailed. 113
5.2. Current Consumption Measurements To check if the system’s clock frequency has an equal impact on the RTOS approach, the same procedure was made. Measurements for the same four clock frequencies were taken, the sleep time was kept at ten seconds and no additional tasks are performed. Figure 5.8 presents the current consumption graphics for the same four clock frequencies previously analyzed. As of before, the measurements were taken from the circuitry test point 2, on the 10000 samples setting. The range was set to 1 mA for the 1.048 MHz test run, and 10 mA for the others, just like before. Figure 5.8: Current consumption graphics – FreeRTOS MCU clock frequencies Table 5.3 gathers the results for the average current consumption and execution time calculated from the cyclic task for this approach. The same principle was applied regarding the exclusive consideration of the reading and sending task. Table 5.3: Average current consumption and execution time related to the graphics in figure 5.8 1.048 MHz 4.194 MHz 16 MHz 32 MHz Average Current (mA) 0.28016 1.1045 5.0938 8.5614 Average Execution Time (s) 2.4223 2.2287 2.1868 2.1829 Similar to the bare-metal’s results, the difference in current consumption for the four clock frequencies considered is notorious in the graphics of figure 5.8, as well as the unclear difference in the execution time. Table 5.3 confirms the similarities in both average current consumption and execution time. With this approach, running the application at 32 MHz also improves the execution time by 10% in 114
Chapter 5. Tests and Results relation to running at 1.048 MHz, and increases the current consumption by 2900%. Although when comparing the lowest clock frequencies measured it shows an improvement of 8% by running at 4.194 MHz instead of 1.048 MHz, it also increases the current consumption by 294%. Based on both results, it is clear that whichever approach used, the higher the clock frequency chose, the higher its current consumption, without significant improvement of the overall performance. This influenced the next measurements comparisons, as they were all taken at 1.048 MHz frequency clock. 5.2.4 Bare-Metal versus RTOS In order to compare the bare-metal approach to the freeRTOs approach developed, previously used graphics were re-analyzed. Then, the graphics for the system’s clock frequency of 1.048 MHz were chosen for both bare-metal and FreeRTOS approaches and put together as shown in figure 5.9. Here, the red line marks the average current consumption calculated before, and the dashed vertical lines emphasize the difference in time for the modem to connect to the network. This delay is not related to the approach used. Figure 5.9: Current consumption graphics – Bare-Metal and FreeRTOS Table 5.4 gathers the average current consumption and execution time from the previous tables and exposes the difference between both approaches. It also adds the average sleep current consumption for later use. 115
5.2. Current Consumption Measurements Table 5.4: Average current consumption and execution time related to the graphics in figure 5.9 Bare-Metal FreeRTOS Difference Average Sleep Current (µA) 23.988 22.483 1.5 Average Active Current (µA) 275.06 280.16 5.1 Average Execution Time (s) 2.2427 2.4223 0.1796 Although the difference was almost undetectable by just observing the graphics, it is there and proves that the bare-metal approach not only executes faster than the FreeRTOS approach, but also consumes less current while doing it. Allied with the memory footprint the FreeRTOS already presented (please see table 4.1), it was not favorable to continue the use of the FreeRTOS approach, so further measurements were taken with the device running the bare-metal approach at 1.048 MHz. 5.2.5 Impact of Low-Power Features As mentioned before, this MCU was chosen not only for its small footprint and microprocessor, but also because of the low-power features it has available. For example, the stop mode allows drastically reducing the current consumption when the MCU does not need to perform any task, as seen in the previous graphics. Besides the stop mode, this MCU also allows changing the core voltage, being presented as one of the most relevant low power features. To better understand the impact that this feature has on the active period of execution, test runs were made with and without it. Figure 5.10 shows the current consumption graphics of running the Read&Send application with and without the specified low-power feature. On the right, the core voltage was at 1.2 V while on the left the core voltage was at the 1.8 V supplied. Both measurements were taken with the 10000 samples settings and 1 mA range from the circuitry test point 2. The red line marks the average current consumption of the cyclic task. 116
Chapter 5. Tests and Results Figure 5.10: Current consumption graphics – Low-power feature impact The difference here is much more visible, which indicates a significant impact on the current consumption. Table 5.5 provides the values calculated based on the graphics shown. Table 5.5: Average current consumption and execution time related to the graphics in figure 5.10 Low Power No Low Power Difference Average Current (µA) 275.06 364.36 89.3 Average Execution Time (s) 2.2427 2.2407 0.002 This specific low-power feature of running the core at a different voltage from the supplied one can save almost 90 µA, which can seem whimsy considering the units in use – 10−6A –, but on a battery powered device it can make a huge difference in its longevity, as will be exposed later on this chapter. This corresponds to a decrease of 24% in current consumption. Of course the cost for this decrease in current consumption is slower execution time, but it is not significant, as it only slows down less than 0.01% when comparing to not using the low-power feature. Out of curiosity, when running at 4.194 MHz, instead of the 1.048 MHz presented, this feature can save up to 345 µA, which is practically the same 24% saved in current consumption. 117
5.2. Current Consumption Measurements reflects the whole ative period, and it is not limited only by the transmission phase, as it was not possible to pinpoint it exactly in modem execution. The idle average current consumption was also above the expected value by double, for which there is no obvious explanation. Since it is in a periodic reachable state, the higher current consumption can be justified by the poor quality signal as well, but there is not a clear indication of this in the datasheet. The one mode that is independent of the signal quality is indeed the PSM, which current consumption is as expected and very promising to enhance the battery lifetime. 5.2.9 TCP versus UDP The current consumption measurement and comparison between using UDP and TCP as the transmission protocol is not as straightforward as other measurements and comparisons. It involves external factors such as network congestion and signal quality which makes it impossible to compare results obtained with simple acquisitions as the ones made for the context of this dissertation. Therefore, for the results exposed in this section the application was using the UDP transmission protocol not because it was the best solution, but because it was the simplest. Additional tests must be performed to assess packet loss ratio and transmissions time in order to properly compare these two transmission protocols and choose the most suitable for the application in hands. 5.2.10 Understanding the Current Consumption Profile for Read&Store Application Before opposing the two applications developed, it is best to better understand the Read&Store application’s current consumption profile. This was an improvement on the functionality of the system and is relevant to analyze its impact on the current consumption of the whole system. Figure 5.15 shows the current consumption profile for this application, when running at 1.048 MHz with two sensors sampling every 5 seconds, and another sensor sampling every 10 seconds. The sensors’ data is sent after 20 seconds. This measurement was taken from the circuitry test point where only the MCU and the sensors’ current consumption is measured. The colored vertical lines are traced based on the timings obtained with the oscilloscope, marking the different parts of the application. 124
Chapter 5. Tests and Results Figure 5.15: Read&Store current consumption graphic - Custom Board v1 @ 1.048 MHz This application starts just like the Read&Send one, so the time from the beginning up until the first line is the time it takes initializing the system. Between that line and the blue one is where it initializes both sensors and modem. It is not clear in the graphic, but there are two blue lines limiting the configuration process of the modem. Then, until the green line the modem is just trying to connect. After successful connection to the network, it starts the sensors sampling period, and prepares and sends a single configuration packet before entering stop mode – between the green and yellow lines. Now it wakes up periodically to read and store the sensors’ data, indicated by the pink lines. The second reading, after ten seconds, takes longer because it has to read the three sensors in one take. When the twenty seconds period for sending ends, it wakes up again to prepare and send the sensor’s data collected so far. The time it takes is limited by the orange and yellow lines, so it is possible to see that a request to sample the sensors was triggered when it was still preparing the packet, so the sensors were only read after that. 5.2.11 Read&Store versus Read&Send The Read&Store application brings more data resolution without adding extra communications, this can be an important upgrade to the use case, but it is necessary to better understand the differences it has when compared to the simpler application of reading and sending immediately. For comparison, both applications have a 20 seconds interval between messages’ transmission, the only diference is the timing 125
5.2. Current Consumption Measurements of sensors’ data reading. The Read&Send reads the sensors right before sending their data, this means that it can only send a set of data every 20 seconds, referring to the time of sending. The Read&Store reads the sensors more periodically, storing and processing the data, so when it is time to send it, it is already a collection of data, on which average, maximum and minimum values can be calculated and sent. Figure 5.16 shows the graphics from the Read&Send and the Read&Store applications’ current consumption, both measured on the Custom Board v1, at 1.048 MHz with the 50000 samples settings and 1 mA range. The dashed vertical lines indicate the time it took for the modem to connect to the network. Figure 5.16: Current consumption graphics – Read&Send and Read&Store The graphics are visually different, so it makes it difficult to compare them. What stands out more is the frequent sampling of the sensors in comparison with the stable current consumption in the Read&Send application. Table 5.10 gathers the average current consumption and execution time of both applications. For the Read&Send it refers to the wake up, read sensors, and send data phases. For the Read&Store it compiles the multiple times it reads the sensors before sending the data collected as well as the transmission process, therefore posterior sensor readings are not considered in the calculations, sleep time between readings does not count either. 126
Chapter 5. Tests and Results Table 5.10: Average current consumption and execution time related to the graphics in figure 5.16 Read&Send Read&Store Difference Average Current (µA) 256.93 336.79 79.86 Average Execution Time (s) 4.2452 2.9059 1.3392 Attending the values calculated, there is one evident difference in the consumption, all summed up, the Read&Store application seems to consume almost 80 µA more than the Read&Send one. However, blind comparison in this case is not advisable, because if it were to send the same amount of data with the Read&Send application, it would have to wake up, read, and send data every five seconds, and this simple process for the Read&Send application already takes more than one second more than the Read&Store. In the end, only the calculation of the power consumption will indicate how much prejudice does the Read&Store bring to the overall battery consumption, if any. For further and better use of the current consumption measured, table 5.11 gathers the average current consumption and execution time of each wake up peak for the Read&Store application. Table 5.11: Average current consumption and execution time related to the read&store graphic in figure 5.16 Peak #1 Peak #2 Peak #3 Peak #4 Peak #4.1 Peak #5 Average Current (µA) 410.66 272.23 394.75 269.52 272.61 391.33 Average Execution Time (ms) 9.5774 425.40 11.174 2459.8 438.17 10.376 Peak 4.1 refers only to the sensors’ reading right after the packet was sent 5.2.12 Custom Board v1 versus Custom Board v2 With most hardware design choices sorted out, a second version of the board could be done. Since the Read&Store is a more robust application which can be adapted easier to other use cases, it was the chosen application for comparison between boards. Both boards ran the application at 1.048 MHz with the same type sensors being sampled every 5 seconds and the same type sensor being sampled every 10 seconds, just like the graphic in figure 5.15. Figure 5.17 shows the graphics for the comparison between running the Read&Store application in the Custom Board v1 and running it in the Custom Board v2. Both measurements were taken with a 50000 samples settings and 1 mA range. Custom Board v1 measurement was taken from the circuitry test point 127
5.2. Current Consumption Measurements which allows measuring the MCU and sensors current consumption. Custom Board v2 measured the current consumption of the LDO, MCU and sensors, because there was no circuitry test point to disregard the LDO current consumption. The red lines mark the average current consumption considering all active periods. Figure 5.17: Current consumption graphics – Custom Board v1 and Custom Board v2 One of the main differences observable in the graphics is the position of the red line. Although both graphics are similar, the fact is that there was one sensor change from one board to the other and that is reflected on the periodic sampling current, which decreased significantly. Another relevant fact is that even though the LDO is being considered in the current consumption of the Custom Board v2, it does not seem to have a great impact on it, comparing with the current consumption from Custom Board v1. Table 5.12 gathers the average current consumption for both active and sleep periods, and the average execution time for the active periods summed up. Table 5.12: Average current consumption and execution time related to the graphics in figure 5.17 Custom Board v1 Custom Board v2 Difference Average Sleep Current (µA) 8.4317 5.8096 2.6221 Average Active Current (µA) 336.79 280.79 56.003 Average Execution Time (s) 2.9059 2.8740 0.0319 128
Chapter 5. Tests and Results As observed, the sleep average current consumption on the Custom Board v2 is already 2 µA lower than the Custom Board v1 consumption (when not considering the LDO), and when comparing to the average sleep current consumption verified in table 5.4, which considers the LDO used in the first version board, the difference is considerable: about 17 µA less, which corresponds to a decrease in 75% of the current consumption. As for the active period, which depends on the application in case, the second version board also proves to be more optimized, with about 56 µA less consumption and even 32 ms faster. This translates to a reduction of 17% in current consumption and a 1.1% improvement in execution time when compared to the Custom Board v1. For more detail about the average current consumption and execution time of the individual active periods, table 5.13 can be consulted. Table 5.13: Average current consumption and execution time related to the Custom Board v2 Graphic in figure 5.17 Peak #1 Peak #2 Peak #3 Peak #4 Peak #5 Peak #6 Average Current (µA) 291.27 265.55 289.84 276.54 265.93 299.24 Average Execution Time (ms) 6.3849 416.62 7.1831 2443.0 416.62 5.5868 5.2.13 MCU Clock Frequency Selection Revised The first measurements related to the impact of the clock frequency used were not only to assess the overall performance of the system but also to compare both coding approaches. The fact is that at a clock frequency lower than 1.048 MHz, the FreeRTOS approach could not work due to UART overrun, that incapacitated the MCU of understanding the modem responses. With new hardware and another application, there was still a doubt of how low the clock frequency can be. It turns out that the lowest clock frequency at which the system can run is 524.288 kHz, the value immediately below 1.048 MHz. Lower than this, it can not understand the modem responses due to UART overrun. Figure 5.18 shows the graphics for 524.288 kHz and 1.048 MHz clock frequencies, with the same Read&Store application with two sensors reading every 5 seconds, one sensor reading every 10 seconds and 20 seconds transmission interval. The measurements were taken with 50000 samples settings and 1 mA range. 129
5.2. Current Consumption Measurements Figure 5.18: Current consumption graphics – Revised MCU clock frequencies As expected, reducing the clock frequency also reduces the current consumption in the same proportion. Table 5.14 gathers the average current consumption and execution time for both measurements, considering only the active periods after connected. Table 5.14: Average current consumption and execution time related to the graphics in figure 5.18 524.288 kHz 1.048 MHz Difference Average Active Current (µA) 162.71 280.79 118.08 Average Execution Time (s) 3.0432 2.8740 0.1692 From the values in the table, reducing the clock frequency allows reducing the current consumption by 42% when compared to running at 1.048 MHz, but it also increases execution time by almost 6%. It seems advantageous to run the system at the lowest clock frequency possible, but further analysis on the battery lifetime is going to clear all doubts about the choices made. For further and better use of the current consumption measured, table 5.15 gathers the average current consumption and execution time of each wake up peak for the Read&Store application at 524.288 kHz. 130
Chapter 5. Tests and Results Table 5.15: Average current consumption and execution time related to the 524.288 kHz graphic in figure 5.18 Peak #1 Peak #2 Peak #3 Peak #4 Peak #4.1 Peak #5 Average Current (µA) 174.81 151.54 171.97 152.51 150.36 166.96 Average Execution Time (ms) 12.770 432.58 15.164 2582.7 433.38 11.972 Peak 4.1 refers only to the sensors’ reading right after the packet was sent 5.2.14 Custom Board v2 Overall The overall current consumption of the device can be seen in the graphic of figure 5.19. The measurement was taken with 50000 samples settings and 1 A range, running at 1.048 MHz for 400 seconds. It was sampling two sensors every 25 seconds and one sensor every 50 seconds. The sending interval was 120 seconds. The vertical lines help understand the application timings and are the same as seen and explained in figure 5.15. Figure 5.19: Current consumption graphic – Custom Board v2 It is not possible to see the impact of the MCU and sensors on the overall current consumption because the modem overtakes it completely. This forces the scale to a range where lower current consumption can not be analyzed with precision. Thus, the process of measuring each module individually is what is going to help when calculating an estimation of the power consumption and consequent battery lifetime. 131
5.3. Battery Lifetime Estimation 5.3 Battery Lifetime Estimation In order to facilitate comparisons, the battery lifetime is going to be calculated in terms of days. The equation to get the number of days one battery of given Ccapacity, in mAh, can last with an Avgdaily average daily load, in mAh/day, is given in equation (5.1): days =C Avgdaily (5.1) Now, simply talking, the average daily load is calculated by taking into consideration the time the system is in sleep mode and wake mode during a full day, as given in equation (5.2). Avgdaily =Iwake ∗Twake +Isleep ∗Tsleep (5.2) where Iwake is the average awake current consumed in mA and Twake is the respective time it stays awake during one day, in hours, and Isleep is the average sleep current consumed in mA and Tsleep is the respective time it stays asleep during one day, in hours. For the next comparisons it was considered an use case with two messages’ transmission every day, for both 3.6 V batteries proposed in table 3.4. For a first perspective, the battery lifetime for both NOS Board and Custom Board v1 was calculated based on this simple formula, considering the values presented in table 5.1, obtained from the measurements presented in figure 5.5. Table 5.16 presents the values to use in power consumption calculation for both NOS Board and Custom Board v1. Table 5.16: Values for power consumption calculation - NOS Board and Custom Board v1 NOS Board Custom Board v1 Iwake (mA) 55.729 28.990 Twake (h) 4.3737 ∗2 3600 3.3069 ∗2 3600 Isleep (mA) 24.336 0.3489 Tsleep (h) 24 −4.3737 ∗2 3600 24 −3.3069 ∗2 3600 In 24 hours the system would wake up only two times and the average time it stays awake, from the measurements taken, is 4.3 s, therefore a conversion to hours is needed, dividing by 3600 (1 hour = 60 min * 60 seconds). The remainder of the time, the system is in sleep mode. Table 5.17 presents the average daily power consumption for both cases analyzed, based on equation 132
Chapter 5. Tests and Results (5.2) and the values in table 5.16. The battery lifetime in days for both batteries selected is also presented, calculated based on equation (5.1). Table 5.17: Average power consumption and battery lifetime - NOS Board and Custom Board v1 NOS Board Custom Board v1 Avgdaily (mAh/day) 584.1403 8.4263 Battery Lifetime (days) C = 3600 mAh 6 427 Battery Lifetime (days) C = 5800 mAh 9 688 The first iteration in a co-designed device with COTS components resulted in improving the battery lifetime from a mere week to more than one year. It still was not sufficient to meet the requirements and that is why more optimizations were explored. However, the consumption profile of the device is a little more complex than the ones presented, and in order to compare some minor changes on software and hardware, another method to calculate the average daily power consumption was used. Since the modem’s consumption overlaps the consumption of the other modules, the power consumption, in mAh/day, was calculated in two modules separately, as shown in equation (5.3) Avgdaily =Avgmodem +AvgMCU (5.3) where Avgmodem is given by equation (5.4) and AvgMCU comprises the consumption of the voltage regulator, the MCU and the sensors, which were measured altogether and can easily apply equation (5.2) for its calculation. Avgmodem =Iactive ∗Tactive +Iidle ∗Tidle +IP SM ∗TP SM (5.4) The modem is the device’s module which less changes suffered throughout the design, so its power consumption is going to be calculated next and used on further battery lifetime calculations. The active time and current from figure 5.14 were used. The same 20 seconds idle period was considered and a 12 hours PSM proposed. Table 5.18 presents these values and the resulting average daily consumption of the modem. 133