Curs d’Arduino – Exercicis: Bluetooth

Pràctiques Bluetooh / Programació:

  • Llistat de ordres per con figurar el BT: hc-05_at_commands.pdf
  • Comunicació a través del Bluetooh. Anem a la pàgina 545 del manual.
  • Executar Sketch per configurar el BT.
  • Executar Sketch per enviar i rebre dades.
  • Instal·lar del PlayStore “Blue Control v2.0”.
  • Podem instal·lar apps del PlayStrore, com per exemple “BT Simple Terminal” o “Arduino Bluetooth Controller”.
  • Podem instal·lar B4A i provar el codi.
  • Sempre a partir de les ordres capturades amb el programa “Blue Control”.
  • Encendre o apagar led, relé.
  • Fer que un led parpellegi cada mig segon i un altra al mateix temps cada segon per exemple, (fer un delay sense delay()  https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
  • Fer un fade amb un for() a partir d’una opció del programa.

Com connectar-ho.

arduino-bluetooth1

Ordres AT:

AT : comprobar la conexión.
AT+NAME : ver el nombre por defecto.
AT+ADDR : ver la dirección por defecto.
AT+VERSION : ver la versión.
AT+UART : ver la velocidad de transmisión.
AT+ROLE: ver el rol del módulo bluetooyth (1 = master, 0 = esclavo).
AT+RESET : reset y salir del modo AT.
AT+ORGL : restaurar a los configuración de fábrica.
AT+PSWD: ver la contraseña por defecto.
Para cambiar la velocidad de transmisión de los datos escribe: AT+BAUDX, donde X= 1 a 8.
Esto es:AT+BAUD1: 1200bps
AT+BAUD2: 2400bps
AT+BAUD3: 4800bps
AT+BAUD4 9600bps (velocidad por defecto)
AT+BAUD5: 19200bps
AT+BAUD6: 38400bps
AT+BAUD7: 57600bps
AT+BAUD8: 115200bps
Para cambiar el pin: AT+PIN y, de nuevo, sin espacios entre el pin y el comando ponemos nuestro pin. Por ejemplo, si quiero que mi pin sea 1234 escribo: AT+PIN1234
Para el módulo Bluetooth HC-05
Hay una diferencia en el firmware que llevan los módulos Bluetooth. Para obtener un parámetro tenemos que acabar el compando con un signo de interrogación:AT+NAME?
AT+VERSION?
AT+UART?
Para escribir un parámetro asignamos con un signo =, por ejemplo: AT+NAME=FABRICA
AT+PIN=1234
AT+BAUD=4

Sketch per configurar:

//To check that AT commands are being accepted, send 'AT' , and you should get OK back.
//Example:
// Sent: AT
// Received: OK
//
//To Set the Baud Rate, send the command: AT+BAUDx ,
//where x is a number corresponding to the baud rate: 1=1200, 2=2400, 3=4800, 4=9600, 5=19200, 6=38400, 7=57600, 8=115200.
//Example:
// Sent: AT+BAUD2
// Received: OK2400
//
//To set the device name, Command: AT+NAMEnewname . Note that the name may take a little while to be 
//shown updated in the app/android devices already paired to it.
//Example:
// Sent: AT+NAME=BT01
// Received: OKsetname
//
//To set the PIN, Command: AT+PINpppp , where pppp is the new pin
//Example:
// Sent: AT+PIN1111
// Received: OKsetPIN
//
//To obtain the version of the HC-06, send AT+VERSION
//Example:
// Sent: AT+VERSION
// Received: OKlinvorV1.8
#include <SoftwareSerial.h>

SoftwareSerial BT1(10, 11); // RX | TX

void setup()
{
  pinMode(8, OUTPUT);     // El VCC del BT.
  pinMode(9, OUTPUT);     // Al poner en HIGH forzaremos el modo AT = PIN KEY DEL BT
                         // En el BT del curs s'ha d'apretar el botó que hi ha mentres 
                         // es posar en marxa l'arduino, al primer blink del BT deixar el butó 
  digitalWrite(9, HIGH);     // Donar alimentació al PIN KEY DEL BT
  delay (500) ;           
  Serial.begin(38400);

  Serial.println("Iniciant el mòdul HC-0X");
  digitalWrite (8, HIGH);  //Encen el mòdul VCC

  Serial.println("Esperant ordres AT:");
  BT1.begin(38400);
}

void loop()
{
  // Keep reading from HC-0X and send to Arduino Serial Monitor
  if (BT1.available())
    Serial.write(BT1.read());

  // Keep reading from Arduino Serial Monitor and send to HC-0X
  if (Serial.available())
    BT1.write(Serial.read());
}

Sketch de proves:

#include <SoftwareSerial.h>

SoftwareSerial BT1(0, 1); // RX | TX

String str;
char s1[100];

const byte inputStringMax = 50;
char strMsg[inputStringMax];

String Data = "";
int counter = 0;

void setup()
{
  Serial.begin(9600);
  delay(100);
  BT1.begin(9600);

  pinMode(13, OUTPUT);
}

void loop()
{
  delay(500);

  int n = random(1, 70);
  int n1 = random(1, 120);
  int n2 = random(10, 520);

  String Data = "";

  Data.concat('[');
  Data.concat(dtostrf(n, 0, 0, s1));
  Data.concat(";");
  Data.concat(dtostrf(n1, 0, 0, s1));
  Data.concat(";");
  Data.concat(dtostrf(n2, 0, 0, s1));
  Data.concat(']');
  Serial.println(Data);
  Data = "";

  CheckSerialIn();
  if (counter > 0)
  {
    counter = 0;
    Serial.println(strMsg);
    switch (strMsg[0])
    {
      case '1':
        digitalWrite(13, HIGH);
        break;
      case '2': //MANUAL PARA
        digitalWrite(13, LOW);
        break;
      case '3': //MANUAL MARXA
        break;
      case '4':
        break;
      case '5':
        break;
    }
    strMsg[0] = 0;
  }
}

//--------------------------------------------------------------------------
int CheckSerialIn()
{
  if (BT1.available() > 0) {
    //We have serial data to grab
    counter = 0;
    while ((counter < inputStringMax) && (BT1.available() > 0))
    {
      //delay(MMsend);    // Allow serial data time to collect
      strMsg[counter] = BT1.read();
      counter++;
    }

    strMsg[counter] = '\0'; // Null string terminator
    return (0);
  }
}

Codi amb B4A per rebre i enviar dades.

  • Arxiu ZIP amb el projecte per B4A. testbt
#Region  Project Attributes 
  #ApplicationLabel: TestBT
  #VersionCode: 1
  #VersionName: 
  'SupportedOrientations possible values: unspecified, landscape or portrait.
  #SupportedOrientations: unspecified
  #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes 
  #FullScreen: False
  #IncludeTitle: True
#End Region

Sub Process_Globals
  'These global variables will be declared once when the application starts.
  'These variables can be accessed from all modules.

  Dim Serial1 As  Serial
  Dim cInici As Boolean
  Dim str As String
End Sub

Sub Globals
  'These global variables will be redeclared each time the activity is created.
  'These variables can only be accessed from this module.
  
  Dim connected As Boolean  
  Dim AStreams As AsyncStreams
  
  Private lbRpm As Label
  Private LbNivell2 As Label
  Private lbNivell1 As Label
  
  Public charset As String = "UTF8"

End Sub

Sub Activity_Create(FirstTime As Boolean)
  Activity.LoadLayout("L1")
  Activity.AddMenuItem("Connectar", "mnuConnect")
  Activity.AddMenuItem("Desconnectar", "mnuDisconnect")
  Activity.Title = "TestBT v1.0 - 2016"

  cInici = False
  
  If FirstTime Then
    Serial1.Initialize("Serial1")
  End If  
End Sub

Sub Activity_Resume
  Try
    If Serial1.IsEnabled = False Then
      Msgbox("Activa el Bluetooth.", "")
    Else
      Serial1.Listen
      If connected = False Then
        ProgressDialogShow("Connectant...")
        Serial1.Connect("20:14:03:19:08:45")
      End If
    End If
  Catch
    ProgressDialogHide
'   Msgbox(LastException.Message, "")
  End Try   
  ProgressDialogHide
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub Serial1_Connected(Success As Boolean)
  If Success Then
    ProgressDialogHide
    AStreams.Initialize(Serial1.InputStream, Serial1.OutputStream ,"AStreams")
    connected = True
  Else
    connected = False
    'Msgbox(LastException.Message, "Error de conexió.")
  End If
End Sub

Sub mnuDisconnect_Click
  Try
    Serial1.Disconnect
  Catch
    Log(LastException.Message)
  End Try   
  connected = False
End Sub

Sub mnuConnect_Click
  Dim PairedDevices As Map
  
  If connected = False Then
    ProgressDialogShow("Connectant...")
    Try   
      PairedDevices = Serial1.GetPairedDevices
      Dim l As List
      l.Initialize
      
      For i = 0 To PairedDevices.Size - 1
        l.Add(PairedDevices.GetKeyAt(i)) 'add the friendly name to the list
      Next
      
      Dim res As Int
      res = InputList(l, "Tria un dispositiu", -1) 'show list with paired devices
      If res <> DialogResponse.CANCEL Then
        Dim smac As String
        smac = PairedDevices.Get(l.Get(res))
        Serial1.Connect(smac) 'convert the name to mac address
      End If
    Catch
      ProgressDialogHide
      'Msgbox(LastException.Message, "")
    End Try   
  End If
  ProgressDialogHide
End Sub

Sub AStreams_NewData(Buffer() As Byte)
  Dim s As String
  Dim n As Int
  
  Try
    s = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Log(s)
  
    For n = 0 To Buffer.Length -1
      If s.CharAt(n) = "["  Then
        cInici = True
      End If
      
      If cInici = True Then
        str = str & s.CharAt(n)
      End If

      If s.CharAt(n) = "]" Then
        str = str.SubString(1)
        str = str.SubString2(0, str.Length-1)
        Dim variable() As String = Regex.Split(";", str)
    
        lbNivell1.Text =  variable(0) 
        LbNivell2.Text =  variable(1) 
        lbRpm.Text =  variable(2) 

        cInici = False
        str = ""
      End If
    Next  
  Catch
    str = ""
  End Try   
End Sub

Sub btON_Click
  If connected Then
    Dim s As String
    s = "1"
    AStreams.Write(s.GetBytes("UTF8"))
  End If
End Sub

Sub btOFF_Click
  If connected Then
    Dim buffer() As Byte
    Dim s As String
    s = "2"
    buffer = s.GetBytes("UTF8")
    AStreams.Write(buffer)  

'   Dim b As Byte
'   b = 0
'   AStreams.Write(Array As Byte(0, b))
  End If
End Sub

Kim Ferran  – Reus 02/11/2016

Comments are closed.