How to use "characteristic.write(value)"



  • What i want is when the Lopy ble received a string then reply a string.
    so i think i need to use "characteristic.read()" and "characteristic.write(value)" in class GATTCCharacteristic.
    How to use them?



  • @jmarcelino
    Thank you,it works now. The lightBlue get the reply in reads.



  • @DongYin
    There you set reply value using characteristic.value(b'Your reply') so next time your client (the other device) reads it will get your reply.



  • @jmarcelino
    Thank you for explain .These are my codes.

    from network import Bluetooth
    #from machine import Pin
    
    #TestButton = Pin('P23', mode=Pin.IN, pull=Pin.PULL_UP)
    
    bluetooth = Bluetooth()
    bluetooth.set_advertisement(name='LoPy', service_uuid=b'1234567890123456')
    
    def conn_cb (bt_o):
        events = bt_o.events()
        if  events & Bluetooth.CLIENT_CONNECTED:
            print("Client connected")
        elif events & Bluetooth.CLIENT_DISCONNECTED:
            print("Client disconnected")
    
    bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
    
    bluetooth.advertise(True)
    
    srv1 = bluetooth.service(uuid=b'1234567890123456', isprimary=True)
    
    chr1 = srv1.characteristic(uuid=b'2234567890123456', value=6)
    
    def char1_cb(chr):
        print("Write request with value = {}".format(chr.value()))
        if chr.value() == b'\xdd' :
            print("reply here")
            #reply here
    
    char1_cb = chr1.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=char1_cb)
    

    so, how to use CHAR_READ_EVENT at #reply here .



  • That is one way to do it, where the LoPy connects to a service and characteristic on the other device.

    In that case you'd usually setup a NOTIFY callback on the LoPy with:

    characteristic.callback(trigger=Bluetooth.CHAR_NOTIFY_EVENT, handler=YourFunctionHere)

    When the other device writes to the characteristic you'll get a notification that the value has changed and you can then characteristic.read() it.

    After that you can characteristic.write(b'Your Reply') if you're reusing the same characteristic.

    As I said this is just one of the ways to do it. Another would be to do the opposite, have the other device connect to the LoPy and accept a write from the other device (via a Bluetooth.CHAR_WRITE_EVENT event callback) and then reply to a read from it (a Bluetooth.CHAR_READ_EVENT event). For that you could use something like the GATTSCharacteristic example:

    https://docs.pycom.io/pycom_esp32/library/network.Bluetooth.html#class-gattscharacteristic


Log in to reply
 

Pycom on Twitter