In this lesson, we will show how to remote control a servo motor via MQTT protocol.
Overhere,we use A0 as the analog input pin.
Connect the NodeMCU to computer via USB cable,open this sketch by using Arduino IDE(Version1.6.4+):
Edit the code to fit your own WiFi and MQTT settings as following operations:
const char* ssid = “your_hotspot_ssid”;
const char* password = “your_hotspot_password”;
Find above code line,put your own ssid and password on there.
2)MQTT Server Address Setting
const char* mqtt_server = “broker.mqtt-dashboard.com”;
You can use your own MQTT broker URL or IP address to set above mqtt_server value. You can also use some famous free MQTT server to test the project such as “broker.mqtt-dashboard.com”, “iot.eclipse.org” etc.
3)MQTT Client Settings
If your MQTT broker require clientID,username and password authentication,you need to change
if (client.connect(clientId,userName,passWord)) //put your clientId/userName/passWord here
If not,just keep them as default.
After do that,choose the coresponding board type and port type as below,then upload the sketch to the NodeMCU.
About how to config the MQTT client,check this link.
Onece the upload done,if wifi hotspot name and password setting is ok and MQTT broker is connected, open the Serial Monitor,you will see following result:
The NodeMCU serial port will show the IP address and the connection satatus, then print the message for the nodemcu subscription:The rotation angle of this servo.
Overhere,we should note:After upload down,the servo motor will rotate to a position of 90 degrees,we’d better to set it to 0 degree.Do as following operations:
1. Open your MQTT client,make sure they are “Conneted” to the MQTT broker.
2. Type “0” to the “Payload” frame，choose “Decimal Array” for your payload type,then publish this data.
After completed above operations, you can see the servo motor turns to 0 degree and the Serial Monitor will output:”[OsoyooCommand: Rotation angle is: 0 °]”
Then,you can control the servo by publishing any integer between 0 and 180 via MQTT protocol.
The SG90 micro servo is a 180 degree servo motor,so its rotation angle can not be greater than 180 degrees.
DownLoad Url osoyoo.com