需求描述

儿子有一堆充电玩具,基本上都是锂电池,经常插上去充电忘了到时拔下来,所以需要一块能设置接通时间的插板以保障电池的安全。

  硬件设计:

首先需要一块插板,接着需要一个继电器,然后采用arduino r3 uno 加 一个时钟模块来控制时间,最后配一个蓝牙模块,通过手机进行时间的设定。

时钟模块:DS3231 AT24C32, 采用I2C链接arduino板上 ,SCL->A5,SDA->A4,VCC->VCC,GND->GND。

蓝牙模块:HC-06, 使用用arduino的软串口,RXT->9,TXD->8,VCC->VCC,GND->GND,后来发现这款没蓝牙链接,会一直有报警,不知道能不能关,声音不大,但是挺烦的。

继续电器:220V 10A,3个脚那种,将公共端与常开端连入220V电源。

Arduino: R3 Uno 板,发现45块的山寨,还没25块的山寨好用,啥情况。

电源模块: 220VAC -> 5VDC ,用的是精密431那款,不小心摔了2下居然还能用,太意外,这里要吐槽下淘宝上卖android外接电源适配器的,没一个好用的,

有一个刚插上就烧的,太无良了。

辅助材料:扎带,胶水,PC板(用的是聚碳酸脂板,耐火,diy的东西安全重要啊),各种型号螺丝。

使用工具:这个是消费的大头,电烙铁(第一次使用是大学那个无良的电子社团,收了28块钱,结果就叫我进去用电烙铁拆了2个电容就没有任何音讯了,哥记住你了。。。),

电转,加各类转头(直接买了个360的电转工具箱),钢钜(拿来切割PC板,后来发现这个是本项目里最难的,昨天淘宝里定了330的切割机)

  软件设计

 arduino端:主要是串口接收手机发来的命令,并返回,代码如下:

/*
DS3231_test.pde
Eric Ayars
4/11Test/demo of read routines for a DS3231 RTC.Turn on the serial monitor after loading this to check if things are
working as they should.*/#include <DS3231.h>
#include <Wire.h>
#include <EEPROM.h>#define powerPin 7
DS3231 Clock;String ReceivedCache="";
String BTime="2010-07-24 11:15:00";
String ETime="2010-07-24 11:15:00";
boolean isFire=false;void setup() {// Start the I2C interface
       Wire.begin();Clock.setClockMode(false);Serial.begin(9600);pinMode(powerPin,OUTPUT);digitalWrite(powerPin,LOW);Clock.turnOnAlarm(1);RetrieveFireSet();
}void loop() {handleCmd();checkFire();
}void checkFire(){String dateTime=GetTime();if(dateTime>=BTime && dateTime<=ETime){digitalWrite(powerPin,HIGH); isFire=true;}else{digitalWrite(powerPin,LOW); isFire=false;}
}String formatNum(int a){if(a<10)return  "0" +(String)a;return (String)a;
}String GetTime(){bool Century=false;bool h12=false;bool PM=false;int second,minute,hour,date,month,year,temperature; second=Clock.getSecond();minute=Clock.getMinute();hour=Clock.getHour(h12, PM);date=Clock.getDate();month=Clock.getMonth(Century);year=Clock.getYear();String dateTime="20" +formatNum(year) +"-" +formatNum(month) +"-"+formatNum(date) +" "+formatNum(hour) +":"+formatNum(minute)+":"+formatNum(second);return dateTime;
}void handleGetTime(){String dateTime=GetTime();Serial.println("OK:"+dateTime);}
void handleSetTime(){int second,minute,hour,date,month,year,dayOfWeek; String dateTime=ReceivedCache.substring(5,24);year  =dateTime.substring(2,4).toInt();month  =dateTime.substring(5,7).toInt();date=dateTime.substring(8,10).toInt();hour=dateTime.substring(11,13).toInt();minute=dateTime.substring(14,16).toInt();second=dateTime.substring(17,19).toInt();dayOfWeek=dateTime.substring(20,21).toInt();Clock.setSecond(second);//Set the second Clock.setMinute(minute);//Set the minute Clock.setHour(hour);  //Set the hour Clock.setDoW(dayOfWeek);    //Set the day of the weekClock.setDate(date);  //Set the date of the monthClock.setMonth(month);  //Set the month of the yearClock.setYear(year);  //Set the year (Last two digits of the year)
Serial.println("OK:");
}void handleGetFire(){String tmp=_ReadFireSet();if(tmp==""){Serial.println("EE:fire time not set!"); }else{Serial.println("OK:" + tmp);}
}void handleSetFire(){for(int address=0;address<43;address++){EEPROM.write(address,(byte)ReceivedCache[address]);//Serial.print((char)EEPROM.read(address));
   }//Serial.println("");String bTime=ReceivedCache.substring(5,24);String eTime=ReceivedCache.substring(24,43);bool flag=RetrieveFireSet();// Serial.println("flag:" + (String)flag);if(flag && (bTime==BTime && eTime==ETime)){Serial.println("OK:"); }else{Serial.println("EE:Set Fail"); }
}String _ReadFireSet(){int address=0;String tmp="";char readChar=' ';for(int address=0;address<5;address++){readChar=(char)EEPROM.read(address);tmp +=readChar;}if(tmp!="SetF:"){return "";}tmp="";for(int address=5;address<43;address++){readChar=(char)EEPROM.read(address);tmp +=readChar;}//Serial.println(tmp);return tmp;
}bool RetrieveFireSet(){String tmp=_ReadFireSet();if(tmp==""){return false;}else{BTime=tmp.substring(0,19);ETime=tmp.substring(19,38);return true;}
}//read Serial data and hand command
//
void handleCmd(){char readChar=' ';while(Serial.available()>0){readChar=(char)Serial.read(); ReceivedCache =ReceivedCache+ (String)readChar;//delayMicroseconds(10);
   }//Serial.println("ABC");// Serial.println(ReceivedCache);if(ReceivedCache.startsWith("GetT:")){handleGetTime();ReceivedCache=ReceivedCache.substring(5);}else if(ReceivedCache.startsWith("SetT:")){//like->SetT:2015-07-24 16:54:23,7if(ReceivedCache.length()>=26){handleSetTime();ReceivedCache=ReceivedCache.substring(26);}}else if(ReceivedCache.startsWith("GetS:")){Serial.println("OK:"+(String)isFire);ReceivedCache=ReceivedCache.substring(5);}else if(ReceivedCache.startsWith("GetF:")){handleGetFire();ReceivedCache=ReceivedCache.substring(5);}else if(ReceivedCache.startsWith("SetF:")){if(ReceivedCache.length()>=43){handleSetFire();ReceivedCache=ReceivedCache.substring(43);}}else if(ReceivedCache.startsWith("GetC:")){int temperature=Clock.getTemperature();Serial.println("OK:" +(String)temperature);ReceivedCache=ReceivedCache.substring(5);}else{if(ReceivedCache.length()>=5){ReceivedCache=""; }}if(readChar=='\n')ReceivedCache="";
}

View Code

android 端:

蓝牙操作部分是参考官方提供的蓝牙串口聊天室,蓝牙操作跟socket差不多,有个蓝牙串口服务协议(程序里体现就一段GUID)用来识别蓝牙链接提供的服务类型,一个标识吧了。

主要代码:

package cn.fustudio.mangospile;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;public class BluetoothService {// Debuggingprivate static final String TAG = "BluetoothService";private static final boolean D = true;// Name for the SDP record when creating server socketprivate static final String NAME_SECURE = "BluetoothSecure";private static final String NAME_INSECURE = "BluetoothInsecure";// Unique UUID for this applicationprivate static final UUID MY_UUID_SECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");private static final UUID MY_UUID_INSECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");// Member fieldsprivate final BluetoothAdapter mAdapter;private final Handler mHandler;private ConnectThread mConnectThread;private ConnectedThread mConnectedThread;private int mState;// Constants that indicate the current connection statepublic static final int STATE_NONE = 0;       // we're doing nothingpublic static final int STATE_LISTEN = 1;     // now listening for incoming connectionspublic static final int STATE_CONNECTING = 2; // now initiating an outgoing connectionpublic static final int STATE_CONNECTED = 3;  // now connected to a remote devicepublic BluetoothService(Context context, Handler handler) {//ff hhmAdapter = BluetoothAdapter.getDefaultAdapter();mState = STATE_NONE;mHandler = handler;}/*** Set the current state of the chat connection* @param state  An integer defining the current connection state*/private synchronized void setState(int state) {if (D) Log.d(TAG, "setState() " + mState + " -> " + state);mState = state;// Give the new state to the Handler so the UI Activity can updatemHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();}/*** Return the current connection state. */public synchronized int getState() {return mState;}/*** Start the chat service. Specifically start AcceptThread to begin a* session in listening (server) mode. Called by the Activity onResume() */public synchronized void start() {if (D) Log.d(TAG, "start");// Cancel any thread attempting to make a connectionif (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}setState(STATE_LISTEN);}/*** Start the ConnectThread to initiate a connection to a remote device.* @param device  The BluetoothDevice to connect* @param secure Socket Security type - Secure (true) , Insecure (false)*/public synchronized void connect(BluetoothDevice device, boolean secure) {if (D) Log.d(TAG, "connect to: " + device);// Cancel any thread attempting to make a connectionif (mState == STATE_CONNECTING) {if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}// Start the thread to connect with the given devicemConnectThread = new ConnectThread(device, secure);mConnectThread.start();setState(STATE_CONNECTING);}/*** Start the ConnectedThread to begin managing a Bluetooth connection* @param socket  The BluetoothSocket on which the connection was made* @param device  The BluetoothDevice that has been connected*/public synchronized void connected(BluetoothSocket socket, BluetoothDevicedevice, final String socketType) {if (D) Log.d(TAG, "connected, Socket Type:" + socketType);// Cancel the thread that completed the connectionif (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}// Cancel any thread currently running a connectionif (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}// Start the thread to manage the connection and perform transmissionsmConnectedThread = new ConnectedThread(socket, socketType);mConnectedThread.start();// Send the name of the connected device back to the UI ActivityMessage msg = mHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);Bundle bundle = new Bundle();bundle.putString(MainActivity.DEVICE_NAME, device.getName());msg.setData(bundle);mHandler.sendMessage(msg);setState(STATE_CONNECTED);}/*** Stop all threads*/public synchronized void stop() {if (D) Log.d(TAG, "stop");if (mConnectThread != null) {mConnectThread.cancel();mConnectThread = null;}if (mConnectedThread != null) {mConnectedThread.cancel();mConnectedThread = null;}setState(STATE_NONE);}/*** Write to the ConnectedThread in an unsynchronized manner* @param out The bytes to write* @see ConnectedThread#write(byte[])*/public void write(byte[] out) {// Create temporary object
        ConnectedThread r;// Synchronize a copy of the ConnectedThreadsynchronized (this) {if (mState != STATE_CONNECTED) return;r = mConnectedThread;}// Perform the write unsynchronizedr.write(out);}/*** Indicate that the connection attempt failed and notify the UI Activity.*/private void connectionFailed() {// Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);Bundle bundle = new Bundle();bundle.putString(MainActivity.TOAST, "Unable to connect device");msg.setData(bundle);mHandler.sendMessage(msg);// Start the service over to restart listening modeBluetoothService.this.start();}/*** Indicate that the connection was lost and notify the UI Activity.*/private void connectionLost() {// Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);Bundle bundle = new Bundle();bundle.putString(MainActivity.TOAST, "Device connection was lost");msg.setData(bundle);mHandler.sendMessage(msg);// Start the service over to restart listening modeBluetoothService.this.start();}/*** This thread runs while attempting to make an outgoing connection* with a device. It runs straight through; the connection either* succeeds or fails.*/private class ConnectThread extends Thread {private final BluetoothSocket mmSocket;private final BluetoothDevice mmDevice;private String mSocketType;public ConnectThread(BluetoothDevice device, boolean secure) {mmDevice = device;BluetoothSocket tmp = null;mSocketType = secure ? "Secure" : "Insecure";// Get a BluetoothSocket for a connection with the// given BluetoothDevicetry {if (secure) {tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);} else {tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);}} catch (IOException e) {Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);}mmSocket = tmp;}public void run() {Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);setName("ConnectThread" + mSocketType);// Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();// Make a connection to the BluetoothSockettry {// This is a blocking call and will only return on a// successful connection or an exception
                mmSocket.connect();} catch (IOException e) {// Close the sockettry {mmSocket.close();} catch (IOException e2) {Log.e(TAG, "unable to close() " + mSocketType +" socket during connection failure", e2);}connectionFailed();return;}// Reset the ConnectThread because we're donesynchronized (BluetoothService.this) {mConnectThread = null;}// Start the connected thread
            connected(mmSocket, mmDevice, mSocketType);}public void cancel() {try {mmSocket.close();} catch (IOException e) {Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);}}}/*** This thread runs during a connection with a remote device.* It handles all incoming and outgoing transmissions.*/private class ConnectedThread extends Thread {private final BluetoothSocket mmSocket;private final InputStream mmInStream;private final OutputStream mmOutStream;public ConnectedThread(BluetoothSocket socket, String socketType) {Log.d(TAG, "create ConnectedThread: " + socketType);mmSocket = socket;InputStream tmpIn = null;OutputStream tmpOut = null;// Get the BluetoothSocket input and output streamstry {tmpIn = socket.getInputStream();tmpOut = socket.getOutputStream();} catch (IOException e) {Log.e(TAG, "temp sockets not created", e);}mmInStream = tmpIn;mmOutStream = tmpOut;}public void run() {Log.i(TAG, "BEGIN mConnectedThread");byte[] buffer = new byte[1024];int bytes;String buffString="";// Keep listening to the InputStream while connectedwhile (true) {try {// Read from the InputStreambytes = mmInStream.read(buffer);String msg=new String(buffer,0,bytes);buffString +=msg;int indexOfNewLine= buffString.indexOf("\n");if(indexOfNewLine>=0){String frameString= buffString.substring(0, indexOfNewLine+1);buffString=buffString.substring(indexOfNewLine+1);mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, frameString).sendToTarget();}if(buffString.length()>1024){buffString="";}// Send the obtained bytes to the UI Activity
//                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
//                            .sendToTarget();
                    } catch (IOException e) {Log.e(TAG, "disconnected", e);connectionLost();break;}}}/*** Write to the connected OutStream.* @param buffer  The bytes to write*/public void write(byte[] buffer) {try {mmOutStream.write(buffer);// Share the sent message back to the UI ActivitymHandler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();} catch (IOException e) {Log.e(TAG, "Exception during write", e);}}public void cancel() {try {mmSocket.close();} catch (IOException e) {Log.e(TAG, "close() of connect socket failed", e);}}}}

View Code

package cn.fustudio.mangospile;import java.util.Date;import java.util.Timer;
import java.util.TimerTask;import cn.fustudio.mangospile.CDateTimeChooseDialog.ICallback;import android.R.bool;
import android.R.string;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;public class MainActivity extends Activity implements ICallback,OnClickListener {// Debuggingprivate static final String TAG = "BluetoothChat";private static final boolean D = true;// Message types sent from the BluetoothChatService Handlerpublic static final int MESSAGE_STATE_CHANGE = 1;public static final int MESSAGE_READ = 2;public static final int MESSAGE_WRITE = 3;public static final int MESSAGE_DEVICE_NAME = 4;public static final int MESSAGE_TOAST = 5;public static final int MESSAGE_SETF_ENABLE=6;public static final int MESSAGE_SETT_ENABLE=7;// Key names received from the BluetoothChatService Handlerpublic static final String DEVICE_NAME = "device_name";public static final String TOAST = "toast";// Intent request codesprivate static final int REQUEST_CONNECT_DEVICE_SECURE = 1;private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;private static final int REQUEST_ENABLE_BT = 3;private static final int CALLBACK_SETBTIME=1;private static final int CALLBACK_SETETIME=2;// Name of the connected deviceprivate String mConnectedDeviceName = null;// String buffer for outgoing messagesprivate StringBuffer mOutStringBuffer;// Local Bluetooth adapterprivate BluetoothAdapter mBluetoothAdapter = null;// Member object for the chat servicesprivate BluetoothService mService = null;private Timer mTimer=new Timer();private Button btnSyncTime=null;private Button btnSetF=null;private TextView txtTime=null;private TextView txtBTime=null;private TextView txtETime=null;private TextView txtStatus=null;private TextView txtTemperature=null;private TextView txtTips=null;private Date getFBTime=null;private Date getFETime=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// If the adapter is null, then Bluetooth is not supportedif (mBluetoothAdapter == null) {Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();finish();return;}init();}private void init(){btnSyncTime=(Button)findViewById(R.id.btnSyncTime);btnSyncTime.setOnClickListener(this);btnSetF=(Button)findViewById(R.id.btnSetF);btnSetF.setOnClickListener(this);txtTime=(TextView)findViewById(R.id.txtTime);txtBTime=(TextView)findViewById(R.id.txtBTime);txtBTime.setOnClickListener(this);txtETime=(TextView)findViewById(R.id.txtETime);txtETime.setOnClickListener(this);txtStatus=(TextView)findViewById(R.id.txtStatus);txtTemperature=(TextView)findViewById(R.id.txtTemperature);txtTips=(TextView)findViewById(R.id.txtTips);    }/* Begin Upload file */private ProgressDialog dialog;@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubif(arg0.getId()==R.id.btnSyncTime){syncTime();}else if(arg0.getId()==R.id.btnSetF){ setF();}else if(arg0.getId()==R.id.txtBTime){String dString=txtBTime.getText().toString();Date dateV= DateUtil.parse(dString,new Date());new CDateTimeChooseDialog(this, CALLBACK_SETBTIME,"开始时间","确定", dateV, this).show();}else if(arg0.getId()==R.id.txtETime) {String dString=txtETime.getText().toString();Date dateV= DateUtil.parse(dString,new Date());new CDateTimeChooseDialog(this, CALLBACK_SETETIME,"结束时间","确定",  dateV, this).show();}}private void setF(){if(mService.getState()!=BluetoothService.STATE_CONNECTED){Toast.makeText(this, "请先链接设备", Toast.LENGTH_LONG).show();return;}String bTimeStr=txtBTime.getText().toString();String eTimeStr=txtETime.getText().toString();if("...".equals(bTimeStr) || "...".equals(eTimeStr)){Toast.makeText(this, "请先输入开始结束时间", Toast.LENGTH_LONG).show();return ;}Date bTime=null;Date eTime=null;try{bTime=DateUtil.parse(bTimeStr);eTime=DateUtil.parse(eTimeStr);}catch(Exception e){Toast.makeText(this, "时间字符解析错误", Toast.LENGTH_LONG).show();return;}if(bTime.compareTo(eTime)>0){Toast.makeText(this, "开始时间大于结束时间", Toast.LENGTH_LONG).show();return ;}btnSetF.setEnabled(false);String cmd="SetF:"+bTimeStr+eTimeStr ;sendMessage(cmd);dialog = ProgressDialog.show(MainActivity.this, null,"执行命令...");Timer timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {mHandler.obtainMessage(MESSAGE_SETF_ENABLE,"").sendToTarget();// TODO Auto-generated method stubif(dialog!=null){dialog.dismiss();dialog=null;}}}, 2000);}private void syncTime() {if(mService.getState()!=BluetoothService.STATE_CONNECTED){Toast.makeText(this, "请先链接设备", Toast.LENGTH_LONG).show();return;}btnSyncTime.setEnabled(false);String cmd="SetT:"+DateUtil.formatLong(new Date())+"," +DateUtil.getWOfD(new Date());sendMessage(cmd);dialog = ProgressDialog.show(MainActivity.this, null,"执行命令...");Timer timer=new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {mHandler.obtainMessage(MESSAGE_SETT_ENABLE,"").sendToTarget();// TODO Auto-generated method stubif(dialog!=null){dialog.dismiss();dialog=null;}}}, 2000);}//========Activity Life Cir
    @Overridepublic void onStart() {super.onStart();if(D) Log.e(TAG, "++ ON START ++");// If BT is not on, request that it be enabled.// setupChat() will then be called during onActivityResultif (!mBluetoothAdapter.isEnabled()) {Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableIntent, REQUEST_ENABLE_BT);// Otherwise, setup the chat session} else {if (mService == null) setupService();}}@Overridepublic synchronized void onResume() {super.onResume();if(D) Log.e(TAG, "+ ON RESUME +");// Performing this check in onResume() covers the case in which BT was// not enabled during onStart(), so we were paused to enable it...// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.if (mService != null) {// Only if the state is STATE_NONE, do we know that we haven't started alreadyif (mService.getState() == BluetoothService.STATE_NONE) {// Start the Bluetooth chat services
              mService.start();}}}private void setupService() {Log.d(TAG, "setupService()");// Initialize the BluetoothChatService to perform bluetooth connectionsmService = new BluetoothService(this, mHandler);// Initialize the buffer for outgoing messagesmOutStringBuffer = new StringBuffer("");//定时任务mTimer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif(mService==null || mService.getState()!=BluetoothService.STATE_CONNECTED) return;MainActivity.this.sendMessage("GetT:");try{ Thread.sleep(100); }catch(Exception e){}MainActivity.this.sendMessage("GetS:");try{ Thread.sleep(100); }catch(Exception e){}MainActivity.this.sendMessage("GetC:");try{ Thread.sleep(100); }catch(Exception e){}MainActivity.this.sendMessage("GetF:");try{ Thread.sleep(100); }catch(Exception e){}}}, 0,1000);}@Overridepublic synchronized void onPause() {super.onPause();if(D) Log.e(TAG, "- ON PAUSE -");}@Overridepublic void onStop() {super.onStop();if(D) Log.e(TAG, "-- ON STOP --");}@Overridepublic void onDestroy() {super.onDestroy();if(mTimer!=null)mTimer.cancel();// Stop the Bluetooth chat servicesif (mService != null) mService.stop();if(D) Log.e(TAG, "--- ON DESTROY ---");}//========End Activity//========Send Msgprivate void sendMessage(String message) {// Check that we're actually connected before trying anythingif (mService.getState() != BluetoothService.STATE_CONNECTED) {Toast.makeText(this, "未链接到设备", Toast.LENGTH_SHORT).show();return;}// Check that there's actually something to sendif (message.length() > 0) {// Get the message bytes and tell the BluetoothChatService to writebyte[] send = message.getBytes();mService.write(send);// Reset out string buffer to zero and clear the edit text fieldmOutStringBuffer.setLength(0);}}//========End Send Msg//=======Handle========// The Handler that gets information back from the BluetoothChatServiceprivate final Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MESSAGE_STATE_CHANGE:if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);switch (msg.arg1) {case BluetoothService.STATE_CONNECTED:MainActivity.this.setTitle("链接到设备->" + mConnectedDeviceName);break;case BluetoothService.STATE_CONNECTING:MainActivity.this.setTitle("正在建立链接...");break;case BluetoothService.STATE_LISTEN:MainActivity.this.setTitle("未链接-待命");break;case BluetoothService.STATE_NONE:MainActivity.this.setTitle("未链接-初始");break;}break;case MESSAGE_WRITE:byte[] writeBuf = (byte[]) msg.obj;// construct a string from the bufferString writeMessage = new String(writeBuf);break;case MESSAGE_READ://byte[] readBuf = (byte[]) msg.obj;// construct a string from the valid bytes in the buffer//String readMessage = new String(readBuf, 0, msg.arg1);//mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                Log.d(TAG, msg.obj.toString());//Toast.makeText(getApplicationContext(),mConnectedDeviceName+":  " + msg.obj.toString(),Toast.LENGTH_LONG).show();
                handleMessageRead(msg.obj.toString());break;case MESSAGE_DEVICE_NAME:// save the connected device's namemConnectedDeviceName = msg.getData().getString(DEVICE_NAME);Toast.makeText(getApplicationContext(), "Connected to "+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();break;case MESSAGE_SETF_ENABLE:btnSetF.setEnabled(true);break;case MESSAGE_SETT_ENABLE:btnSyncTime.setEnabled(true);break;case MESSAGE_TOAST:Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),Toast.LENGTH_SHORT).show();break;}}};private void handleMessageRead(String msg){if(msg!=null && msg.length() >=7){msg=msg.trim();boolean isSuccess=false;if(msg.startsWith("OK-"))isSuccess=true;msg=msg.substring(3);if(msg.startsWith("SetT:")){Toast.makeText(getApplicationContext(), isSuccess ? "时间同步成功" : "时间同步失败",Toast.LENGTH_SHORT).show();}else if(msg.startsWith("SetF:")){String err=msg.substring(5);Toast.makeText(getApplicationContext(), isSuccess ? "定时设置成功" : "定时设置失败:" + err,Toast.LENGTH_SHORT).show();if(isSuccess){setTips();}}else if(msg.startsWith("GetT:")){txtTime.setText(msg.substring(5));}else if(msg.startsWith("GetS:")) {String status=msg.substring(5);txtStatus.setText(  "1".equals(status) ?"开" :"关"); }else if(msg.startsWith("GetC:")) {String c=msg.substring(5);txtTemperature.setText(c);}else if (msg.startsWith("GetF:")) {if(isSuccess && msg.length()>=43){String bTime=msg.substring(5,24);String eTime=msg.substring(24,43);try{getFBTime=DateUtil.parse(bTime);getFETime=DateUtil.parse(eTime);}catch(Exception e){}if("...".equals(txtBTime.getText().toString())&&    "...".equals(txtETime.getText().toString())){txtBTime.setText(bTime);txtETime.setText(eTime);}setTips();}}if(dialog!=null){dialog.dismiss();dialog=null;}}}private void setTips() {Date now=null;Date bTime=null;Date eTime=null;try{now=DateUtil.parse(txtTime.getText().toString());if(getFBTime!=null){bTime=getFBTime;}else {bTime=DateUtil.parse(txtBTime.getText().toString()); }if(getFETime!=null){eTime=getFETime;}else{eTime=DateUtil.parse(txtETime.getText().toString());}}catch(Exception e){Toast.makeText(this, "时间字符解析错误,请重新设置开始结束时间", Toast.LENGTH_LONG).show();return;}if(eTime.compareTo(now)<0){txtTips.setText("定时设置:执行时段已过");txtTips.setTextColor(Color.rgb(0xaa, 0xaa, 0xaa));}else if(bTime.compareTo(now)>0) {//还未开始long duration= DateUtil.getSeconds(now, bTime);int bHour=(int)( duration / (60 * 60));int bMinutes=(int)( (duration - (bHour * 3600)) / 60);duration= DateUtil.getSeconds(bTime, eTime);int eHour=(int)( duration / (60 * 60));int eMinutes=(int)( (duration - (eHour * 3600)) / 60);String msg="定时设置:"+ bHour+"小时"+bMinutes+"分钟后开始,持续"+eHour+"小时"+eMinutes+"分钟";txtTips.setText(msg);txtTips.setTextColor(Color.rgb(0x00, 0x00, 0xee));}else {//已经开始long duration= DateUtil.getSeconds(now, eTime);int hour=(int)( duration / (60 * 60));int minutes=(int)( (duration - (hour * 3600)) / 60);txtTips.setText("定时设置:已经开始,"+hour+"小时"+minutes+"分钟后结束");txtTips.setTextColor(Color.rgb(0x00, 0xee, 0x00));}}private void ensureDiscoverable() {if(D) Log.d(TAG, "ensure discoverable");if (mBluetoothAdapter.getScanMode() !=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);startActivity(discoverableIntent);}}private void connectDevice(Intent data, boolean secure) {// Get the device MAC addressString address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);// Get the BLuetoothDevice objectBluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);// Attempt to connect to the device
        mService.connect(device, secure);}//=======End handle//=========onActivityResultpublic void onActivityResult(int requestCode, int resultCode, Intent data) {if(D) Log.d(TAG, "onActivityResult " + resultCode);switch (requestCode) {case REQUEST_CONNECT_DEVICE_SECURE:// When DeviceListActivity returns with a device to connectif (resultCode == Activity.RESULT_OK) {connectDevice(data, true);}break;case REQUEST_CONNECT_DEVICE_INSECURE:// When DeviceListActivity returns with a device to connectif (resultCode == Activity.RESULT_OK) {connectDevice(data, false);}break;case REQUEST_ENABLE_BT:// When the request to enable Bluetooth returnsif (resultCode == Activity.RESULT_OK) {// Bluetooth is now enabled, so set up a chat session
                setupService();} else {// User did not enable Bluetooth or an error occuredLog.d(TAG, "BT not enabled");Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();finish();}}}//=========EndonActivityResult==//=========DateTime pick call back
    @Overridepublic void callback(int callbackType, Object... params) {//活动时间if( params != null && params.length == 1){if (params[0] instanceof Date) {Date setTime = (Date) params[0];long currentTime = System.currentTimeMillis() ;if(callbackType==CALLBACK_SETBTIME){txtBTime.setText(DateUtil.formatLong(setTime));} else if(callbackType==CALLBACK_SETETIME) {txtETime.setText(DateUtil.formatLong(setTime));}else {Toast.makeText(this, "异常", Toast.LENGTH_LONG).show();}}}}//=========End DateTime pick call back
    @Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {Intent serverIntent = null;switch (item.getItemId()) {case R.id.secure_connect_scan:// Launch the DeviceListActivity to see devices and do scanserverIntent = new Intent(this, DeviceListActivity.class);startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);return true;case R.id.insecure_connect_scan:// Launch the DeviceListActivity to see devices and do scanserverIntent = new Intent(this, DeviceListActivity.class);startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);return true;case R.id.discoverable:// Ensure this device is discoverable by others
            ensureDiscoverable();return true;case R.id.exit:finish();return true;}return false;}}

View Code

最后上图:

------------------------------------------------------------------------------------------------------------

最后谁将本文从首页移除死全家(诅咒有效期2天)

最后的最后,如有人按上面设计做出的插板或者在制作过程中,发生一切事故或意外本人一概不负责。。。

1000多块整个插板,arduino + android 蓝牙插板的实现--屌丝版相关推荐

  1. Android 蓝牙连接(简单简单版)

    该博客只是记录,不会详细说明(本人技术有限不会说) 一:声明蓝牙权限和定位权限 <!--蓝牙权限--> <uses-permission android:name="and ...

  2. android通过代码设置铃声_Android App驱动Arduino通过蓝牙控制交流调光器

    背景知识视频教程 使用App Inventor创建Android应用​viadean.com Arduino分步指南:完整指南 - 国外课栈​viadean.com Arduino仿真和块编码 - 国 ...

  3. android蓝牙通信_使用Arduino构建OLED显示屏与Android手机接口的智能手表

    背景知识视频教程 Arduino 训练营:通过项目学习​viadean.com 通过制作Arduino UNO FM收音机接收器学习Arduino I2C​viadean.com 通过构建实际应用程序 ...

  4. 【转载】Android蓝牙自动配对Demo

    注:新版本安卓需增加权限 <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION ...

  5. arduino陀螺仪蓝牙通讯手势小车

    新的改变 目录 手势小车 1 一.学习目标 2 知识目标 2 技能目标 2 二.背景知识 2 三.知识储备 3 ARDUINO NANO 2 ARDUINO UNO 4 面包板 6 智能小车模块 4 ...

  6. android 蓝牙管理

    蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最多可以同时和7个 ...

  7. ym——物联网入口之中的一个Android蓝牙4.0

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么? ...

  8. android 蓝牙自动断开,Android蓝牙:连接()/断开()

    我目前正在设计一个应用程序,它需要连接到设备,写入/读取数据,并可靠地关闭连接.目前我有写/读固体.我的断开连接然后重新连接非常不可靠,并且经常实际上使手机崩溃.我一直在寻找通过大量文章试图弄清楚和. ...

  9. Android 蓝牙监听与扫描

    基础知识 蓝牙操作主要有四项任务:设置蓝牙.查找局部区域内的配对设备或可用设备.连接设备,以及在设备间传输数据. 蓝牙的分类 传统蓝牙(Classic Bluetooth) 电池使用强度大 可用于数据 ...

最新文章

  1. McAfee可能要收购NitroSecurity?
  2. python时间序列因果检验_用python做时间序列预测八:Granger causality test(格兰杰因果检验)...
  3. Java jni 底层_Java中的native是如何实现的(JNI)
  4. 收集MySQL常用函数,值得收藏!
  5. 如何用“向上管理”搞垮一个团队?
  6. Java 中时间处理SimpleDateFormat 中HH和hh的区别
  7. 到底是大数据还是“拍脑门”?
  8. JAVA五子棋小游戏
  9. CHIP-SEQ 芯片分析时,对于来自重复实验的数据,怎样进行MACS peaks calling 分析?
  10. 论文总结:云安全研究方向及进展综述
  11. 服务器晚上自动重启是什么原因,服务器经常自动重启是什么原因
  12. 【读懂Autosar代码】-1-概述
  13. 内存条性能测试软件,性能测试之内存篇测试方法整理
  14. 疑似小米汽车全车设计效果图曝光 小米Logo上车
  15. golang打造p2p网络
  16. 计算机网络的基本组成包括哪些,计算机网络系统一般由哪些部分组成?
  17. mysql rds 迁移_数据库迁移:如何将数据库从本地MySQL迁移到服务器RDS上?
  18. Game Maker 基金会呈献:归属之谷
  19. JavaScript 数组遍历方法的对比
  20. Revit学习之路01_Revit基础

热门文章

  1. 随机梯度下降matlab,matlab随机梯度下降法
  2. 电脑网络图标有*号,或者本地连接图标有红叉,但能正常上网问题解决
  3. 内网穿透之Http穿透(让全网都可以访问你的项目)
  4. .Net 面试题整理(一)
  5. VBA -[知识点]: 字典
  6. 详解 JVM Garbage First(G1) 垃圾收集器
  7. Eclipes配置代码模糊匹配(部分匹配)
  8. 基于单片机的数字温度计设计
  9. Linux---Apache网页优化---网页压缩
  10. 计算机网络-自顶向下方法 第三章课后习题答案(第七版)