前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux(RaspberryPi)上通

Linux(RaspberryPi)上通

作者头像
py3study
发布2020-01-03 11:55:47
1.2K0
发布2020-01-03 11:55:47
举报
文章被收录于专栏:python3python3

使用python的第三方库bluepy可以很方便的在linux主机如树莓派上进行蓝牙通信。

  • bluepy的安装
代码语言:javascript
复制
sudo apt-get install python-pip libglib2.0-dev
代码语言:javascript
复制
sudo pip install bluepy

源码安装如下:

代码语言:javascript
复制
$ sudo apt-get install git build-essential libglib2.0-dev
$ git clone https://github.com/IanHarvey/bluepy.git
$ cd bluepy
$ python setup.py build
$ sudo python setup.py install

官方示例代码

代码语言:javascript
复制
import btle

class MyDelegate(btle.DefaultDelegate):
    def __init__(self, params):
        btle.DefaultDelegate.__init__(self)
        # ... initialise here

    def handleNotification(self, cHandle, data):
        # ... perhaps check cHandle
        # ... process 'data'


# Initialisation  -------

p = btle.Peripheral( address )
p.setDelegate( MyDelegate(params) )

# Setup to turn notifications on, e.g.
#   svc = p.getServiceByUUID( service_uuid )
#   ch = svc.getCharacteristics( char_uuid )[0]
#   ch.write( setup_data )

# Main loop --------

while True:
    if p.waitForNotifications(1.0):
        # handleNotification() was called
        continue

    print "Waiting..."
    # Perhaps do something else here

这是自己写的一个和arduino(arduino bluno)上的BLE通讯的代码,先遍历输出目标的服务(server)信息 在与目标通讯。 在arduino上只是接收到’B’字符后开始发送数据

代码语言:javascript
复制
from bluepy import btle
from bluepy.btle import DefaultDelegate
import time

class NotifyDelegate(DefaultDelegate):
    def __init__(self):
            DefaultDelegate.__init__(self)
    def handleNotification(self,cHandle,data):
        print("notify from "+str(cHandle)+str(data)+"\n")

dev=btle.Peripheral("50:65:83:94:28:02").withDelegate(NotifyDelegate())

time.sleep(0.5)

for ser in dev.getServices():
    print(str(ser))
    for chara in ser.getCharacteristics():
        print(str(chara))
        print("Handle is "+str(chara.getHandle()))
        print("properties is "+chara.propertiesToString())
        if(chara.supportsRead()):
            print(type(chara.read()))
            print(chara.read())
    print("\n")



dev.writeCharacteristic(37,b'A',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'b',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'A',withResponse=True)
dev.waitForNotifications(1)
dev.writeCharacteristic(37,b'b',withResponse=True)

i=0
dev.writeCharacteristic(37,b'B',withResponse=False)
while(True):
    if(dev.waitForNotifications(1)):
        i=i+1
        if(i>1000):
            break
        continue
    print("Waiting...")
time.sleep(0.5)

dev.disconnect()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档