Code Cart (Little Endian)
In this guide I'll be explaining how you can inplement the code that you need to make the little endian drive forward and rotate based on degrees and milimeters you give it.
Include Libraries:
| #include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
|
These lines include necessary libraries for working with ESP8266, handling WiFi connections, parsing JSON data, and
implementing MQTT (Message Queuing Telemetry Transport) communication.
Define the cart its ID:
This line defines a constant named ADDRESSED_CART with a value of 1.
Set MQTT Server Details:
| const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
|
These lines define the MQTT broker server and port to which the ESP8266 will connect.
Initialize WiFiManager:
This line initializes the WiFiManager library, which helps manage WiFi connections and allows the ESP8266 to act as an access point for configuration.
Define Motor Control Pins:
| int motorRightPin1 = D1; // Input 1 of L293D
int motorRightPin2 = D2; // Input 2 of L293D
int motorRightEnable = D5; // Enable 1 of L293D
int motorLeftPin1 = D3; // Input 3 of L293D
int motorLeftPin2 = D4; // Input 4 of L293D
int motorLeftEnable = D6; // Enable 2 of L293D
|
These lines define the pins used for controlling the motors connected to the L293D motor driver.
Initialize Variables:
| long distance = 6875; // full 360 degree;
long timePerDegree = 5; // time per degree in milliseconds;
long timePerCentimeter = 5; // time per millimeter;
int speed = 255;
bool goForward = false;
bool connected = false;
bool newDataAvailable = false;
long callbackDistance = 0;
long callbackAngle = 0;
|
These lines initialize various variables that will be used throughout the program.
Setup Function:
1
2
3
4
5
6
7
8
9
10
11
12
13 | void setup() {
Serial.begin(9600);
pinMode(motorRightPin1, OUTPUT);
pinMode(motorRightPin2, OUTPUT);
pinMode(motorRightEnable, OUTPUT);
pinMode(motorLeftPin1, OUTPUT);
pinMode(motorLeftPin2, OUTPUT);
pinMode(motorLeftEnable, OUTPUT);
wifiManager.autoConnect("WemosAPC1"); // "WemosAP" is the access point name, change as needed
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}
|
The setup function initializes the serial communication, sets up motor control pins, connects to WiFi using WiFiManager,
and sets up MQTT connection and subscription.
Reconnect Function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
delay(100);
// Attempt to connect
if (client.connect("WemosClient")) {
Serial.println("Connected to MQTT broker!");
// Subscribe to the topic you're interested in
client.subscribe("nietBelangrijkeNlBroker/led");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
// Wait 5 seconds before retrying
delay(5000);
}
connected = false;
}
}
|
The reconnect function attempts to establish and reconnect to the MQTT broker.
Callback Function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
// Parse JSON data
DynamicJsonDocument doc(256); // Adjust the size based on your JSON payload
DeserializationError error = deserializeJson(doc, payload, length);
if (error) {
Serial.print(F("JSON parsing failed! Error code: "));
Serial.println(error.c_str());
return;
}
// Extract individual variables
callbackDistance = doc["distance"];
callbackAngle = doc["angle"];
newDataAvailable = true;
}
|
The callback function is called when a message is received on the subscribed MQTT topic. It parses the JSON payload and
extracts distance and angle data.
Loop Function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | void loop() {
if (!connected) {
connected = true;
reconnect();
}
client.loop();
if (newDataAvailable) {
newDataAvailable = false;
controlMotors(callbackAngle, callbackDistance);
}
callbackDistance = 0;
callbackAngle = 0;
}
|
The loop function continuously checks for MQTT connection, processes MQTT messages, and controls the motors based on received data.
Control Motors Function:
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 | void controlMotors(long angle, long distance) {
Serial.println("Cart starts turning");
int turnTime = angle * timePerDegree;
digitalWrite(motorRightPin1, HIGH);
digitalWrite(motorRightPin2, LOW);
analogWrite(motorRightEnable, 255); // Adjust the PWM value for speed control
digitalWrite(motorLeftPin1, HIGH);
digitalWrite(motorLeftPin2, LOW);
analogWrite(motorLeftEnable, 255); // Adjust the PWM value for speed control
delay(turnTime); // Turn the amount of degrees
// Stop the motors
digitalWrite(motorRightEnable, LOW);
digitalWrite(motorLeftEnable, LOW);
int moveTime = distance * timePerCentimeter;
digitalWrite(motorRightPin1, LOW);
digitalWrite(motorRightPin2, HIGH);
analogWrite(motorRightEnable, 185); // Adjust the PWM value for speed control
digitalWrite(motorLeftPin1, HIGH);
digitalWrite(motorLeftPin2, LOW);
analogWrite(motorLeftEnable, 155); // Adjust the PWM value for speed control
delay(moveTime); // Move the cart forward
// Stop the motors
digitalWrite(motorRightEnable, LOW);
digitalWrite(motorLeftEnable, LOW);
}
|
The controlMotors function is responsible for controlling the motors based on the received angle and distance data.
It uses the L293D motor driver for motor control. First it rotates the cart to the recieved angle from the MQTT and
after rotating it moves the cart forward the amount of distance it recieves from the server.
The overall functionality is to receive MQTT messages containing angle and distance information, and based on this data,
control the motors to make the cart or robot move and turn. The code also handles WiFi configuration using WiFiManager
for easy setup.