somaya mohamad
somaya mohamad

Reputation: 19

the servos and buzzer do not reply

The idea is that I have an application that has a button that when pressed sends 1 and in this case the default servo angle changes from zero to 90 and the bells work for two seconds and when pressed again sends 2 and in this case the servo returns to the default state of 0 The Bluetooth is connected to the application well and the tr and rx flash in the Arduino when I press the button which means that the Arduino receives the message but here is the problem nothing works from the bells or the servo whyyyy And these are the application codes and the Arduino code:

    #include <Arduino.h>
#include <Servo.h>

// تعريف المنافذ
const int buzzer1 = 2;
const int buzzer2 = 3;
const int servo1 = 4;
const int servo2 = 5;
const int servo3 = 6;
const int servo4 = 7;

char data; // متغير لتخزين البيانات المستلمة

Servo myServo1;
Servo myServo2;
Servo myServo3;
Servo myServo4;

void setup() {
  Serial.begin(9600); // فتح الاتصال التسلسلي

  pinMode(buzzer1, OUTPUT);
  pinMode(buzzer2, OUTPUT);

  myServo1.attach(servo1);
  myServo2.attach(servo2);
  myServo3.attach(servo3);
  myServo4.attach(servo4);

  // تحديد الوضع الافتراضي للسيرفو عند البدء
  myServo1.write(0);
  myServo2.write(0);
  myServo3.write(0);
  myServo4.write(0);
}

void loop() {
  if (Serial.available()) { 
    data = Serial.read(); // قراءة البيانات المستلمة

    Serial.print("Received: ");
    Serial.print(data);

    if(data==1){
      // إعادة المحركات للوضع الابتدائي
        Serial.println("Command 1: Resetting servos");
        myServo1.write(0);
        myServo2.write(0);
        myServo3.write(0);
        myServo4.write(0);
       
    }
      if(data==2){ // تشغيل الجرس وتحريك المحركات
        Serial.println("Command 2: Activating servos and buzzers");
        
        // تشغيل البازارات لمدة 1 ثانية
        tone(buzzer1, 1000);
        tone(buzzer2, 1000);
        delay(1000);
        noTone(buzzer1);
        noTone(buzzer2);
        
        // تحريك السيرفو
        myServo1.write(180);
        myServo2.write(180);
        myServo3.write(180);
        myServo4.write(180);
      }

      
        
    }
  }

/////////////////////////////////////////

import 'dart:typed_data';
import 'package:bluetooth_classic/bluetooth_classic.dart';
import 'package:flutter/material.dart';
import 'premission.dart';
import 'package:permission_handler/permission_handler.dart';

String weathercon1 = "غبار";
String weathercon2 = "8:00 PM";
List<String> weathercon = ["غبار", "لا غبار"];
List<String> firstImage = [
  "assets/images/sandstorm.png",
  "assets/images/no-removebg-preview.png"
];
List<String> secondImage = [
  "assets/images/sundist.png",
  "assets/images/Untitled-removebg-preview.png"
];
List<String> thirdImage = [
  "assets/images/storm.png",
  "assets/images/no-removebg-preview.png"
];

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  bool bluetoothGranted = await requestBluetoothAccess();
  if (bluetoothGranted) {
    debugPrint("Bluetooth permissions granted!");
  } else {
    debugPrint("Bluetooth permissions denied!");
  }
  runApp(const MainApp());
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  final BluetoothClassic bluetooth = BluetoothClassic();
  bool isConnected = false;
  dynamic connection;
  final String deviceAddress = "00:23:00:01:68:07"; // عنوان جهاز البلوتوث

  String curImage = firstImage[0];
  String curImage1 = secondImage[0];
  String curImage2 = thirdImage[0];
  String curWeather = weathercon[0];
  int curImageIndex = 0;
  int curImageIndex1 = 0;
  int curImageIndex2 = 0;
  int curWeatherIndex = 0;

  // الاتصال بالجهاز
  void connectToDevice() async {
    try {
      // محاولة الاتصال بالجهاز
      bool success = await bluetooth.connect(
        deviceAddress,
        "00001101-0000-1000-8000-00805F9B34FB",
      ).timeout(
        const Duration(seconds: 10),
        onTimeout: () {
          throw Exception("Connection timed out");
        },
      );

      if (success) {
        setState(() {
          isConnected = true;
        });
        debugPrint("تم الاتصال بنجاح.");
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('تم الاتصال بنجاح!'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        debugPrint("فشل في الاتصال.");
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('فشل في الاتصال!'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      debugPrint("خطأ أثناء الاتصال: $e");
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('خطأ أثناء الاتصال: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }




  // إرسال البيانات عبر البلوتوث
  void sendBluetoothDataAlt(String data) async {
    if (isConnected) {
      try {
        await bluetooth.write(data);
        debugPrint("تم إرسال البيانات: $data");

        // التأكد من استخدام ScaffoldMessenger داخل السياق الصحيح
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('تم إرسال البيانات بنجاح!'),
              backgroundColor: Colors.green,
            ),
          );
        }
      } catch (e) {
        debugPrint("خطأ أثناء إرسال البيانات: $e");

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('فشل في إرسال البيانات: $e'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } else {
      debugPrint("الجهاز غير متصل");

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('الجهاز غير متصل'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }


  // تبديل الصور وإرسال البيانات
  void toggleImage(BuildContext context) {
    setState(() {
      curImageIndex = (curImageIndex + 1) % firstImage.length;
      curImage = firstImage[curImageIndex];
      sendBluetoothDataAlt( curImageIndex == 0 ? "1" : "2");

      curImageIndex1 = (curImageIndex1 + 1) % secondImage.length;
      curImage1 = secondImage[curImageIndex1];

      curImageIndex2 = (curImageIndex2 + 1) % thirdImage.length;
      curImage2 = thirdImage[curImageIndex2];

      curWeatherIndex = (curWeatherIndex + 1) % weathercon.length;
      curWeather = weathercon[curWeatherIndex];
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          toolbarHeight: 20,
          backgroundColor: Colors.white,
        ),
        backgroundColor: Colors.white,
        body: SingleChildScrollView(
          child: Column(
            children: [
              Stack(
                children: [
                  Row(
                    children: [
                      SizedBox(
                        height: 218,
                        child: Image.asset("assets/images/weather1.png"),
                      ),
                    ],
                  ),
                  Positioned(
                    top: 0,
                    right: 0,
                    child: Image.asset(
                      "assets/images/string.png",
                      width: 200,
                    ),
                  ),
                ],
              ),
              Container(
                height: 90,
                width: 300,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: const Color.fromARGB(255, 211, 198, 164),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    const Padding(
                      padding: EdgeInsets.all(10.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text("صباح الخير", style: TextStyle(fontSize: 17)),
                          Text(
                            "موقعك الحالي",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      height: 90,
                      width: 100,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        gradient: const LinearGradient(
                          begin: Alignment.bottomCenter,
                          end: Alignment.topCenter,
                          colors: [
                            Color.fromARGB(255, 61, 132, 152),
                            Colors.white,
                          ],
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(
                            height: 50,
                            width: 50,
                            child: GestureDetector(
                              onTap: () {
                                toggleImage(context);

                              },
                              child:
                              Image.asset(curImage, height: 20, width: 20),
                            ),
                          ),
                          Text(
                            curWeather,
                            style: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 11,
                            ),
                          ),
                          Text(
                            weathercon2,
                            style: const TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 11),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 100, width: 500, child: Image.asset(curImage1)),
              Container(
                height: 140,
                width: 353,
                decoration: const BoxDecoration(
                  color: Color.fromARGB(255, 211, 198, 164),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Column(
                      children: [
                        const Text("حالة الطقس اليوم"),
                        const Text("الطقس المتوقع في الساعات القادمة"),
                        const Text(".....توقعات الطقس لمدة عشر أيام"),
                        Row(
                          children: [
                            SizedBox(
                              height: 60,
                              width: 75,
                              child: Image.asset(curImage2),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Container(color: Colors.black, height: 120, width: 3),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Image.asset(
                          "assets/images/logo-removebg-preview.png",
                          width: 90,
                          height: 90,
                        ),
                        const Text(
                          "الطقس",
                          style: TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 15),
                        ),
                        const Text(
                          "اليوم",
                          style: TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 15),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Align(
                alignment: Alignment.bottomLeft,
                child: Row(
                  children: [
                    Container(
                      margin: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.black, width: 2),
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child:ElevatedButton(
                        onPressed: connectToDevice, // الاتصال فقط عند الضغط
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green, // اللون الأخضر
                        ),
                        child: Text("Connect"),
                      ),

                    ),



                  ],
                ),
              ),
              Column(
                children: [
                  Image.asset(
                    'assets/images/Picture1.png',
                    width: 100,
                    height: 100,
                  ),
                  const Text("مدرسة أم كلثوم بنت عقبة المتوسطة بنات")
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: -1

Views: 26

Answers (0)

Related Questions