Flutter and Arduino Control LEDs

Created At: 2024-07-09 10:34:53 Updated At: 2024-07-09 10:39:31

Here we will see how to control leds from Flutter app along with Arduino sketch. To follow this tutorial you need to have Arduino IDE, Flutter IDE(Android Studio) and Arduino Board and ESP-01 module. 

At the same time you need three leds, jumper wires, and resisters. Here is the sketch for Arduino. Make sure you have the correct Wifi and IP address.

#include <SoftwareSerial.h>


SoftwareSerial ESPSerial(2, 3); // RX, TX for ESP-01
Servo myServo; // Create a Servo object

const char* ssid = "BSL-Chengrenjiaoyu";
const char* password = "bsl888888";
const char* port = "80"; // Default HTTP port

const int ledPin1 = 13; // LED 1 connected to digital pin 13
const int ledPin2 = 12; // LED 2 connected to digital pin 12
const int ledPin3 = 11; // LED 3 connected to digital pin 11
const int servoPin = 9; // PWM pin to which the servo is connected

void setup() {
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
myServo.attach(servoPin); // Attach the servo to the PWM pin
Serial.begin(115200);
ESPSerial.begin(115200);

Serial.println("Connecting to Wi-Fi...");
sendATCommand("AT+CWMODE=1", 1000, true); // Set Wi-Fi mode to station
sendATCommand("AT+CWJAP=\"" + String(ssid) + "\",\"" + String(password) + "\"", 10000, true); // Connect to Wi-Fi

// Check if connected
Serial.println("Getting IP address...");
sendATCommand("AT+CIFSR", 1000, true); // Get IP address
sendATCommand("AT+CIPMUX=1", 1000, true); // Enable multiple connections
sendATCommand("AT+CIPSERVER=1," + String(port), 1000, true); // Start the TCP server
}

void loop() {
if (ESPSerial.available()) {
String response = ESPSerial.readString(); // Read the response from ESP-01
Serial.println("Raw response from ESP: " + response); // Print raw response for debugging

// Trim any leading or trailing whitespace characters from the response
response.trim();
if (response.startsWith("0,CONNECT")) {
Serial.println("Client connected");
} else if (response.startsWith("+IPD")) {
int clientId = response.charAt(5) - '0'; // Extract client ID
String data = response.substring(response.indexOf(':') + 1);
Serial.println("Data from client: " + data);

// Control LEDs and servo based on the received command
controlDevices(data);
// Echo the response back to the client
sendToClient(clientId, data);
} else {
Serial.println("Response from ESP: " + response); // Print other responses for debugging
}
}
if (Serial.available()) {
while (Serial.available()) {
char c = Serial.read();
ESPSerial.write(c);
}
}
}

void controlDevices(String command) {
if (command == "LED1_ON") {
digitalWrite(ledPin1, HIGH);
} else if (command == "LED1_OFF") {
digitalWrite(ledPin1, LOW);
} else if (command == "LED2_ON") {
digitalWrite(ledPin2, HIGH);
} else if (command == "LED2_OFF") {
digitalWrite(ledPin2, LOW);
} else if (command == "LED3_ON") {
digitalWrite(ledPin3, HIGH);
//rotateServoContinuously(); // Start rotating servo when LED3 is on
} else if (command == "LED3_OFF") {
digitalWrite(ledPin3, LOW);
//myServo.detach(); // Stop rotating servo when LED3 is off
}
}

void sendATCommand(String cmd, const int timeout, boolean debug) {
ESPSerial.println(cmd);
long int time = millis();
while ((time + timeout) > millis()) {
while (ESPSerial.available()) {
char c = ESPSerial.read();
if (debug) {
Serial.write(c);
}
}
}
}

void sendToClient(int clientId, String response) {
// Send the AT+CIPSEND command
String cmd = "AT+CIPSEND=" + String(clientId) + "," + String(response.length());
ESPSerial.println(cmd);
Serial.println("Sent command: " + cmd); // Debug: Command sent

// Wait for the response after sending the AT+CIPSEND command
String sendResponse = "";
long startTime = millis();
bool promptReceived = false;

while (millis() - startTime < 5000) { // Wait up to 5 seconds for response
if (ESPSerial.available()) {
char c = ESPSerial.read();
Serial.print(c); // Debug: Show characters received
sendResponse += c;
if (c == '>') {
promptReceived = true;
break;
}
}
}

if (promptReceived) {
// Send the actual data
ESPSerial.print(response);
Serial.println("Sent to client: " + response);

// Wait for the send to complete
delay(1000);

// Read any remaining response
while (ESPSerial.available()) {
char c = ESPSerial.read();
Serial.print(c);
sendResponse += c;
}
} else {
Serial.println("Failed to send to client: '>' prompt not found");
}

// Print the full response for debugging
Serial.println("Response received: " + sendResponse);
}

Here is the Flutter code. Make sure you change ESP correctly. 

 import 'dart:io';

import 'package:flutter/material.dart';

class WiFiPageThreeLed extends StatefulWidget {

  @override

  _WiFiPageThreeLedState createState() => _WiFiPageThreeLedState();

}

class _WiFiPageThreeLedState extends State<WiFiPageThreeLed> {

  late Socket _socket;

  String _response = '';

  @override

  void initState() {

    super.initState();

    _connectToServer();

  }

  void _connectToServer() async {

    try {

      _socket = await Socket.connect('192.168.1.113', 80);

      _socket.listen((List<int> event) {

        setState(() {

          // Decode the response as ASCII text (assuming it's ASCII or similar)

          _response = String.fromCharCodes(event).trim();

        });

        print('Response: $_response');

      });

      print('Connected to ESP-01 module');

    } catch (e) {

      print('Error: $e');

    }

  }

  void _sendMessage(String message) {

    if (_socket != null) {

        print(message);

      _socket.write(message);

    }

  }

  @override

  void dispose() {

    _socket.close();

    super.dispose();

  }

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('ESP-01 WiFi Communication'),

      ),

      body: Padding(

        padding: EdgeInsets.all(16.0),

        child: Column(

          children: [

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED1_ON');

              },

              child: Text('Turn LED 1 ON'),

            ),

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED1_OFF');

              },

              child: Text('Turn LED 1 OFF'),

            ),

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED2_ON');

              },

              child: Text('Turn LED 2 ON'),

            ),

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED2_OFF');

              },

              child: Text('Turn LED 2 OFF'),

            ),

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED3_ON');

              },

              child: Text('Turn LED 3 ON'),

            ),

            ElevatedButton(

              onPressed: () {

                _sendMessage('LED3_OFF');

              },

              child: Text('Turn LED 3 OFF'),

            ),

            SizedBox(height: 20),

            Text('Response:'),

            SizedBox(height: 10),

            Text(_response),

          ],

        ),

      ),

    );

  }

}

The above code assumes that you have set up Flutter correctly. I am using iOS device to control the LEDs.

Comment

Add Reviews

Latest Posts

Subscribe our newsletter