Conexión Bluetooth arduino a hc06 app inventor

Tengo el siguiente código de Arduino, lo voy a cortar solo pondré lo que me interesa.... Pero no he podido crear el archivo apk en app inventor ya que no manejo mucho la aplicación, necesito ayuda.

Borre unas líneas de código ya que es muy extenso lo que hace el código es timbrar de manera automática dependiendo de los horarios que estén configurados y seleccionar la opción de manera manual, además tiene configurados unos timbres especiales ya monte el circuito con Arduino y funciona todo bien pero quiero una aplicación sencilla en Appinventor para instalarla y manejar el timbre de manera manual por eso tiene T1: Clase, T2: Formación T3: Reunión, Man: Manual, H1, H2, H3 porque configura dependiendo de los minutos de cada clase, muchas gracias a quien me pueda ayudar con mi apk o al menos me pueda guiar como hacer. Gracias

// ------------------ Bluetooth HC-06 ------------------
#define BT_RX 10   // Arduino RX ← HC-06 TX
#define BT_TX 11   // Arduino TX → HC-06 RX (con divisor 1k + 1k)

// ------------------ Estado ------------------
bool horariosHabilitados = true;
volatile bool enToque = false;

// Tipo de sonido
int tipoTimbre = 1;  // 1=Clase, 2=Formación, 3=Reunión

// Selección de horario por Bluetooth
int horarioActivo = 1; // 1=55, 2=50, 3=45

// Lectura de selector (solo usado para activar o no fines de semana)
int contacto4;

// ------------------ Relé ------------------
void timbreON()  { digitalWrite(timbre, LOW); }
void timbreOFF() { digitalWrite(timbre, HIGH); }

// ------------------ Nombre en LCD ------------------
String nombreTipo(){
  switch(tipoTimbre){
    case 1: return "Clase";
    case 2: return "Formac";
    case 3: return "Reunion";
  }
  return "Clase";
}

// ------------------ Timbres ------------------
void ringNTimes(int n, int onMs, int offMs){
  for(int i=0; i<n; i++){
    timbreON(); delay(onMs);
    timbreOFF(); if(i<n-1) delay(offMs);
  }
}

void ringTipo(int tipo){
  switch(tipo){
    case 1: ringNTimes(1, tiempo_timbre, 400); break; // Clase
    case 2: ringNTimes(2, 2000, 800); break;          // Formación
    case 3: ringNTimes(3, 1000, 500); break;          // Reunión
  }
}

void ringEmergencia(int n){
  if(n<5) n=5;
  ringNTimes(n, 700, 300);
}

void activar_timbre(){
  ringTipo(tipoTimbre);
}

// ------------------ HORARIO 1 (55 minutos) ------------------
int h1_c1=7; int m1_c1=00; int s1_c1=0;
int h2_c1=7; int m2_c1=55; int s2_c1=0;
int h3_c1=8; int m3_c1=50; int s3_c1=0;
// ------------------ HORARIO 2 (57 minutos)de 7:30 ------------------
int h1_c2=7; int m1_c2=30; int s1_c2=0;
int h2_c2=8; int m2_c2=25; int s2_c2=0;
int h3_c2=9; int m3_c2=20; int s3_c2=0;
// ------------------ HORARIO 3 (45 minutos) ------------------
int h1_c3=7; int m1_c3=30; int s1_c3=0;
int h2_c3=8; int m2_c3=15; int s2_c3=0;
int h3_c3=9; int m3_c3=00; int s3_c3=0;
// ------------------ SETUP ------------------
void setup(){
  pinMode(timbre, OUTPUT);
  timbreOFF(); // Arrancar apagado

  Wire.begin();
  RTC.begin();

  Serial.begin(9600);
  BT.begin(9600);

  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("Timbre Escolar");
  delay(1000);
  lcd.clear();
}

// ------------------ DIA SEMANA ------------------
int dia_de_semana(){
  int tablaMes[]={0,3,3,6,1,4,6,2,5,0,3,5};
  DateTime now = RTC.now();
  int n=(now.day()+tablaMes[now.month()-1]+(now.year()-2000)+((now.year()-2000)/4)+6)%7;
  lcd.setCursor(13,1);
  const char* d[]={"Dom","Lun","Mar","Mie","Jue","Vie","Sab"};
  lcd.print(d[n]);
  return n;
}

// ------------------ HORARIOS ------------------
void horario_1(){ if(hora==h1_c1 && minuto==m1_c1 && segundo==s1_c1) activar_timbre();
if(hora==h2_c1 && minuto==m2_c1 && segundo==s2_c1) activar_timbre();

void horario_2(){ if(hora==h1_c2 && minuto==m1_c2 && segundo==s1_c2) activar_timbre();
if(hora==h2_c2 && minuto==m2_c2 && segundo==s2_c2) activar_timbre();

void horario_3(){ if(hora==h1_c3 && minuto==m1_c3 && segundo==s1_c3) activar_timbre();
if(hora==h2_c3 && minuto==m2_c3 && segundo==s2_c3) activar_timbre();
if(hora==h3_c3 && minuto==m3_c3 && segundo==s3_c3) activar_timbre();
if(hora==h4_c3 && minuto==m4_c3 && segundo==s4_c3) activar_timbre();
// ------------------ Bluetooth ------------------
void procesarComando(String cmd){
  cmd.trim();
  cmd.toUpperCase();

  if(cmd=="T1"){ tipoTimbre=1; BT.println("Timbre CLASE"); return; }
  if(cmd=="T2"){ tipoTimbre=2; BT.println("Timbre FORMACION"); return; }
  if(cmd=="T3"){ tipoTimbre=3; BT.println("Timbre REUNION"); return; }

  if(cmd=="MAN"){ enToque=true; ringTipo(tipoTimbre); enToque=false; return; }
  if(cmd=="F"){   enToque=true; ringTipo(2); enToque=false; return; }
  if(cmd=="R"){   enToque=true; ringTipo(3); enToque=false; return; }

  if(cmd.startsWith("E")){
    int n = cmd.substring(1).toInt();
    ringEmergencia(n);
    return;
  }

  if(cmd=="H1"){ horarioActivo=1; BT.println("Horario 55min desde 7"); return; }
  if(cmd=="H2"){ horarioActivo=2; BT.println("Horario 55min desde 7:30"); return; }
  if(cmd=="H3"){ horarioActivo=3; BT.println("Horario 45min desde 7:30"); return; }
}

// ------------------ LOOP ------------------
void loop(){
  DateTime now = RTC.now();

  segundo = now.second();
  minuto  = now.minute();
  hora    = now.hour();

  contacto4 = analogRead(A3);

  lcd.setCursor(0,0);
  lcd.print("T:");
  if(hora<10) lcd.print('0'); lcd.print(hora); lcd.print(':');
  if(minuto<10) lcd.print('0'); lcd.print(minuto); lcd.print(':');
  if(segundo<10) lcd.print('0'); lcd.print(segundo);

  lcd.setCursor(0,1);
  lcd.print("Tipo:");
  lcd.print(nombreTipo());
  lcd.print(" H");
  lcd.print(horarioActivo);

  r_diaSemana = dia_de_semana();

  static String buffer="";
  while(BT.available()){
    char c = BT.read();
    if(c=='\n'){ procesarComando(buffer); buffer=""; }
    else buffer+=c;
  }

  if(horariosHabilitados){
    if(!( (r_diaSemana==6 || r_diaSemana==0) && (contacto4 <= 1000) )){
      if(horarioActivo==1) horario_1();
      if(horarioActivo==2) horario_2();
      if(horarioActivo==3) horario_3();
    }
  }

  timbreOFF();
  delay(200);
}

(Canned Reply: ABG- Export & Upload .aia)
Export your .aia file and upload it here.

export_and_upload_aia

.

Dear @Nanita9684, your approach is near to be a "suicide".... sorry if I am so rude, but since you say that you are a newbie in programming (at least on AI2 side), my hint is to start from a super simple code on both Arduino and AI2 sides, and then, when you're done with the basics about BT data exchange, you can go further with your code.

So, first of all, your Arduino code (at least what you have posted) is missing of some lines that typically are in the top of the listing. I mean the declaration of what are the libraries that are included. I see you use the SoftwareSerial one, because you assign pins 10 and 11 to the BT Rx and Tx, but nor the library declaration, neither its initialization are present in the code. This only thing will impede to your code to work at all. So, before looking at the rest of the code, please be sure that what you are willing to use is complete.

In addition to what @ABG has already suggested about the basics on BT data exchange, since I see you are of Spanish mothertongue, you coud have benefit in reading the web site of @Juan_Antonio (KIO4.com) where you can find a lot of examples and ready made apps precisely related to the BT use.

As soon as you'll have a simple code on both sides (AI2 and Arduino) but you'll still have troubles, please don't hesitate to write again to ask for help.
Best wishes.

I think you have to describe "a little more" what your app has to do.
If I get it right, it should be "super simple":

  • a few buttons to send the commands ( T1,T2... ) to the 'arduino'
  • a label to display the reply/status from the 'arduino'
    ( there is also "some pairing" to be done )

If you have already debugged the simple communication between 'arduino' and 'android' ( maybe using one of those bluetooth/serial apps ) you shold be good to go ( in particular pay attention at the \r and/or \n appended at the end of the "commands" sent/received )

P.S.
I like your "oneliners", help in keeping everything "tidy and clean" ( or maybe because I use them too ; - )

Hola a todos, borre unas líneas de código ya que es muy extenso lo que hace el código es timbrar de manera automática dependiendo de los horarios que estén configurados y seleccionar la opción de manera manual, además tiene configurados unos timbres especiales ya monte el circuito con Arduino y funciona todo bien pero quiero una aplicación sencilla en Appinventor para instalarla y manejar el timbre de manera manual por eso tiene T1: Clase, T2: Formación T3: Reunión, Man: Manual, H1, H2, H3 porque configura dependiendo de los minutos de cada clase,

1 Like

Borre unas líneas de código ya que es muy extenso, la librerías y la declaración de variables funciona perfectamente, pero no he podido crear la apk en Appinventor ahí tengo dificultad, porque el circuito ya montado funciona a la perfección con este código, es un timbre.

Borre unas líneas de código ya que es muy extenso, la librerías y la declaración de variables funciona perfectamente, pero no he podido crear la apk en Appinventor ahí tengo dificultad, porque el circuito ya montado funciona a la perfección con este código, es un timbre escolar, con T1: Clase, T2: Formación T3: Reunión, Man: Manual, H1, H2, H3 porque configura dependiendo de los minutos de cada clase, muchas gracias a quien me pueda ayudar con mi apk o al menos me pueda guiar como hacer. Gracias

Sorry but I have to disagree. I dont' understand how the calls to BT() can work if the respective library is not declared as #include <SoftwareSerial.h> and without instantiate it as
SoftwareSerial BT(BT_RX,BT_TX);
Which Arduino board are you using in conjunction with the HC06 ? Because you declare Rx pin 10 and Tx pin 11 it seems an UNO board ? And which Arduino IDE: i.e. 1.x.x or 2.x.x ?
Before any attempt with your own app, you shall be sure that the BT comm's is working between your Arduino system and the Android device. To this purpose I strongly suggest you to test it by using the following ready made app (free on the Google Playstore):

What code have you done in AI2 to interface the Arduino code, so far ? Can you post your .aia so to have a look on it ?

Hola buenas tardes, con la aplicación serial bluetooth funciona perfectamente pero me gustaría trabajar la apk en Appinventor con la nueva aplicación.

Ok perfect,
now please post your preliminary .aia so to have a look on it.

Can you please also answer my previous questions ? What Arduino board are you using ? What version of IDE ? So to understand a bit more about the Arduino side.

La verdad ahí voy, ya que en appinventor tengo muy poca experiencia, la placa de arduino utilizada es Arduino UNO, IDE 1.8.12.

Se que en el segundo bloque tengo errores donde dice Cuando. SelectorDeLista1.DespuesdeSelección-->Ejecutar------>no se si va así o que debo hacer. Gracias


I'll see it tomorrow... :yawning_face: :yawning_face: :yawning_face: :sleeping: :sleeping: :sleeping:

1 Like

OK last post for tonite... since with Serial Bluetooth Terminal it works, this means that you can discover which is the IP address of your HCO6 in the /device menu of SBT.
Then, instead of let it be choosen within a list, fix it at block level. like the example below.
You see also that I initialize a clock to receive data on the BT. But this is another story, and a bit longer to explain, and I really have my eyes broken.....

Have a pleasant night :sleeping:

1 Like

Dear @Nanita9684, just one more hint: when you post your blocks, or whenever you'll post your .aia, please select the English language, before, so to allow a wider number of participants to read and help you.
Please also consider (since you say you're not so deep in AI2 knowledge) to have a look to what @ABG has already lined earlier in this thread about BT comm's. It is really worth having a look to it (it's not a waste of time ,though you are in a hurry).
Cheers