220 Volt Lamp On-Off Application with Bluetooth
We continue our Bluetooth applications. This application is similar to the previous Bluetooth led lighting application. This time we connected the pin to the relay input to light the LED and applied a 220 volt lamp on-off.
You can watch our youtube video about the application:
We coded the Android application with Flutter-Dart. There are three buttons on the application. One is the “Connect” button, the others are on and off buttons. On/off buttons send "on" and "off" information to the bluetooth module connected to Arduino on the bluetooth adapter. When the Arduino program receives this information, it turns the lamp on or off.
Below are the Flutter-Dart codes:
//import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
const MyApp({super.key});
// ignore: library_private_types_in_public_api
_MyAppState createState() => _MyAppState();
}
List<BluetoothDevice> _devices = [];
late BluetoothConnection connection;
String adr="00:21:07:00:50:69"; // my bluetooth device MAC Adres
void initState() {
super.initState();
_loadDevices();
}
List<BluetoothDevice> devices = await FlutterBluetoothSerial.instance.getBondedDevices();
}
//----------------------------
Future<void> sendData(String data) async {
try {
List<int> list = data.codeUnits;
Uint8List bytes = Uint8List.fromList(list);
connection.output.add(bytes);
await connection.output.allSent;
if (kDebugMode) {
// print('Data sent successfully');
}
} catch (e) {
//print(e.toString());
}
}
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Bluetooth 220 Volt LAMP Control"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("MAC Adress: 00:21:07:00:50:69"),
connect(adr);
SizedBox(height: 30.0,),
sendData("on");
ElevatedButton(child:Text("220 VOLT CLOSE"),onPressed: () {
sendData("off");
],
),
),
)
}
try {
connection = await BluetoothConnection.toAddress(address);
sendData('111');
//durum="Connected to the device";
connection.input!.listen((Uint8List data) {
//Data entry point
// durum=ascii.decode(data);
});
// durum="Cannot connect, exception occured";
}
}
//Future send(Uint8List data) async {
//connection.output.add(data);
//await connection.output.allSent;
}
//------------*********** data gonder end
Arduino codes are below:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
String rec_data="off"; // closed
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
mySerial.begin(9600); // BlueTooth Data baud,set the data rate for the SoftwareSerial port
}
void loop() { // run over and over
if (mySerial.available()) {
rec_data=mySerial.readString();
if(rec_data=="on"){digitalWrite(9, HIGH);} // RELAY out ---> pin 9---> on
if(rec_data=="off"){digitalWrite(9, LOW);} // RELAY out ---> pin 9 --- off
Serial.println(rec_data);
delay(100);
}
}