![](/img/trans.png)
[英]How to communicate between two raspberry pi via Bluetooth and send sensor data from one pi to another?
[英]How to send data via bluetooth to Pi pico
我需要一種通過藍牙向我的 pi pico 發送整數數組(0-63)的方法。 我已經讓 pico 發送“就緒”。 成功連接到我的計算機,並研究了從 pc 向 pico 發送數據,但我能找到的只是發送手動輸入的單比特數據的程序。 我沒有任何有用的代碼可以發布,因為我不知道從哪里開始。
注意:我的 pico 是用 C 語言配置的,我更喜歡用 Python 在我的電腦上編寫傳輸程序。
編輯:我得到了這個基本的代碼。 它似乎已連接並且不會引發錯誤,但是當我點擊 Pico 上發送“就緒”的按鈕時。 它的字符串不會顯示在終端中。
# This code doesn't throw any errors but it doesn't receive the "Ready." string from the Pico
import bluetooth
hostMACAddress = '' # My computer's main bluetooth address??
port = 10 # Pico shows up on com 9 and com 10 (dev b) neither work though
backlog = 1
size = 1024
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while 1:
data = client.recv(size)
if data:
print(data)
except:
print("Closing socket")
client.close()
s.close()
最直接(但不是最有效的方法)是將整數數組轉換為分隔的 C 字符串,並按照發送“就緒”的方式發送。 假設數組分隔符是“[”和“]”,那么下面的數組
int arr[] = {1,2,3};
可以轉換為如下字符串
char str[] = "[010203]";
要將整數數組轉換為分隔字符串,您可以執行以下操作:
int arr[] = {1,2,3};
int str_length = 50; // Change the length of str based on your need.
char str[str_length] = {0};
int char_written = 0;
char_written = sprintf(str,'[');
for (int i = 0; i< sizeof(arr)/sizeof(int) - 1; i++){
char_written = sprintf(&str[char_written], "%02d", arr[i]);
char_written = sprintf(&str[char_written], ']');
現在您可以使用現有代碼發送此字符串。 在接收端,需要根據“[”、“]”以及字符串中每個整數的寬度為2這一事實來處理字符串。
編輯:將數組轉換為字符串並通過python通過藍牙發送字符串。
要在python中將數組轉換為字符串,以下將完成這項工作
a = [1,2,3,4,5]
a_string = "[" + "".join(f"{i:02d}" for i in a) + "]"
要通過藍牙通過 python 發送此字符串,您需要使用PyBlues庫。
首先你需要找到pico藍牙的MAC地址
import bluetooth
# Make sure the only bluetooth device around is the pico.
devices = bluetooth.discover_devices()
print(devices)
現在您知道了 MAC 地址,您需要連接到它
bt_mac = "x:x:x:x:x:x" # Replace with yours.
port = 1
sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr, port))
知道你可以發送像這樣的字符串
sock.send(a_string.encode())
最后,在你的 python 程序結束時關閉套接字
sock.close()
PS:我沒有可用的藍牙來測試它,但它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.