Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:iot-open:remotelab:sut:generalpurpose2:u7 [2019/08/08 16:00] pczekalskien:iot-open:remotelab:sut:generalpurpose2:u7 [2020/07/20 09:00] (current) – external edit 127.0.0.1
Line 1: Line 1:
-==== U7: ==== +==== U7: Controlling fan speed and servo angle via MQTT ==== 
-//Give few words about this scenario. Provide some objectives and impact on the students.//+In this scenario, you will learn how to remotely control fan speed using PWM and how to control servo angle using MQTT messages. This scenario is a practical extension to the scenario U4 where you learned, how to receive and handle MQTT messages.
 === Target group === === Target group ===
-//This hands-on lab guide is intended for the Beginners/Undergraduates/Masters/Professionals. Choose appropriate.//+Undergraduate Bachelor Engineering Students
  
 === Prerequisites === === Prerequisites ===
-//Provide prerequisite readings/hardware/software/software libraries/skills if other than stated in the Laboratory DescriptionIf noneremove along with the headerPlease note some of those may be common for all scenarios (i.e. MQTT library)so provide it in the laboratory description levelnot in the scenario level.//+We assume you already know how to: 
 +  * handle LCD screen to present information, 
 +  * connect to the existing WiFi network: internal.IOT, 
 +  * receive and handle MQTT messages using ''PubSubClient'' library 
 +  * additionally we will ask you to install and use an MQTT client of your choice. We suggest using MQTT Spy, but any MQTT client that will let you subscribe to the MQTT messages is OKYou connect it to the public IP of the MQTT broker (see below). 
 +MQTT broker present in the internal.IOT network is also visible under public address. So whenever you subscribe to the MQTT message using VREL node that is connected to the internal.IOT networkyou may publish to it using other devices connected to the internal.IOT, i.e. other VREL node or if you're physically present at SUT in the IOT laboratory room 320, then you can connect your mobile and laptop to the internal.IOT network and use “internal” IP address. However, if you're in a remote location, you can access the same broker under public IP as stated in the node description. When you publish an MQTT message using public IPit will be delivered to the subscribers in the private internal.IOT network as well. Mind, to access MQTT broker you need to use IP, user and password (applies to both public and private IPs of the MQTT Broker). Refer to the node documentation for the latest information. 
 +<note important>Note - information present in source code samples can be not up-to-date - remember to refer to the VREL node documentation for the latest information on IPs, users and passwords for both internal.IOT network access and for the MQTT Broker.</note> 
 + 
 +<note warning>Warning - physical servo range is ONLY between 0 and 90 degrees! Going over 90 degrees may cause a break to the equipment and you may be charged for repair!</note> 
 + 
  
 === Scenario === === Scenario ===
-//Describe scenario to let the user understand its idea and process. Write information about the approach, algorithm, etc(depends on the lab). Provide useful information about protocols, assumptions, addresses (i.e. communication servers), credentials, etc.//+In this scenario, you will handle incoming MQTT messages (one for controlling fan, other for servo, opening and closing the flapParallelly you will present incoming messages on the LCD screen.
  
 === Result === === Result ===
-//Describe expected result when scenario is finished.//+You should be able to remotely control fan rotation speed and flap angle (0..90 degrees), observe connection status and incoming MQTT messages for your device on the LCD screen.
  
 === Start === === Start ===
-//Write starting conditionsi.e. what to do at the beginning, what to pay attention before beginninghow the mechanical part should look like etc.//+Define some identifiers to separate and update AP's SSID and passphrase easily. To format lines for the LCDwe suggest using a char buffer of 20 characters (one full line) and some 2-3 integers for iterators and storing current PWM for servo and fanRemember to declare the LCD control class in your code. You do not need to instantiate WiFi communication class - as you have only one interface hereit is singleton class you can refer directly using WiFi. Reading analogue input brings you an integer value. 
 + 
 +Servo is controlled using GPIO pin D5 (GPIO14) while the fan is controlled using GPIO pin D8 (GPIO15). As servo we use is a small one, it is powered and controlled directly through the ESP8266 while in case of the FAN, it is controlled indirectlyusing a transistor. 
 + 
 +<note warning>Legal range for the servo is 0...90 degree! Exceeding over 90 degrees may break the construction!</note> 
 +<note tip>Valid range for controlling fan is 0 (stopped) till 4095 (full speed). Please note, characteristics are non-linear, so setting output 2047 does not mean that rotation speed nor airflow is half of the maximum.</note>
  
 === Steps === === Steps ===
-// Write some extra information if i.e. some steps are optional otherwise cancel this paragraph (but do not remove header).//+Following steps do not present full code - you need to supply missing parts on your own! We do not present here how to connect to the WiFi APIf you're in doubt, rever to the U1 scenario. Please refer to scenario B1, if you need a recall on how to handle LCD screen. In case you're in doubt how to handle MQTT messages communication (here publishing/sending), please refer to the U4 scenario.
 == Step 1 == == Step 1 ==
-//Describe activities done in Step 1.//+Include all necessary libraries. We use PubSubClient library to contact MQTT broker. The minimum set here is: 
 +<code c> 
 +#include <Arduino.h> 
 +#include <ESP8266WiFi.h> 
 +#include <PubSubClient.h> 
 +#include <LiquidCrystal_I2C.h> 
 +#include <Servo.h> 
 +... 
 +</code> 
 +Here we use ''Servo.h'' library to easily handle servomotor control for regular, modeller's servos, mostly used in RC toys.  
 +Declare some identifiers to let you easier handle necessary modifications and keep code clear: 
 +<code c> 
 +#define wifi_ssid "internal.IOT" 
 +#define wifi_password "IoTlab32768" 
 +#define mqtt_server "192.168.90.5" 
 +#define mqtt_user "vrel" 
 +#define mqtt_password "vrel2018" 
 +... 
 +</code> 
 + 
 +== Step 2 == 
 +Declare some identifiers, here MQTT messages' topics, MQTT client ID and payloads for the status notification (on / off). 
 +<note important>Use unique names for topics and for the MQTT client, do some random, use your MAC as part of it. It is important because MQTT broker identifies client using its name thus if your device shares name with some other that is already working, you may not get information about connection lost because another device with the same name is still active on the network. Unique topics are also essential: if you accidentally overlap, you may get an invalid reading with someone that is using the same topic but different payload.</note> 
 +<code c> 
 +// MQTT messages 
 +#define MQTTClientName "myVREL2clientname" 
 +#define servoTopic ...<some topic for servo>... // give it some unique topic  
 +                                                // i.e. including your name 
 +#define fanTopic   ...<some topic for fan>...   // give it some unique topic  
 +                                                // i.e. including your name 
 + 
 +//MQTT last will 
 +#define lastWillTopic ..<some topic for exposing state and last will>...    
 +                                                // give it some unique topic  
 +                                                // i.e. including your name 
 +#define lastWillMessage "off" 
 +#define mqttWelcomeMessage "on" 
 +</code> 
 +Finally, declare GPIOs pin numbers connecting to the servo and fan: 
 +<code c> 
 +//Hardware 
 +#define PWMFanPin D8  
 +#define servoPin D5 
 +</code>
  
 +== Step 3 ==
 +Declare ''WiFiCilent'', ''PubSubClient'', initialise, instantiate and connect to the network. If in doubt, refer to the scenario U4 on how to prepare networking code for your solution.
 +Additionally, instantiate a servo controlling the flap:
 +<code c>
 ... ...
 +Servo servo;
 +...
 +</code>
  
-== Step == +Later, in your initialisation section (possibly in ''setup()'' function) bind your servo with physical one using appropriate GPIO and set it to 0 degrees (close the flap, down). Also, initialise fan's GPIO for output, to control PWM and set it to 0 (stop fan): 
-//Describe activities done in Step n.//+<code c> 
 +... 
 +void setup() 
 +
 +... 
 +  // Servo and PWM fan 
 +  servo.attach(servoPin); 
 +  servo.write(0);  //set servo down to 0 degrees 
 +  pinMode(PWMFanPin,OUTPUT); 
 +  analogWrite(PWMFanPin,0); //stop FAN 
 +... 
 +</code> 
 + 
 +Note - here you see how to control servo and fan. In the case of the servo, we use a ''Servo'' library, so function ''servo.write(deg)'' sets servo to the desired number of degrees. While the fan is controlled using RAW values on 12bit resolution (in fact it is PWM as well) from 0 to 4095, using ''analogWrite(pin, value)''. Word "analog" may mislead you here: output on the digital pin is not a continuous analogue voltage value, but its approximation using PWM anyway, it works perfectly for the fan and many other devices. 
 + 
 +== Step == 
 +Implement MQTT callback - a function that is being called, whenever there comes an MQTT message. You should have subscribed only to the selected MQTT messages (one for the fan, other for the servo) so only those messages may trigger your callback function. Anyway, it is a matter to distinguish, which one message comes. Your function may look like this: 
 +<code c> 
 +void mqttCallback(char* topic, byte* payload, unsigned int length) { 
 +  lcd.setCursor(0,2); 
 +  lcd.print("Servo:"); 
 +  lcd.setCursor(0,3); 
 +  lcd.print("Fan:"); 
 +  String sTopic(topic); 
 +  if(sTopic.startsWith(servoTopic)) 
 +  { 
 +    //Handle servo message 
 +    for(int i=0; i< length; i++) 
 +      { 
 +        buffer[i] = (char)payload[i]; 
 +      } 
 +    buffer[length]='\0'; 
 +    srv = atoi(buffer); 
 +    servo.write(srv); 
 +    lcd.setCursor(9,2); 
 +    sprintf(buffer,"%2d deg",srv); 
 +    lcd.print(buffer); 
 +  } 
 +  if(sTopic.startsWith(fanTopic)) 
 +  { 
 +    //Handle fan message 
 +    for(int i=0; i< length; i++) 
 +      { 
 +        buffer[i] = (char)payload[i]; 
 +      } 
 +      buffer[length]='\0'; 
 +      fan = atoi(buffer); 
 +      analogWrite(PWMFanPin,fan); 
 +      lcd.setCursor(7,3); 
 +      sprintf(buffer,"%4d PWM",fan); 
 +      lcd.print(buffer); 
 +  }  // give it some unique topic i.e. including your name 
 +
 +</code> 
 +As you see, we do not only receive the value but also drive LCD display to present it. Still you may inject some validation code, particularly for the servo, i.e. check if incoming MQTT payload for the servo message is more than 90 degres then truncate it not to break the device physically. 
 +== Step 5 == 
 +Remember to bind your MQTT callback function to the MQTT PubSubClient. Perhaps you will do it in the ''setup()'' or in the ''reconnect()'' functions: 
 +<code c> 
 +... 
 +client.setCallback(mqttCallback); 
 +... 
 +</code>
  
 === Result validation === === Result validation ===
-//Provide some result validation methods, for self assesment.//+Observe flap moving out and in. As the fan is mounted perpendicular to the video camerayou cannot observe rotation directly (video stream is too slow to present it on the other hand). You can observe value on the analogue gauge to the right but also indirectly through the flap mounted in the corresponding air receiving node (RX). Those are VREL1 and VREL3 for sending nodes VREL2 and VREL4 respectively. You will see the air stream pushing the flap thus you can monitor the airflow.
  
 === FAQ === === FAQ ===
-This section is to be extended as new questions appear. \\ +**What is the valid range for controlling the fan?**: The fan is connected to the digital pin and controlled via PWM (12-bit resolution). Thus valid range is from 0 (min) to 4095 (max). Note rotation speed and airflow do not have linear characteristic vs PWM controlling value, So issuing 2047 on the GPIO pin controlling the fan won't make your fan to rotate 50% nor the airflow will be 50% of the maximum oneYou need to experiment individually!\\ 
-When using the printed version of this manual please refer to the latest online version of this document to obtain the valid and up-to-date list of the FAQ. +**What is the valid range for controlling the servo?**: The valid range is from 0 to 90 degreesExceeding 90 degrees can break the construction! Never go beyond 90 degrees!
-//Provide some FAQs in the following form:\\ +
-**Question?**: Answer. +
-// +
en/iot-open/remotelab/sut/generalpurpose2/u7.1565280021.txt.gz · Last modified: 2020/07/20 09:00 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0