Skip to content

Commit 9f2f2b9

Browse files
authored
Merge pull request #2877 from adafruit/rs232_ble
code for BLE RS232 controller
2 parents 171be2c + 695724c commit 9f2f2b9

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

BLE_RS232_Controller/code.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
import board
6+
import busio
7+
from adafruit_bluefruit_connect.packet import Packet
8+
from adafruit_bluefruit_connect.button_packet import ButtonPacket
9+
from adafruit_ble import BLERadio
10+
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
11+
from adafruit_ble.services.nordic import UARTService
12+
import neopixel
13+
14+
# baud rate for your device
15+
baud = 38400
16+
# commands for your device
17+
commands = ["AVI=1", "AVI=2", "AVI=3", "AVI=4"]
18+
# Initialize UART for the RS232
19+
uart = busio.UART(board.TX, board.RX, baudrate=baud)
20+
# onboard neopixel
21+
pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.5, auto_write=True)
22+
RED = (255, 0, 0)
23+
BLUE = (0, 0, 255)
24+
# BLE setup
25+
ble = BLERadio()
26+
ble_uart = UARTService()
27+
advertisement = ProvideServicesAdvertisement(ble_uart)
28+
advertising = False
29+
print("advertising..")
30+
while True:
31+
if not ble.connected and not advertising:
32+
# not connected in the app yet
33+
pixels.fill(RED)
34+
ble.start_advertising(advertisement)
35+
advertising = True
36+
37+
while ble.connected:
38+
pixels.fill(BLUE)
39+
# after connected via app
40+
advertising = False
41+
if ble_uart.in_waiting:
42+
# waiting for input from app
43+
packet = Packet.from_stream(ble_uart)
44+
if isinstance(packet, ButtonPacket):
45+
# if buttons in the app are pressed
46+
if packet.pressed:
47+
if packet.button == ButtonPacket.BUTTON_1:
48+
uart.write((commands[0] + "\r\n").encode('ascii'))
49+
if packet.button == ButtonPacket.BUTTON_2:
50+
uart.write((commands[1] + "\r\n").encode('ascii'))
51+
if packet.button == ButtonPacket.BUTTON_3:
52+
uart.write((commands[2] + "\r\n").encode('ascii'))
53+
if packet.button == ButtonPacket.BUTTON_4:
54+
uart.write((commands[3] + "\r\n").encode('ascii'))
55+
# empty buffer to collect the incoming data
56+
response_buffer = bytearray()
57+
# check for data
58+
time.sleep(1)
59+
while uart.in_waiting:
60+
data = uart.read(uart.in_waiting)
61+
if data:
62+
response_buffer.extend(data)
63+
# decode and print
64+
if response_buffer:
65+
print(response_buffer.decode('ascii'), end='')
66+
print()

0 commit comments

Comments
 (0)