Control a Relay with ESP32 via Bluetooth Using MIT App Inventor _Part 4
In Part 4 of our ESP32 Bluetooth series, we shift focus from the hardware to the software. Today, you will learn how to **build the Android Controller App** from scratch using MIT App Inventor.
We will not just drag-and-drop buttons; we will configure the BluetoothClient component to scan for devices and set up the logic to send serial data characters ('1' and '0') that trigger our ESP32 relay.
Step 1: Interface Design (Designer View)
Before programming the logic, we need to arrange our visual components. Open MIT App Inventor and drag the following components into your workspace:
| Component Type | Name (Rename to) | Purpose |
|---|---|---|
| ListPicker | ConnectBtn |
Opens the list of paired Bluetooth devices (ESP32). |
| Button | Btn_ON |
Sends signal to turn Relay ON. |
| Button | Btn_OFF |
Sends signal to turn Relay OFF. |
| BluetoothClient | BluetoothClient1 |
Non-visible component that handles the connection. |
Important: You can find the BluetoothClient under the Connectivity tab in the palette on the left side.
Step 2: The Block Logic (Blocks Editor)
Now, switch to the Blocks view. We need to create three distinct pieces of logic:
1. Scanning for Devices
When the user clicks the "Connect" list picker, we need to show available devices.
Block: When ConnectBtn.BeforePicking > Set ConnectBtn.Elements to BluetoothClient1.AddressesAndNames
2. Connecting to the ESP32
Once a user selects a device, the app must attempt to pair.
Block: When ConnectBtn.AfterPicking > Call BluetoothClient1.Connect address (ConnectBtn.Selection)
3. Sending Commands
This is where we talk to the Arduino code we wrote in Part 2.
- ON Button Logic:
When Btn_ON.Click > Call BluetoothClient1.SendText text: "1" - OFF Button Logic:
When Btn_OFF.Click > Call BluetoothClient1.SendText text: "0"
Troubleshooting Connection Issues
If your app crashes when you click "Connect," check these common errors:
- Bluetooth Not Enabled: Ensure Bluetooth is turned on in your phone settings before launching the app.
- Error 507 (Unable to Connect): This means the ESP32 is not powered on or is too far away.
- Device Not Paired: You must pair with the ESP32 in your phone's native Bluetooth settings (Passkey: 1234) before it appears in the app list.
Resources & Downloads
You can download the completed .aia file to import directly into MIT App Inventor, or grab the Arduino code from GitHub.
📂 Download Project Files (GitHub)
Watch the Full Tutorial
Seeing the blocks snap together can be helpful. Watch the full build process here:
Next Step: Learn how to export and install your APK in Part 5.
Comments
Post a Comment