Skip to first unread message

Gustavo Iglesias

unread,
Mar 5, 2019, 12:12:22 PM3/5/19
to MIT App Inventor Forum

Hola buenas tardes,
Trate de encontrar algún hilo que resuelva mi problema pero no lo encuentro, en fin.

Hice un programa en arduino para controlar reles y leds, dentro del programa utilizo el modulo bluetotth HC-05, un sensor de temperatura DHT11 y un sensor ultrasonico HC-SR04, hice también o al menos estoy intentando hacer una aplicación en App Inventor para controlar dichos leds y reles vía bluetooth, todo esto funciona de maravilla hasta que cree una ventana para mostrar los resultados de los sensores y allí es donde empiezan mis problemas.
Al inicio todo va bien pero después de un rato recibo un error en pantalla que dice: Select list item: Attempt to get item number 2 of a list of length 1: (2), y no tengo la mas remota idea de que se trata.

Adjunto la imagen de pantalla "Screenshot_20190305-104123.png" donde se puede apreciar que el dato de temperatura se monta con los datos de distancia y bueno, trabaja así aun después de que salta el error de pantalla antes mensionado.

Adjunto el codigo de Arduino:
#include <SoftwareSerial.h>
#include <DHT.h>

// El TX del modulo BT va al pin10 de Arduino
// El RX del modulo BT va al pin11 de Arduino
SoftwareSerial myBluetooth(10, 11);

// Variables sensor DHT11
const int pinDHT11 = A0;
DHT dht11(pinDHT11, DHT11);
long ultimaLectura = 0;

// Iniciando buffer y matrix
char buffer[13];
int matrix[2][2];

// Variables captura datos de App
int datoRecibido;

// Variables sensor HC-RS04 (Ultrasonico)
const int pinTrig = 2;
const int pinEcho = 3;

// Variables Leds
const int pinVer = 4;
const int pinAzu = 5;
const int pinRoj = 6;
const int pinAma = 7;

// Variables Reles
const int pinRele1 = 8;
const int pinRele2 = 9;

void setup() {
  Serial.begin(9600);
  myBluetooth.begin(38400);
  dht11.begin();
  pinMode(pinDHT11, INPUT);
  pinMode(pinTrig, OUTPUT);
  pinMode(pinEcho, INPUT);
  pinMode(pinVer, OUTPUT);
  pinMode(pinAzu, OUTPUT);
  pinMode(pinRoj, OUTPUT);
  pinMode(pinAma, OUTPUT);
  pinMode(pinRele1, OUTPUT);
  pinMode(pinRele2, OUTPUT);
  digitalWrite(pinRele1, HIGH);
  digitalWrite(pinRele2, HIGH);
}

void loop() {
  datoRecibido = "";
  if(myBluetooth.available()) {
    datoRecibido = myBluetooth.read();
  }

  estadoLeds(datoRecibido);
  estadoReles(datoRecibido);
  estadoAmbiente();
  estadoHCSR04();
  
  // Empaquetamos los datos para enviar a la App
  sprintf(buffer, "%d, %d, %d", matrix[0][0], matrix[0][1], matrix[1][0]);
  myBluetooth.write(buffer);

  //Serial.println(buffer);
  Serial.print("Temperatura : ");
  Serial.print(matrix[0][0]);
  Serial.println("°C");
  Serial.print("Humedad     : ");
  Serial.print(matrix[0][1]);
  Serial.println("%");
  Serial.print("Distancia   : ");
  Serial.print(matrix[1][0]);
  Serial.println("cms.");
  Serial.println("");
  Serial.println("");
  
  delay(500);
}

// Funcion leds
int estadoLeds(char valLed) {

  switch(valLed) {
    case '1':   // Enciende luz principal sala
      digitalWrite(pinVer, !digitalRead(pinVer));
      break;
    case '2':   // Enciende luz lampara sala
      digitalWrite(pinAzu, !digitalRead(pinAzu));
      break;
    case '3':   // Enciende luz principal comedor
      digitalWrite(pinRoj, !digitalRead(pinRoj));
      break;
    case '4':   // Enciende luz lampara comedor
      digitalWrite(pinAma, !digitalRead(pinAma));
      break;
  }
}

// Funcion reles
int estadoReles(char valRele) {

  switch(valRele) {
    case '5':   // Enciende aire acondicionado / ventilador sala
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
    case '6':   // Enciende aire acondicionado / ventilador comedor
      digitalWrite(pinRele2, !digitalRead(pinRele2));
      break;
  }
}

// Funcion temperatura
// Temperatura con DHT11
float estadoAmbiente() {
  if(millis() - ultimaLectura >= 2000) {
    matrix[0][0] = dht11.readTemperature();
    matrix[0][1] = dht11.readHumidity();
    ultimaLectura = millis();
  }
}
// Tempreatura con LM385
/*
  float lm35 = analogRead(A0);
  float temp = (5.0 * lm35 * 100.0) / 1023.0;
*/


// Funcion sensor HCSR04
float estadoHCSR04() {
  digitalWrite(pinTrig, LOW);
  delayMicroseconds(2);
  digitalWrite(pinTrig, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrig, LOW);
  
  float tiempo = pulseIn(pinEcho, HIGH);
  float distancia = (tiempo / 58);
  matrix[1][0] = distancia;
}

Adjunto codigo de App Inventor "IMG_20190305_104233774.jpg"donde trato de capturar las variables que vienen desde mi Android.

Espero y ojala alguien con mas experiencia en esto me pueda ayudar, se los agradecería muchísimo.
Saludos
Screenshot_20190305-104123.png
IMG_20190305_104233774.jpg

Boban Vukovic

unread,
Mar 5, 2019, 1:47:18 PM3/5/19
to mitappinv...@googlegroups.com
I am not very familiar with arduino,but it seems that your variable "buffer" from arduino is not formatted as you expect it.

So when you receive data in your app and try to split at comma (,) you sometimes have only one data,and your list has only 1 item.

Maybe the problem is with inserting commas or something like that,I really dont SPEAK arduino !

Try using "list from csv row" instead

Gustavo Iglesias

unread,
Mar 5, 2019, 3:10:13 PM3/5/19
to MIT App Inventor Forum
Hola Boban Vukovic, agradezco tu respuesta.

El código de arduino lo adjunte para que mas o menos tengan una idea de donde provienen los datos y como se les trata antes de enviarlos, tampoco soy experto en Arduino pero quien sabe podría estar ahí parte del error.

Mas que todo quiero centrarme en el código de App Inventor ya que para mi esto es realmente nuevo y no lo se usar, salvo por algunos tutoriales en Youtube,   :)

Por ejemplo, el consejo que me mencionas para usar "list from csv row", me parece interesante, como cometas, puede ser que no se este recibiendo la cadena completa y me este dando error por los espacios en blanco, es lo que entiendo.

Voy a ver de que se trata esa solución que me das y aplicarla, ya te comento.

Saludos.

Chris Ward

unread,
Mar 5, 2019, 5:52:14 PM3/5/19
to MIT App Inventor Forum
Hello Gustavo

Some notes re your Sketch and App:
  • You must print value delimiters that the App Inventor "split" function will use - in your App code, the delimiter is a comma ",", that needs to be Serial.print(",") after each value in the Sketch.
  • There is no need to print value titles or value units - you already know what these are and they can be permanent labels in the App - just send the values, much easier  to process.
  • There should be only one Serial.println() at the end of the loop -with no content at all, just Serial.println()
  • The App Inventor Timer must be set to be slightly faster than the Sketch Loop Delay (will require tweaking). 
  • Do not set the send/receipt of data faster than is necessary. Humans are unable to follow 500ms updates - way too fast!

Reply all
Reply to author
Forward
0 new messages