f1437857/... · 2020. 6. 16. · 7xzexx g[xf\f b.sc mechatronic engineering, 180 credits smart...

71
Degree Thesis HALMSD UNIVERSITY B.Sc Mechatronic Engineering, 180 credits Smart Greenhouse A microcontroller based architecture for autonomous and remote control Degree Project in Mechatronics, 15 credits Oscar Johansson, Gustav Andersson

Upload: others

Post on 29-Jan-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

  • Degree Thesis

    HALMSTAD

    UNIVERSITY

    B.Sc Mechatronic Engineering, 180 credits

    Smart Greenhouse

    A microcontroller based architecture for autonomousand remote control

    Degree Project in Mechatronics, 15credits

    Oscar Johansson, Gustav Andersson

  • Halmstad University

    School of Information Technology

    Smart GreenhouseA microcontroller based architecture for autonomous and remote control

    Author:Johansson, OscarAndersson, Gustav

    Supervisor:Ourique de Morais, Wagner

    A thesis submitted for the degree of

    B.Sc. Mechatronic Engineering

    June 9, 2020

  • Abstract

    Expensive and complex automated systems for greenhouses are frequently utilized in the horticul-ture industry. In parallel, smart systems for home automation has recently seen a rapid increasein popularity. This project aims to combine the climate optimization capabilities of industrial sys-tems with the convenience of home automation systems. More specifically, this project is focusedon the design and implementation of electrical and mechanical requirements of a smart greenhousesystem. This involved the selection of hardware components, such as sensors, actuators and con-trollers. It also involved the interconnection between these components and the development ofmeasurement and control systems to autonomously manage the greenhouse. The system is basedon a WiFi-connected microcontroller. Parameters monitored include; temperature, humidity andwind-speed. Irrigation is controlled by a solenoid valve and can be scheduled to desired intervals.Ventilation and temperature optimization is done by controlling the roof-hatch with a linear ac-tuator and control of a heater. The results demonstrate a accurate and reliable system with lowpower consumption. The resulting prototype can be installed in new and existing greenhouses.Functionalities can be remotely controlled and monitored by the convenience of an android appli-cation. The total cost of the components used was around 4 500 SEK. Further development couldbe done to enable seamless scalability with additional components and functionalities. Climateoptimization by incorporation of weather forecast as a parameter could be implemented to furtherreduce energy consumption.

    Sammanfattning

    Dyra och komplexa automatiserade växthussystem är vanligt förekommande inom industrin förhortikultur. Parallellt har populariteten för "Smart Home" system för hemautomatisering radikaltökat. Målet med detta projekt är att kombinera klimatoptimiseringsmöjligheterna hos indus-triella system med lättanvändligheten hos system för hemautomatisering. Detta projekt fokuserarspecifikt på designen och implementationen av de elektriska och mekaniska krav som ställs på ett"smart greenhouse system". Detta innefattar; val av komponenter såsom sensorer, aktuatorer samtstyrenhet men även sammankopplingen mellan dessa komponenter och utvecklingen av mjukvaratill reglersystemet, som i sin tur syftar till automatiseringen i växthuset. Systemet är baserat på enWiFi-uppkopplad mikrokontroller. Parametrar som monitoreras är; temperatur, luftfuktighet ochvindhastighet. Bevattning kontrolleras av en magnetventil och kan schemaläggas för bevattningi önskade intervall. Ventilering och temperaturoptimisering sker genom kontroll av taklucka medhjälp av ett linjärt ställdon samt kontroll av ett värmeelement. Resultatet demonstrerar ett pål-itligt och punktligt system med låg energiförbrukning. Prototypen som utvecklats kan installeras ibåde nya och befintliga växthus. Funktionaliteterna kan smidigt fjärrkontrolleras och monitorerasfrån en android applikation. Den totala kostnaden för de komponenter som använts var runt 4500kr. Vidareutveckling vad gäller skalbarhet för att sömlöst lägga till komponenter och funktion-aliteter bör övervägas. För ytterligare minskad energiförbrukning med hjälp av klimatoptimeringkan väderprognos adderas som en parameter.

  • Acknowledgements

    We’d like to thank Thomas Munther for consultation regarding power-supply of the system, TommySalomonsson for valuable inputs regarding software for the microcontroller as well as electronic cir-cuits. Further, we’d like to thank Halmstad University and especially Thomas Lithén and NicolinaMånsson for lending of electrical appliances and office-space. We’re also thankful for the importantfeedback and critique received on the report from our supervisor Wagner De Morais.

    A special thanks to Willab Garden for collaborating with the idea that we had. Further, we’regrateful for the expertise in horticulture as well as the funding of development expenses.

    Best regards,Oscar Johansson & Gustav Andersson

  • Contents

    1 Introduction 11.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Aim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.5 Delimitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

    1.5.1 Degree of Scalability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5.2 Degree of Autonomy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5.3 Aesthetics of Cable Integration . . . . . . . . . . . . . . . . . . . . . . . . . 41.5.4 Energy Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    1.6 Outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    2 Background 72.1 Smart Home Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 Industrial Greenhouse Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3 Related Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

    2.3.1 Sensors and Actuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.3.2 System Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    3 Theory 113.1 Potential System Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    3.1.1 Microcomputer-based Design . . . . . . . . . . . . . . . . . . . . . . . . . . 123.1.2 Microcontroller-based Design . . . . . . . . . . . . . . . . . . . . . . . . . . 133.1.3 Microcontroller- and Microcomputer-based Design . . . . . . . . . . . . . . 13

    3.2 Automating Control of Roof-Hatch Window . . . . . . . . . . . . . . . . . . . . . . 143.3 Automating Control of Heater . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.4 Enable Automated and User-Controlled Water Irrigation . . . . . . . . . . . . . . . 153.5 Simultaneously Running Entire System . . . . . . . . . . . . . . . . . . . . . . . . 163.6 Useful Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    3.6.1 Interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173.6.2 Analog-to-digital Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    4 Methodology 194.1 Project Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194.2 Testing Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.3 System Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    4.3.1 Microcontroller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.3.2 Temperature-Humidity Sensor . . . . . . . . . . . . . . . . . . . . . . . . . 214.3.3 Anemometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.3.4 Solenoid Valve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.3.5 Linear Actuator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.3.6 Additional Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    4.4 Implementation of Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.4.1 Temperature-Humidity Sensor . . . . . . . . . . . . . . . . . . . . . . . . . 224.4.2 Anemometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.4.3 Solenoid Valve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.4.4 Linear Actuator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    I

  • 4.4.5 Ambient Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.5 Implementation of System Functionalities . . . . . . . . . . . . . . . . . . . . . . . 28

    4.5.1 Heater Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.5.2 Roof-Hatch Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.5.3 Irrigation Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.5.4 Periodic Ticker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    4.6 Measuring of End-Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.6.1 Software for Linear Actuator . . . . . . . . . . . . . . . . . . . . . . . . . . 324.6.2 Logging and Visualization of Data . . . . . . . . . . . . . . . . . . . . . . . 324.6.3 Power Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    4.7 Analysis of End-Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    5 Results & Analysis 355.1 Linear Actuator Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.2 Periodic Ticker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.3 Automated Temperature Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.4 Anemometer Safety Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.5 Automated Irrigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385.6 Power Consumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395.7 System Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405.8 Expenses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

    6 Discussion 436.1 Overall Project Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436.2 Integrity, Safety and Environmental Impact . . . . . . . . . . . . . . . . . . . . . . 44

    6.2.1 Integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446.2.2 Safety . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456.2.3 Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    7 Conclusion 47

    Bibliography 49

    A First Appendix 53

    II

  • List of Figures

    1.1 Overview of envisioned system integrated in a greenhouse . . . . . . . . . . . . . . 3

    2.1 System Architecture in [26] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    3.1 System Architecture - Microcomputer-based design . . . . . . . . . . . . . . . . . . 123.2 System Architecture - Microcontroller-based design . . . . . . . . . . . . . . . . . . 133.3 System Architecture - Microcontroller- and Microcomputer-based design . . . . . . 143.4 Closed-loop feedback system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143.5 Schmitt Trigger Functionality [28] . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.6 Theoretical Run-Time Execution Sequence . . . . . . . . . . . . . . . . . . . . . . . 163.7 Simplified overview of interrupt in Cortex-M processor . . . . . . . . . . . . . . . . 173.8 Simplified overview of the process of reading Analog Inputs . . . . . . . . . . . . . 17

    4.1 Waterfall Model of System Development [30] . . . . . . . . . . . . . . . . . . . . . 194.2 Test Station . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.3 Response sequence followed by 40 bits of data from DHT22 . . . . . . . . . . . . . 234.4 Anemometer Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.5 Correlation between Output Voltage and Wind Speed . . . . . . . . . . . . . . . . 244.6 Relevant portion in ADC working range . . . . . . . . . . . . . . . . . . . . . . . . 244.7 Solenoid Valve circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.8 Motor Control Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.9 Hall Effect feedback - Extending . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.10 Hall Effect feedback - Retracting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.11 LED Control Circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.12 Simplified flowchart over roof-hatch software . . . . . . . . . . . . . . . . . . . . . . 304.13 Linear Regression Model Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.14 Log-file Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    5.1 Measured distances of Motor Extension with an input of 0%, 66% and 100% respec-tively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

    5.2 Purple: indicating ticker, Yellow: indicating scheduled task . . . . . . . . . . . . . 365.3 Result of software for Automated Temperature Control . . . . . . . . . . . . . . . 375.4 Result of software for Anemometer Safety Function . . . . . . . . . . . . . . . . . . 385.5 Circuit integrated into mounting box . . . . . . . . . . . . . . . . . . . . . . . . . . 405.6 Overview of the system components . . . . . . . . . . . . . . . . . . . . . . . . . . 415.7 Control page in application, motor and LED result, monitoring interface in application 41

    A.1 Visualisation of "1" and "0" bits respectively, where "1" bit is high for 70 µs and"0" is high for 26-28 µs represented by high-voltage-level . . . . . . . . . . . . . . 53

    A.2 Direct response from anemometer when rotated at random speeds . . . . . . . . . 53A.3 Valve open duration with input 5 and 15 seconds respectively . . . . . . . . . . . . 55A.4 Valve open duration with input 30 and 60 seconds respectively . . . . . . . . . . . 55A.5 Valve open duration with input 120 and 180 seconds respectively . . . . . . . . . . 55A.6 Measured Duration of Valve Opening using Oscilloscope . . . . . . . . . . . . . . . 55

    III

  • List of Tables

    4.1 Functionality table - Motor Control . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    5.1 Input Value and Expected Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355.2 Heater and Roof-Hatch Temperature Thresholds . . . . . . . . . . . . . . . . . . . 375.3 Result, Duration of Solenoid-opening with Compensation . . . . . . . . . . . . . . 395.4 Measured Power Consumption in Various States . . . . . . . . . . . . . . . . . . . 39

    A.1 Raw Sampled Data, Solenoid Error Prior to Compensation . . . . . . . . . . . . . 54A.2 Expenses excluding VAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

    IV

  • List of Algorithms

    1 Schmitt-Trigger Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Hall Effect Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Determine direction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Set Desired Temperature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Evaluate Heater . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 Evaluate Solenoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 Ticker Conditional Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

    V

  • Chapter 1

    Introduction

    The idea of growing plants and crops in a controlled environment date back to the Roman times.Cucumis were planted in wheeled carts with a specularium (an ancient greenhouse using mirror-stone or mica). Carts were put in the sun during warm-sunny days and subsequently put insideduring nights and rainy days [1]. The modern greenhouse was first built in Leiden, Holland inthe 1800s [2]. A traditional greenhouse, due to its translucent materials, enables light to easilyenter. The light is absorbed by the ground and plants in the greenhouse and is thus convertedinto infrared light. The disparity in wavelength of infrared and visible light enables the translucentmaterial to reflect infrared rays, which, in turn, heats the interior temperature of the greenhouse.

    Although the greenhouse provides horticulture with a more optimal environment, the lack ofability to control the climate can result in non-optimal temperature, soil moisture, and air humidity.A modern approach to overcome these issues is the implementation of a smart system. One thatemploys sensors and actuators to enable one to remotely and autonomously control the greenhouse.

    Automated greenhouses that monitor and act upon parameters such as humidity, temperature,and crop nutrients are widely developed for large-scale horticulture industries [3][4]. However, suchsystems often adopt Supervisory Control and Data Acquisition (SCADA) systems, which tend tobe expensive [5] and complex to implement for the end-user [6]. As a consequence, such systemsmay not necessarily be suitable for hobby gardeners.

    Considering the limited availability of simple, affordable, and user-friendly systems for small-scale greenhouse gardening, that can remotely and autonomously control and monitor the green-house, Willab Garden AB was contacted. Willab Garden is one of the largest greenhouse producersin Sweden, the idea was presented and the interest of such system was investigated. Successfully,an agreement to implement the project in collaboration with Willab Garden in Båstad was made.

    Willab Garden has previously collaborated with a company from Italy regarding the develop-ment of a similar product. However, the envisioned product was never implemented due to theanticipated expenses for an end customer as well as the then insufficient market demand. WillabGarden has recently seen a growth in the market demand for this type of product and were henceinterested in collaborating with the project idea.

    1.1 Motivation

    The possible benefits of a smart greenhouse include, but are not limited to, climate optimizationon parameters such as temperature & humidity, monitorability and controllability via the use ofa mobile application. In addition, preventive safety actions such as automatic roof-hatch closingdue to wind-speed. Optimizing the environment for crops entails the possibility of increased yieldand extension of seasons [7].

    Field studies for home automation technology have shown the potential to achieve substantialenergy savings in the form of heating, cooling and electricity [8]. Considering the growth in home

    1

  • automation (discussed further in section 2.1), these technologies are expected to improve and de-velop. This would be positive for a potential smart greenhouse market since already proven anddeveloped technologies could be implemented there as well.

    Even though a smart greenhouse would increase energy consumption, due to installation ofelectrical components, compared to a traditional greenhouse, the results regarding energy savingthat smart home devices entail could potentially be implemented into a smart greenhouse as well.The benefits of the addition of a smart system may be; minimized water usage, optimized temper-ature and improved crop yield. Further, implementations for studying plant and crop behaviourvia machine learning could bring knowledge for smart greenhouse owners to extend the growthseason.

    As the project is done in collaboration with Willab Garden, there is a motivation to look athow a smart product would work in the market. Considering the current paradigm shift towardsconnected and smart products, transforming a Product into a Smart Product might be a goodidea from a business point-of-view. However, there are some non-functional aspects to take intoconsideration when taking the step from a non-smart product to a smart product. For instance,even though there’s numerous of possible features to add to a product, the marginal benefit ofadding such features needs to exceed the marginal cost for customers. Also, connecting a productto the internet may induce a new set of security risks that need to be handled accordingly [9]. Con-nected products could entail integrity intrusion since personal data may be stored. Furthermore,autonomous systems that include moving parts and electrical components may, if used wrong,impose danger to the customer.

    1.2 Aim

    The project aims to develop a prototype that incorporates sensors and actuators for smart andconnected control of a greenhouse. Further, users of the envisioned smart greenhouse system canconveniently monitor and control the greenhouse via a mobile application. The system shouldalso be able to autonomously control features such as temperature and irrigation. These featuresshall be reliable, accurate and safe. Moreover, the aim is for the system to be scalable, meaningthat new components and features can be added to the system. In order to keep the greenhousepleasurable for potential customers, it is important that the system provides ambient lighting andis adequately integrated from an aesthetic point of view.

    1.3 Objectives

    As the project is quite extensive and involves numerous of different technologies that require differ-ent knowledge, the project has been divided into two different parts. This part, the Mechatronicspart involves mainly the hardware and hardware-related software. The other part, Computer en-gineering part, focuses more on connectivity, data management and the application.In order to fulfil the aims of the project the following objectives for the Mechatronics part will besolved:

    • Choice of ComponentsArchitecture and components need to be suited for the climate in a greenhouse. Exposedcomponents need to have a IP54 (minimum) classification, other components shall be inte-grated in sufficient encapsulation.

    • Parameter SensingThe system should sense and enable monitoring of temperature, humidity and wind-speed.Parameters shall serve as input to autonomous control as well as being available to be dis-played in a mobile application.

    • Temperature ControlTemperature control entails keeping the greenhouse temperature at a certain pre-set level.

    2

  • The control should be done autonomously or remotely by artificial heating with the help of aheating element. Furthermore, control of the roof-hatch shall serve as ventilation and coolingof the greenhouse.

    • Safety FeaturesIf excessive wind-speeds are present, the roof hatch shall autonomously close and stay closeduntil wind-speeds are at acceptable levels.

    • Remote and Automated IrrigationThe system should control existing water source for further distribution inside the greenhouse.Users shall remotely as well as autonomously be able to control irrigation.

    • Ambient Lighting and IntegrationUser shall remotely and via a physical button be able to control ambient lighting in thegreenhouse. Further, the system should be integrated into a greenhouse.

    Figure 1.1 shows an overview of the envisioned system integrated into a greenhouse. The imageis divided into the Mechatronics part on the left and the Computer engineering part on the right.

    Figure 1.1: Overview of envisioned system integrated in a greenhouse

    1.4 Approach

    The thesis work will be separated into five phases. These phases will be utilized to efficientlycomplete the objectives (section 1.3) of this project and are as follows:

    1. Research - related work, choice of hardware and architecture.

    2. Wiring, programming and testing of individual hardware

    3. Programming and testing of all hardware connected to a single controller

    4. Integration between Mechatronics part and Computer engineering part

    5. Integration of system into a greenhouse

    3

  • Research into projects developing similar systems, especially smart greenhouses, will be crucialin the discussion of what system architecture to use. Further, research into hardware and softwareis intended to give an overview of tried and tested components. Once research has been conducted,the next phase can be initiated.

    Each specific sensor and actuator will be tested individually. Sensors will be wired and pro-grammed to the extent that input data can be read. Actuators will be operated from a controllerto see expected functionalities. Once testing returns expected results, this phase will be consideredcomplete. Tests include the following:

    • Control electrical and mechanical characteristics of all hardware in comparison with data-sheet.

    • For sensors: Compare input-data with data-sheet.

    • For actuators: Compare the output with expected outcome compared to data-sheet.

    Once this has been accomplished, all individual components need to be connected simulta-neously to one controller. The hardware includes not only sensors and actuators but also otherpossible peripheral components, for example, power supply unit and relays. Functionalities for thismechatronic system will be developed, such as automation between the temperature sensor androof-hatch actuator.

    The next step will be to integrate the mechatronics system with the findings and results in theComputer engineering part. This includes sending and receiving data in order to control actuatorsand manipulate sensor data. The system will also be implemented into a greenhouse requiringhousing for all components as well as wiring inside the greenhouse.

    1.5 Delimitations

    Due to time constraints and limited experience/resources amongst the authors, the project willhave a set of delimitations regarding the scope and aim of the project.

    1.5.1 Degree of Scalability

    Scalability in a finalized product refers to the possibility of removing certain parts of the systemwhilst still retaining functionality in connected components. For instance, one might not be in-terested in a dedicated irrigation system, hence, the system should still be able to function in theabsence of an electrical valve. That is, the system should still monitor and control upon datareceived from connected sensors or inputs from the user. Scalability also refers to the possibilityof for instance adding a secondary roof-hatch motor if the greenhouse possesses multiple hatches.During the development of the system this will be taken into account in designing the prototypebut will not be fully implemented.

    1.5.2 Degree of Autonomy

    Autonomy in the smart greenhouse implies that the system should, dependant on a set of predefinedparameters, autonomously strive to keep the interior environment optimal for plants and crops inthe greenhouse. However, optimality for crop yield is a branch of science itself which require expertknowledge on what parameters to monitor, what specific temperature and humidity level best suitsan arbitrary plant etc. Thus, the intention of this project is rather to develop a framework thatenables one to set parameters based on expert knowledge that the system, in turn, can act upon.

    1.5.3 Aesthetics of Cable Integration

    The integration of cables and components is of great importance according to Willab Garden.Ideally, one shouldn’t visually notice cables and components in the greenhouse. However, completeinvisibility of the system is, of course, not possible. Nevertheless, integrating as much of the cablesas possible in the frame profiles will be an integral part of a final product. However, during

    4

  • the development of the prototype system, this will not be highly prioritized as it might requiremodifications of the greenhouse frame itself as well as custom cables etc.

    1.5.4 Energy EfficiencyIn order for an automated system in a greenhouse to have a positive environmental impact, itrequires that the marginal yield obtained by the addition of the system exceed the electricityconsumption and impact that producing required components entails. However, verifying suchclaims requires rigorous testing over extended periods of time as well as in different geographicalpositions. Thus, due to the aforementioned reasons, energy efficiency will be considered in thechoice of components as well as in software development but verification of actual results will belimited.

    1.6 OutlineThis report is organized as follows. Chapter 2 presents works related to the development of smartgreenhouses. It also presents and discusses industry applications and smart home systems. Atheoretical background is presented in Chapter 3, with system architectures as well as possibletheories that can be applied to solve various functionalities. Chapter 4 describes the developmentmethod, software used, the measurement methods utilized and implementations of system com-ponents and functionalities. The findings and results from the implementations are demonstratedand analyzed in Chapter 5. Chapter 6 further analyses the aggregate system, partly in regards toto the aim and purpose, partly from an economical, ethical and environmental aspect. Lastly, abrief summarization of the dissertation is subsequently found in Chapter 7.

    5

  • 6

  • Chapter 2

    Background

    This Chapter will look into similar areas of interest such as smart home systems and industrialgreenhouse applications. Moreover, related work around smart greenhouses will be discussed andanalyzed to obtain information regarding what has previously been developed in this area.

    2.1 Smart Home Systems

    Recent years have seen a rapid increase in the use of home automation, also known as smart homes.The home automation market was valued at around USD 13.6 billion (2018) and is expected togrow at a compound annual growth rate (CAGR) of 24% up to USD 61.5 billion by 2025 [10]. Smarthomes can control and monitor functions in the home without an individual intervening. Thesesystems often monitor parameters such as energy consumption and can unlock doors via applica-tions, for instance. Examples of areas where home automation are being increasingly implementedare [10]:

    • Lighting

    • Safety and Security

    • Heating, Ventilation and Air Conditioning (HVAC)

    • Entertainment

    Such devices are often connected to the internet and the "cloud", making them accessible fromanywhere. This is often referred to as Internet of Things (IoT). Since this project includes sensors,actuators and internet connectivity it closely relates to a smart home system. Consequently, there’sa motivation to look into what’s been implemented in this area and see how it can be transferredto a smart greenhouse.

    Samsungs’s SmartThings [11] is a smart home system that currently exists on the market. Thesystem uses something called "The Hub" which connects to a router via ethernet. Compatibledevices in the home can be connected to the hub via the SmartThings app. Custom automationcan be created for devices added to the application, creating schedules and scenarios for exam-ple. Smart products compatible with the system are for example outlets, light figures, sensorsand cameras. Adding custom automation and scheduling of functions into a greenhouse system isparticularly interesting.

    In Mobile based home automation using Internet of Things (IoT) [12] a home automation sys-tem is developed using an Arduino with Ethernet connection. Here, the microcontroller is actingas a server where the user can send requests via an IP-address to turn on one of the appliances(simulated by LEDs). The drawback of this system in terms of applicability to a smart greenhouseis the wired connection (discussed in section 3.1) which requires the greenhouse to have wiredEthernet-cable.

    7

  • In IOT Based Home Automation Using Arduino[13] the system is based on an Arduino Uno.Here, a WiFi-module, particularly the ESP2866 is used to connect the microcontroller. Addition-ally, relay-modules are used to control actuators. Amongst other sensors, a DHT11 temperatureand humidity sensor is used. The usage of relay’s to control high voltage actuators with a low volt-age signal is an interesting solution that may very well be implemented in a "Smart Greenhouse"system.

    2.2 Industrial Greenhouse ApplicationsAs briefly mentioned in the Introduction (Chapter 1), there are advanced PLC systems in the in-dustry that can scale up and handle large heating sources, compressors for watering systems, cropnutrition, etc. When the authors of the Computer engineering part visited Tönnersjö Trädgårdarthey described their system in detail and the investment that had been done. The total expensesfor the SCADA system they are using is in the price range of 1–2 MSEK. The system includespellets burner (heat source), large compressors for water distribution, water nutrition amongstother functionalities. Consequently the cost, scale and complexity of industrial solutions do not fitthe private market. Although this, there is a motivation to look further into how these implemen-tations can be scaled down to fit a traditional garden greenhouse.

    Soon Industrial Co., Ltd [14] have a variety of actuators for window-opening applications. Forthe outward opening windows, linear actuators or electric chain actuators are used to perform themotion required. Whereas for sliding windows, "Track linear actuators" that instead of extendinga cylinder from the housing, moves along the housing is implemented. As these type of actuatorsare frequently implemented in various window-opening applications it may be suitable for the win-dows in "at home" greenhouses as well.

    Visser Horti System, a Dutch company designing and supplying horticultural machinery devel-ops numerous automated solutions for the large-scale horticulture industry. For example, Visserprovides irrigation systems that incorporate a watering boom that operates on rails mounted overthe plants [15]. This type of solution requires rails, a boom and the ability to freely move abovethe plants. Hence, implementing a solution like this into a greenhouse in one’s garden may notbe suitable as it is not very aesthetically appealing nor does it enable one to freely furnish theirgreenhouse.

    2.3 Related Work

    2.3.1 Sensors and ActuatorsIn Willab Garden’s point of view, the most important environmental parameters to look at aretemperature, humidity and soil moisture. The following list over sensor characteristics was broughtforward together with Willab Garden to be used as a guide when selecting sensors:

    • Low cost

    • Sensing range accurate to greenhouse climate

    • Ability to operate in greenhouse climate

    Since the greenhouse operations aren’t time-critical, sensors that are highly accurate with fastresponse times will not be required. For instance, temperature readings do not need to be highlyaccurate nor updated with a high frequency. A time-critical operation can, for example, be thebraking system in a car, which if not responsive enough, could be fatal.

    In Review of sensors for greenhouse climate monitoring [16], regarding temperature measur-ing, comparing resistance temperature detectors (RTD) and thermistors, the article concludes thatthermistors are not as accurate nor stable as RTDs but easier to wire and cost less. Although theRTDs are more accurate, thermistors are still accurate over a small temperature range, the articleestablishes.

    8

  • Further, the article discusses three types of humidity sensing technologies: capacitive, resistiveand thermal conductivity. When comparing capacitive humidity sensors (CHS) and resistive hu-midity sensors (RHS), the article concludes that CHSs are reasonable resistant to harsher climates,has high accuracy and a low cost while the RHSs has a higher response time but a lower conden-sation tolerance than CHSs.

    The system will need a wind sensor to monitor high-speed winds that may cause damage to anopen roof-hatch. According to The cup anemometer, a fundamental meteorological instrument forthe wind energy industry [17], among the three types of wind speed anemometers, cup, propellerand sonic anemometers, the cup anemometer is currently the most used device in the wind energysector (2011). The cup anemometer is inexpensive compared to the sonic anemometer, it has alinear response to normal wind speeds and is able to operate under extreme weather conditions, thearticle explains. On the basis of wind tunnel and environmental experiments, the sonic anemome-ter has been determined to be a highly accurate wind sensor [18]. The cup anemometer, on theother hand, has been shown to overestimate the wind speed by 8-16% according to [18].

    Concluding the findings around sensors it seems to be a evident trade-off between high accu-racy and cost. However, since the parameters monitored in a greenhouse do not necessarily requiresensors with high accuracy more weight is put on the price-point. As previously mentioned, thelow cost is of more importance to minimize the overall price of the system.

    The irrigation system will rely on external water pressure, e.g. communal water or an externalwater pump. The external water flow will need to be controlled and distributed inside the green-house. In Remote sensing and control of an irrigation system using a distributed wireless sensornetwork [19], a remote sensing and control system for irrigation was developed using a systemcomposed of PLC, relay modules and solenoid valves. In another automatic irrigation system [20],solenoid valves were also used for controlling the water, as well as sensors and a pump. The articleclaims that solenoids offer fast and safe switching, high reliability, long service life and low controlpower. Looking at a small scale smart irrigation system [21], the use of a pump and a motor wasselected instead of a valve. Although this, the article established in the future scope section thata solenoid valve could be used for varying the volume of water flow.

    As the roof-hatch will aid in ventilating the greenhouse via automation and user input, anactuator is required to open and close the hatch. In Automatic sliding window [22], the authorscreated an automatic sliding window using a dc motor and a lead screw. The motor drives thelead screw attached to the sliding window until a limit switch is activated. The window movementis initiated via remote control. Willab Garden greenhouses have roof-hatch windows which openoutwards, making the implementation of a sliding window non-feasible. Although this, the use oflead screw to create linear motion is of interest.

    An interesting aspect too look at when it comes to ventilation is off what importance the degreeof window opening has. This idea is thoroughly inspected in Natural ventilation of greenhouses:experiments and model [23]. The article measured temperature and humidity for various heightsof the window opening and concluded, as expected, that a larger area of window opening resultsin lower temperature and humidity. In order to control the temperature and humidity inside thegreenhouse better, the option to regulate the degree of window opening might be of interest.

    2.3.2 System Architecture

    In order to provide a structured solution that organizes these components and functionalities, asufficient system architecture needs to be adopted. The architecture shall be able to efficientlyhandle the components and functionalities required in the smart greenhouse.

    Similar projects have been implemented before, such as in IOT Based Smart Greenhouse Au-tomation Using Arduino [24] where an Arduino UNO is used as a microcontroller. The sensorsincluded in this implementation were soil moisture, light, humidity, and temperature. The sensordata is intended to aid in controlling a sprinkler and an air vent. According to the article, an

    9

  • architecture like this can be made with fairly cheap components.

    In Automated control system for arduino and android based intelligent greenhouse [25] the ar-chitectural approach adopted is one based on an Arduino and a Wi-Fi module. Furthermore, asystem timer is used to enable the system to keep track of time and an SD card module is used tosave settings of the autonomous system. In terms of this project, it’s seen as an advantage thatthe system incorporates Wi-Fi connectivity.

    In "An Automated Greenhouse Control System Using Arduino Prototyping Platform" [26] amicrocontroller-based architecture is adopted, relay modules are used to control various actuatorssuch as fans, drippers and artificial light. Parameters monitored are temperature, light intensity,humidity and moisture. The architecture design is shown in figure 2.1.

    Figure 2.1: System Architecture in [26]

    In the aforementioned projects, the software is written in Arduino IDE which lacks the possibil-ity of JTAG debugging [27] meaning the code cant be executed in small chunks or in a line-by-lineexecution, nor does it possess the ability to monitor certain registers in the processor in run-time.Thus, from a developer’s point of view, a proper debugging environment is highly valuable.

    10

  • Chapter 3

    Theory

    The project will incorporate a variety of functionalities and automated features. Possible architec-ture designs that enable these functionalities are discussed. Further, this Chapter will put forwardconcepts and theories required to develop the proposed smart greenhouse system. The theorieshave been influenced by the findings in Chapter 2 as well as the authors’ prior knowledge.

    3.1 Potential System ArchitecturesThree broad system architectures were considered and investigated during the research phase ofthe project. All of them involve sensors/actuators and an application. The differentiator is ratherthe things that merges them. Challenges and requirements that apply to both parts of the project,that is, theMechatronics part and Computer engineering part when choosing architecture included:

    • Internet connectivity

    • Data storage

    • Run-time automation

    • Communication between sensors/actuators and application

    • I/O possibilities

    In terms of Internet connectivity there are multiple variants that could possibly be implemented,a few of them are briefly discussed here. Power-Line Communication (PLC) has the advantageof reducing infrastructure needs. People who will utilize a smart greenhouse will inevitably needpower and thus a PLC solution removes the need for a dedicated cable for connection. However,since the communication is executed on the power line it requires that the transmitter and receiverlie on the same phase, which in many circumstances, might not be the case. Using Mobile Net-work for communication to the internet would in most cases give a relatively stable connection.However, mobile networks require either the consumer or the company that provides the smart-greenhouse to have a subscription. According to Willab Garden, most consumers that would wantto install a "smart system" in an existing greenhouse already have power installed. Hence, WiredConnection might require the consumer to install a dedicated internet cable to the greenhouse.A strong advantage of wired connectivity is the reliability and stability that it entails. Wi-Fi havethe advantage of being wireless without the need for a separate subscription (apart from the sub-scription in the house that is) as well as being a profoundly established communication standard.As with any wireless communication methodology, the risk of noise as well as range constraints isinevitably present.

    Data Storage and the different methodologies that apply to it are mostly examined in the Com-puter engineering part of the project. Succinctly, requirements and challenges included; shouldobtained data be stored locally in the system or online in some form of cloud-based storage? Inthe case of local storage, does the system have enough memory? In case of online storage, doesthe solution require paid subscriptions and in that case, should the subscription be assigned to theconsumer or shall the company host that service?

    11

  • As the greenhouse will incorporate some degree of Run-time automation, that is, automatedcontrol of data gathered from the sensors. For instance, the system should, depending on definedparameters, automatically turn on a heater if the temperature falls below a certain threshold. Thisraised questions such as, what type of system suits real-time controlling of sensors/actuators mostproperly and should the algorithms that control the automation be implemented in the databaseor in the controller itself?

    Since various sensors with different ways of communication will be used in the system, I/Opossibilities on the choice of architecture plays a major role. For example, some sensors output ananalogue signal which entails that an analog-to-digital converter (ADC) is required. Some motorsare controlled by pulse width modulation (PWM) and hence PWM-support might be a requirementon the architecture.

    3.1.1 Microcomputer-based Design

    Implementing a microcomputer-based design (as shown in figure 3.1) entails several benefits interms of connectivity and data management. This is mainly due to the integrated operating systemwhich simplifies setup and usage of a local database and a server. As a microcomputer essentiallyincorporates all the functionalities of a regular computer it also simplifies communication with theapplication for instance.

    Figure 3.1: System Architecture - Microcomputer-based design

    However, numerous of the functionality that a microcomputer possesses is redundant in thisparticular application and can hence, lead to unnecessary power consumption and in extension leadto an expensive end-product. Microcomputers, such as the Raspberry Pi lacks analogue inputswhich for particular sensors might be necessary. This can be solved by adding an ADC to thesystem but that will increase the number components needed as well as possibly increasing theprice of an end product.

    12

  • 3.1.2 Microcontroller-based DesignA microcontroller-based design (as shown in figure 3.2) that doesn’t incorporate a lot of redundantfeatures makes it appropriate for embedded systems as the power consumption required is thuslower, most microcontrollers also incorporate a wide variety of different I/O ports such as, analogueI/O, hardware PWM etc. This entails that it may be appropriate in order to control and monitorvarious sensors/actuators. The drawback of a microcontroller is mainly on the connectivity anddata-management side, most microcontrollers have a very limited memory by design and is thusnot suitable for hosting a database. Many microcontrollers do not retain on-chip connectivitymodules (such as Wi-Fi) and hence, a separate module with proper communication in betweenmay need to be added.

    Figure 3.2: System Architecture - Microcontroller-based design

    In a potentially final product, one might want to develop a dedicated printed circuit board(PCB). Partly to get rid of redundant features, partly to get a competitive advantage. Thus, asa microcontroller is a relatively simple component, the transition from a prototype to a dedicatedPCB might be more facile.

    3.1.3 Microcontroller- and Microcomputer-based DesignA design that incorporates both a microcontroller and microcomputer (as seen in figure 3.3) wouldcontain the sum of benefits that the individual designs incorporated. This includes:

    • Wide variety of I/O ports

    • Possibility to locally host a server and deploy a database

    • Simplified application communication with the help of an operating system

    • No requirement of web-based storage

    However, this entails that two different processors are running simultaneously, which from an effi-ciency point of view may not be satisfiable. This design, as with the microcomputer-based design,would embody even more redundant features and hardware. In terms of a potential end-product,developing a optimal PCB from two vastly different prototype-boards may be challenging. Also,as microcomputers often use e.g. Python and microcontrollers usually C/C++, the degree of re-usability of prototype code to the final code will be significantly lower. Some form of communicationbetween the two would also need to be established.

    13

  • Figure 3.3: System Architecture - Microcontroller- and Microcomputer-based design

    3.2 Automating Control of Roof-Hatch Window

    The roof-hatch window serves as ventilation for the greenhouse, both to lower temperature anddecrease air humidity. It also needs to be protected in case the wind speed is too high. To automatethis process there are three components needed; sensors, actuator and a controller. Sensors gatherinformation regarding temperature, air humidity and wind speed. The sensor feedback needs tobe processed via a controller in order to decide what to do with the information. The controllercontrols the actuator to open and close the window. To solve this, a closed-loop feedback systemcan be used which uses the concept of an open-loop system as its forward path but has one ormore feedback loops as shown in figure 3.4.

    Figure 3.4: Closed-loop feedback system

    The system could have a temperature input for example. This would entail that the roof-hatchwindow stays closed while the temperature is on the set value or below. If the temperature goesabove the set value the roof-hatch window will open accordingly. It can be of interest to have anactuator that can position the window at certain levels, making it easier to regulate the temperature(see last part of section 2.3.1 for more information). If temperature functions as the main input,humidity might take precedence at certain levels or function as a safety feature. Say, for instance,that the humidity goes above a predefined percentage, the window will open completely to protectthe greenhouse from, for example, fungal infections.The anemometer should always function as protection for the roof-hatch meaning that if the windspeed is too high the roof-hatch should close and stay closed until the wind calms down again.

    3.3 Automating Control of Heater

    The heater in the greenhouse serves two main purposes. Firstly, the heater shall serve as a frostguard, meaning it serves to prevent the temperature falling below 0 ◦C. Secondly, the heater shallaid in keeping the temperature to a certain set-point determined by the consumer. Most sim-ple and cheap heaters are rarely analogue, meaning they’ll usually only have an ON and OFFsetting (sometimes a few predefined power-levels). Thus, developing a system that’s based onnon-analogue heaters paves the way for consumers to choose a variety of different heaters basedon their requirements in terms of size-capabilities and power-needs.

    14

  • Figure 3.5: Schmitt Trigger Functionality[28]

    The condition to turn the heater could be a prede-fined temperature level where the heater is OFF foras long as the temperature is above the threshold,and ON for as long as the temperature is lower thanthe threshold. However, as the temperature may fluc-tuate around the threshold it may lead to multipleunnecessary switching of the relay (demonstrated incase A in figure 3.5). This leads to increased weardamage on the relay as well as the heater element.The wear damage can be mitigated by incorporatingsoftware functionality that simulates that as seen ina Schmitt-trigger circuit. Unlike a regular compara-tor (case A in figure 3.5) this possesses the ability tohave two different thresholds, creating a "hysteresis".In such case, two threshold values around the desiredvalue are chosen. For the relay to switch, the tem-perature needs to either go from above the upper threshold value to below the lower thresholdvalue or the other way around. The functionality is illustrated in case B in figure 3.5. In order toimplement the aforementioned functionality in software, one can utilize the pseudo-code shown inalgorithm 1.

    Algorithm 1 Schmitt-Trigger Algorithmflag = Falsewhile True dotemp = get_temp()if flag then

    if temp > upper_threshold thenturn off heaterflag = False

    end ifelse

    if temp < lower_threshold thenturn on heaterflag = True

    end ifend if

    end while

    3.4 Enable Automated and User-Controlled Water IrrigationThe setting in different greenhouses varies greatly, some prefer scattered pots around the green-house, some prefer rows next to the walls with an intermediate alley. Consequently, one wouldideally have different controllable "irrigation nodes" for each type of plant in the greenhouse toaccurately optimize the amount of water. Doing so would, however, require several valves and/orflow-meters which inevitably would increase the price of a potential product as well as raise thelevel of complexity. Thus, using one single valve that controls the amount of water by the durationit’s opened is a possibility.

    To control the water flow with only one valve a timer and schedule based solution may beimplemented. This means that the solenoid can, for example, be configured to open for 15 secondsevery 12 hours. In order to achieve such functionality, the processor needs to be able to keep trackof time. As power failures sometimes inevitably occur keeping track of real time in the processorwithout backup power might cause issues with keeping precise time. However, creating timers thatcan be utilized to keep the valve open for a shorter amount of time can be implemented by usingtimer and alarm functions in the processor. That, for instance, generate an interrupt whenever aset time has passed. Subsequently, one could utilize the time on the database (implemented byComputer engineering part) to keep track of longer intervals.

    15

  • 3.5 Simultaneously Running Entire System

    As the system involves numerous functions that, in order to be pleasurable to use, shall be ableto function simultaneously. Meaning, for instance, the LED shall be able to be switched on or offeven though the irrigation system is currently turned on. Or that the system shall still send datato the database even though the automated system for roof-hatch is enabled. To facilitate suchfunctionality one needs to minimize software loops that wait for values and/or states as well aswriting generally resource-efficient code. Some parts of the code shall, however, only be executedin various time-periods. Thus, a periodic "ticker" that enables the system to keep track of time(not necessarily real "time") may be needed. The periodic ticker can be utilized to conditionallyexecute code depending on time.

    Some functionality, such as turning the lights on when one presses a button in the greenhouse,neither depends on time nor some arbitrary condition. Hence, the system shall be able to executecertain code when an external state has changed, for example, when the led-button is pressed. Inorder to achieve such functionality, interrupts (further discussed in 3.6.1) can be utilized.

    The system will require run-time logic in order to involve all these features. A theoreticalexample of this can be seen in figure 3.6. The figure shows a main function incorporating scheduletasks, interrupts, checking ticker information and handling user request.

    Figure 3.6: Theoretical Run-Time Execution Sequence

    3.6 Useful Peripherals

    For a system of this nature to function reliably with sensor input, actuator output, automationand app compatibility certain peripherals can be useful. For instance, to avoid constantly pollinginput data etc, interrupt management can be preferred. Interrupts enable the system to multi-taskand deal with a process when needed (section 3.6.1). Polling, on the other hand, is the state ofcontinuously checking a status to see if a desired condition is met.

    16

  • Peripherals to keep track of time can be useful when creating a system with time-related func-tionalities. Examples of this can be Real Time Clock (RTC), Real Time Timer (RTT) or TimerCounter (TC). These peripherals may be interrupt enabled and in one way or another possessthe ability to keep track of time, either real time or "periodic ticking". The other option is touse delays that temporarily suspend all executions by "waiting" in a loop. However, using delays(especially longer ones) decreases system responsiveness significantly.

    As some sensors generate analogue signals, and computers only use binary numbers, a conver-sion between the two may be applicable. To achieve this an analog-to-digital converter (ADC) canbe used (see section 3.6.2 for more information).

    3.6.1 InterruptAn interrupt is a hardware or software generated signal which notifies the CPU to suspend thecurrently executing task and immediately execute different code. This code is processed in aninterrupt handler. The interrupt handlers are also referred to as Interrupt Service Routine (ISR).In the Cortex-M3 processors [29], for example, exceptions are processed by the Nested VectorInterrupt Control (NVIC) (see figure 3.7). The NVIC is a method of prioritizing interrupts,improving performance and reducing interrupt latency. The processor also incorporates a SystemTick Timer (SysTick) which can generate time interrupt requests.

    Figure 3.7: Simplified overview of interrupt in Cortex-M processor

    3.6.2 Analog-to-digital ConverterAn ADC is a circuit that converts a continuous voltage input (analogue) to a binary value (digital)(see figure 3.8). In a microcontroller (Cortex M3 for example), the measured voltage can be readas a 10-bit or 12-bit value. The difference in resolution determines the precision of the conversion.As the system for a smart greenhouse does not rely on high precision parameters a lower resolutionmay be sufficient. For instance, if a 10-bit ADC has a reference voltage of 3V and an input of thesame voltage, the corresponding output would be 210 − 1 = 1023. If the input voltage is 2V theresult would be 1023−341 = 682. This number can subsequently be converted into a representativenumber depending on the unit measured.

    Figure 3.8: Simplified overview of the process of reading Analog Inputs

    17

  • 18

  • Chapter 4

    Methodology

    This Chapter presents the various steps taken to create the greenhouse system. Section 4.1 andsection 4.2 describe the process and tools needed to conduct the work. In section 4.3, the choice ofsystem components will be presented and discussed. Further, section 4.4 describes how the afore-mentioned components are implemented with wiring and programming. Section 4.5 will demon-strate the different software functionalities that use the implemented components. Lastly, section4.6 and section 4.7 will present how the different results from such functionalities will be measuredand analyzed.

    4.1 Project Management

    Figure 4.1: Waterfall Model of System De-velopment [30]

    The project is managed and executed in five phasesas discussed in section 1.3. The development method-ology is similar to that of a waterfall method (fig-ure 4.1). However, maintenance is not included here.Development started with compiling (together withWillab Garden) requirements (section 1.3) of the sys-tem. Subsequently, with the influence of informationgathered from Background (Chapter 2), architecturedesign and components were selected and individuallytested. Next stage included implementation of func-tionalities discussed in Theory (Chapter 3) togetherwith integration of aforementioned work with findingsin the Computer engineering part. Lastly, results areevaluated and verified based on the set requirements.

    To streamline the development and enable implementation of the system, various software,tools and methodologies are necessary. A brief overview and description of these are given below:

    • HardwareOscilloscope, Multimeter and similar electrical appliances provided by Halmstad University(HU) enables testing, troubleshooting and verification of hardware. A JTAG-unit enablesreal-time software debugging (provided by HU).

    • Collaboration SoftwareFree cloud-based collaboration software will help in collaboration between Mechatronics partand Computer engineering part as well as streamline communication within the team. Theseinclude, for instance, Slack, GitHub, Overleaf, Google Spreadsheets and Discord.

    • Integrated Development Environment (IDE)Atmel Studio 7 is being used as the IDE of choice for hardware-related programming. Mi-crochip’s Advanced Sofware Framework (ASF) [31] will be utilized to streamline softwaredevelopment. ASF is a library of proven drivers and code modules that can simplify numer-ous implementations when programming microcontrollers.

    19

  • • Programming LanguageThe C language will be used to program the microcontroller. C enables hardware-closeprogramming that paves the way for efficient real-time code. C is also versatile, making apotential transition to a different processor quite facile.

    • FundingA development budget of 10 000 SEK has been given from Willab Garden. The fundingreceived is intended towards purchases of hardware required for the prototype. No restric-tions on specific purchases have been set by Willab Garden. The budget is shared with theComputer engineering part.

    4.2 Testing EnvironmentIn order to be able to test all the components individually as well as jointly, a test station was built.Doing so entailed the possibility to experiment with various components as well as temporarilyhave something to mount them on. As seen in figure 4.2, the actuators do not actually control thewindow, nor the water but the functionality could be tested and verified.

    Figure 4.2: Test Station

    4.3 System ComponentsThe smart greenhouse will include a variety of sensors and actuators to fulfil the Objectives (section1.3) as well as the project Aim (section 1.2). The choice of components has been influenced by thefindings in Chapter 2.

    4.3.1 MicrocontrollerA microcontroller-based design (discussed in section 3.1.2) resulted in the design of choice. Themain drivers in going towards this particular design were:

    • Variety of I/O ports

    • Minimal amount of redundant features

    • Fairly low price point

    • Paves the way for a more streamlined transition to a PCB

    More specifically the Arduino DUE [32] is going to be used. The processor used on the ArduinoDUE chip is Atmel’s ATSAM3X8E [33]. This micro-controller is used firstly since the authors ofthe project have used it extensively in prior courses, which reduces the time required to learn anenvironment for another type of processor. Secondly, the generous amount of different I/O-portsintegrated on the chip paves the way for easier experimenting/developing. ATSAM3X8E supportsfeatures and communication protocols such as:

    20

  • • Two-Wire Serial Interface (TWI)

    • Inter-Integrated Circuit (I2C)

    • Pulse Width Modulation (PWM)

    • Real Time Clock (RTC)

    • Real Time Timer (RTT)

    • Timer Counter (TC)

    • Controller Area Network (CAN)

    • Universal Asynchronous Receiver/Transmitter (UART)

    • Universal synchronous and asynchronous receiver-transmitter (USART)

    Hence, these features entail the possibility of experimenting with different types of sensors/ac-tuators and different communication protocols during the development phase.

    4.3.2 Temperature-Humidity SensorThe sensing of temperature and humidity is made with a wired and capsulated version of theDHT22 sensor from Adafruit. This sensor uses a capacitive humidity sensor and a thermistor tomeasure the surrounding air. The sensor runs on 3.3–5V and has a single wire for digital dataoutput and input. It also has an operating range between -40–80◦C with ±0.5◦C accuracy.As gathered from the related work (see section 2.3.1), the CHSs has high accuracy, low cost andcan withstand reasonably harsh climates. These characteristics are suitable for this project. Thethermistor sensing element is accurate over a small temperature range and has a low cost. Thegreenhouse does not require the same level of stability as other more critical systems. An ±0.5◦Caccuracy and lower stability won’t affect the system as a whole. Along with these features, theencapsulation will help protect the sensor and the wiring makes it easy to install. Alternatively,the AM2320 could have been used but was not chosen for two main reasons, the communicationprotocol and design. The wired and capsulated DHT22 simplifies installation significantly, it ismore suitable to be installed in a greenhouse and the communication is simple with no need toadd any additional protocol.

    4.3.3 AnemometerAn anemometer is used for measuring wind speed. The cup anemometer used in this project has ananalogue output that correlates with the current wind speed. The measuring range is 0–32.4m/scorrelating to 0.4–2V output.As a safety precaution, the anemometer will protect the open roof-hatch from strong winds thatmay damage the construction. The accuracy is not a high priority since the usage is mainly forprotection and not constant readings. Since the cup anemometer is inexpensive, reliable and canhandle extreme weather situations (see section 2.3.1) this is more prioritised than high accuracy.There is a lack of simple and affordable anemometers that are suitable to be used with a mi-crocontroller. Most anemometers are compact components with display, keypad and propellersinterconnected, for example the Testo 417. This does not fit the project as it is intended to beintegrated into the system. Some variant also include functionalities that are redundant for thisproject, such as measuring the volume flow of air which inevitably increases the price.

    4.3.4 Solenoid ValveA solenoid valve is an electromechanical valve for liquid or gas. In this project, a two-way, normallyclosed (NC), 12V monostable valve will be used. Monostable refers to the valve being opened witha positive voltage (12V) and closed when no voltage (0V) is added to the circuit. This is preferablesince the solenoid will only consume power when it is opened, i.e watering. The valve requiresa water pressure of 0.2–8 bar and can produce a water flow of 30 litres/min at 5 bar. Solenoidvalves are commonly used in smart irrigation systems (see section 2.3.1) making it an establishedproduct for this type of application. The majority of the alternatives are mainly intended towards

    21

  • industrial applications and does hence not include dedicated cables etc. Most alternatives havea higher price-point and run on 230 V. Some alternatives are normally open (NO) which wouldentail that the solenoid would constantly need power to stay closed.

    4.3.5 Linear Actuator

    The electrical linear actuator converts rotational motion from a DC-motor into linear motionthrough a series of gears to a lead screw. This actuator, LD3-12-30-K3-300-C11-HS2-65, has agear ratio of 30:1 and a max speed of 9.5mm/s. It has a push/pull maximum force of 800N and astroke of 300mm. The actuator also includes two hall effect sensors for positional feedback. Thefeedback sensors are important in order to control the position of the window. The LD3 is IP65classified which makes it suitable for the climate in a greenhouse.There are three specific reasons for choosing a linear motor for this project. Firstly, a linear motiongives the ability to open and close objects without any additional hardware. If a circular motionwas to be used, the project would need additional functionalities in order to convert it into linearmotion. This might be a cheaper option, but since the IP-classification is of importance whenoperating inside a greenhouse a linear actuator is an optimal choice. A minimalist look also carriesweight from an aesthetic point of view. Secondly, the linear motor has a strong push and pullforce in exchange for speed. Since the roof-hatch movement is not time-critical, this is not anissue. Thirdly, the linear motor with hall effect sensors gives the possibility to set the window atany level thus the ability to control ventilation and greenhouse temperature more accurately (seesection 2.3.1).

    4.3.6 Additional Hardware

    The system will need a power supply unit to bring down and transform the 230V (AC) from thesocket output. The power supply unit used in the project has an input voltage of 88–264 V (AC),an output voltage of 12V (DC) and a max output effect of 150W. The output effect of the powersupply unit is oversized for this project, the reason is in case additional hardware will be added.

    The power supply unit powers all the components of the system, however, the microcontrollertransforms the 12V to 5V and 3.3V. All the actuators run on 12V entailing that everything canbe supplied directly by the power supply unit. Furthermore, a relay module will be used to controlthe different actuators. The relay module will function as an on/off switch for actuators and canbe controlled by outputs from the microcontroller (3.3V). Relays are ideal for controlling highvoltage circuits with low voltage signals. A 12V LED-strip is further used for ambient lighting,however, the LED-strip is mainly used for the display of the functionality, and can be switched toan arbitrary 12V luminary.

    4.4 Implementation of Components

    Circuits and implementation of the software for the aforementioned components are here presented.Psuedo-code for various algorithms are shown and equations that are utilized are demonstrated.

    4.4.1 Temperature-Humidity Sensor

    The circuit for the DHT22 sensor is very simple with a 3 wire connection, black to ground, red toVCC (5V) and a yellow data wire connected to the microcontroller.Data from the DHT22 consists of 40 bits where the first 16 bits represent humidity, adjoining 16bits represent temperature. The last 8 bits are the sum of the previous 32 bits and can be usedas a check function. The first bit of the temperature reading is a sign bit representing negativetemperatures when returned as "1". To start a data-read the MCU, in this case the microcontroller,needs to pull down for at least 500 µs. This means that the pin on the MCU is connected to thedata pin of the DHT22. This pin will be set as an output, giving the ability to set the pin highor low. After going low for at least 500 µs, the pin needs to be set high and then switched to aninput. The explained start sequence will trigger the DHT22 from low-power-consumption-modeto running-mode. The DHT22 will send a response signal of a specific pattern before transmittingdata (see figure 4.3). Before each bit of transmission, the DHT22 will send a low signal for 50 µs

    22

  • followed by a specific length of high-voltage-level representing "0" or "1". A signal representing a"1" can bee seen in appendix A figure A.1, here, the signal is high for 70 µs. The complete sequenceof data reading can only be repeated in 2 second intervals.

    Figure 4.3: Response sequence followed by 40 bits of data from DHT22

    4.4.2 Anemometer

    The wiring for the anemometer is rather simple as it only incorporates V-, V+ and a Signal Outcable. The circuit can be seen in figure 4.4.

    Figure 4.4: Anemometer Circuit

    The anemometer has an linear output of 0.4-2V corresponding to 0-32.4 m/s (as seen in figure4.5). The analogue signal when the anemometer is rotated at some arbitrary speed can be seenin appendix A figure A.2. An Analog-to-digital converter (ADC) (discussed in section 3.6.2) isneeded in order to convert the analogue anemometer output. The ADC needs to be initiated withthe following steps:

    • Enable peripheral clock for ADC.

    • Initiated ADC with the system clock and ADC clock.

    • Enable channel for input.

    • Set ADC to be triggered by software only.

    23

  • Apart from this, the ADC is interrupt enabled. The interrupt is set to be triggered once thedata ready bit is changed in the "ADC Interrupt Status Register" (ADC_ISR) [29]. This entailsthat the ADC conversion is finished and the data is stored in the "ADC Last Converted DataRegister" (ADC_LCDR) [29] and can subsequently be retrieved and processed.

    Figure 4.5: Correlation between Output Voltage and Wind Speed

    As the integrated ADC has a reference voltage of 3300 mV and the anemometer output rangesfrom 400-2000 mV a "calibration" of the range is required. That is, only a limited range as shown infigure 4.6 (highlighted in green) shall be utilized. The ADC in the ATSAM3X8E can be configuredto have a 10 or 12-bit resolution. However, as discussed in section 4.3.3 the wind-speed is onlymeasured as a safety precaution for the roof-hatch, hence, there’s no particular need for highprecision values. Thus, the ADC is configured to 10 bits which entails a range of [0, 210 − 1] ∈ N.

    Figure 4.6: Relevant portion in ADC working range

    24

  • In order to convert the digital data that the ADC generates to an actual wind speed value thatcan be used further in the software, the formula shown in equation 4.1 is used. The digital valuefrom the ADC in the range [124, 620] ∈ N is linearly converted into the wind speed range [0, 32.4].

    w(d) =max(ws)−min(ws)f(2000)− f(400)︸ ︷︷ ︸

    slope

    d+

    (max(ws)− max(ws)−min(ws))

    f(2000)− f(400)

    )︸ ︷︷ ︸

    intersect

    =32.4− 0620− 124

    d+

    (32.4− 32.4− 0

    620− 124

    )=

    32.4

    496d− 8.1

    (4.1)

    where w(d) is the software generated float that represents wind speed,max(ws) is the maximum wind-speed that the anemometer can measure,min(ws) is the minimum wind-speed that the anemometer can measure,f(x) is the correlation between input voltage and ADC output shown in figure 4.6,d is the output from ADC in the range [124, 620] ∈ N

    As the anemometer has a working range of [124, 620] ∈ N, input values outside that range shallbe deemed invalid. Hence, a piece-wise defined function as shown in equation 4.2 can be derived.

    w(x) =

    0 x ≤ 12432.4496 d− 8.1 124 < x < 62032.4 x ≥ 620

    (4.2)

    4.4.3 Solenoid Valve

    The solenoid valve circuit is very basic with only two wires, a flyback diode and a relay included.The scheme can be seen in figure 4.7. The diode serves to prevent the sudden voltage surge thatoccurs when an inductor (here, the solenoid) is switched off. The absence of a flyback diode mayinterfere and/or damage other sensitive components in the system.

    Figure 4.7: Solenoid Valve circuit

    The valve is subsequently controlled by the input to the relay. For as long as the input is high,the solenoid will stay open.

    25

  • 4.4.4 Linear Actuator

    The control circuit for the linear actuator is implemented with two relay’s, one for extending andone for retracting the motor. As seen in figure 4.8 two normally closed (NC) relays are used. Thecircuit is controlled by two digital outputs from the microcontroller which, in turn, switches therelays. The behaviour dependant on the output from the microcontroller can be seen in table 4.1.

    Figure 4.8: Motor Control Circuit

    Input 1 Input 2 Motor0 0 -0 1 Retracting1 0 Extending1 1 -

    Table 4.1: Functionality table - Motor Control

    The linear actuator incorporates two Hall-Effect sensors for positional feedback. One millimeterof extension (or retraction) corresponds to 11 pulses from the sensors. That is, if the microcontrollerreceives 110 pulses, the motor have traveled 10mm. As shown in figure 4.9 and figure 4.10 one candetermine whether the motor is retracting or extending by looking at the relative phase of the twosignals. However, as the motor will only be controlled by software in this project, keeping track ofthe direction can thus be done directly in the software and hence, only require data from one ofthe sensors.

    26

  • Figure 4.9: Hall Effect feedback - Extending Figure 4.10: Hall Effect feedback - Retracting

    Algorithm 2 Hall Effect Handlerif Hall effect pin triggered interrupt then

    if extending thencurrentPulse++

    else if retracting thencurrentPulse−−

    end ifif setPulse == currentPulse thenmotorStop()

    end ifend if

    The positional feedback in the motor lacks "memory". Meaning, unless the current state (innumber of pulses) is kept track of in the software there’s no way of knowing where the motor isat any given time. Thus, a variable to keep track of the position is implemented. Pulses from thesensor are configured to trigger interrupts which, in turn, increments or decrements the variablevalue depending on the direction the motor is travelling. Checking whether the motor has reachedthe set value in the interrupt handler enables one to simultaneously execute different code. Briefimplementation of this is shown in algorithm 2.

    To simplify control of the motor via the application a function that takes an integer between 0and 100 is implemented. The received value correspond to the desired percentage of extension onthe linear actuator. The set value equation can bee seen in equation 4.3.

    Pset =s

    100∗ Pmax (4.3)

    where Pset is the set value (in number of pulses),s is the percentage of desired extension in the range [0, 100] ∈ N,Pmax is the number of pulses with full extension,

    Apart from setting the new desired extension-value the function also calculates which directionthe motor shall move in order to reach the desired value. That procedure can be seen in algorithm3.

    Algorithm 3 Determine directiondiff = setPulse− currentPulseif diff > 0 thenmotorExtend()

    else if diff < 0 thenmotorRetract()

    end if

    27

  • 4.4.5 Ambient LightingTo enable the user to control the ambient light in the greenhouse a LED-strip is utilized. The LEDcircuit consists of two parts, one for the physical button and one that controls the LED. As it shouldbe possible to turn the LED on/off both in the application and physically in the greenhouse, atraditional circuit, where a switch controls the supply voltage to the LED cant be used. The reasonbeing, if the consumer toggles the LED in the application and the physical switch is switched offthere is no way to turn the LED on unless done physically. Hence, a software-controlled approachas seen in figure 4.11 is implemented. Here, a retractive switch monitored by an interrupt to theprocessor is implemented. Having a retractive button enables the system to either turn on or turnoff the LED depending on the current state.

    Figure 4.11: LED Control Circuit

    The state of the desired LED "value" is continuously monitored from the application. If thephysical button is pressed, an interrupt is generated that subsequently will notify the applicationthat a change has been made. That is, if the LED is turned on with the physical button theapplication will be notified so that the visual state of the LED is shown as "on" in the userinterface.

    4.5 Implementation of System FunctionalitiesImplementations of various system functionalities are presented here. The following functions arealso discussed in Chapter 3. Heater Software (4.5.1) and Roof-Hatch Software (4.5.2) are used toregulate the temperature. The Roof-Hatch Software also incorporates the safety feature using theanemometer.

    4.5.1 Heater SoftwareAs mentioned in section 3.3 most heaters are digital, hence, the heater is simulated with an LEDin this project. In practice, one would instead control a power outlet instead of an LED but thesoftware required is essentially the same. A function that takes a value that corresponds to thedesired temperature by the user is processed as shown in algorithm 4. Internally, two boundaries

    28

  • are set in order to prevent values that are not feasible. That is, the heater will likely not be able toraise the temperature in the greenhouse to 35 ◦C when the outdoor temperature is −10 ◦C. Theseboundaries are currently set to 0 ◦C and 30 ◦C. However, these values might need to be changeddepending on the type of heater, size of greenhouse etc.

    Algorithm 4 Set Desired Temperatureif desiredTemp > lowerBoundary & desiredTemp < upperBoundary thenset the desired temperatureupper_threshold = desired_temp+ hysteresislower_threshold = desired_temp− hysteresis

    end if

    The threshold values shown in algorithm 4 are used to achieve the Schmitt-trigger like featurediscussed in section 3.3. The hysteresis variable is set to 1 to allow the temperature to fluctuateslightly without the system intervening. The evaluation that continuously determines whether themotor shall be turned on/off is shown in algorithm 5.

    Algorithm 5 Evaluate Heaterif flag then

    if temp > upper_threshold thenstop_heater()flag = 0

    end ifelse

    if temp < lower_threshold thenstart_heater()flag = 1

    end ifend if

    4.5.2 Roof-Hatch SoftwareThe automated roof-hatch circuit consists of three sensor inputs; temperature, air humidity andwind speed. These inputs control the linear actuator which in turn opens and closes the roof-hatch.This implementation uses functions created for the DHT22 (4.4.1), the anemometer (4.4.2) andthe linear actuator (4.4.4).

    The temperature is the main input for this software while the air humidity and wind speedcan be seen as safety parameters. To start, the system will need some set values to act around.This includes a set temperature (preferred temperature in the greenhouse), the maximum windspeed accepted and the maximum percentage of air humidity accepted. These set values willcontinuously be compared to current values from the sensors. This can only be done every twoseconds due to the DHT22 data read sequence (section 4.4.1). When comparing the temperature,if it’s above the preferred temperature a linear relationship between the motor extension intervaland the temperature interval is made (see equation 4.4).

    y =Mmax −MminTbound − Tset︸ ︷︷ ︸

    Slope

    ∗x+Mmin −Mmax −Mmin|Tbound − Tset|

    ∗ Tset︸ ︷︷ ︸Intercept

    (4.4)

    where Mmax is the maximum percentage of extension for the motor,Mmin is the minimum percentage of extension for the motor,Tbound is the upper boundary for the temperature,Tset is the set temperature which the system should strive for.

    If the wind speed exceeds or is equal to the set limit for 6 samples the roof-hatch will close.This is done in order to prevent the system from reacting to wind gusts. A sample is done ap-proximately every third second meaning that the wind speed must be high for at least 18 seconds

    29

  • before the roof-hatch will be closed. The same principle goes for the air humidity, it has to havebeen higher or equal to the set limit for 6 samples before opening the roof-hatch fully.

    Further, if the wind speed or air humidity has triggered a change in the roof-hatch, the temper-ature can not control the roof-hatch until the parameters are below their limits again. The valueshave to be below the limits for 6 samples, yet again. This is done to avoid anomalies and insteadlook for patterns. Figure 4.12 shows a simplified flowchart over the aforementioned software.

    Figure 4.12: Simplified flowchart over roof-hatch software

    4.5.3 Irrigation SoftwareIn order to have timer-set irrigation, the alarm function incorporated within the Real Time Timer(RTT) in the processor is used. The RTT possesses the ability to generate an interrupt when theconfigured value (time) has been reached. The RTT is configured to decrement the counter everysecond. Thus, the value the alarm is configured with corresponds to the number of seconds thetimer shall wait before generating an alarm.

    When the duration configured have passed the RTT will as mentioned generate an interrupt,the handler used to process the interrupt sets an alarm flag which acts as a condition in order tosubsequently clear the output that controls the relay for the solenoid. Additionally, a flag thatindicates that the solenoid is opened is set, this is to prevent multiple queries simultaneously. Theslow clock that controls peripherals like the RTT in the processor is configured to have a clockspeed of 32.768 kHz. Thus, in order to generate a 1 Hz periodic counter with the RTT (accordingto the data-sheet [29]) it shall be initialized with a prescaler of 32.768 kHz. The NVIC for theRTT (discussed in section 3.6.1) is initialized to enable the interrupts to occur.

    It was discovered that a systematic error was present in the alarm-times for the solenoid. Theerror appeared to be linearly increasing with the input value. Hence, a linear regression model wasinvestigated (with the help of Mathematica [34]) on some arbitrary input values between 0 and30 shown in figure 4.13. The "best fit" model resulted as shown in equation 4.5 and is plotted infigure 4.13. The raw sampled data (measured using an oscilloscope) can be seen in appendix Atable A.1.

    1.1469x+ 0.125488 (n = 31) (4.5)

    In order to compensate for this the systematic error needs to be subtracted from the "inputvalue". That is, if the consumer wants to keep the valve open for 10 seconds, the alarm shallinstead be loaded with a value that takes the error at 10 seconds into account. The function forcalculating the load-value with compensation is shown in equation 4.6.

    30

  • Figure 4.13: Linear Regression Model Plot

    LV (x) = x− �= x− (1.1469x+ 0.125488︸ ︷︷ ︸

    regression fit

    −x)

    = 0.8531x− 0.125488

    (4.6)

    where x is the desired opening time for the valve,� is the systematic error,LV (x) is the load value with error compensation.

    Now, due to the nature of integers and that the value that LV (x) returns is a float, there isinevitably an error introduced when rounded to the nearest integer. However, this error will berelatively low compared to the set value and the difference in actual water-flow will be minimal.

    To achieve the schedule functionality (discussed in 3.4), five functions obtained from the Com-puter engineering part is utilized. One returns the current hour (0–23, retrieved from database),one returns the last hour that irrigation was done and one is to notify that a new irrigation havebeen executed. Furthermore, one function returns the desired irrigation interval (in hours) andone the duration that the valve shall be opened every interval.

    Algorithm 6 calculates the time difference between the current time and the time of the lastirrigation. Subsequently, if the desired interval have elapsed the solenoid will be set with theduration desired.

    Algorithm 6 Evaluate Solenoidif watering_duration > 0 then

    if last_watering_hour > current_hour thentime_difference = 24− |last_watering_hour − current_hour|

    elsetime_difference = current_hour − last_watering_hour

    end ifif time_difference ≥ watering_interval thenset_irrigation_time(watering_duration)

    end ifend if

    4.5.4 Periodic TickerAs discussed in section 3.5 the usage of a periodic ticker can be utilized to be able to execute certaincode at certain intervals. The implementation of such functionality is here shown. The Timer

    31

  • Counter (TC) incorporated in the processor [29] will be used to obtain the "ticker" functionality.TC is configured to generate an interrupt with a frequency of 1Hz. The handler (discussed insection 3.6.1) that administer the interrupt generated will increment a ticker variable as well asactivate a ticker_triggered flag. If something shall be executed every 10 seconds one can utilizethe aforementioned functionality with the condition that the ticker variable modulo 10 shall beequal to 0. Continuously monitor this will, however, lead to multiple executions as the conditionwill be satisfied for 1 second until the ticker variable is again incremented. To prevent this fromhappening a executed flag is introduced. An example of two different tasks that shall be executedevery 3 and 10 seconds respectively as well as a task that shall be executed "continuously