[英]How to establish a continuous Bluetooth connection with BlueZ so I can transfer to and receive data from an Arduino?
我一直在用 Arduino 為 class 制作一個 map 制作機器人汽車。我想在 C 中為它制作一個用戶界面(在運行 Linux 的 PC 上),它可以像這樣工作:用戶可以按開始和停止按鈕,或點擊map的特定區域將機器人發送到那里。 現在我的測試設置代碼如下所示: Arduino :`
if (BTSerial.available() > 0) {
c = BTSerial.readStringUntil('\n').toInt();
BTSerial.write(c);
if(c == 8) {
Buzzing(SOS);
BTSerial.println("eight");
}
}
**PC program**:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 };
int s, status;
char dest[18] = "98:DA:60:03:F2:92";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "8", 2);
}
if( status < 0 ) perror("uh oh");
int client, bytes_read;
char buf[1024] = { 0 };
// put socket into listening mode
listen(s, 1);
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
close(s);
return 0;
}
` 理想情況下,如果我將數字 8 發送到 Arduino,它會發回字符串“8”。 當我運行我的 PC 程序時,我的 PC 連接到 Arduino(我從操作系統收到一條通知,表明我的 PC 已連接,並且連接到 Arduino 的 HC-06 藍牙模塊上的 LED 停止閃爍,表明設備已連接到它)和連接到 Arduino 的蜂鳴器開始按預期發出 SOS 的摩爾斯電碼。 然而,在我的程序終止一秒鍾后,藍牙連接結束(我收到一條通知,告知我的 PC 已斷開連接,藍牙模塊上的 LED 再次開始閃爍)並且我沒有返回預期的“8”字符串。 對於 C 語言,我仍然只是一個初學者,而且由於找不到 BlueZ 的詳細文檔,我有點卡住了。 任何幫助將不勝感激!
我試圖從這個網站結合服務器和客戶端代碼: https://people.csail.mit.edu/albert/bluez-intro/x502.html#rfcomm-server.c
我還在 Arduino 上使用 PC 上的 Putty 測試了我的代碼,它可以正常工作。
在套接字上調用listen
並不像您認為的那樣。 收聽並不意味着“等待數據”。 這意味着“等待連接”。 而且您無法從監聽套接字中讀取; 你只能接受連接。
您的套接字已連接。 別listen
。 剛read
。
所以經過一些工作,我終於可以讓它工作了。 我只需要更改 read() function 的第一個參數。這是我的最終代碼:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc addr = { 0 }, rem_addr = { 0 };
int s, status;
char dest[18] = "98:DA:60:03:F2:92";
// allocate a socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// set the connection parameters (who to connect to)
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t) 1;
str2ba( dest, &addr.rc_bdaddr );
// connect to server
status = connect(s, (struct sockaddr *)&addr, sizeof(addr));
// send a message
if( status == 0 ) {
status = write(s, "8", 2);
}
if( status < 0 ) perror("uh oh");
int bytes_read;
char buf[1024] = { 0 };
// read data from the client
bytes_read = read(s, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("%s", buf);
}
close(s);
return 0;
}
此代碼將數字“8”發送到 Arduino,Arduino 回復該字符串“8”。 它可能不是最好的 C 藍牙連接代碼,但我猜至少它在工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.