Я могу отправить «X», «Y» или «Z» от Raspberry Pi на карту памяти, и она ответит Pi значением G-Force.
Этот код Python работает на Pi:
Код: Выделить всё
import serial
import time
import threading
ser = serial.Serial('/dev/rfcomm5') #init serial port
input_line = []#init input char array
def process_data(_data):
#called every time a sream is terminated by \n
#and the command string is ready to use
command = convert(_data)
print(command)
def convert(s): #convert the char list in a string
new = "" #init string to append all chars from char array
for x in s: # traverse in the string
new += str(x)
return new # return string
def processIncomingByte(inByte):#adding incoming chars to input_line
global input_line# globalize the input_line
if(inByte == '\n'):#if \n is incoming, end the chararray and release process data method
process_data(input_line)
input_line = []#reset input_line for next incoming string
elif(inByte == '\r'):
pass
else:#put all incoming chars in input_line
input_line.append(inByte)
while True:
while(ser.in_waiting > 0):#while some data is waiting to read....
processIncomingByte(ser.read())#.... process bytes whit method
ser.write(b'X\n')
time.sleep(0.5)
Но теперь я хотел бы подключить флешку к rfcomm5 через Python. Вы можете предположить, что MAC-адрес известен, он будет указан в файле конфигурации позже. Я начал немного исследовать, но чем больше я исследую, тем больше запутываюсь. Я читал о сокетах и подходах сервер-клиент с использованием отдельного скрипта.
Я протестировал этот код:
Код: Выделить всё
from bluetooth import *
target_name = "M5-Stick-C"
target_address = None
nearby_devices = discover_devices()
for address in nearby_devices:
if (target_name == lookup_name( address )):
target_address = address
break
if (target_address is not None):
print ("found target bluetooth device with address ", target_address)
else:
print ("could not find target bluetooth device nearby")
Но действительно ли мне нужно создавать второй скрипт/процесс для подключения из моего скрипта?
Является ли M5stack Stick-C сервером, а rfcomm — сокетом, или это ошибочное предположение? Я много программировал, но никогда не использовал сокеты или сервер-клиент, что меня смущает.
В принципе связь (сервер/клиент?) работает.
Мне просто нужно подключить устройство, которое я нашел во втором скрипте, через macadress к rfcomm5 (или чему-то другому rfcomm).
Нужен ли мне разъем Bluetooth, как в этом примере?
Подробнее здесь: https://stackoverflow.com/questions/633 ... ing-python
Мобильная версия