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>
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.