'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="33"/>
<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
'End of default text.
AddPermission(android.permission.ACCESS_FINE_LOCATION)
AddPermission(android.permission.BLUETOOTH_SCAN)
AddPermission(android.permission.BLUETOOTH_CONNECT)
	#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region
'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=BLEExample.zip
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private btnReadData As B4XView
    Private btnDisconnect As B4XView
    Private btnScan As B4XView
    Private lblDeviceStatus As B4XView
    Private lblState As B4XView
    Private pbReadData As B4XLoadingIndicator
    Private clv As CustomListView
    #if B4A
    Private manager As BleManager2
    Private rp As RuntimePermissions
    #else if B4i
    Private manager As BleManager
    #end if
    Private currentStateText As String = "UNKNOWN"
    Private currentState As Int
    Private connected As Boolean = False
    Private ConnectedName As String
    Private ConnectedServices As List
    Private pbScan As B4XLoadingIndicator
    
'    ..........................................................
        
    Private ledServiceUUID As String = "0000180a-0000-1000-8000-00805f9b34fb" ' UUID del servicio
    Private switchCharacteristicUUID As String = "00002a29-0000-1000-8000-00805f9b34fb" ' UUID de la característica
    Private SeekBarCharacteristicUUID As String ="00002a2a-0000-1000-8000-00805f9b34fb" ' UUID de la característica
    Private statusCharacteristicUUID As String = "00002a2b-0000-1000-8000-00805f9b34fb" ' UUID del estado
    Private connected As Boolean = False
'    ..........................................................
    Dim CharacteristicsMap As Map
'    ..........................................................   
End Sub
Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("1")
    B4XPages.SetTitle(Me, "BLE Example")
    manager.Initialize("manager")
'    .........................................................
    CharacteristicsMap.Initialize ' Inicializa el mapa aquí
'    .........................................................
    
    StateChanged
End Sub
Public Sub StateChanged
    lblState.Text = currentStateText
    If connected Then
        lblDeviceStatus.Text = "Connected: " & ConnectedName
    Else
        lblDeviceStatus.Text = "Not connected"
    End If
    btnDisconnect.Enabled = connected
    btnScan.Enabled = Not(connected)
    pbReadData.Hide
    pbScan.Hide
    btnReadData.Enabled = connected
    btnScan.Enabled = (currentState = manager.STATE_POWERED_ON) And connected = False
End Sub
Sub btnScan_Click
    
    #if B4A
    'Don't forget to add permission to manifest
    Dim Permissions As List
    Dim phone As Phone
    If phone.SdkVersion >= 31 Then
        Permissions = Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT", rp.PERMISSION_ACCESS_FINE_LOCATION)
    Else
        Permissions = Array(rp.PERMISSION_ACCESS_FINE_LOCATION)
    End If
    For Each per As String In Permissions
        rp.CheckAndRequest(per)
        Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            ToastMessageShow("No permission: " & Permission, True)
            Return
        End If
    Next
    #end if
    pbScan.Show
    StartScan
End Sub
Sub btnDisconnect_Click
    manager.Disconnect
    Manager_Disconnected
End Sub
Sub btnReadData_Click
    pbReadData.Show
    clv.Clear
    For Each s As String In ConnectedServices
        manager.ReadData(s)
    Next
End Sub
Sub CreateServiceItem (service As String) As Panel
    Dim pnl As B4XView = xui.CreatePanel("")
    pnl.Color = 0xFF808080
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 30dip)
    Dim lbl As B4XView = XUIViewsUtils.CreateLabel
    lbl.Text = service
    lbl.SetTextAlignment("CENTER", "CENTER")
    lbl.Font = xui.CreateDefaultBoldFont(14)
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 30dip)
    Return pnl
End Sub
Sub CreateCharacteristicItem(Id As String, Data() As Byte) As Panel
    Dim pnl As B4XView = xui.CreatePanel("")
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 40dip)
    pnl.Color = Colors.White
    Dim lbl As B4XView = XUIViewsUtils.CreateLabel
    lbl.Text = Id
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 20dip)
    Dim lbl2 As B4XView = XUIViewsUtils.CreateLabel
    Try
        lbl2.Text = BytesToString(Data, 0, Data.Length, "UTF8")
    Catch
        Log(LastException)
        lbl2.Text = "Error reading data as string"
    End Try
    lbl2.TextColor = 0xFF909090
    lbl2.TextSize = 14
    pnl.AddView(lbl2, 0, 20dip, clv.AsView.Width, 20dip)
    Return pnl
End Sub
Sub Manager_StateChanged (State As Int)
    Select State
        Case manager.STATE_POWERED_OFF
            currentStateText = "POWERED OFF"
        Case manager.STATE_POWERED_ON
            currentStateText = "POWERED ON"
        Case manager.STATE_UNSUPPORTED
            currentStateText = "UNSUPPORTED"
    End Select
    currentState = State
    StateChanged
End Sub
Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
    Log("Found: " & Name & ", " & Id & ", RSSI = " & RSSI & ", " & AdvertisingData) 'ignore
'    If Id = "6D:D4:F2:0C:A4:74" Then
    ConnectedName = Name
    manager.StopScan
    Log("connecting")
        #if B4A
    manager.Connect2(Id, False) 'disabling auto connect can make the connection quicker
    #else if B4I
    manager.Connect(Id)
    #end if
'    End If
End Sub
Public Sub StartScan
    If manager.State <> manager.STATE_POWERED_ON Then
        Log("Not powered on.")
    Else
        manager.Scan2(Null, False)
    End If
End Sub
Sub Manager_CharacteristicChanged (Characteristic As Map)
    Log("Read -> ")
End Sub
Sub Manager_DataAvailable (ServiceId As String, Characteristics As Map)
    pbReadData.Hide
    clv.Add(CreateServiceItem(ServiceId), "")
    For Each id As String In Characteristics.Keys
'................................................................
        Dim Data() As Byte = Characteristics.Get(id)
'................................................................       
        
        clv.Add(CreateCharacteristicItem(id, Characteristics.Get(id)), "")
        
'...............................................................   
        If Data.Length > 0 Then
        ' Verifica si es el UUID del estado
        If id = statusCharacteristicUUID Then
        
            Dim Data() As Byte = Characteristics.Get(id)
            Dim status As Int = Data(0) ' Suponiendo que el valor es un solo byte
            Log("Estado recibido: " & status)
                ' Puedes almacenar el estado en una variable si lo necesitas
            End If
        Else
            Log("No hay datos para la característica: " & id)
        End If
'..........................................................       
        
    Next
End Sub
Sub Manager_Disconnected
    Log("Disconnected")
    connected = False
    StateChanged
End Sub
Sub Manager_Connected (services As List)
    Log("Connected")
    connected = True
    ConnectedServices = services
'    ............................................
    CharacteristicsMap.Initialize ' Asegúrate de inicializarlo en cada conexión
'    ............................................
'    services.Add("AAAA-E8F2-537E-4F6C-D104768A1214")
    For i = 0 To services.Size - 1 ' Recorre la lista
    
        Log("Número: " & services.Get(i)) ' Muestra cada número
        
        ' Aquí asumiendo que tienes una lista de UUIDs de características
        Dim characteristicUUIDs As List = GetCharacteristicUUIDs ' Método a implementar
        For Each charId As String In characteristicUUIDs
            Dim properties As Int = manager.GetCharacteristicProperties(ledServiceUUID, charId)
            Log("Propiedades para " & charId & ": " & properties)
            ' Verifica si tiene la propiedad de notificación
            If (properties) <> 0 Then
                manager.SetNotify(ledServiceUUID, charId, True)
                Log("Notificaciones habilitadas para: " & charId)
            End If
        Next
    Next
    StateChanged
End Sub
' Implementa este método para devolver los UUIDs de características según tu lógica
Private Sub GetCharacteristicUUIDs() As List
    Dim uuidList As List
    uuidList.Initialize
    ' Agrega tus UUIDs de características aquí
       uuidList.Add("00002a2b-0000-1000-8000-00805f9b34fb") ' Reemplaza con tus UUIDs reales
 
    Return uuidList
End Sub
'utility to convert short UUIDs to long format on Android
Private Sub UUID(id As String) As String 'ignore
#if B4A
'    Return "0000" & id.ToLowerCase & "-0000-1000-8000-00805f9b34fb"
    Return   id.ToLowerCase
#else if B4I
    Return id.ToUpperCase
#End If
End Sub
'.............................................
Sub btnTurnOff_Click
    If connected Then
        Dim c As ByteConverter
        manager.WriteData(ledServiceUUID, switchCharacteristicUUID, c.HexToBytes("01"))
    End If
End Sub
Sub btnTurnOn_Click
    If connected Then
        Dim c As ByteConverter
        manager.WriteData(ledServiceUUID, switchCharacteristicUUID, c.HexToBytes("02"))
    End If
End Sub
'.............................................
 
Private Sub SeekBar1_ValueChanged (Value As Int, UserChanged As Boolean)
    
    If connected Then
        ' Dim n As String ="ffff"
        ' Dim DataToSend() As Byte=bc.HexToBytes(n)
        
        Dim DataToSend() As Byte = Array As Byte(Value, 0, 0, 0)
        
        Log(Value)
    
        If connected Then
            manager.WriteData(ledServiceUUID, SeekBarCharacteristicUUID, DataToSend) ' Envía el valor del PWM
        End If
    
    End If
End Sub
	#include <ArduinoBLE.h>
// By  Pablo Arrieta
// Define PWM pin
const int PWM = 7; // Change to your blue LED pin
BLEService ledService("180a"); // BLE LED Service
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("2a29", BLERead | BLEWrite);
// Característica para el PWM
BLEByteCharacteristic pwmCharacteristic("2a2a", BLERead | BLEWrite); // Nuevo UUID
// Definir una nueva característica para enviar el estado
BLEByteCharacteristic statusCharacteristic("2a2b", BLERead | BLEWrite | BLENotify ); // Nuevo UUID para el estado
void setup() {
  Serial.begin(9600);
  while (!Serial);
  // set LED's pin to output mode
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);         // when the central disconnects, turn off the LED
  // begin initialization
  if (!BLE.begin()) {
    Serial.println("Starting Bluetooth® Low Energy failed!");
    while (1);
  }
  // set advertised local name and service UUID:
  BLE.setLocalName("MKR WIFI1010");
  BLE.setAdvertisedService(ledService);
  // add the characteristic to the service
  ledService.addCharacteristic(switchCharacteristic);
  ledService.addCharacteristic(pwmCharacteristic); // Añadir nueva característica pwmCharacteristic.writeValue(0); // Inicializar PWM
  ledService.addCharacteristic(statusCharacteristic);
  // add service
  BLE.addService(ledService);
  // set the initial value for the characteristic:
  switchCharacteristic.writeValue(0);
  pwmCharacteristic.writeValue(0); // Inicializar PWM
  statusCharacteristic.writeValue(0); // Inicializar el estado
  // start advertising
  BLE.advertise();
  Serial.println("BLE LED Peripheral");
}
void loop() {
  // listen for Bluetooth® Low Energy peripherals to connect:
  BLEDevice central = BLE.central();
  // if a central is connected to peripheral:
  if (central) {
    Serial.print("Connected to central: ");
    // print the central's MAC address:
    Serial.println(central.address());
    digitalWrite(LED_BUILTIN, LOW);            // turn on the LED to indicate the connection
    // while the central is still connected to peripheral:
    while (central.connected()) {
      // if the remote device wrote to the characteristic,
      // use the value to control the LED:
      if (switchCharacteristic.written()) {
        switch (switchCharacteristic.value()) {   // any value other than 0
          case 01:
            Serial.println("LED on");
                   digitalWrite(LED_BUILTIN, HIGH);            // turn on the LED_BUILTIN to indicate the connection
            break;
          case 02:
                  digitalWrite(LED_BUILTIN, LOW);            // turn Off the LED_BUILTIN to indicate the connection
            break;
          default:
            Serial.println(F("LED off"));
            digitalWrite(LED_BUILTIN, HIGH);            // turn on the LED_BUILTIN to indicate the connection
            break;
        }
      // Enviar el estado actual
      statusCharacteristic.writeValue(switchCharacteristic.value());
      }
     if (pwmCharacteristic.written()) {
        int pwmValue = pwmCharacteristic.value(); // Obtener valor PWM
        analogWrite(PWM, pwmValue); // Aplicar valor PWM al pin 6
        Serial.print("PWM Value: ");
        Serial.println(pwmValue);
        // Enviar el valor PWM actual
        statusCharacteristic.writeValue(pwmValue);
      }
    }
    // when the central disconnects, print it out:
    Serial.print(F("Disconnected from central: "));
    Serial.println(central.address());
    digitalWrite(LED_BUILTIN, LOW);         // when the central disconnects, turn off the LED
  }
}
	#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region
'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=BLEExample.zip
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private btnReadData As B4XView
    Private btnDisconnect As B4XView
    Private btnScan As B4XView
    Private lblDeviceStatus As B4XView
    Private lblState As B4XView
    Private pbReadData As B4XLoadingIndicator
    Private clv As CustomListView
    
    #if B4A
    Private manager As BleManager2
    Private rp As RuntimePermissions
    #else if B4i
    Private manager As BleManager
    #end if
    
    Private currentStateText As String = "UNKNOWN"
    Private currentState As Int
    Private connected As Boolean = False
    Private ConnectedName As String
    Private ConnectedServices As List
    Private pbScan As B4XLoadingIndicator
    
    ' UUIDs
    Private ledServiceUUID As String = "0000180a-0000-1000-8000-00805f9b34fb"
    Private switchCharacteristicUUID As String = "00002a27-0000-1000-8000-00805f9b34fb"
    Private SeekBarCharacteristicUUID As String = "00002a28-0000-1000-8000-00805f9b34fb"
    Private analogCharacteristicUUID As String = "00002a29-0000-1000-8000-00805f9b34fb"
    Private digitalCharacteristicUUID As String = "00002a2a-0000-1000-8000-00805f9b34fb"
    Private statusCharacteristicUUID As String = "00002a2b-0000-1000-8000-00805f9b34fb"
    Private statusCharacteristicUUIDUno As String = "00002a2c-0000-1000-8000-00805f9b34fb"
    Private statusDigitalCharacteristicUUID As String = "00002a2d-0000-1000-8000-00805f9b34fb"
    Private statusAnalogicaCharacteristicUUID As String = "00002a2e-0000-1000-8000-00805f9b34fb"
    Private CharacteristicsMap As Map
    Private Label3 As Label
End Sub
Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("1")
    B4XPages.SetTitle(Me, "BLE Example")
    manager.Initialize("manager")
'    .........................................................
    CharacteristicsMap.Initialize ' Inicializa el mapa aquí
'    .........................................................
    
    StateChanged
End Sub
Public Sub StateChanged
    lblState.Text = currentStateText
    If connected Then
        lblDeviceStatus.Text = "Connected: " & ConnectedName
    Else
        lblDeviceStatus.Text = "Not connected"
    End If
    btnDisconnect.Enabled = connected
    btnScan.Enabled = Not(connected)
    pbReadData.Hide
    pbScan.Hide
    btnReadData.Enabled = connected
    btnScan.Enabled = (currentState = manager.STATE_POWERED_ON) And connected = False
End Sub
Sub btnScan_Click
    
    #if B4A
    'Don't forget to add permission to manifest
    Dim Permissions As List
    Dim phone As Phone
    If phone.SdkVersion >= 31 Then
        Permissions = Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT", rp.PERMISSION_ACCESS_FINE_LOCATION)
    Else
        Permissions = Array(rp.PERMISSION_ACCESS_FINE_LOCATION)
    End If
    For Each per As String In Permissions
        rp.CheckAndRequest(per)
        Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            ToastMessageShow("No permission: " & Permission, True)
            Return
        End If
    Next
    #end if
    pbScan.Show
    StartScan
End Sub
Sub btnDisconnect_Click
    manager.Disconnect
    Manager_Disconnected
End Sub
Sub btnReadData_Click
    pbReadData.Show
    clv.Clear
    For Each s As String In ConnectedServices
        manager.ReadData(s)
    Next
End Sub
Sub CreateServiceItem (service As String) As Panel
    Dim pnl As B4XView = xui.CreatePanel("")
    pnl.Color = 0xFF808080
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 30dip)
    Dim lbl As B4XView = XUIViewsUtils.CreateLabel
    lbl.Text = service
    lbl.SetTextAlignment("CENTER", "CENTER")
    lbl.Font = xui.CreateDefaultBoldFont(14)
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 30dip)
    Return pnl
End Sub
Sub CreateCharacteristicItem(Id As String, Data() As Byte) As Panel
    Dim pnl As B4XView = xui.CreatePanel("")
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 40dip)
    pnl.Color = Colors.White
    Dim lbl As B4XView = XUIViewsUtils.CreateLabel
    lbl.Text = Id
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 20dip)
    Dim lbl2 As B4XView = XUIViewsUtils.CreateLabel
    Try
        lbl2.Text = BytesToString(Data, 0, Data.Length, "UTF8")
    Catch
        Log(LastException)
        lbl2.Text = "Error reading data as string"
    End Try
    lbl2.TextColor = 0xFF909090
    lbl2.TextSize = 14
    pnl.AddView(lbl2, 0, 20dip, clv.AsView.Width, 20dip)
    Return pnl
End Sub
Sub Manager_StateChanged (State As Int)
    Select State
        Case manager.STATE_POWERED_OFF
            currentStateText = "POWERED OFF"
        Case manager.STATE_POWERED_ON
            currentStateText = "POWERED ON"
        Case manager.STATE_UNSUPPORTED
            currentStateText = "UNSUPPORTED"
    End Select
    currentState = State
    StateChanged
End Sub
Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
    Log("Found: " & Name & ", " & Id & ", RSSI = " & RSSI & ", " & AdvertisingData) 'ignore
'    If Id = "6D:D4:F2:0C:A4:74" Then
    If Name = "MKR WIFI1010" Then
        ConnectedName = Name
        manager.StopScan
        Log("connecting")
        #if B4A
        manager.Connect2(Id, False) 'disabling auto connect can make the connection quicker
    #else if B4I
    manager.Connect(Id)
    #end if
    End If
End Sub
Public Sub StartScan
    If manager.State <> manager.STATE_POWERED_ON Then
        Log("Not powered on.")
    Else
        manager.Scan2(Null, False)
    End If
End Sub
Sub Manager_CharacteristicChanged (Characteristic As Map)
    Log("Read -> ")
End Sub
Sub Manager_DataAvailable(ServiceId As String, Characteristics As Map)
    pbReadData.Hide
    clv.Add(CreateServiceItem(ServiceId), "")
    
    For Each id As String In Characteristics.Keys
        Dim Data() As Byte = Characteristics.Get(id)
        If Data.Length > 0 Then
            If IsStatusCharacteristic(id) Then
                Dim status As Int = Data(0)
                Log("Estado recibido: " & status)
                Label3.Text = status
                clv.Add(CreateCharacteristicItem(id, Data), "")
            End If
        Else
            Log("No hay datos para la característica: " & id)
        End If
    Next
End Sub
Private Sub IsStatusCharacteristic(id As String) As Boolean
    Return id = statusCharacteristicUUID Or id = statusCharacteristicUUIDUno Or id = statusDigitalCharacteristicUUID Or id = statusAnalogicaCharacteristicUUID
End Sub
Sub ReadData
    If connected Then
        manager.ReadData2(ledServiceUUID, statusCharacteristicUUID)
        manager.ReadData2(ledServiceUUID, statusCharacteristicUUIDUno)
        manager.ReadData2(ledServiceUUID, statusDigitalCharacteristicUUID)
        manager.ReadData2(ledServiceUUID, statusAnalogicaCharacteristicUUID)
    End If
End Sub
Sub Manager_Disconnected
    Log("Disconnected")
    connected = False
    StateChanged
End Sub
Sub Manager_Connected(services As List)
    Log("Connected")
    connected = True
    ConnectedServices = services
    CharacteristicsMap.Initialize ' Initialize on each connection
    For Each charId As String In GetCharacteristicUUIDs
        Dim properties As Int = manager.GetCharacteristicProperties(ledServiceUUID, charId)
        Log("Propiedades para " & charId & ": " & properties)
        If properties <> 0 Then
            manager.SetNotify(ledServiceUUID, charId, True)
            Log("Notificaciones habilitadas para: " & charId)
            Sleep(1000)
        End If
    Next
    StateChanged
End Sub
Private Sub GetCharacteristicUUIDs() As List
    Dim uuidList As List
    uuidList.Initialize
    uuidList.Add(statusCharacteristicUUID)
    uuidList.Add(statusCharacteristicUUIDUno)
    uuidList.Add(statusDigitalCharacteristicUUID)
    uuidList.Add(statusAnalogicaCharacteristicUUID)
    Return uuidList
End Sub
' Utility to convert short UUIDs to long format on Android
Private Sub UUID(id As String) As String
    #if B4A
    Return id.ToLowerCase
    #else if B4I
    Return id.ToUpperCase
    #end if
End Sub
Sub btnTurnOff_Click
    If connected Then
        Dim c As ByteConverter
        manager.WriteData(ledServiceUUID, switchCharacteristicUUID, c.HexToBytes("01"))
    End If
End Sub
Sub btnTurnOn_Click
    If connected Then
        Dim c As ByteConverter
        manager.WriteData(ledServiceUUID, switchCharacteristicUUID, c.HexToBytes("02"))
    End If
End Sub
Private Sub SeekBar1_ValueChanged(Value As Int, UserChanged As Boolean)
    If connected Then
        Dim DataToSend() As Byte = Array As Byte(Value, 0, 0, 0)
        Log(Value)
        manager.WriteData(ledServiceUUID, SeekBarCharacteristicUUID, DataToSend)
    End If
End Sub
Sub Manager_MtuChanged(Success As Boolean, MTU As Int)
    Log("MTU: " & Success & ", " & MTU)
End Sub
Private Sub READ2_Click
    ReadData
End Sub
Private Sub Clr_Click
    clv.Clear
End Sub
Sub btnWriteDigital_Click
    Dim value As Byte = 1 ' Or 0, depending on what you want to write
    manager.WriteData(ledServiceUUID, digitalCharacteristicUUID, Array As Byte(value))
End Sub
	#include <ArduinoBLE.h>
// Define pins
const int PWM = 7;
// Definir pines para las entradas
const int pinDigital = 5;
const int pinAnalog = A1;
// Variables para las lecturas
int lastAnalogValue = -1;
int lastDigitalValue = -1;
// BLE Service y Características
BLEService ledService("180a");
BLEByteCharacteristic switchCharacteristic("2a27", BLERead | BLEWrite);
BLEByteCharacteristic pwmCharacteristic("2a28", BLERead | BLEWrite);
BLEByteCharacteristic digitalInputCharacteristic("2a29", BLERead | BLEWrite);
BLEByteCharacteristic analogInputCharacteristic("2a2a", BLERead | BLEWrite);
BLEByteCharacteristic statusCharacteristicUno("2a2b", BLERead | BLEWrite | BLENotify);
BLEByteCharacteristic statusCharacteristicDos("2a2c", BLERead | BLEWrite | BLENotify);
BLEByteCharacteristic statusCharacteristicTres("2a2d", BLERead | BLEWrite | BLENotify);
BLEByteCharacteristic statusCharacteristicCuatro("2a2e", BLERead | BLEWrite | BLENotify);
unsigned long previousMillis = 0; // Para manejar el tiempo
const long interval = 100; // Intervalo de lectura
void setup() {
  Serial.begin(9600);
  while (!Serial);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(pinDigital, INPUT);
  pinMode(pinAnalog, INPUT);
  digitalWrite(LED_BUILTIN, LOW);
  if (!BLE.begin()) {
    Serial.println("Starting Bluetooth® Low Energy failed!");
    while (1);
  }
  BLE.setLocalName("MKR WIFI1010");
  BLE.setAdvertisedService(ledService);
 
  ledService.addCharacteristic(switchCharacteristic);
  ledService.addCharacteristic(pwmCharacteristic);
  ledService.addCharacteristic(digitalInputCharacteristic);
  ledService.addCharacteristic(analogInputCharacteristic);
  ledService.addCharacteristic(statusCharacteristicUno);
  ledService.addCharacteristic(statusCharacteristicDos);
  ledService.addCharacteristic(statusCharacteristicTres);
  ledService.addCharacteristic(statusCharacteristicCuatro);
  BLE.addService(ledService);
 
  // Inicializar características
  switchCharacteristic.writeValue(0);
  pwmCharacteristic.writeValue(0);
  digitalInputCharacteristic.writeValue(0);
  analogInputCharacteristic.writeValue(0);
  statusCharacteristicUno.writeValue(0);
  statusCharacteristicDos.writeValue(0);
  statusCharacteristicTres.writeValue(0);
  statusCharacteristicCuatro.writeValue(0);
  BLE.advertise();
  Serial.println("BLE LED Peripheral");
}
void loop() {
  BLEDevice central = BLE.central();
  if (central) {
    Serial.print("Connected to central: ");
    Serial.println(central.address());
    digitalWrite(LED_BUILTIN, LOW); // Indicar conexión
    while (central.connected()) {
      if (switchCharacteristic.written()) {
        handleSwitchCharacteristic();
      }
      if (pwmCharacteristic.written()) {
        handlePwmCharacteristic();
      }
      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        readAndSendValues();
      }
    }
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
    digitalWrite(LED_BUILTIN, HIGH);
  }
}
void handleSwitchCharacteristic() {
  switch (switchCharacteristic.value()) {
    case 01: // Encender LED_BUILTIN
      digitalWrite(LED_BUILTIN, HIGH);
      break;
    case 02: // Apagar LED_BUILTIN
      digitalWrite(LED_BUILTIN, LOW);
    default:
      digitalWrite(LED_BUILTIN, LOW);
      break;
  }
  statusCharacteristicUno.writeValue(switchCharacteristic.value());
  Serial.print("SWITCH Value: ");
  Serial.println(switchCharacteristic.value());
}
void handlePwmCharacteristic() {
  int pwmValue = pwmCharacteristic.value();
  analogWrite(PWM, pwmValue);
  Serial.print("PWM Value: ");
  Serial.println(pwmValue);
  statusCharacteristicDos.writeValue(pwmValue);
}
void readAndSendValues() {
  int digitalValue = digitalRead(pinDigital);
  if (digitalValue != lastDigitalValue) {
    digitalInputCharacteristic.writeValue(digitalValue);
    statusCharacteristicTres.writeValue(digitalValue);
    Serial.print("Digital Value: ");
    Serial.println(digitalValue);
    lastDigitalValue = digitalValue;
  }
  int analogValue = analogRead(pinAnalog);
  if (analogValue != lastAnalogValue) {
    analogInputCharacteristic.writeValue(analogValue);
    statusCharacteristicCuatro.writeValue(analogValue);
    Serial.print("Analog Value: ");
    Serial.println(analogValue);
    lastAnalogValue = analogValue;
  }
}