Mostrando las entradas con la etiqueta socket bluetooth. Mostrar todas las entradas
Mostrando las entradas con la etiqueta socket bluetooth. Mostrar todas las entradas
Vamos a programar #43 - Actualizando clock view.
Hola de nuevo a todos, el día de hoy vamos a ver una actualizacion del código de clock view.
Cómo recordarás, hace un buen rato dije que iba a actualizar el código, pero por varias razones lo pospuse, hasta que finalmente casí lo olvide. No se le hicieron muchos cambios, solo optimizaron algunas partes y se saco un poco más de provecho a las partes que ya se usaban y se agregaron unas cuantas más. Sí previamente ya habías hecho el proyecto, solo bastará con cargar el código al arduino, de cualquier forma, el código estará disponible para su descarga.
El código es funcional, pero demostrativo. Uno de los cambios más notorios que se puede observar, es que los número son más grandes.
Además se hace uso de pulsadores para que tambien sea manipulable, en este caso, el código hace uso de 4, pero tal vez en un futuro, se usen solo 3, he visto muchos relojes que solo hacen el uso de ese número.
El código se actualizará nuevamente, pero por ahora lo público así para que te sientas libre de probar con tus propios ajustes. Si no dispones de pulsadores, no te preocupes, aun es totalmente utilizable solo por medio de bluetooth. El código anterior lo puedes descargar de la seccion de descargas y si quieres hacer uso de este, basta con copiarlo; todas las conexiones vienen en el código.
Por ahora es todo, los leo luego.
Cómo recordarás, hace un buen rato dije que iba a actualizar el código, pero por varias razones lo pospuse, hasta que finalmente casí lo olvide. No se le hicieron muchos cambios, solo optimizaron algunas partes y se saco un poco más de provecho a las partes que ya se usaban y se agregaron unas cuantas más. Sí previamente ya habías hecho el proyecto, solo bastará con cargar el código al arduino, de cualquier forma, el código estará disponible para su descarga.
El código.
El código actualizado del Clock View es el siguiente:
//Clockview 2.0
#include <DS1302.h>
#include "LedControl.h"
#include <SD.h>
/*
Para la conexión del modulo SD se siguen los siguientes:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 10 - Este es el que se puede cambiar
*/
//Pin SD
int CS_PIN = 10;
//Constantes para los pines usados en la matriz
const int MaxDIn = 9;
const int MaxCS = 8;
const int MaxCLK = 7;
int MaxNDevices = 3;
bool IsConnected = false;
//Constantes para los pines usados en el reloj
const int kCePin = 6; // RST
const int kIoPin = 5; // Dat
const int kSclkPin = 4; // Serial Clock
//Inicializacion de la matriz
//DIN,CLK,CS
LedControl lc = LedControl(MaxDIn, MaxCLK, MaxCS, MaxNDevices);
//Inicializacion del reloj
DS1302 rtc(kCePin, kIoPin, kSclkPin);
//Algunas variables
File Archivo;
char Texto[24];
int MatrixB = 10;
bool H24 = true;
bool HalfSecond = true;
bool IsScreenEnable = true;
bool ShowSeconds = true;
bool SDCardReady = false;
bool EditMode = false;
bool ShowDate = false;
bool Demo = false;
//Matriz con los "Numeros"
const unsigned char Numbers[] = {
B11111110, B10000010, B11111110, //0
B10000100, B11111110, B10000000, //1
B11110010, B10010010, B10011110, //2
B10000010, B10010010, B11111110, //3
B00011110, B00010000, B11111110, //4
B10011110, B10010010, B11110010, //5
B11111110, B10010010, B11110010, //6
B00000010, B00000010, B11111110, //7
B11111110, B10010010, B11111110, //8
B00011110, B00010010, B11111110, //9
B11111110, B00010010, B11111110, //A - 10
B11111110, B00011100, B11111110, //M - 11
B11111110, B00010010, B00011110, //P - 12
B11111110, B00010000, B11111110, //H - 13
B11111110 ,B00110010, B11011110, //R - 14
};
//Definimos simbolos
const unsigned char Symbols[] = {
B01000100, B00101000, B00010000, B11111110, B01010100, B00101000, //BT 0
B00111100, B01000110, B01011010, B01001010, B01001010, B00111100, //Clock Adjust 1
B11010110, B10111010, B01000100, B01000100, B10111010, B11010110//Brightness 2
};
//Imprimir simbolos
void PrintSymbol(byte Index,byte SymDevice){
for (int Y = 1; Y < 7; Y++){
lc.setRow(SymDevice, Y, Symbols[Index * 5 + Y - 1]);
}
}
//Funcion para escribir los numero en la matriz.
void PrintNumber(byte NumberOne, byte NumberTwo, byte Device){
for (int X = 1; X < 8; X++){
if (X < 4){
lc.setRow(Device, X, Numbers[NumberOne * 3 + X - 1]);
}
if (X == 4){
lc.setRow(Device, 4, 0);
}
if (X > 4){
lc.setRow(Device, X, Numbers[NumberTwo * 3 + X - 5]);
}
}
}
void printDate(){
Time t = rtc.time();
const String day = dayAsString(t.day);
char buf[50];
snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec);
int ShortYear = t.yr % 100;
PrintNumber(t.date / 10, t.date % 10, 0);
PrintNumber(t.mon / 10, t.mon % 10, 1);
PrintNumber(ShortYear / 10, ShortYear % 10, 2);
}
//Imprimir el tiempo en las matrices y en el monitor serie.
void printTime(){
Time t = rtc.time();
const String day = dayAsString(t.day);
char buf[50];
snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d",
day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec);
PrintNumber(AdjustTime(t.hr, H24) / 10,AdjustTime(t.hr, H24) % 10, 0);
PrintNumber(t.min / 10, t.min % 10, 1);
if (ShowSeconds){
PrintNumber(t.sec / 10, t.sec % 10, 2);
}else{
if(H24)
PrintNumber(13, 14, 2);
if(!H24 && t.hr < 13)
PrintNumber(10, 11, 2);
if(!H24 && t.hr > 12)
PrintNumber(12, 11, 2);
}
//PrintSymbol(0, 2);
if (IsScreenEnable == true)
{
if (HalfSecond == true){
digitalWrite(3, HIGH);
HalfSecond = false;
}else{
digitalWrite(3, LOW);
HalfSecond = true;
}
}
Serial.println(buf);
}
//Demo directo del ejemplo de la libreria
void ScreenDemo(){
int devices=lc.getDeviceCount();
for(int row=0;row<8;row++) {
for(int col=0;col<8;col++) {
for(int address=0;address<devices;address++) {
int DemoButton = analogRead(A5);
if(DemoButton < 200){
Demo = false;
break;
}
delay(40);
lc.setLed(address,row,col,true);
delay(40);
lc.setLed(address,row,col,false);
}
}
}
}
//Ajustar la hora
int AdjustTime(int Hour, bool In24Hformat){
if(In24Hformat == true){
return Hour;
}
if(In24Hformat == false && Hour > 12){
Hour = Hour - 12;
return Hour;
}else{
return Hour;
}
}
//Guardar los ajustes
void SaveSettings(){
Archivo = SD.open("Settings.clv", O_WRITE | O_CREAT);
char SaveBuf[8];
snprintf(SaveBuf, sizeof(SaveBuf), "%s%02d",">SETB", MatrixB);
Serial.println(SaveBuf);
if (Archivo){
Archivo.seek(0);
Archivo.println(SaveBuf);
if(H24)
Archivo.println(">SETF");
else
Archivo.println("XSETF");
if (ShowSeconds)
Archivo.println(">DISS");
else
Archivo.println("XDISS");
Archivo.flush();
Archivo.close();
Serial.println("Guardado");
} else {
Serial.println("error writing test.txt");
}
}
//Enviar un resumen de las configuraciones actuales
void SendResume(){
}
//Cargar los ajustes
void LoadSettings(){
Archivo = SD.open("Settings.clv", FILE_READ);
int B = 0;
byte CurRead;
char SettBuf[22];
if (Archivo) {
while (Archivo.available() > 0){
CurRead = Archivo.read();
if (CurRead != 10 && CurRead != 13){
SettBuf[B] = CurRead;
B++;
Serial.print(B);
}else{
CheckPetition(SettBuf, false);
Serial.print(B);
B = 0;
for (int BF = 0; BF < 22; BF++)
SettBuf[BF]=0;
}
}
Archivo.close();
}else{
Serial.println("error opening file");
}
}
//Comprobar si hay algun comando
void CheckPetition(char DATA[], bool Save){
int i = 0;
int j = 0;
String Texto(DATA);
//>SETH2016122119001004
if (Texto.startsWith(">DISS")){
ShowSeconds = !ShowSeconds;
if (Save)
SaveSettings();
Serial.print("No/Se muestran los segundos");
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.shutdown(CurrentDevice, !IsScreenEnable);
}
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
if (Texto.startsWith(">SCRA")){
IsScreenEnable = !IsScreenEnable;
Serial.print("Las matrices se apagaron/encendieron");
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.shutdown(CurrentDevice, !IsScreenEnable);
}
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
if (Texto.startsWith(">RESET")){
SD.remove("Settings.clv");
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.shutdown(CurrentDevice, !IsScreenEnable);
}
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
if (Texto.startsWith(">SETF")){
H24 = !H24;
if (Save)
SaveSettings();
Serial.print("EL reloj cambio de formato 12H-24H");
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
if (Texto.startsWith(">SETH")){
AdjustTime(Texto.substring(9, 5).toInt(),Texto.substring(11,9).toInt(),Texto.substring(13, 11).toInt(),
Texto.substring(15, 13).toInt(), Texto.substring(17, 15).toInt(), Texto.substring(19, 17).toInt(),
Texto.substring(21, 19).toInt());
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
if (Texto.startsWith(">SETB")){
MatrixB = Texto.substring(5).toInt();
if (Save)
SaveSettings();
Serial.println("El brillo se cambio");
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.setIntensity(CurrentDevice, MatrixB);
}
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
else {
for (j = 0; j < 11; j++) {
DATA[j] = 0;
}
i = 0;
}
}
//Convertir los dias
String dayAsString(const Time::Day day){
switch (day){
case Time::kSunday: return "DOM";
case Time::kMonday: return "LUN";
case Time::kTuesday: return "MAR";
case Time::kWednesday: return "MIE";
case Time::kThursday: return "JUE";
case Time::kFriday: return "VIE";
case Time::kSaturday: return "SAB";
}
return "(unknown day)";
}
//Ajustar la hora
void AdjustTime(int Year,int Month, int Day, int Hour, int Minute, int Second, int DayOfWeek){
Time::Day CurrentDay;
switch (DayOfWeek){
case 1:
CurrentDay = Time::kSunday;
break;
case 2:
CurrentDay = Time::kMonday;
break;
case 3:
CurrentDay = Time::kTuesday;
break;
case 4:
CurrentDay = Time::kWednesday;
break;
case 5:
CurrentDay = Time::kThursday;
break;
case 6:
CurrentDay = Time::kFriday;
break;
case 7:
CurrentDay = Time::kSaturday;
break;
}
//Esta parte se usa para actualizar la hora.
rtc.writeProtect(false);
rtc.halt(false);
Time t(Year, Month, Day, Hour, Minute, Second, CurrentDay);
rtc.time(t);
}
//Inicializar la tarjeta SD para usarla
void InitializeSD(){
pinMode(CS_PIN, OUTPUT);
if (SD.begin()){
SDCardReady = true;
Serial.println("La tarjeta SD esta lista");
}else{
SDCardReady = false;
Serial.println("La tarjeta SD no esta lista");
return;
}
}
//Setup
void setup(){
Serial.begin(9600);
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.shutdown(CurrentDevice, false);
lc.setIntensity(CurrentDevice, MatrixB);
lc.clearDisplay(CurrentDevice);
}
InitializeSD();
pinMode(A2, INPUT_PULLUP);
pinMode(A3, INPUT_PULLUP);
pinMode(A4, INPUT_PULLUP);
pinMode(A5, INPUT_PULLUP);
pinMode(3, OUTPUT);
if(SDCardReady){
LoadSettings();
}else{
Serial.println("La tarjeta no está lista");
}
}
//Loop
void loop(){
int SetEditButton = analogRead(A2);
int ShowDateButton = analogRead(A3);
int TurnOffMatrixButton = analogRead(A4);
int DemoButton = analogRead(A5);
while (Demo == true){
ScreenDemo();
}
if(DemoButton < 200){
Demo = !Demo;
}
Serial.println(SetEditButton);
if(SetEditButton < 200){
EditMode = !EditMode;
}
if(ShowDateButton < 200){
ShowDate = true;
}
if(TurnOffMatrixButton < 200){
IsScreenEnable = !IsScreenEnable;
for (int CurrentDevice = 0; CurrentDevice < MaxNDevices; CurrentDevice++){
lc.shutdown(CurrentDevice, IsScreenEnable);
}
}
if(ShowDate){
printDate();
delay(3000);
ShowDate = false;
}
if(EditMode){
int PotB = analogRead(A0);
// print out the value you read:
int MatrixB = map(PotB, 0, 1000, 1, 15);
char SaveBuf[8];
snprintf(SaveBuf, sizeof(SaveBuf), "%s%02d",">SETB", MatrixB);
CheckPetition(SaveBuf, false);
PrintNumber(MatrixB / 10,MatrixB % 10, 2);
PrintSymbol(2,1);
delay(100);
}else{
int i = 0;
printTime();
delay(100);
if (Serial.available()) {
while (Serial.available() > 0) {
Texto[i] = Serial.read();
i++;
}
Texto[i] = '\0';
}
CheckPetition(Texto, true);
}
}
El código es funcional, pero demostrativo. Uno de los cambios más notorios que se puede observar, es que los número son más grandes.
![]() |
| Los números eran de 3x5 LEDs, en su lugar, ahora son de 7x3 |
El código se actualizará nuevamente, pero por ahora lo público así para que te sientas libre de probar con tus propios ajustes. Si no dispones de pulsadores, no te preocupes, aun es totalmente utilizable solo por medio de bluetooth. El código anterior lo puedes descargar de la seccion de descargas y si quieres hacer uso de este, basta con copiarlo; todas las conexiones vienen en el código.
Por ahora es todo, los leo luego.
11/05/2017 02:14:00 p.m.
Arduino
,
bluetooth
,
electronica basica
,
how to
,
LED
,
matriz led
,
max7219
,
programacion
,
socket bluetooth
Vamos a programar #32 - Clock view en Windows.
Hola de nuevo a todos, el día de hoy vamos a continuar con un poco más de clock view.
En los post anteriores, vimos cómo controlarlo desde una aplicación para android, pero mucha gente me pregunto si era posible hacer algo similar pero desde una computadora con Windows.
La respuesta: Clock View para Windows.
Para llevar a cabo la conexión, primeramente debemos emparejar el bluetooth de Clock view con el de la computadora que vayamos a usar.
Cuando ya estén emparejados, hay que revisar cual es el puerto que se asigno al bluetooth. Para eso, hay que ir a: Panel de control > Dispositivos e impresoras > "Nombre del Arduino", luego hay que hacer clic secundario y después propiedades.En la ficha "Servicios", nos mostrará cual es el puerto que se usará.
Una vez que sabemos esa información, pasaremos al código de C# que es el siguiente:
Para hacer uso del puerto serial, debemos de crear un objeto SerialPort que se incluye en el espacio de nombres System.IO.Ports.
Cuando el formulario se carga, lo primero que hará es buscar todos los puertos disponibles, pero eso no quiere decir que este conectado o en uso el periférico. Si cuando inicias el programa no puedes ver el puerto al que está conectado tu arduino, basta con que escribas el nombre en la lista. Despues solo hay que hacer clic en conectar y si todo está en orden, se podrá controlar ClockView desde la computadora con BlueTooth.
Al igual que la aplicación para android, en está aplicación se incluyen los controles que cambian las configuraciones de ClockView. Además está aplicación sirve con un cable, si conectas Clock View con un cable USB, también podrás cambiar los ajustes, pero esa no es la idea; aun si prefieres hacer uso del cable, es recomendable que desconectes el módulo HC-05/06 del arduino para que no haya ningún tipo de problemas.
Al igual que todos los otros programas, dejo el código fuente para que los descargues y lo pruebes. El Código fuente de la aplicacion para android, aun lo voy a mejorar un poco y el software para arduino también.
Por ahora es todo. Los leo luego.
En los post anteriores, vimos cómo controlarlo desde una aplicación para android, pero mucha gente me pregunto si era posible hacer algo similar pero desde una computadora con Windows.
La respuesta: Clock View para Windows.
Para llevar a cabo la conexión, primeramente debemos emparejar el bluetooth de Clock view con el de la computadora que vayamos a usar.
![]() |
| En mi caso es "Siqueiros printer" (ignora el nombre es un arduino) |
Cuando ya estén emparejados, hay que revisar cual es el puerto que se asigno al bluetooth. Para eso, hay que ir a: Panel de control > Dispositivos e impresoras > "Nombre del Arduino", luego hay que hacer clic secundario y después propiedades.En la ficha "Servicios", nos mostrará cual es el puerto que se usará.
Una vez que sabemos esa información, pasaremos al código de C# que es el siguiente:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
using System.Configuration;
namespace ClockView
{
public partial class FrmMain : Form
{
private SerialPort Port = new SerialPort();
private void ArduinoMessage(string Message)
{
try
{
Port.Write(Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public FrmMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] Ports = SerialPort.GetPortNames();
CboPorts.Items.AddRange(Ports);
Port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
if (indata == "Done")
{
}
}
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
if (Port.IsOpen == false)
{
Port.BaudRate = int.Parse(TxtSpeed.Text);
Port.PortName = CboPorts.Text;
Port.Parity = Parity.None;
Port.StopBits = StopBits.One;
Port.Parity = Parity.Even;
Port.DataBits = 8;
Port.Open();
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BtnDisconnect_Click(object sender, EventArgs e)
{
if (Port.IsOpen == true)
{
Port.Close();
}
}
private void Btn1224_Click(object sender, EventArgs e)
{
ArduinoMessage(">SETF");
}
private void BtnShowSeconds_Click(object sender, EventArgs e)
{
ArduinoMessage(">DISS");
}
private void BtnLights_Click(object sender, EventArgs e)
{
ArduinoMessage(">SCRA");
}
private void trkbarBrillo_MouseUp(object sender, MouseEventArgs e)
{
ArduinoMessage(">SETB" + trkbarBrillo.Value.ToString());
}
private void BtnSync_Click(object sender, EventArgs e)
{
//>SETH2016122119001004
string HourData = string.Concat(">SETH", DateTime.Now.Year, DateTime.Now.Month.ToString("D2"), DateTime.Now.Day.ToString("D2"),
DateTime.Now.Hour.ToString("D2"), DateTime.Now.Minute.ToString("D2"), DateTime.Now.Second.ToString("D2"),
(((int)DateTime.Now.DayOfWeek)+1).ToString("D2"));
ArduinoMessage(HourData);
}
}
}
Para hacer uso del puerto serial, debemos de crear un objeto SerialPort que se incluye en el espacio de nombres System.IO.Ports.
Cuando el formulario se carga, lo primero que hará es buscar todos los puertos disponibles, pero eso no quiere decir que este conectado o en uso el periférico. Si cuando inicias el programa no puedes ver el puerto al que está conectado tu arduino, basta con que escribas el nombre en la lista. Despues solo hay que hacer clic en conectar y si todo está en orden, se podrá controlar ClockView desde la computadora con BlueTooth.
Al igual que la aplicación para android, en está aplicación se incluyen los controles que cambian las configuraciones de ClockView. Además está aplicación sirve con un cable, si conectas Clock View con un cable USB, también podrás cambiar los ajustes, pero esa no es la idea; aun si prefieres hacer uso del cable, es recomendable que desconectes el módulo HC-05/06 del arduino para que no haya ningún tipo de problemas.
Al igual que todos los otros programas, dejo el código fuente para que los descargues y lo pruebes. El Código fuente de la aplicacion para android, aun lo voy a mejorar un poco y el software para arduino también.
Por ahora es todo. Los leo luego.
3/24/2017 01:47:00 a.m.
bluetooth
,
clock view
,
csharp
,
DIY
,
ds1302
,
LED
,
matriz led
,
max7219
,
programacion
,
rfcomm
,
socket bluetooth
Vamos a programar #30 - El código de Clock View (Android)
Hola de nuevo a todos, el día de hoy vamos a explicar el código que hace funcionar la aplicación de android Clock View.
Para mostrar la interfaz principal, en el Layout principal, debemos de agregar el siguiente código.
Tras implementar el código, la aplicacion lucira algo similar a la siguiente imagen:
Cómo verás, solo consta de 6 botones, una barra de seek y las etiquetas para mostrar texto.
La funcion de cada uno, la veremos en el código Java, pero antes, vamos a terminar con la interfaz. La lista que contiene los dispositivos emparejados, es un layout que solo contiene un list view y su código es el siguiente;
Con esto completamos la parte de la interfaz, además en el código completo he agregado el diseño para cuando la orientacion del dispositivo es vertical y para cuando es horizontal, en lo personal preferí forzar a que la aplicacion siempre este en horizontal, pero eres libre de cambiarla a tu gusto.
Ahora con el código actualizado vamos a ver que hace cada parte del el.
Clock view está compuesto por tres clases, la primera de ellas es la que se encarga de mostrar todos los componente de la interfaz principal (crear lo eventos para los botones, inflar las cosas necesarias, etc), la segunda es ConnectedThread.
La clase ConnectedThread, es la que se va a encarga de enviar y recibir los datos de y hacia la aplicación.
En ella hay dos métodos: run() y write(). En el método run es donde vamos a leer todos los datos que vienen desde el arduino. Lo pasaremos cómo mensaje y despues el manejado h, se encargará de re-direccionar el contenido y mostrarlo en un textview.
El método write(), servirá para enviar datos hacia el arduino, está es la función que se debe de usar para enviar los comandos, por ejemplo, para enviar el comando para mostrar los segundos, debemos de llamar a la función con el parámetro ">DISS" write(">DISS").
La tercera clase es la que se encarga de crear la conexion y mostrar un dialogo de progreso/espera, cuando la conexión se realiza, deja un socket bluetooth listo para usarse.
Cómo verás, la aplicación es realmente sencilla, pero aun queda mucho por agregar a ambas partes de Clock View, por ahora el código fuente completo lo reservo para cuando ya tenga todas la funciones listas, pero con lo anterior, ya puedes crear tu propia versión.
La parte del código para arduino se actualizará, pero ese en cuanto lo cambie, también actualizaré el vinculo en dropbox.
Por ahora es todo, pero a esto aun le resta bastante para que sea un reloj funcional (más funcional).
Los leo luego.
La interfaz.
Antes que nada vamos a empezar ´por la interfaz, para el caso de Clock View esta compuesta de 2 partes. La primera son todos los botones de "acción" y parte principal de la aplicacion; la segunda solo es la lista que se encarga de mostrar todos los dispositivos que estén emparejados al dispositivo.
Para mostrar la interfaz principal, en el Layout principal, debemos de agregar el siguiente código.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.mdev.clockview.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="La hora actual es:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/TXTView"
tools:ignore="HardcodedText" />
<TextClock
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:id="@+id/TXTClock"
android:typeface="sans"
android:textAlignment="center"
android:textSize="30sp"
android:fontFamily="monospace"/>
<Button
android:text="Conectar con arduino."
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/BtnConnect"
android:textAlignment="center"
android:textAllCaps="false" />
<Button
android:text="Cambiar 12/24 Horas."
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/BtnFormat" />
<Button
android:text="No/Mostrar segundos."
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/BtnShowS"/>
<Button
android:text="Apagar/Encender matrices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/BtnOn"/>
<Button
android:text="Sincronizar hora."
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/BtnSync"/>
<TextView
android:text="Nivel de brillo:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginStart="11dp"
android:layout_marginTop="10dp"
android:id="@+id/textView2" />
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:id="@+id/SKBrillo"
android:max="15"
android:progress="5" />
<TextView
android:text="Brillo: 15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtSeekValue"/>
<TextView
android:text="Esperando a ClockView."
android:layout_width="match_parent"
android:id="@+id/TxtArduinoReturn"
android:layout_height="wrap_content" />
<Button
android:text="Desconectar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/BtnDisconnect" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Tras implementar el código, la aplicacion lucira algo similar a la siguiente imagen:
Cómo verás, solo consta de 6 botones, una barra de seek y las etiquetas para mostrar texto.
La funcion de cada uno, la veremos en el código Java, pero antes, vamos a terminar con la interfaz. La lista que contiene los dispositivos emparejados, es un layout que solo contiene un list view y su código es el siguiente;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/bt_list" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/BTList" android:layout_width="match_parent" android:layout_height="200dp" android:headerDividersEnabled="true" android:footerDividersEnabled="false"> </ListView> </LinearLayout>
Con esto completamos la parte de la interfaz, además en el código completo he agregado el diseño para cuando la orientacion del dispositivo es vertical y para cuando es horizontal, en lo personal preferí forzar a que la aplicacion siempre este en horizontal, pero eres libre de cambiarla a tu gusto.
El código en java.
El código en Java, lo he modificado un poco desde la última vez, corregi algunos errores, uno de ellos era: cuando se intentaba hacer la conexion y esta fallaba, al hacer click en cualquier botón, este intentaba mandar algo a traves del socket que supestemente debio de haber sido creado, al no estar disponible, la aplicion "crasheaba" y salia; el error se debia que a pesar de no haber conexion, la condicion que se debia de comprobar era verdadera debido a que se verificaba si el bluetooth estaba activado; la condicion se podia cumplir, pero eso significaria necesariamente que el socket ya se hubiera creado. Para solucionarlo, simplemente use un flag boleano que solo se cambiaba cuando se abria o cerraba la conexion, ahora si no hay conexion, simplemente no se intenta enviar nada.
Ademas coerregi algunos detalles y bugs minimos. El código actualizado es el siguiente:
package com.mdev.clockview;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.Calendar;
import static com.mdev.clockview.R.layout.paired_devices_list;
public class MainActivity extends Activity {
BluetoothAdapter myBluetoothAdapter = null;
Button BtnConnect, BtnOnOff, BtnSecondsShow, BtnSyncHour, BtnChangeFormat,BtnDisconnect;
SeekBar SkBright;
TextView TxtArduinoRec, TxtBrigthValue;
String address = null;
private ProgressDialog progress;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
final int RECEIVE_MESSAGE = 1;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
Handler h;
private Set<BluetoothDevice> pairedDevices;
ListView myListView;
ArrayAdapter BTArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BtnConnect = (Button)findViewById(R.id.BtnConnect);
myListView = (ListView)findViewById(R.id.BTList);
TxtArduinoRec = (TextView)findViewById(R.id.TxtArduinoReturn);
BtnOnOff = (Button)findViewById(R.id.BtnOn);
BtnSecondsShow = (Button)findViewById(R.id.BtnShowS);
BtnSyncHour = (Button)findViewById(R.id.BtnSync);
BtnChangeFormat = (Button)findViewById(R.id.BtnFormat);
BtnDisconnect = (Button)findViewById(R.id.BtnDisconnect);
SkBright = (SeekBar)findViewById(R.id.SKBrillo);
TxtBrigthValue = (TextView)findViewById(R.id.txtSeekValue);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (myBluetoothAdapter == null) {
msg("El bluetooth no es soportado por este dispositivo");
}
else {
msg("Esperando la conexion");
}
SkBright.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
TxtBrigthValue.setText("Brillo: " + String.valueOf(progress));
if (isBtConnected)
{
String result = String.format(">SETB%1$02d", progress);
mConnectedThread.write(result);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
BtnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, 1);
}else{
showBTDialog();
}
}
});
BtnOnOff.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">SCRA");
}
}
});
BtnSecondsShow.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">DISS");
}
}
});
BtnSyncHour.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(BuildHour(true));
}
}
});
BtnChangeFormat.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">SETF");
}
}
});
BtnDisconnect.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
Disconnect();
}
}
});
//encargado de procesar los mensajes.
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what)
{
case RECEIVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0)
{
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
TxtArduinoRec.setText("Data from Arduino: " + sbprint);
}
break;
}
};
};
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private String BuildHour(boolean ForArduino){
//>SETH2016122119001004
//>SETHAAAAMMDDHHMMSSWW
Calendar c = Calendar.getInstance();
int DiaSemana = c.get(Calendar.DAY_OF_WEEK);
int Anio = c.get(Calendar.YEAR);
int Mes = c.get(Calendar.MONTH);
int Dia = c.get(Calendar.DAY_OF_MONTH);
int Horas = c.get(Calendar.HOUR_OF_DAY);
int Minutos = c.get(Calendar.MINUTE);
int Segundos = c.get(Calendar.SECOND);
String Fecha = null;
if (ForArduino == true){
Fecha = String.format(">SETH%1$04d%2$02d%3$02d%4$02d%5$02d%6$02d%7$02d",
Anio, Mes + 1, Dia, Horas, Minutos,Segundos, DiaSema);
msg(Fecha);
}else {
Fecha = String.format("%1$04d/%2$02d/%3$02d - %4$02d:%5$02d:%6$02d",
Anio, Mes + 1, Dia, Horas, Minutos,Segundos);
}
return Fecha;
}
private void Disconnect()
{
if (btSocket!=null)
{
try
{
btSocket.close();
isBtConnected = false;
}
catch (IOException e)
{ msg("Error");}
}
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3) {
if (myBluetoothAdapter.isEnabled()) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
msg(info);
} else {
msg("El Bluetooth debe de estar encendido.");
}
}
};
public void showBTDialog() {
final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View Viewlayout = inflater.inflate(paired_devices_list, (ViewGroup) findViewById(R.id.bt_list));
popDialog.setTitle("Dispositivos Bluetooth:");
popDialog.setView(Viewlayout);
myListView = (ListView) Viewlayout.findViewById(R.id.BTList);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
pairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
myListView.setOnItemClickListener(myListClickListener);
// Button OK
popDialog.setPositiveButton("Conectar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (address != null)
{
new ConnectBT().execute();
}
dialog.dismiss();
}
});
popDialog.create();
popDialog.show();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
msg("Error al enviar: " + e.getMessage());
}
}
}
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
private boolean ConnectSuccess = true;
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(MainActivity.this, "Conectando ("+ address +")...", "Espera...!!!");
}
@Override
protected Void doInBackground(Void... devices)
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
BluetoothDevice dispositivo = myBluetoothAdapter.getRemoteDevice(address);
btSocket = createBluetoothSocket(dispositivo);
btSocket.connect();
}
}
catch (IOException e)
{
ConnectSuccess = false;
}
return null;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, myUUID);
} catch (Exception e) {
msg("No se pudo crear la conexion");
}
}
return device.createRfcommSocketToServiceRecord(myUUID);
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("La conexion falló, intentelo de nuevo");
isBtConnected = false;
}
else
{
msg("Conectado.");
isBtConnected = true;
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
progress.dismiss();
}
}
}
Ahora con el código actualizado vamos a ver que hace cada parte del el.
Clock view está compuesto por tres clases, la primera de ellas es la que se encarga de mostrar todos los componente de la interfaz principal (crear lo eventos para los botones, inflar las cosas necesarias, etc), la segunda es ConnectedThread.
La clase ConnectedThread, es la que se va a encarga de enviar y recibir los datos de y hacia la aplicación.
En ella hay dos métodos: run() y write(). En el método run es donde vamos a leer todos los datos que vienen desde el arduino. Lo pasaremos cómo mensaje y despues el manejado h, se encargará de re-direccionar el contenido y mostrarlo en un textview.
El método write(), servirá para enviar datos hacia el arduino, está es la función que se debe de usar para enviar los comandos, por ejemplo, para enviar el comando para mostrar los segundos, debemos de llamar a la función con el parámetro ">DISS" write(">DISS").
La tercera clase es la que se encarga de crear la conexion y mostrar un dialogo de progreso/espera, cuando la conexión se realiza, deja un socket bluetooth listo para usarse.
Cómo verás, la aplicación es realmente sencilla, pero aun queda mucho por agregar a ambas partes de Clock View, por ahora el código fuente completo lo reservo para cuando ya tenga todas la funciones listas, pero con lo anterior, ya puedes crear tu propia versión.
La parte del código para arduino se actualizará, pero ese en cuanto lo cambie, también actualizaré el vinculo en dropbox.
Por ahora es todo, pero a esto aun le resta bastante para que sea un reloj funcional (más funcional).
Los leo luego.
2/02/2017 05:37:00 p.m.
Android studio
,
Arduino
,
bluetooth
,
capacitores
,
clock view
,
DIY
,
electronica basica
,
how to
,
java
,
LED
,
matriz led
,
max7219
,
programacion
,
Resistencias
,
rfcomm
,
socket bluetooth
Vamos a programar #29 - Inútil Apps #2 - Creando un socket bluetooth (arduino y android)
Hola a todos, el día de hoy vamos a continuar con Clock View. Ahora con todo el hardware listo y con la parte de software de arduino también listo, solo queda crear una forma de interactuar con el hardware de Clock View. Al carecer de botones solo nos queda la opción de usar el modulo Bluetooth, para comunicarnos por medio de este, podemos usar aplicaciones que ya estan disponibles en la Playstore (S2 Terminal for bluetooth por ejemplo), pero esa no es la idea del blog, en la mediada de lo posible trataremos de usar nuestro propio software para hacer las cosas.
El dia de hoy les quiero presentar Clock View para android, una aplicación que tiene cómo unica función; conectar con el modulo bluetooth HC-05 o HC-06 y cambiar los ajustes de Clock View.
La aplicacion dispone de 6 botones y una barra de "seek". Para usarla, primero debes de asegurarte de que todo el hardware está listo, despues debes de iniciar la conexion con el boton "Conectar con clock view", cuando aparace un mensaje diciendo que la conexion se llevo a cabo, puedes modificar los ajustes.
Hoy solo veremos el código, en el siguiente post, explicaré un poco acerca de cómo se realiza el intercambio de datos entre arduino y android.
Cómo todo el código requiere una explicacion detallada (o si no quieres meterte en programacion), por ahora solo dejo el APK ya compilado,
Los leo luego.
El dia de hoy les quiero presentar Clock View para android, una aplicación que tiene cómo unica función; conectar con el modulo bluetooth HC-05 o HC-06 y cambiar los ajustes de Clock View.
La aplicacion dispone de 6 botones y una barra de "seek". Para usarla, primero debes de asegurarte de que todo el hardware está listo, despues debes de iniciar la conexion con el boton "Conectar con clock view", cuando aparace un mensaje diciendo que la conexion se llevo a cabo, puedes modificar los ajustes.
Hoy solo veremos el código, en el siguiente post, explicaré un poco acerca de cómo se realiza el intercambio de datos entre arduino y android.
El código.
El siguiente es el código en java que se encarga de hacer funcionar las cosas, los estilos y demás "layouts", irán en la descarga completa al final del post.
package com.mdev.clockview;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.Calendar;
import static com.mdev.clockview.R.layout.paired_devices_list;
public class MainActivity extends Activity {
BluetoothAdapter myBluetoothAdapter = null;
Button BtnConnect, BtnOnOff, BtnSecondsShow, BtnSyncHour, BtnChangeFormat,BtnDisconnect;
SeekBar SkBright;
TextView TxtArduinoRec, TxtBrigthValue;
String address = null;
private ProgressDialog progress;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
final int RECEIVE_MESSAGE = 1;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
Handler h;
private Set<BluetoothDevice> pairedDevices;
ListView myListView;
ArrayAdapter BTArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BtnConnect = (Button)findViewById(R.id.BtnConnect);
myListView = (ListView)findViewById(R.id.BTList);
TxtArduinoRec = (TextView)findViewById(R.id.TxtArduinoReturn);
BtnOnOff = (Button)findViewById(R.id.BtnOn);
BtnSecondsShow = (Button)findViewById(R.id.BtnShowS);
BtnSyncHour = (Button)findViewById(R.id.BtnSync);
BtnChangeFormat = (Button)findViewById(R.id.BtnFormat);
BtnDisconnect = (Button)findViewById(R.id.BtnDisconnect);
SkBright = (SeekBar)findViewById(R.id.SKBrillo);
TxtBrigthValue = (TextView)findViewById(R.id.txtSeekValue);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (myBluetoothAdapter == null) {
msg("El bluetooth no es soportado por este dispositivo");
}
else {
msg("Esperando la conexion");
}
SkBright.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
TxtBrigthValue.setText(String.valueOf(progress));
if (isBtConnected)
{
String result = String.format(">SETB%1$02d", progress);
mConnectedThread.write(result);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
BtnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, 1);
}else{
showBTDialog();
}
}
});
BtnOnOff.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">SCRA");
}
}
});
BtnSecondsShow.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">DISS");
}
}
});
BtnSyncHour.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(BuildHourToArduino());
}
}
});
BtnChangeFormat.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
mConnectedThread.write(">SETF");
}
}
});
BtnDisconnect.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view){
if (isBtConnected)
{
Disconnect();
}
}
});
//encargado de procesar los mensajes.
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what)
{
case RECEIVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0)
{
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
TxtArduinoRec.setText("Data from Arduino: " + sbprint);
}
break;
}
};
};
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private String BuildHourToArduino(){
//>SETH2016122119001004
//>SETHAAAAMMDDHHMMSSWW
Calendar c = Calendar.getInstance();
int DiaSemana = c.get(Calendar.DAY_OF_WEEK);
int Anio = c.get(Calendar.YEAR);
int Mes = c.get(Calendar.MONTH);
int Dia = c.get(Calendar.DAY_OF_MONTH);
int Horas = c.get(Calendar.HOUR_OF_DAY);
int Minutos = c.get(Calendar.MINUTE);
int Segundos = c.get(Calendar.SECOND);
String DateForArduino = String.format(">SETH%1$04d%2$02d%3$02d%4$02d%5$02d%6$02d%7$02d",
Anio, Mes + 1, Dia, Horas, Minutos,Segundos, DiaSemana);
msg(DateForArduino);
return DateForArduino;
}
private void Disconnect()
{
if (btSocket!=null)
{
try
{
btSocket.close();
isBtConnected = false;
}
catch (IOException e)
{ msg("Error");}
}
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3) {
if (myBluetoothAdapter.isEnabled()) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
msg(address);
} else {
msg("El Bluetooth debe de estar encendido.");
}
}
};
public void showBTDialog() {
final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
final View Viewlayout = inflater.inflate(paired_devices_list, (ViewGroup) findViewById(R.id.bt_list));
popDialog.setTitle("Dispositivos Bluetooth:");
popDialog.setView(Viewlayout);
myListView = (ListView) Viewlayout.findViewById(R.id.BTList);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
pairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
myListView.setOnItemClickListener(myListClickListener);
// Button OK
popDialog.setPositiveButton("Conectar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (address != null)
{
new ConnectBT().execute();
}
dialog.dismiss();
}
});
popDialog.create();
popDialog.show();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String message) {
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
msg("Error al enviar: " + e.getMessage());
}
}
}
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
private boolean ConnectSuccess = true;
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(MainActivity.this, "Conectando...", "Espera...!!!");
}
@Override
protected Void doInBackground(Void... devices)
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
BluetoothDevice dispositivo = myBluetoothAdapter.getRemoteDevice(address);
btSocket = createBluetoothSocket(dispositivo);
btSocket.connect();
}
}
catch (IOException e)
{
ConnectSuccess = false;
}
return null;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, myUUID);
} catch (Exception e) {
msg("No se pudo crear la conexion");
}
}
return device.createRfcommSocketToServiceRecord(myUUID);
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("La conexion falló, intentelo de nuevo");
isBtConnected = false;
}
else
{
msg("Conectado.");
isBtConnected = true;
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
progress.dismiss();
}
}
}
Cómo todo el código requiere una explicacion detallada (o si no quieres meterte en programacion), por ahora solo dejo el APK ya compilado,
Los leo luego.
1/26/2017 06:02:00 p.m.
android
,
bluetooth
,
capacitores
,
clock view
,
ds1302
,
electronica basica
,
how to
,
java
,
LED
,
matriz led
,
max7219
,
programacion
,
Resistencias
,
rfcomm
,
socket bluetooth
Suscribirse a:
Entradas
(
Atom
)









