Internet Of Things And Arduino - Halvorsen.blog

Transcription

https://www.halvorsen.blogInternet of Thingsand ArduinoHans-Petter Halvorsen

Table of Contents IntroductionArduinoTemperature SensorsLowpass FilterPID Controller and Arduino Analog OutArduino LibraryAir HeaterThingSpeakLabVIEW LINXCyber Security

Introduction Cloud services and IoT solutions arebecoming increasingly popular. Even the industry embrace IoT as IndustrialInternet of Things (IIoT) IIoT is an important part of the nextgeneration Automation Systems We will use Arduino as our IoT device Arduino is popular to use in different IoTapplications

Topics Internet of Things (IoT)Microcontrollers (Arduino)PWM (Pulse Width Modulation)AutomationThingSpeak (IoT Cloud Service)Cyber Security

Delivery In this Assignment we will create an embedded Arduino PI(D)controller from scratch. One of the challenges is that Arduino UNO has no Analog Out. How can we solve that? The Data should be stored in the Cloud The Final System should be tested on the Air Heater System, i.e., youshould control the Air Heater System Compare the results using LabVIEW LINX You should start your work by creating a System sketch. In that wayyou will get an overview of the system you are going to create and areable to plan your work and progress, so you are finished within thegiven deadlineFor more details, see the web site

https://www.halvorsen.blogArduinoHans-Petter HalvorsenTable of Contents

ArduinoReset buttonUSB for PCconnectionExternal PowerSupplyDigital ports (2-13)632Analog In ports (0-5)15V, GND 45

Arduino SoftwareUpload Code to Arduino BoardSaveOpen Serial MonitorCompile and Checkif Code is OKCreates a New Code WindowIn this windowyou create yourProgramOpen existing CodeAn be downloaded for free:www.arduino.ccError Messagescan be seen here

ArduinoProgramsAll Arduino programs must follow the following main structure:// Initialization, define variables, etc.void setup(){// Initialization.}void loop(){//Main Program.}

Blinking LED ExampleArduino UNO has a builtin LED that is connectedto Port 13void setup(){pinMode(13, OUTPUT);}void loop(){Turn ON LEDdigitalWrite(13, HIGH);Wait 1 Seconddelay(1000);digitalWrite(13, LOW);Turn OFF LEDdelay(1000);Wait 1 Second}

https://www.halvorsen.blogTemperature SensorsHans-Petter HalvorsenTable of Contents

Temperature SensorsTMP36 Temperature Sensor10k Thermistor Temperature Sensor 5V10π‘˜ ThermistorAnalog In (AI)𝑅 10π‘˜Ξ©GND

https://www.halvorsen.blogLowpass FilterHans-Petter HalvorsenTable of Contents

Lowpass FilterThe Transfer Function for a Low-pass filter is given by:𝑦' (𝑠)1𝐻 𝑠 𝑦(𝑠) 𝑇' 𝑠 1Where:𝑦 is the Signal from the DAQ device(that contains noise)𝑦! is the Filtered Signal𝑇! is the Filter Time ConstantWhy Lowpass Filter? In Measurement systems and Control Systems we typically need to deal with noise Noise is something we typically don’t want Lowpass Filters are used to remove noise from the measured signals Noise is high-frequency signals A Lowpass Filter make sure the low frequencies pass (the measurements) and removesthe high frequencies (the noise)

Discrete Lowpass FilterLowpass Filter:𝑦! (𝑠)1𝐻 𝑠 𝑦(𝑠)𝑇! 𝑠 1We can find the Differential Equation for this filterusing Inverse Laplace:𝑇! 𝑦̇! 𝑦! 𝑦We use Euler Backward method: π‘₯Μ‡ " # " # %𝑦! π‘˜ &"&" (&!𝑦! π‘˜ 1 𝑇' π‘Žπ‘‡! 𝑇'Finally, we get the following discreteversion of the Lowpass Filter:&!Then we get:𝑦! π‘˜ 𝑦! π‘˜ 1𝑇! 𝑦! π‘˜ 𝑦 π‘˜π‘‡'This gives:We define:𝑦! π‘˜ 1 π‘Ž 𝑦! π‘˜ 1 π‘Žπ‘¦ π‘˜&!&" (&!𝑦 π‘˜This equation can easily beimplemented using the Arduinosoftware or another programminglanguage

https://www.halvorsen.blogPID ControllerHans-Petter HalvorsenTable of Contents

PID Controller&𝐾#( π‘’π‘‘πœ 𝐾# 𝑇' 𝑒̇𝑒 𝑑 𝐾# 𝑒 𝑇 %Where 𝑒 is the controller output and 𝑒 is thecontrol error:𝑒 𝑑 π‘Ÿ 𝑑 𝑦(𝑑)π‘Ÿ is the Reference Signal or Set-point𝑦 is the Process value, i.e., the Measured valueTuning Parameters:𝐾!𝑇"𝑇#Proportional GainIntegral Time [sec. ]Derivative Time [sec. ]

Discrete PI controllerWe start with the continuous PI Controller:𝐾" %𝑒 𝑑 𝐾" 𝑒 . π‘’π‘‘πœπ‘‡# We derive both sides in order to removethe Integral:𝑒̇ 𝐾) 𝑒̇ 𝐾)𝑒𝑇*We can use the Euler Backward Discretization method:π‘₯Μ‡ π‘₯ π‘˜ π‘₯ π‘˜ 1𝑇&Where 𝑇' is the Sampling TimeThen we get:𝑒' 𝑒'()𝑒' 𝑒'() 𝐾" 𝐾" 𝑒𝑇&𝑇&𝑇# 'Finally, we get:𝑒8 𝑒89: 𝐾; 𝑒8 𝑒89:Where 𝑒# π‘Ÿ# 𝑦#𝐾; 𝑇 𝑒8𝑇

Alternative PI controllerWe can also put the PI Controller onTransfer Function form (we use Laplace):𝐾;𝑒 𝑠 𝐾; 𝑒 𝑠 𝑒 𝑠𝑇 𝑠%We can set 𝑧 𝑒 𝑠𝑧 𝑒 𝑧̇ 𝑒'This gives:𝑧̇ 𝑒𝐾)𝑒 𝐾) 𝑒 𝑧𝑇*This is the PI controller on State-space formUsing Euler, we get the following discrete PIcontroller:𝑒# π‘Ÿ# 𝑦#𝐾)𝑒# 𝐾) 𝑒# 𝑧𝑇* #𝑧#(% 𝑧# 𝑇' 𝑒#This algorithm can easily be implemented in theArduino software.

Arduino Analog OutThe Output (typically 0-5V) of the PI(D)controller should be sent to the process.Arduino UNO has no Analog Output PinsSolutions: Smooth PWM output using RC Circuit DAC chip (Digital to Analog Converter)

Smooth PWM output using RC CircuitPWM SignalRC Circuit(HardwareLowpass Filter)β€œReal” Analog Signale.g., 𝑅 3.9π‘˜Ξ©e.g., 𝐢 10πœ‡πΉ

Electrical ComponentsCapacitore.g., 𝐢 10πœ‡πΉResistor𝑅 3.9π‘˜Ξ©A capacitor stores and releases electrical energy in acircuit. When the circuits voltage is higher than what isstored in the capacitor, it allows current to flow in, givingthe capacitor a charge. When the circuits voltage is lower,the stored charge is released. Often used to smoothfluctuations in voltagehttps://en.wikipedia.org/wiki/CapacitorA resistor resists the flow of electrical energy in acircuit, changing the voltage and current as a result(according to Ohms law, π‘ˆ 𝑅𝐼). Resistor values aremeasured in ohms (Ξ©). The color stripes on the sidesof the resistor indicate their values. You can also usea Multi-meter in order to find the value of a givenresistor.These electronics components are typically included in a β€œStarter Kit”, or they can be bought β€œeverywhere” for a few bucks.

DAC ChipArduino UNO has no Analog Output Pins, so we need aDAC such as, e.g., Microchip MCP4911, MCP4725 orsimilarMCP4725MCP4911: 10-bit single DAC, SPI Interface12-bit resolutionI2C InterfaceThe MCP4725 is a little moreexpensive, but simpler to useMicrochip MCP4911 can be bought β€œeverywhere” (10 NOK).

PWMPWM is a digital (i.e., square wave) signal that oscillates according to a given frequency andduty cycle.The frequency (expressed in Hz) describes how often the output pulse repeats.The period is the time each cycle takes and is the inverse of frequency.The duty cycle (expressed as a percentage) describes the width of the pulse within thatfrequency window.You can adjust the duty cycleto increase or decrease theaverage "on" time of thesignal. The following diagramshows pulse trains at 0%,25%, and 100% duty:

https://www.halvorsen.blogArduino LibraryHans-Petter HalvorsenTable of Contents

Arduino LibraryWhy create your own Libraries? Better Code structure Reuse your Code in different Applications Distribute to othersYou need at least two files for a library: Header file (.h) - The header file has definitions for the library Source file (.cpp) – The Functions within the ClassNote the Library Name, Folder name, .h and .cpp files all needto have the same name

Arduino Library Example#include Fahrenheit.h Fahrenheit fahr;void setup(){float f;float c;Serial.begin(9600);}void loop(){.f fahr.c2f(c);Serial.println(f);.c fahr.f2c(f);Serial.println(c);}

https://www.halvorsen.blogAir HeaterHans-Petter HalvorsenTable of Contents

Air Heater SystemWe can, e.g., use thefollowing values in thesimulation:πœƒ% 22 π‘ πœƒ* 2 𝑠 𝐾 3.5𝑉𝑇,-. 21.5 Mathematical Model:𝑇̇GHI1 𝑇GHI 𝐾J 𝑒 𝑑 πœƒK 𝑇LMNπœƒI

Discrete Air HeaterContinuous Model:𝑇̇GHI 1 𝑇GHI 𝐾J 𝑒 𝑑 πœƒK 𝑇LMNπœƒIWe can use e.g., the Euler Approximation in order to find the discrete Model:π‘₯ π‘˜ 1 π‘₯ π‘˜π‘₯Μ‡ 𝑇&𝑇' - Sampling Timeπ‘₯ π‘˜ - Present valueπ‘₯ π‘˜ 1 - Next (future) valueThe discrete Model will then be on the form:π‘₯ π‘˜ 1 π‘₯ π‘˜ We can then implement the discrete model in any programming language

https://www.halvorsen.blogThingSpeakHans-Petter HalvorsenTable of Contents

ThingSpeak ThingSpeak is an IoT analytics platform servicethat lets you collect and store sensor data in thecloud and develop Internet of Things applications. ThingSpeak has a free Web Service (REST API) thatlets you collect and store sensor data in the cloudand develop Internet of Things applications. It works with Arduino, Raspberry Pi, MATLAB andLabVIEW, Python, etc.https://thingspeak.com

ThingSpeak Arduino

ThingSpeak Arduino Install the β€œthingspeakβ€œ Arduino Library using the LibraryManager in your Arduino IDE Use e.g., the built-in example "WriteSingleField" as a startingpoint. This example is available for different boards andconfiguration, such as Arduino WiFi rev2 board, Arduino WiFishield, etc. Then you can modify the example to suit your needsCurrently, a single channel can only beupdated once every 15 seconds.

ThingSpeak ArduinoThis Example uses an Arduino WiFi rev2board.The Example reads values from TMP36Temperature Sensor and write the valuesto ThingSpeak#include "ThingSpeak.h"#include WiFiNINA.h #include "secrets.h"char ssid[] SECRET SSID;// your network SSID (name)char pass[] SECRET PASS;// your network passwordint keyIndex 0;// your network key Index number (needed only for WEP)WiFiClient client;unsigned long myChannelNumber SECRET CH ID;const char * myWriteAPIKey SECRET WRITE APIKEY;int channelField 3;int SensorPin 0;float adcValue;float voltageValue;float temperatureValue 0;int samplingTime 20000; // Wait 20 seconds between each hannel updatevoid setup() {Serial.begin(115200); // Initialize serialif (WiFi.status() WL NO MODULE) {Serial.println("Communication with WiFi module failed!");// don't continuewhile (true);// Use this file to store all of the private credentials}// and connection detailsString fv WiFi.firmwareVersion();if (fv ! "1.0.0") {Serial.println("Please upgrade the firmware");#define SECRET SSID "MySSID"// replace MySSID with your WiFi network name}secrets.h#define SECRET PASSThingSpeak.begin(client);"xxxxxx"//Initialize ThingSpeak// replace MyPassword with your WiFi password#define SECRET CH ID 000000// replace 0000000 with your channel number}#define SECRET WRITE APIKEY"XYZ"// replace XYZ with your channel write API Keyvoid loop() {// Connect or reconnect to WiFiif(WiFi.status() ! WL CONNECTED){Serial.print("Attempting to connect to SSID: ");Serial.println(SECRET SSID);while(WiFi.status() ! WL CONNECTED){WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP ln("\nConnected.");}adcValue analogRead(SensorPin); // Get Data from Temperature SensorvoltageValue (adcValue*5)/1023;temperatureValue 100*voltageValue - 50;Serial.println(temperatureValue);// Write to ThingSpeakint x ThingSpeak.writeField(myChannelNumber, channelField, temperatureValue, myWriteAPIKey);if(x 200){Serial.println("Channel update successful.");}else{Serial.println("Problem updating channel. HTTP error code " String(x));}delay(20000); // Wait 20 seconds to update the channel again}

Read/Write using a Web BrowserSet Kp Remotely Example:Enter the following in a Web Browser (or from a Programming Language)We set Kp 2https://api.thingspeak.com/update?api key WriteKey &field3 2Read Kp Remotely Example:https://api.thingspeak.com/channels/ ChannelId /fields/3/last.json?key ReadKey Response in Browser: {"created at":"2017-06-26T07:41:54Z","entry id":1270,"field3":"2"}We read Kp 2

https://www.halvorsen.blogLabVIEW LINXHans-Petter HalvorsenTable of Contents

LabVIEW LINXThe LabVIEW LINX Toolkit adds supportfor Arduino, Raspberry Pi, etc.

LabVIEW LINX Example

ThingSpeak LabVIEW ThingSpeak uses standard HTTP REST API,which can be used from any kind ofProgramming Language, including LabVIEW In LabVIEW you can use the HTTP client VIshttps://api.thingspeak.com/update?api key xxxxxxx&field1 22.5

ThingSpeak LabVIEW

https://www.halvorsen.blogCyber SecurityHans-Petter HalvorsenTable of Contents

Cyber Security and IoT IoT solutions and Data Security? How can we makesure our applications and data are safe? Security is crucial in IoT/IIoT Applications. Why? What issues do we need to deal with regarding IoTand Cyber Security? What can be (or what have you) done to protect thesystem (and data) you have created? How does ThingSpeak handle security? Etc.

Hans-Petter HalvorsenUniversity of South-Eastern Norwaywww.usn.noE-mail: hans.p.halvorsen@usn.noWeb: https://www.halvorsen.blog

Internet of Things (IIoT) IIoT is an important part of the next generation Automation Systems . will use Arduino as our IoT device Arduino is popular to use in different IoT applications Introduction Internet of Things (IoT) Microcontrollers (Arduino) PWM (Pulse Width Modulation) Automation ThingSpeak (IoT Cloud Service .