App inventor 2 en español
Cómo programar los teléfonos móviles con Android.
Bluetooth, Arduino y App inventor 2 - Juan Antonio Villalpando
-- Tutorial de iniciación de App Inventor 2 en español --
Volver al índice del tutorial
___________________________
9A0.- Resumen de códigos Bluetooth. Enviar. Recibir.
p9A0_bluetooth_caracter.aia
- App Inventor le envía automáticamente números al Arduino y éste le devuelve la información recibida.
_______________________________________________
- Diseño.
_______________________________________________
- Bloques.
___________________________
- Conexión Arduino.
___________________________
- Código Arduino.
- IMPORTANTE: Para cargar el programa en el Arduino, debe estar desconectado el módulo Bluetooth.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pin12 12
#define Pin13 13
char caracter;
void setup() {
Serial.begin(9600);
pinMode(Pin12, OUTPUT);
pinMode(Pin13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
if(caracter == 'a'){ digitalWrite(Pin12, HIGH);}
if(caracter == 'b'){ digitalWrite(Pin12, LOW);}
if(caracter == 'c'){ digitalWrite(Pin13, HIGH);}
if(caracter == 'd'){ digitalWrite(Pin13, LOW);}
}
}
|
___________________________
p9A0_bluetooth_texto.aia
_______________________________________________
- Bloques.
_______________________________________________
- Bloques.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pin12 12
#define Pin13 13
char caracter;
String palabra;
void setup() {
Serial.begin(9600);
pinMode(Pin12, OUTPUT);
pinMode(Pin13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
if(caracter == '*') {
palabra = palabra.substring(0, palabra.length() - 1); // Delete last char *
Serial.println(palabra);
if (palabra == "on12"){digitalWrite(Pin12, HIGH);}
if (palabra == "off12"){digitalWrite(Pin12, LOW);}
if (palabra == "on13"){digitalWrite(Pin13, HIGH);}
if (palabra == "off13"){digitalWrite(Pin13, LOW);}
palabra = "";
delay(100);
}
}
}
|
_______________________________________________
- Sin asterisco.
p9A0i_bluetooth_texto_2.aia
- Utilzando en el código de Arduino palabra.indexOf, no es necesario poner el asterisco.
- palabra.indexOf nos informará si la cadena enviada contiene "on12", "off12", "on13", "off13".
_______________________________________________
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pin12 12
#define Pin13 13
char caracter;
String palabra;
void setup() {
Serial.begin(9600);
pinMode(Pin12, OUTPUT);
pinMode(Pin13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
Serial.println(palabra);
if (palabra.indexOf("on12")>= 0){digitalWrite(Pin12, HIGH); palabra = "";}
if (palabra.indexOf("off12")>= 0){digitalWrite(Pin12, LOW); palabra = "";}
if (palabra.indexOf("on13")>= 0){digitalWrite(Pin13, HIGH); palabra = "";}
if (palabra.indexOf("off13")>= 0){digitalWrite(Pin13, LOW); palabra = "";}
delay(100);
}
}
|
_______________________________________________
- Enviar varios mensajes a la vez
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pin12 12
#define Pin13 13
char caracter;
String palabra;
void setup() {
Serial.begin(9600);
pinMode(Pin12, OUTPUT);
pinMode(Pin13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
if(caracter == '*') {
palabra = palabra.substring(0, palabra.length() - 1); // Delete last char *
Serial.println(palabra);
if(palabra.indexOf("on12")>= 0){digitalWrite(Pin12, HIGH);}
if(palabra.indexOf("off12")>= 0){digitalWrite(Pin12, LOW);}
if(palabra.indexOf("on13")>= 0){digitalWrite(Pin13, HIGH);}
if(palabra.indexOf("off13")>= 0){digitalWrite(Pin13, LOW);}
palabra = "";
delay(100);
}
}
}
|
_______________________________________________________
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
char caracter;
String palabra;
String red;
String green;
String blue;
int ind1;
int ind2;
int ind3;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
if(caracter == '*') {
palabra = palabra.substring(0, palabra.length() - 1); // Delete last char *
Serial.println(palabra);
ind1 = palabra.indexOf(',');
red = palabra.substring(0, ind1);
ind2 = palabra.indexOf(',', ind1+1 );
green = palabra.substring(ind1+1, ind2);
ind3 = palabra.indexOf(',', ind2+1 );
blue = palabra.substring(ind2+1);
Serial.print("red = ");
Serial.println(red);
Serial.print("green = ");
Serial.println(green);
Serial.print("blue = ");
Serial.println(blue);
Serial.println();
palabra = "";
delay(10);
}
}
}
|
__________________________________________
Temperatura humedad
p9A0_bluetooth_temperatura.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
char caracter;
int temperature = 0;
int humidity = 0;
String tempera_humidity;
void setup() {
Serial.begin(9600);
}
void loop() {
temperature = random(20,40);
humidity = random(50,95);
delay(500);
if(Serial.available()) {
caracter = Serial.read();
if(caracter == 'T'){Serial.println(temperature);}
if(caracter == 'H'){Serial.println(humidity);}
if(caracter == 'D'){
tempera_humidity = (String) temperature + "," + (String) humidity;
Serial.println(tempera_humidity);
}
}
}
|
_________________________________________________
- Estado dos pulsadores.
p9A0i_bluetooth_pulsadores.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
char caracter;
#define push7 7 // PushButton 7.
#define push8 8 // PushButton 8.
String status_push7;
String status_push8;
String status;
void setup() {
Serial.begin(9600);
pinMode(push7, INPUT);
pinMode(push8, INPUT);
}
void loop() {
delay(50);
if(Serial.available()) {
caracter = Serial.read();
if (digitalRead(push7) == HIGH) {status_push7 = "Push7 ON";} else {status_push7 = "Push7 OFF";}
if (digitalRead(push8) == HIGH) {status_push8 = "Push8 ON";} else {status_push8 = "Push8 OFF";}
status = status_push7 + "," + status_push8;
if(caracter == '7'){Serial.println(status_push7);}
if(caracter == '8'){Serial.println(status_push8);}
if(caracter == 'D'){Serial.println(status);}
}
}
|
________________________________________
:La app recibe el valor de dos potenciómetros.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pot0 7 // Potentiometer 0.
#define Pot1 8 // Potentiometer 1.
int value_pot0;
int value_pot1;
String value;
void setup() {
Serial.begin(9600);
}
void loop() {
value_pot0 = analogRead(A0);
value_pot1 = analogRead(A1);
value = (String) value_pot0 + "," + (String) value_pot1;
Serial.println(value);
delay(200); // It should be slower than the Clock Interval.
}
|
____________________________________________________________
- Envío de número aleatorio.
p9A0i_bluetooth_potenciometro.aia (3.3 KB)
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int aleatorio;
void setup() {
Serial.begin(9600);
}
void loop() {
aleatorio = random(0,100);
Serial.println(aleatorio);
delay(200); // It should be slower than the Clock Interval.
}
|
____________________________________________
- Gráfico dinámico.
p9A0i_bluetooth_dinamico.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int value_pot0;
void setup() {
Serial.begin(9600);
}
void loop() {
value_pot0 = analogRead(A0);
Serial.println(value_pot0);
delay(100); // It should be slower than the Clock Interval.
}
|
____________________________________________
- Secuencia de LED.
p9A0i_bluetooth_secuencia3LED
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
char caracter;
String palabra;
int LED11 = 11;
int LED12 = 12;
int LED13 = 13;
int valor11;
int valor12;
int valor13;
int Tiempo = 1000000;
unsigned long currentMillis;
unsigned long previousMillis = currentMillis;
int k1;
int k2;
int k3;
int k4;
void setup() {
Serial.begin(9600);
pinMode(LED11, OUTPUT);
pinMode(LED12, OUTPUT);
pinMode(LED13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
palabra = palabra + caracter;
Serial.println(palabra);
if(caracter == '*') {
palabra = palabra.substring(0, palabra.length() - 1); // Quita último caracter *
k1 = palabra.indexOf('-');
valor11 = palabra.substring(0, k1).toInt();
k2 = palabra.indexOf('-', k1+1);
valor12 = palabra.substring(k1+1, k2).toInt();
k3 = palabra.indexOf('-', k2+1);
valor13 = palabra.substring(k2+1, k3).toInt();
k4 = palabra.indexOf('-', k3+1);
Tiempo = 1000 * palabra.substring(k3+1, k4).toInt();
palabra = "";
digitalWrite(LED11, valor11);
digitalWrite(LED12, valor12);
digitalWrite(LED13, valor13);
}
previousMillis = currentMillis;
} // =>Fin del available
tiempo();
} // =>Fin del loop
void tiempo() {
currentMillis = millis();
if (currentMillis >= (previousMillis + Tiempo)) {
previousMillis = currentMillis;
Serial.println("send_me_next"); // Envíame el siguiente.
}
}
|
____________________________________________
- Pantallas virtuales.
p9A0i_bluetooth_virtual.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define LED13 13
byte StatusLED13;
void setup()
{
Serial.begin(9600);
pinMode(LED13, OUTPUT);
}
void loop() {
if(Serial.available())
{
int dato = Serial.read();
if(dato == 153){digitalWrite(LED13, HIGH);}
if(dato == 168){digitalWrite(LED13, LOW);}
if(dato == 221){
StatusLED13 = digitalRead(LED13);
Serial.print(StatusLED13); // Sends 48 or 49
}
}
}
|
____________________________________________
- Servos.
p9A0i_bluetooth_servos.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#include <Servo.h>
Servo servo3;
Servo servo5;
const int pwmPin3 = 3; // Servo3 pin3 PWM
const int pwmPin5 = 5; // Servo5 pin5 PWM
char caracter;
String palabra;
String angulo_1;
String angulo_2;
int k1;
void setup() {
Serial.begin(9600);
pinMode (pwmPin3, OUTPUT);
pinMode (pwmPin5, OUTPUT);
servo3.attach(pwmPin3);
servo5.attach(pwmPin5);
}
void loop() {
if(Serial.available())
{
caracter = Serial.read();
palabra = palabra + caracter;
if (caracter == '*') {
Serial.println(palabra);
palabra = palabra.substring(0, palabra.length() - 1); // Delete last char *
k1 = palabra.indexOf(',');
angulo_1 = palabra.substring(0, k1);
angulo_2 = palabra.substring(k1+1, -1);
servo3.write(angulo_1.toInt());
servo5.write(angulo_2.toInt());
palabra = "";
}
}
} // => Fin Loop
|
_______________________________
Papaopaso
p9A0i_bluetooth_pasopaso.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#include <Stepper.h>
#define STEPS 64
// Secuencia 1-3-2-4
Stepper motor(STEPS, 8, 10, 9, 11);
char caracter;
void setup() {
Serial.begin(9600);
motor.setSpeed(200);
}
void loop() {
if( Serial.available() ) {
caracter = Serial.read();
Serial.print(caracter);
if(caracter == '1'){motor.step(60);}
if(caracter == '2'){motor.step(-60);}
if(caracter == '3'){motor.step(510);}
if(caracter == '4'){motor.step(-510);}
if(caracter == '5'){motor.step(1020);}
if(caracter == '6'){motor.step(-1020);}
if(caracter == '7'){motor.step(2040);}
if(caracter == '8'){motor.step(-2040);}
if(caracter == 'A'){motor.step(100);}
if(caracter == 'B'){motor.step(-100);}
}
}
|
|
#define stepper PORTB
#define waiting_time 2 // or 2 change here!
void setup() {
for (int z = 8; z < 12; z++) { // FULL STEP DRIVE
pinMode(z, OUTPUT); // pins 8,9,10,11 output for driving the motor
}
}
void loop() {
stepper = 0B0011; // 0x03;
delay(waiting_time);
stepper = 0B0110; // 0x06;
delay(waiting_time);
stepper = 0B1100; // 0x0C;
delay(waiting_time);
stepper = 0B1001; // 0x09;
delay(waiting_time);
}
|
__________________________________________________________
- Conectar BT
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define Pin13 13
char caracter;
void setup() {
Serial.begin(9600);
pinMode(Pin13, OUTPUT);
}
void loop() {
if(Serial.available()) {
caracter = Serial.read();
if(caracter == 'a'){ digitalWrite(Pin13, HIGH);}
if(caracter == 'b'){ digitalWrite(Pin13, LOW);}
Serial.println(caracter);
}
}
|
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#include <SoftwareSerial.h>
SoftwareSerial I2CBT(10,11);
// El TX del módulo BT va al pin10 del Arduino
// El RX del módulo BT va al pin11 del Arduino
#define Pin13 13
char caracter;
void setup() {
I2CBT.begin(9600); // To read and write Bluetooth
Serial.begin(9600); // To print in Serial Monitor
pinMode(Pin13, OUTPUT);
}
void loop() {
if(I2CBT.available()) {
caracter = I2CBT.read();
if(caracter == 'a'){ digitalWrite(Pin13, HIGH);}
if(caracter == 'b'){ digitalWrite(Pin13, LOW);}
Serial.println(caracter); // Serial Monitor
I2CBT.println(caracter); // return Bluetooth
// I2CBT.write(caracter); // return Bluetooth
}
}
|
__________________________________________________________
- Enviar archivo.
==========================================================================
__________________________________________________________
- Enviar Imagen.
Server.
Client
__________________________________________________________
- Interrupciones.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#define LED13 13
void setup()
{
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(2), on_13, RISING);
attachInterrupt(digitalPinToInterrupt(3), off_13, RISING);
pinMode(LED13, OUTPUT);
}
void loop()
{
//
}
// Interruptions ISR.
void on_13() // When pin2 RISING...
{
digitalWrite(LED13, HIGH);
Serial.print(1);
}
void off_13() // When pin3 RISING...
{
digitalWrite(LED13, LOW);
Serial.print(0);
}
|
___________________________________
- Fallo en la conexión
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int aleatorio;
void setup() {
Serial.begin(9600);
}
void loop() {
aleatorio = random(0,100);
Serial.println(aleatorio);
delay(400); // Clock.Interval < delay Arduino
}
|
______________________________________
- JoyStick
p9A0_bluetooth_laberinto.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int x;
int y;
int c;
String datos;
void setup() {
Serial.begin(9600);
pinMode(2,INPUT_PULLUP);
}
void loop() {
x = analogRead(A0);
y = analogRead(A1);
if (digitalRead(2) == HIGH){c=0;} else {c=1;}
datos = (String) x + "," + (String) y + "," + (String) c;
Serial.println(datos);
delay(100);
}
|
________________________________________________
- Arduino envía tres números aleatorios
p9A0i_bluetooth_aleatorios.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int x;
int y;
int z;
String datos;
void setup() {
Serial.begin(9600);
}
void loop() {
x = random(0, 10);
y = random(10, 100);
z = random(100,1000);
datos = (String) x + "," + (String) y + "," + (String) z;
Serial.println("Números aleatorios:");
Serial.println("Random numbers:");
Serial.println(datos);
delay(800);
}
|
-------------------------------------------------------
p9A0i_bluetooth_aleatorio2.aia
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
int alea_1;
int alea_2;
unsigned long tiempo_actual_1 = 0;
unsigned long tiempo_actual_2 = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if((millis()-tiempo_actual_1)>= 1000){
int alea_1 = random(0,100);
tiempo_actual_1 = millis();
Serial.println(String(alea_1));
}
if((millis()-tiempo_actual_2)>= 2000){
int alea_2 = random(200,300);
tiempo_actual_2 = millis();
Serial.println(String(alea_2));
}
}
|
______________________________________________________
- Multitouch I, con reloj.
p9A0i_bluetooth_multitouch.aia
- Multitouch consiste en pulsar varios Botones a la vez.
- Podemos utilizar la extensión: 295_extension_multitouch.htm
- Pero vamos a realizarlo mediante los eventos TouchDown y TouchUp.
- Tenemos 4 Botones y queremos hacer funcionar 4 motores conectados a un Arduino UNO, de tal manera que podemos pulsar varios botones a la vez y hacer girar varios motores según los botones pulsados.
- Mostraré un código elemental.
_______________________________________________
- Diseño.
_______________________________________________
- Bloques.
_______________________________________________
- Arduino.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
byte byte_received;
String motor;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available()) {
byte_received = Serial.read();
// Serial.println(byte_received, BIN);
// Serial.println(byte_received, DEC);
motores();
}
}
void motores(){
if (bitRead(byte_received, 0)){Serial.print("Motor0: RUN ");} else {Serial.print("Motor0: --- ");}
if (bitRead(byte_received, 1)){Serial.print("Motor1: RUN ");} else {Serial.print("Motor1: --- ");}
if (bitRead(byte_received, 2)){Serial.print("Motor2: RUN ");} else {Serial.print("Motor2: --- ");}
if (bitRead(byte_received, 3)){Serial.print("Motor3: RUN ");} else {Serial.print("Motor3: --- ");}
Serial.println();
}
|
- Pulsamos a la vez los Botones 2 y 4, enviamos un 6 en Byte.
______________________________________________________
- Multitouch II, sin reloj.
p9A0i_bluetooth_multitouch_noclock.aia
- El mismo código que hemos visto anteriormente, pero sin Reloj.
_______________________________________________
- Bloques.
_____________________________________
- ReadUntil. ReadString.
p9A1_bluetooth_textoi_2.aia
_______________________________________________
- Diseño.
_______________________________________________
- Bloques.
- En este ejemplo el módulo Bluetooth está conectado a los terminales 2 y 3 de Arduino.
|
// Juan A. Villalpando
// http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm
#include <SoftwareSerial.h>
SoftwareSerial Bluetooth(2,3);
String texto;
void setup() {
Serial.begin(9600);
Bluetooth.begin(9600);
Bluetooth.setTimeout(100);
}
void loop() {
if(Bluetooth.available()) {
// texto = Bluetooth.readStringUntil('\n');
texto = Bluetooth.readString();
Serial.println(texto);
Bluetooth.println(texto);
}
}
|
_____________________________________
-
App envía un número como texto y Arduino lo convierte a binario. Retorno.
p9A2_ConvertirBinario.aia
- Escribimos un número decimal en la App y Arduino lo recibe y lo convierte en binario.
1.- Binario 8 bits
Binario.ino |
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
int num = Serial.parseInt(); // Read number received as text
String binary = String(num, BIN); // To binary
while (binary.length() < 8) {
binary = "0" + binary; // Fill 0 left
}
Serial.println(binary); // Print binary number and return.
}
}
|
2.- Binario posicional.
Binario_2.ino |
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
int num = Serial.parseInt(); // Read number received as text
String binary = "";
for (int i = 0; i < 48; i++) {
if (i == num) {
binary += "1"; // Agregar "1" en la posición correspondiente al número
} else {
binary += "0"; // Agregar "0" en las demás posiciones
}
}
Serial.println(binary); // Print binary number and return.
}
}
|
3.- BCD (Binary-Coded Decimal).
- Se debe enviar un número de 4 cifras, por ejemplo 1257.
Binario_3.ino |
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
String textReceived = Serial.readStringUntil('\n');
if (textReceived.length() == 4) {
for (int i = 0; i < 4; i++) {
int num = textReceived.charAt(i) - '0'; // Get numeric value.
String bcd = String(num, BIN); // To BCD
bcd = ("0000" + bcd).substring(bcd.length()); // BCD with 4 bits
Serial.print(bcd + " "); // Print binary number and return.
}
Serial.println();
}
}
}
|
_____________________________________
- Arduino envía dos números con decimales.
pA0_Bluetooth_Arduino_envia.aia
- Arduino envía dos números aleatorios con dos decimales separado por coma.
Decimales.ino |
float temperature = 0.0;
float humidity = 0.0;
String tempera_humidity;
void setup() {
Serial.begin(9600);
}
void loop() {
temperature = random(20, 40) * 5.555;
humidity = random(50, 95) * 3.333;
tempera_humidity = String(temperature, 3) + "," + String(humidity, 3);
Serial.println(tempera_humidity);
delay(1000);
}
|
_____________________________________
- Distancia por ultrasonido.
pA0_Bluetooth_Arduino_Ultrasonido.aia
Ultrasonic.zip
_______________________________________________
- Bloques.
ultrasonico.ino |
#include <Ultrasonic.h>
Ultrasonic ultrasonic(12,13); // (Trig PIN, Echo PIN)
void setup() {
Serial.begin(9600);
}
void loop()
{
Serial.println(ultrasonic.Ranging(CM));
delay(500);
}
|
__________________________________
|