Keywords: MQTT, IoT, Motor Control, PWM control, GPIO, ESP8266-ThingSpeak, Connecting ESP8266 to WiFi, ESP8266, MicroPython, uPyCraft, Connecting ‘Thing – ESP8266’ to ‘Internet’, ESP8266-IoT
We hear many times the word IoT, after all what does this word mean – Internet of Things, that seems to be the full form but what does Internet of Things mean???????
Yes you guessed it right, connecting Things to Internet. Things can be sensors, machines, cars, etc.
I have ‘Things’ with me like motor and LED, now I have to send the motor average voltage value to server. For that I need a cloud space to Visualize live data and this platform would be ‘ThingSpeak‘. Now what is this ‘ThingSpeak‘ – ThingSpeak is an IoT analytics platform service that allows us to visualize live data streams in the cloud. We can send data to ThingSpeak from our devices, create instant visualization of live data, and send alerts. It is free of cost but with some limitations.
Now lets learn about how to connect Things – Servo Motor to Internet
Prerequisites:
- ThingSpeak Account – You can follow the below steps to create and account in ThingSpeak.
- Step 1 – Sign Up
-
- Step 2 – Click on Create Account and enter valid email address.
-
- Step3 – Click on continue.
-
- Step4 – Click on continue.
-
- Step 5 – Click on continue, you would receive an email from Mathworks which is an activation link for ThingSpeak.
-
- Step 6 – Once clicked on the emailed link, it states that the profile is verified.
-
- Step 7 – Once email is verified crate a password for this account.
-
- Step 8 – After login the page would be like this
-
- Step 9 – To create a new channel follow this link
- Step 10 – This is the channel which I have created.
Now that we are done with setting ThingSpeak server account and creating channels and fields, we have achieved the Internet part. Here comes the great challenge, Thing is ready and Internet is ready but connection is still pending. How do we connect this, we need a medium which is capable of connecting thing to internet which I choose to be ESP8266 WiFi board here.
There are many IoT protocols but MQTT is most commonly used.It basically works on Publish and Subscribe model.
Here are few terminologies used in MQTT
Client
The Client is some thing which gets connected to server. For example I am using my laptop/mobile/desktop to connect to google website, so my laptop/mobile/desktop is a client and google is a server.
Broker
The MQTT broker (or server) is the central server to which all MQTT clients connect. The MQTT broker manages message topics. When a client updates a topic, the broker sends the new messages to all of the clients who subscribed the same topic.
Topic
MQTT Messages are arranged in a hierarchy of topics that are addressed as UTF-8 strings. Levels in the topic hierarchy are separated by forward slash characters (ā/ā) similar to how files are arranged on your local disk. Topic strings (paths) are used to access MQTT messages in the same way file paths are used to access files.
For example: āmyChannel/field1/voltageā and āmyChannel/field2/stateā.
Publish
If a client updates the data associated with topic in broker, it is called Publishing. If any client subscribes for that same topic the same updated data is reflected and broker publishes new messages for the topicās subscribers . There is no limit to the number of clients that can publish to a topic.Ā Clients can only publish to one topic at a time.
Subscribe
Once a client subscribes to a topic on the MQTT broker, it will receive all of the subsequent messages that have been published to the topic. There is no limit to the number of clients that can subscribe to a topic.Ā Clients can subscribe to either a specific topic such as āmyChannel/field1/voltageā or to a range of topics which would be discussed later.
MQTT Payloads
MQTT payloads are the body of each MQTT message ā the application data carried by the MQTT packet.Ā The payload is data format agnostic and can support anything including text, images, binary numbers, etc.
Prerequisites continued:
- Software
- uPyCraftIDE
- esp8266 latest bin file
- Python
- Hardware
-
- ESP8266 WiFi board
- WiFi broadband/hotspot/LAN
- Servo Motor
-
Environment SetUp
Please go through this link just for reference.
IoT – MQTT publish
- I have already mentioned in my earlier posts about Servo Motor Control and Connecting ESP8266 to WiFi.
- So combining those two codes and adding few more network components, here is the final code which I present.š
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
''' Author : Seetha Akella Purpose : 1.IoT - Connecting Servo Motor to ThingSpeak server 2.Send Average voltage value and Current LED status to server 3.Data transmission rate is considered to be 20 seconds Language : MicroPython Harware : ESP8266, Servo Motor ''' ''' The network module provides network drivers and routing configuration. ''' import network ''' The time module provides functions for getting 1. the current date and time 2. for sleeping ''' import time # The machine module contains specific functions related to the hardware on a particular board. import machine # Network request module import urequests # The building block of most of the internet is the TCP socket # The first thing to do is import socket module import socket ''' class Pin - Control I/O pins The pin class has methods 1. to set the mode of pin (IN, OUT) 2. to get and set the digital logic level ''' from machine import Pin ''' This module provides access to Transport Layer Security (often known as āSecure Sockets Layerā) encryption and peer authentication facilities for network sockets, both client-side and server-side ''' import ussl as ssl from umqtt.simple import MQTTClient # Define a method to connect to a WiFi def do_connect(): ''' Constructor - WLAN Create a WLAN network interface object. Supported interfaces are 1. network.STA_IF (station aka client, connects to upstream WiFi access points) 2. network.AP_IF (access point, allows other WiFi clients to connect) ''' sta_if = network.WLAN(network.STA_IF) ''' Method - isconnected() 1. In case of STA mode, returns True if connected to a WiFi access point and has a valid IP address. 2. In AP mode returns True when a station is connected. Returns False otherwise. ''' if not sta_if.isconnected(): print('connecting to network...') ''' Method - active() Activate (āupā) or deactivate (ādownā) nwk interface, if boolean argument is passed. Otherwise, query current state if no argument is provided. ''' sta_if.active(True) ''' Method - connect() Activate (āupā) or deactivate (ādownā) nwk interface, if boolean argument is passed. Otherwise, query current state if no argument is provided. ''' sta_if.connect('SSID', 'PASSWORD') while not sta_if.isconnected(): sta_if.active(True) pass ''' Method - ifconfig() Get/set IP-level network interface parameters: IP address, subnet mask, gateway and DNS server. When called with no arguments, this method returns a 4-tuple with the above information. ''' print('network config:', sta_if.ifconfig()) do_connect() CHANNEL_ID = "xxxxxxx" WRITE_API_KEY = "xxxxxxxx" response = urequests.get('https://api.thingspeak.com/update?api_key=WRITE_API_KEY&field1=0&field2=0') print(type(response)) SERVER = "mqtt.thingspeak.com" client = MQTTClient("umqtt_client", SERVER) topic = "channels/" + CHANNEL_ID + "/publish/" + WRITE_API_KEY STEP_SIZE = 25 SLEEP_TIME = 20 # set GPIO16 as output pin for LED led = Pin(16,Pin.OUT) # set machine GPIO2 as p2 p2 = machine.Pin(2) # configure PWM on pin p2 pwm2 = machine.PWM(p2) # set the PWM frequency as 50Hz # the frequency must be between 1Hz and 1kHz. pwm2.freq(50) iDutyCycle = 0 # I considered the Maximum voltage value to be 3.3V fVact = 3.3 fVavg = 0 bBlink = 0 while True: bBlink = bBlink ^ 1 if iDutyCycle < 100: iDutyCycle = iDutyCycle + STEP_SIZE else: iDutyCycle = STEP_SIZE pwm2.duty(iDutyCycle) # Average Voltage = Duty Cycle x Actual Voltage Level fVavg = iDutyCycle * (fVact/100) led.value(bBlink) payload = "field1="+str(fVavg)+"&field2="+str(bBlink) client.connect() client.connect() client.publish(topic, payload) print(topic) print(payload) client.disconnect() time.sleep(SLEEP_TIME) |
- Here is the output of this code.
- Now we know how to publish to a server using MQTT protocol. KUDOS!
NOTE : All the code written in posts are all well tried and tested personally.
THANK YOU and many more programs coming your way!
Please put your queries in comment section, I will get back to you with answers ASAP.
Please like and share Techawarey. Find and Like Techawarey on Facebook.š
[…] Connecting ESP8266 to a server Thingspeak/AWS for IoTĀ […]