在安卓下使用python连接蓝牙串口模块(HC-06)

在安卓上安装Python:

请参考:https://github.com/kuri65536/python-for-android/blob/master/README.md
下载程序文件需要访问 https://github-cloud.s3.amazonaws.com ,一般需要FQ
下载如下文件:
sl4a-r6.1.1-arm-debug.apk,
PythonForAndroid-debug.apk,
python_r26.zip,
python_extras_r26.zip,
python_scripts_r26.zip
我已经将程序上传到百度网盘:
SL4A: http://pan.baidu.com/s/1dDWNt0P
Py4A: http://pan.baidu.com/s/1kUombmn
Python: http://pan.baidu.com/s/1i4stQYD
Script: http://pan.baidu.com/s/1pJVMYqZ
Extras: http://pan.baidu.com/s/1skbO7cp
 
运行SL4A以及Py4A的apk安装他们
随后运行Py4A(Python for Android)
可以点击Install自动下载Python运行环境,这一步会需要一定时间,并且需要FQ
也可以点击Local Install安装手动下载的数据文件。
如果选择本地安装需要将手动下载的zip包(python, extras, scripts)放在/内部存储/com.googlecode.pythonforandroid(如果有sd卡则是/sdcard/com.googlecode.pythonforandroid)下
安装完成后即可使用SL4A添加python脚本

 

Python脚本

打开SL4A界面,点击菜单选择添加一个Python2.7的脚本
起名为喜欢的名字,如blueserial_monitor.py
向脚本中写入如下内容:
 1 import android
 2 import time
 3     
 4 droid = android.Android()
 5 droid.toggleBluetoothState(True)
 6 cnRst = droid.bluetoothConnect(
 7     "00001101-0000-1000-8000-00805F9B34FB")
 8     
 9 print(cnRst)
10     
11 if cnRst.result: 
12     while True:
13         message = droid.bluetoothReadLine().result
14         print(message)
15     
16 droid.exit()
解释:
anroid库的具体用法请参阅SL4A的文档 http://www.mithril.com.au/android/doc/BluetoothFacade.html
与蓝牙串口连接的主要操作在于加粗部分:droid.bluetoothConnect("00001101-0000-1000-8000-00805F9B34FB")
做为参数的字符串是用于bluetoothConnect的uuid,它是蓝牙串口服务ID,因为SL4A没有提供类似createRfcommSocketToServiceRecord的API,所以我们需要使用该uuid来打开蓝牙串口服务
 
当bluetoothConnect执行完成,cnRst会得到成功的返回值,这时候就可以使用bluetoothReadLine等函数读写该串口了
 

posted on 2015-12-18 15:22  闻冥  阅读(3974)  评论(2编辑  收藏  举报

导航