[問題] 想請問藍芽socket傳輸資料被截掉的問題

看板C_and_CPP (C/C++)作者 (kiwi90310)時間11年前 (2015/03/24 16:51), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 樹莓派(Linux,但程式用C寫) 問題(Question): 新手小弟用BTdongle藍芽連接HC-05接收感測器傳來的值 但收到的值都被裁掉了 想請問各位大大該如何修改程式碼讓他不被裁掉? 之前發過很像的問題 這次想從另一方向著手 但解決的函數沒有開放原始碼所以不知該怎設變數去做修改與運算 (想用完整的字串atof轉浮點樹去做運算) 在此先感謝各位大大!! 餵入的資料(Input): 藍芽傳來的字串資料 預期的正確結果(Expected Output): 0~255的值 錯誤結果(Wrong Output): 字串被裁掉,如下網址 http://ppt.cc/ZmYT 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <bluetooth/bluetooth.h> #include <bluetooth/sdp.h> #include <bluetooth/sdp_lib.h> #include <sys/socket.h> #include <bluetooth/rfcomm.h> //-- 搜尋遠端 SPP Server 所使用的 RFCOMM Port Number // 回傳 RFCOMM Port Number int main(int argc, char **argv) { struct sockaddr_rc addr = { 0 }; int status, len, rfcommsock; char rfcommbuffer[255]; char dest[18] = "10:14:07:10:29:52"; // 藍牙 SPP Server 的位址 // allocate a socket rfcommsock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); // set the connection parameters (who to connect to) addr.rc_family = AF_BLUETOOTH; // 先找到 SPP Server 可被連接的 Port Number ( or channel number ) addr.rc_channel = 1; str2ba( dest, &addr.rc_bdaddr ); // 等幾秒鐘之後再連接到 SPP Server sleep(5); // 連接 SPP Server status = connect(rfcommsock, (struct sockaddr *)&addr, sizeof(addr)); //------------------------------------------------------------------------------ // send/receive messages if( status == 0 ) { // say hello to client side status = send(rfcommsock, "hello!", 6, 0); if( status < 0 ) { perror( "rfcomm send " ); close(rfcommsock); return -1; } while(1) { // 從 RFCOMM socket 讀取資料 // 這個 socket // this socket has blocking turned off so it will never block, // even if no data is available len = recv(rfcommsock, rfcommbuffer, 255, 0); // EWOULDBLOCK indicates the socket would block if we had a // blocking socket. we'll safely continue if we receive that // error. treat all other errors as fatal if (len < 0 && errno != EWOULDBLOCK) { perror("rfcomm recv "); break; } else if (len > 0) { // received a message; print it to the screen and // return ATOK to the remote device rfcommbuffer[len] = '\0'; printf("rfcomm received data: %s\n",rfcommbuffer); status = send(rfcommsock, "ATOK\r\n", 6, 0); if( status < 0 ) { perror("rfcomm send "); break; } } } } else if( status < 0 ) { perror("uh oh"); } close(rfcommsock); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.125.20.81 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1427187108.A.A10.html

03/24 21:40, , 1F
可能while(1)裡面需要時間等數字傳過來?因為二位數傳
03/24 21:40, 1F

03/24 21:40, , 2F
過來應該是當成兩個字元在傳。看程式感覺當第一個字
03/24 21:40, 2F

03/24 21:40, , 3F
傳過來的時候就判斷len>0然後讀取輸出
03/24 21:40, 3F

03/30 17:06, , 4F
感謝大大的回覆~
03/30 17:06, 4F
文章代碼(AID): #1L4IMaeG (C_and_CPP)
文章代碼(AID): #1L4IMaeG (C_and_CPP)