Episode 8: Motor control
-
I will be using a dedicated motor driver IC to control the direction and speed of a DC motor via a virtual joystick widget.
I will be using GUI-O Bluetooth Low Energy (LE) connection, but the example can be easily be ported to other connection types.
Software prerequisites:
-
Arduino IDE (https://www.arduino.cc/en/software)
-
ESP32 Arduino board support, if using ESP32 based board (see https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html)
-
GUI-O design tool (https://www.gui-o.com/design-tool)
-
GUI-O application (https://play.google.com/store/apps/details?id=com.guio.guioapp)
-
For additional information about the GUI-O application, download the developer manual from https://www.gui-o.com/
Components needed:
- ESP32-WROOM-32 (or any other Arduino supported Bluetooth Low Energy capable board)
- L239D motor driver
- Small DC motor
The entire tutorial is split into various steps. All necessary information is given in each step.
0. DESIGN THE GUI (optional)
The best way to create a GUI layout is to use GUI-O live designer tool.
Note that the Arduino source code already includes the necessary commands, so this step is not needed, unless you want to make some visual adjustments. If you make adjustments, please include the generated ASCII code in the Arduino source code (see section 1. UPLOAD THE SOURCE CODE).
First, you need to establish a TCP/IP connection between the designer tool and GUI-O application:
- Determine the local IP address of your PC's network interface (WiFi or Ethernet)
- Under Windows, open the command prompt, enter
ipconfig
and press Enter - Under Linux, open the terminal, enter
ifconfig
and press Enter
-
Open GUI-O application and open settings menu. Select "Connections -> Ethernet" and create a new device with IP address (determined from 1.) and any port between 49152 - 65535
-
Open GUI-O designer and select "TCP/IP connection" tab. Set the IP address and port. Both values must match the device settings created within the GUI-O application. Click "Start server" button.
-
Within the GUI-O application, tap the created device and wait for successful connection.
-
In the GUI-O designer, select "File -> Load designer file" and load the MotorControl.gdf design file. Make the desired adjustments, if necessary. Copy / replace the GUI-O commands into the Arduino source code (see section 1. UPLOAD THE SOURCE CODE).
1. CONNECT THE COMPONENTS
Connecting the components is straightforward. "D25" pin is used to set the motor speed (via PWM output), while pins "D33" and "D32" are used to control the motor direction.
2. UPLOAD THE SOURCE CODE
The source code has inline comments, describing the important parts of the code. You can copy the source code from the snippet below, or download it here.
Upload the code to your board (make sure that the correct board and upload port are selected). Reset the board after upload.
/* * GUI-O Motor control Bluetooth example (using ESP32-WROOM-32) * * Copyright (C) 2022, kl3m3n * last updated on 3.12.2022 * * SPDX-License-Identifier: BSD-3-Clause */ #include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> namespace uuid { static const char *SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"; static const char *RX_CHARACTERISTIC_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"; static const char *TX_CHARACTERISTIC_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"; } // namespace uuid // forward declare parser for incoming messages void parseGuioMsg(const String &msg); // setup done flag bool setupDone = false; // setup motor control pins const int enablePin = 25; const int inPin_1 = 32; const int inPin_2 = 33; // for controlling motor speed... const double PWM_FREQ = 1000.0; const uint8_t PWM_BITS = 8; const uint8_t PWM_CHANNEL = 0; // custom handling of server callbacks class CustomBLEServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { Serial.println("Connected!"); }; void onDisconnect(BLEServer* pServer) { Serial.println("Disconnected!"); // restart advertising after disconnect, otherwise GUI-O cannot re-connect if(setupDone) { // restart advertising on disconnect delay(500); pServer->startAdvertising(); } } }; // custom handling of characteristic callbacks class CustomBLECharacteristicCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string msg = pCharacteristic->getValue(); // parse message string parseGuioMsg(String(msg.c_str())); } }; // global ptr BLECharacteristic *pTxCharacteristic; void setup() { // debug output Serial.begin(115200); // motor control setup (speed, direction) ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_BITS); ledcAttachPin(enablePin, PWM_CHANNEL); pinMode(inPin_1, OUTPUT); pinMode(inPin_2, OUTPUT); // create device BLEDevice::init("MotorControl"); // create server and register callback BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new CustomBLEServerCallbacks()); // create service BLEService *pService = pServer->createService(uuid::SERVICE_UUID); // crate Tx characteristic and add descriptor pTxCharacteristic = pService->createCharacteristic(uuid::TX_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_NOTIFY); pTxCharacteristic->addDescriptor(new BLE2902()); // crate Rx characteristic and register callback BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(uuid::RX_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); pRxCharacteristic->setCallbacks(new CustomBLECharacteristicCallbacks()); // start the service and start advertising pService->start(); pServer->getAdvertising()->start(); // setup done flag setupDone = true; } void loop() { } void sendMsg(const String &msg) { pTxCharacteristic->setValue(std::string(msg.c_str())); pTxCharacteristic->notify(); delay(50); } void parseGuioMsg(const String &msg) { if(msg.startsWith("@init")) { Serial.println("GUI-O app is requesting INITIALIZATION!"); // clear screen and set background sendMsg("@cls\r\n"); sendMsg("@guis BGC:#FFFFFF\r\n"); delay(100); // initialize GUI sendMsg("|LB UID:title X:50 Y:20 FSZ:4 FFA:\"font8\" TXT:\"Motor<br>control\"\r\n"); sendMsg("|JOY UID:ctrl X:50 Y:50 W:60 BGC:#00FFFFFF SHE:1 SHC:#806D9DC5 BTH:0.25\r\n"); sendMsg("|LB UID:dir X:50 Y:75 FGC:#000000 SHE:1 FSZ:5 TXT:\"n/a\"\r\n"); sendMsg("|LB UID:details X:50 Y:90 FSZ:2 TXT:\"GUI-O motor control<br>demonstration by kl3m3n\"\r\n"); } else if(msg.startsWith("@ctrl")) { const auto s_idx = msg.indexOf(' '); const auto e_idx = msg.lastIndexOf(' '); if(s_idx > 0 && e_idx > 0) { String xDirStr = msg.substring(s_idx + 1, e_idx); xDirStr.trim(); // "convert" values between 0.0 to 1.0 / -1.0 to percent 0 to 100 / -100 (two decimal places, round...) const int8_t motorSpeed = static_cast<int8_t>(roundf(xDirStr.toFloat() * 100.0)); Serial.print("Motor direction: "); Serial.print(motorSpeed > 0 ? "CW" : "CCW"); Serial.print(", speed [%]: "); Serial.println(abs(motorSpeed)); // determine direction if(motorSpeed > 0) { digitalWrite(inPin_1, HIGH); digitalWrite(inPin_2, LOW); // update label sendMsg("@dir TXT:\"CW\"\r\n"); } else if(motorSpeed < 0) { digitalWrite(inPin_1, LOW); digitalWrite(inPin_2, HIGH); // update label sendMsg("@dir TXT:\"CCW\"\r\n"); } else sendMsg("@dir TXT:\"OFF\"\r\n"); // map motor speed to duty cycle for speed control ledcWrite(PWM_CHANNEL, map(abs(motorSpeed), 0, 100, 0, 255)); } } }
3. ESTABLISH CONNECTION
Open GUI-O application and navigate to settings menu. Select "Connections -> Bluetooth LE and IoT" and search for devices (enable Bluetooth and Location services, if prompted). Tap on the "MotorControl" device, select Nordic UART service and wait for successful connection (confirm device pairing if prompted).
Close the settings menu and press the Initialize button (see image below) from the GUI-O application home screen.
4. THE RESULT
Image below shows the result (screen capture) on my Android device after pressing the "Initialize" button. Motor direction and speed is controlled by the virtual joystick position (only in horizontal direction). If the joystick is pushed all the way to the right (or left), the speed of the motor is at its maximum. When in this position, pushing the joystick up or down decreases the speed of the motor.
If you have any questions or run into any problems, please let me know!
Best regards,
kl3m3n -