这次期末的课程设计做了一个智能灯光控制系统,系统整体的功能不在此赘述,系统主要是要实现下位机同上位机的通信,上位机选用的是Android手机端,下位机是52单片机,通过蓝牙模块实现通信。虽然系统很简单,但还是第一次完成的走完从下位机数据采集,数据传输,再到上位机的处理这个流程,故在这里做一个记录,也希望能够帮到有需要的人。

一、下位机通信

下位机选用的是52单片机,数据来自几个传感器,传感器采集到数据后通过串口发送到蓝牙模块,然后蓝牙模块发送到上位机。因代码量较大,所以只在这里贴出传输有关的函数。

//利用串口发送一个字符
void SendOneByte(unsigned char c)
{SBUF = c;while(!TI);TI = 0;
}
//重写putchar函数,就可以直接调用printf()函数向串口发送数据,程序自动将printf()中的数据转换成char调用putchar发送
char putchar(char ch)
{ES=0;SBUF=ch;while(!TI);TI=0;ES=1;return 0;
}
//初始化串口
void InitUART()
{TMOD = 0x20;PCON = 0x00;SCON = 0x50;    TH1 = 0xFD;TL1 = 0xFD;TR1 = 1;ES = 1;EA = 1;
}
//串口中断
void UARTInterrupt() interrupt 4
{//RI为1则表示串口接收到数据if(RI){RI = 0;r_buf = SBUF;//价格SBUF中的数据赋给r_buf,然后就可以对数据进行处理      }
}
void main()
{InitUART();while(1){}
}

、蓝牙模块

蓝牙模块我选用的是HC-05,这个模块我之前也没用使用过,查询了一些资料后就能够上手了,感觉还是很好用。模块有六个引脚,如果用的是带一个小按钮的HC-05,EN就不用接;然后VCC和GND分别接电源和地;TXD 和 RXD在配置AT指令的时候分别接单片机的TXD和RXD,但是在正常使用时,HC-05的TXD和RXD分别接单片机的RXD和TXD,这个需要注意;还有一个引脚是state,当有蓝牙连接的时候会置1,将其随意连接到单片机的引脚上。

使用前先利用AT指令集配置模块,设置波特率和主从模式等,然后就可以连线使用。连接后蓝牙模块会进入快闪模式,进入AT指令集后会进入慢闪模式,当有蓝牙设备连接后会进入双闪模式。

三、Android端程序

Android端主要就是接受数据,做出一定处理,还需发送指令给单片机。我用的代码也是在网上找的然后又做了一些修改,源代码出处找不到了。主要代码如下:

1、DeveiceListActivity类

public class DeviceListActivity extends Activity {// 调试用private static final String TAG = "DeviceListActivity";private static final boolean D = true;// 返回时数据标签public static String EXTRA_DEVICE_ADDRESS = "设备地址";// 成员域private BluetoothAdapter mBtAdapter;private ArrayAdapter<String> mPairedDevicesArrayAdapter;private ArrayAdapter<String> mNewDevicesArrayAdapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 创建并显示窗口requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  //设置窗口显示模式为窗口方式setContentView(R.layout.device_list);// 设定默认返回值为取消setResult(Activity.RESULT_CANCELED);// 设定扫描按键响应Button scanButton = (Button) findViewById(R.id.button_scan);scanButton.setOnClickListener(new OnClickListener() {public void onClick(View v) {doDiscovery();v.setVisibility(View.GONE);}});// 初使化设备存储数组mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);// 设置已配队设备列表ListView pairedListView = (ListView) findViewById(R.id.paired_devices);pairedListView.setAdapter(mPairedDevicesArrayAdapter);pairedListView.setOnItemClickListener(mDeviceClickListener);// 设置新查找设备列表ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);newDevicesListView.setAdapter(mNewDevicesArrayAdapter);newDevicesListView.setOnItemClickListener(mDeviceClickListener);// 注册接收查找到设备action接收器IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(mReceiver, filter);// 注册查找结束action接收器filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(mReceiver, filter);// 得到本地蓝牙mBtAdapter = BluetoothAdapter.getDefaultAdapter();}@Overrideprotected void onDestroy() {super.onDestroy();// 关闭服务查找if (mBtAdapter != null) {mBtAdapter.cancelDiscovery();}// 注销action接收器this.unregisterReceiver(mReceiver);}public void OnCancel(View v){finish();}/*** 开始服务和设备查找*/private void doDiscovery() {if (D)Log.d(TAG, "doDiscovery()");// 在窗口显示查找中信息setProgressBarIndeterminateVisibility(true);setTitle("查找设备中...");// 显示其它设备(未配对设备)列表findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);// 关闭再进行的服务查找if (mBtAdapter.isDiscovering()) {mBtAdapter.cancelDiscovery();}//并重新开始mBtAdapter.startDiscovery();}// 选择设备响应函数private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {// 准备连接设备,关闭服务查找mBtAdapter.cancelDiscovery();// 得到mac地址String info = ((TextView) v).getText().toString();String address = info.substring(info.length() - 17);// 设置返回数据Intent intent = new Intent();intent.putExtra(EXTRA_DEVICE_ADDRESS, address);// 设置返回值并结束程序setResult(Activity.RESULT_OK, intent);finish();}};// 查找到设备和搜索完成action监听器private final BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();// 查找到设备actionif (BluetoothDevice.ACTION_FOUND.equals(action)) {// 得到蓝牙设备BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示if (device.getBondState() != BluetoothDevice.BOND_BONDED) {mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());}else{  //添加到已配对设备列表mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());}// 搜索完成action} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {setProgressBarIndeterminateVisibility(false);setTitle("选择要连接的设备");if (mNewDevicesArrayAdapter.getCount() == 0) {String noDevices = "没有找到新设备";mNewDevicesArrayAdapter.add(noDevices);}}}};
}

2、Client类

public class BTClient extends Activity {private final static int REQUEST_CONNECT_DEVICE = 1;    //宏定义查询设备句柄private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号private InputStream is;    //输入流,用来接收蓝牙数据private EditText edit0;    //发送数据输入句柄private TextView lightSwitch;private TextView lightStrength;private TextView lightMode;private TextView lightPower;private String switchMsg= "";private String strengthMsg= "";private String modeMsg= "";BluetoothDevice _device = null;     //蓝牙设备BluetoothSocket _socket = null;      //蓝牙通信socketboolean bRun = true;boolean bThread = false;boolean timesign=false;private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();    //获取本地蓝牙适配器,即蓝牙设备/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);   //设置画面为主画面 main.xmledit0 = (EditText)findViewById(R.id.Edit0);   //得到输入框句柄lightSwitch = (TextView) findViewById(R.id.lightSwitch);lightStrength=(TextView) findViewById(R.id.lightStrength);lightMode=(TextView) findViewById(R.id.lightMode);lightPower=(TextView) findViewById(R.id.lightpower);lightSwitch.setText("关闭");lightStrength.setText("8");lightMode.setText("时间调节模式");lightPower.setText("无数据");//如果打开本地蓝牙设备不成功,提示信息,结束程序if (_bluetooth == null){Toast.makeText(this, "无法打开手机蓝牙,请确认手机是否有蓝牙功能!", Toast.LENGTH_LONG).show();finish();return;}// 设置设备可以被搜索new Thread(){public void run(){if(_bluetooth.isEnabled()==false){_bluetooth.enable();}}}.start();}//发送按键响应public void onSendButtonClicked(View v){try{OutputStream os = _socket.getOutputStream();   //蓝牙连接输出流modeMsg=edit0.getText().toString();if(modeMsg.equals("1")||modeMsg.equals("2")||modeMsg.equals("3")){if(modeMsg.equals("1")) {lightMode.setText("手动调节模式");lightPower.setText("无数据");timesign=false;}else if(modeMsg.equals("2")) {lightMode.setText("自动调节模式");timesign=false;}else if(modeMsg.equals("3")) {lightMode.setText("时间调节模式");lightPower.setText("无数据");}}if(timesign){final int timec = Integer.valueOf(modeMsg).intValue() * 1000;
//                CountDownTimer cdt = new CountDownTimer(timec, timec) {
//                    @Override
//                    public void onTick(long millisUntilFinished) {
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        edit0.setText("3");
//                    }
//                };
//                cdt.start();try{Thread.currentThread().sleep(timec);} catch (InterruptedException e) {e.printStackTrace();}edit0.setText("3");}if(modeMsg.equals("3")&& !timesign)timesign=true;byte[] bos = edit0.getText().toString().getBytes();edit0.setText("");os.write(bos);}catch(IOException e){}}//接收活动结果,响应startActivityForResult()public void onActivityResult(int requestCode, int resultCode, Intent data) {switch(requestCode){case REQUEST_CONNECT_DEVICE:     //连接结果,由DeviceListActivity设置返回// 响应返回结果if (resultCode == Activity.RESULT_OK) {   //连接成功,由DeviceListActivity设置返回// MAC地址,由DeviceListActivity设置返回String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);// 得到蓝牙设备_device = _bluetooth.getRemoteDevice(address);// 用服务号得到sockettry{_socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));}catch(IOException e){Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();}//连接socketButton btn = (Button) findViewById(R.id.Button03);try{_socket.connect();Toast.makeText(this, "连接"+_device.getName()+"成功!", Toast.LENGTH_SHORT).show();btn.setText("断开");}catch(IOException e){try{Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();_socket.close();_socket = null;}catch(IOException ee){Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();}return;}//打开接收线程try{is = _socket.getInputStream();   //得到蓝牙数据输入流}catch(IOException e){Toast.makeText(this, "接收数据失败!", Toast.LENGTH_SHORT).show();return;}if(bThread==false){ReadThread.start();bThread=true;}else{bRun = true;}}break;default:break;}}//接收数据线程Thread ReadThread=new Thread(){public void run(){int num = 0;byte[] buffer = new byte[1024];bRun = true;//接收线程while(true){try{while(is.available()==0){while(bRun == false){}}while(true){num = is.read(buffer);         //读入数据String s=new String(buffer,0,num);switchMsg=s;strengthMsg=s;if(is.available()==0)break;  //短时间没有数据才跳出进行显示}//发送显示消息,进行显示刷新handler.sendMessage(handler.obtainMessage());}catch(IOException e){}}}};//消息处理队列Handler handler= new Handler(){public void handleMessage(Message msg){super.handleMessage(msg);}};//关闭程序掉用处理部分public void onDestroy(){super.onDestroy();if(_socket!=null)  //关闭连接sockettry{_socket.close();}catch(IOException e){}}//连接按键响应函数public void onConnectButtonClicked(View v){if(_bluetooth.isEnabled()==false){  //如果蓝牙服务不可用则提示Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();return;}//如未连接设备则打开DeviceListActivity进行设备搜索Button btn = (Button) findViewById(R.id.Button03);if(_socket==null){Intent serverIntent = new Intent(this, DeviceListActivity.class); //跳转程序设置startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);  //设置返回宏定义}else{try{//关闭连接socket_socket.close();is.close();_socket = null;bRun = false;btn.setText("连接");}catch(IOException e){}}return;}//退出按键响应函数public void onQuitButtonClicked(View v){finish();}
}

Android端 同 单片机 利用蓝牙模块的通信实现相关推荐

  1. STM32单片机与蓝牙模块HC-05通信数据帧处理

    本章将会详细讲述蓝牙模块(HC-05)和STM32单片机之间的通信收发的数据如何处理,在测试开始前首先在手机上下载好一个蓝牙调试APP,此APP可以是手机端和PC端口的,以我常用的手机端的为例. 在配 ...

  2. 单片机蓝牙烧录_单片机和蓝牙模块的完美结合

    是近年来发展迅速的短距离无线通信技术,可以用来替代数字设备间短距离的有线电缆连接.利用蓝牙技术构建数据采集无线传输模块,与传统的电线或红外方式传输测控数据相比,在测控领域应用篮牙技术的优点主要有: 1 ...

  3. 嵌入式单片机基础篇(二十七)之Stm32F103单片机给蓝牙模块发送AT指令程序

    Stm32F103单片机给蓝牙模块发送AT指令程序 #include "stm32f10x.h" #include "string.h" #include &q ...

  4. 单片机HC06蓝牙模块与手机APP

    学习HC06蓝牙模块遇到一些问题,特此写下作为记录. 用USB转TTL连接,插到电脑上,发AT怎么也不回 USB转TTL与蓝牙模块连接图 打开串口助手: 一开始用的是丁丁串口助手,发·AT不回OK. ...

  5. HC-05蓝牙模块arduino通信实例代码以及注意事项

    HC-05蓝牙模块arduino通信实例代码以及注意事项 HC-05的接线及使用 进入蓝牙的设置模式 进入AT命令模式(设置蓝牙参数) 注意事项 进入AT模式的代码(注意在通电之前让蓝牙模块进入设置模 ...

  6. android 与 蓝牙模块 hc06通信app 开发要点

    2016.8.24:这里非常抱歉,做完这个综合训练我个人忙于考研,没能第一时间把这篇博文写完.由于时间已经过了一年,而且我个人正在改行研究NLP,导致我现在对于其中一些要点已经忘记了.之前有些朋友私信 ...

  7. Android开发-连接开发板蓝牙模块发送和接收数据

    帮同学写一个连接小车蓝牙模块遥控小车的APP,在网上搜阅了很多资料,大概了解了蓝牙的工作原理,再经历了种种BUG后终于是成功连上了小车蓝牙,并可以发送数据,小车可以接收到,测试的蓝牙是Arduino小 ...

  8. Android手机无法连接HC-05蓝牙模块

    目录 前言 问题描述 尝试方法 问题原因 解决方法 总结 前言 这学期选的毕业设计中需要用到蓝牙模块与Android手机通信,于是我就在淘宝购买了一款HC-05的蓝牙模块,到货之后首先使用蓝牙模块连接 ...

  9. 基于51单片机的蓝牙模块

    文章目录 蓝牙模块 接线 蓝牙软件 串口相关知识链接: 代码 运行结果 结束 蓝牙模块 蓝牙模块,又称为蓝牙串口模块. 串口透传技术 透传即透明传送,是指在数据的传输过程中,通过无线的方式这组数据不发 ...

最新文章

  1. linux下配置vnc的方法
  2. 企业建设呼叫中心需要考虑哪些因素
  3. 作者:杜圣东(1981-),男,西南交通大学信息科学与技术学院讲师,中国计算机学会(CCF)和国际计算机学会(ACM)会员。...
  4. 2015.4.19 为什么footer下a的索引值那么大
  5. Opencv--warpPerspective +remap结合
  6. pandas dataframe 使用多进程apply(原生、pandarallel多进程、swifter多进程)
  7. Vue中this.$router.replace和this.$router.push的区别
  8. centos是什么linux操作系统,Linux 操作系统之CentOS的介绍
  9. NOIP2017 普及组题解
  10. 电脑主机服务器中毒文件怎么恢复出厂设置,服务器中毒了 物理文件怎么拷贝呢 以及如何恢复数据呢...
  11. 凤凰网php,凤凰网房产频道招聘 web 前端工程师、PHP 工程师 15-25k,欢迎简历来砸~...
  12. 软件测试开发高频面试题及参考答案(适用校招)
  13. 编译原理( 词法分析程序 语法分析程序 语义分析程序 中间代码生成程序 代码优化程序 目标代码生成程序 符号表管理程序)
  14. 【游戏数据库】大型网络游戏数据库设计方面讨论?(微软平台) 游戏数据库
  15. php上一页下一页代码博客,连接数据库上一页下一页_帮助文档_Thinkphp手册
  16. 91.【SpringBoot-03】
  17. 班尼机器人维修方法_工业机器人常见故障和修理方法
  18. 中华英才网java在线笔试_牛客网校招全国统一模拟笔试(三月场)- Java方向
  19. COM ATL IDispatchEx InvokeEx 钩子
  20. 2023年上半年软考程序员考试总结体会

热门文章

  1. 晶体管测试仪系统 能测 IGBT. Mosfet. Diode. BJT......
  2. 2020年高教社杯全国大学生数学建模竞赛---校园供水系统智能管理(Python代码实现)
  3. 新一代烧写工具—STM32CubeProgrammer!
  4. 投资理财-害怕的事情
  5. 免费图片或PDF文档转换为文本在线网站
  6. 尚硅谷商城购物系统 安卓App
  7. 2022年起重机械指挥考试模拟100题模拟考试平台操作
  8. 图片转文字工具怎样进行批量识别?
  9. 编程基础:计算机相关知识
  10. 杭州内推 | 网易互娱AI Lab招聘NLP/数据挖掘/图像算法实习生