0

`I am trying to scan for devices advertising the UART service using Micropython on esp32. but I get AttributeError: 'NoneType' object has no attribute 'scan'

below is my code:

# Initialize and enable the BLE radio.
ble = ubluetooth.BLE()
ble.active(True)

# Create a BLE scanner object.
scanner = ble.gap_scan(10, 30000, 30000)

# Scan for devices advertising the UART service.
print('Scanning for devices advertising the UART service...')
devices = scanner.scan(10)

# Connect to the first device with the matching UART service UUID.
for device in devices:
    for advertised_service in device.services:
        if advertised_service.uuid == UART_SERVICE_UUID:
            # Connect to the device.
            print(f'Connecting to device {device.name}...')
            connection = ble.connect(device)
            # Wait for the connection to be established.
            while not connection.is_connected:
                pass
            print('Connection established!')
            # Stop scanning.
            scanner.stop()
            break
    if connection.is_connected:
        break

`

1

1 Answer 1

0

Your code reads:

# Create a BLE scanner object.
scanner = ble.gap_scan(10, 30000, 30000)

# Scan for devices advertising the UART service.
print('Scanning for devices advertising the UART service...')
devices = scanner.scan(10)

You're using the gap_scan() method incorrectly. According to the documentation, when the scanner detects a device it calls the callback function. You're getting an error because gap_scan() doesn't return anything, which is consistent with the documentation.

You need to register an event handler in order to see the results of a scan. So:

def ble_callback_handler(event, data):
    if event == _IRQ_SCAN_RESULT:
        # A single scan result. Do whatever you need with this
        addr_type, addr, adv_type, rssi, adv_data = data
    elif event == _IRQ_SCAN_DONE:
        # Scan duration finished or manually stopped.

# register a callback handler
ble.irq(ble_callback_handler)

# start scanning
ble.gap_scan(10, 30000, 30000)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.