GVKun编程网logo

Raspberry Pi 和 Arduino 不与 Python Serial 通信(arduino和raspberry的区别)

2

这篇文章主要围绕RaspberryPi和Arduino不与PythonSerial通信和arduino和raspberry的区别展开,旨在为您提供一份详细的参考资料。我们将全面介绍RaspberryP

这篇文章主要围绕Raspberry Pi 和 Arduino 不与 Python Serial 通信arduino和raspberry的区别展开,旨在为您提供一份详细的参考资料。我们将全面介绍Raspberry Pi 和 Arduino 不与 Python Serial 通信的优缺点,解答arduino和raspberry的区别的相关问题,同时也会为您带来Arduino + RFID 读取 IC 卡 Arduino uno中获得RFID的UID 并通过串口转发RFID卡号、Arduino - Raspberry Pi,使用 D-BUS API 的蓝牙连接、Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入、Arduino Serial.Available() 在 255 个字节后为假的实用方法。

本文目录一览:

Raspberry Pi 和 Arduino 不与 Python Serial 通信(arduino和raspberry的区别)

Raspberry Pi 和 Arduino 不与 Python Serial 通信(arduino和raspberry的区别)

如何解决Raspberry Pi 和 Arduino 不与 Python Serial 通信

我正在尝试让 RaspBerry Pi 向 Arduino 发送串行命令,然后 Arduino 解释该命令并相应地打开或关闭引脚。我已经编写了一个 python 脚本,它简单地接受命令(它是一个整数)并将其转换为字符串,然后再对其进行编码并通过串行方式将其发送到 Arduino。当我在命令行上尝试每个命令时,我得到了预期的结果并且 Arduino 会打开,但是当我尝试使用命令作为参数运行脚本时,它不起作用。一路上我没有收到任何错误,并且在发送命令之前的所有打印都符合预期。我大致遵循本教程:

https://roboticsbackend.com/raspberry-pi-arduino-serial-communication/

Python 代码:

  1. import serial
  2. import sys
  3. import time
  4. command = sys.argv[1]
  5. if __name__ == ''__main__'':
  6. print(command)
  7. ser=serial.Serial(''/dev/ttyACM0'',9600,timeout=1)
  8. print((str(command)+"\\n").encode(''ascii''))
  9. ser.write((str(command)+"\\n").encode(''ascii''))
  10. time.sleep(0.2)
  11. response = ser.readline().decode(''ascii'').rstrip()
  12. f=open(''/home/pi/responselog.txt'',''w'')
  13. f.write(response)
  14. f.close()
  15. ser.close()

通过脚本尝试命令 118 时返回:

  1. 118
  2. b''118\\n''

通过Python shell执行write命令时返回:

  1. 4

Arduino 代码:

  1. #define F_cpu 16000000L //defines clock frequency
  2. #include <avr/io.h> // Call in the AVR/IO library
  3. #include <avr/delay.h> //Call in the AVR/delay library
  4. #include <Arduino.h> //Call in the Arduino library
  5. int incomingByte = 0;
  6. int incoming[3];
  7. int command = 0;
  8. int ActivePump = 1;
  9. int error = 0;
  10. void setup() {
  11. Serial.begin(9600);
  12. // Set data direction registers for digital pins: each bit is set to 1 for output,0 for input
  13. DDRA = 0xFF;
  14. DDRB = 0b00001111;
  15. DDRC = 0xFF;
  16. DDRD = 0x8F;
  17. DDRE = 0x38;
  18. DDRG = 0x27;
  19. DDRH = 0x08;
  20. DDRJ = 0x00;
  21. DDRL = 0xFF;
  22. //Set inital port values for digital pins
  23. PORTA = 0;
  24. PORTB = 0xF0;
  25. PORTC = 0;
  26. PORTD = 0;
  27. PORTE = 0;
  28. PORTG = 0;
  29. PORTH = 0x73;
  30. PORTJ = 0x03;
  31. PORTL = 0;
  32. }
  33. /*int ReadFlowRate(SensorNum) {
  34. SIGNAL(TIMER0_COMPA_vect){
  35. }
  36. }*/
  37. int ActivatePump(){
  38. if((PINB4 && ActivePump == 1) || (PINB5 && ActivePump == 2)){
  39. error = 1;
  40. return 1;
  41. }
  42. if(ActivePump == 1){
  43. PORTE += 0x10;
  44. return 0;
  45. } else {
  46. PORTE += 0x20;
  47. return 0;
  48. }
  49. }
  50. void StopPump(){
  51. if(ActivePump == 1){
  52. PORTE -= 0x10;
  53. } else {
  54. PORTE -= 0x20;
  55. }
  56. }
  57. void OpenMains(){
  58. PORTG += 0x20;
  59. PORTE += 0x08;
  60. PORTH += 0x08;
  61. }
  62. void CloseMains(){
  63. PORTG -= 0x20;
  64. PORTE -= 0x08;
  65. PORTH -= 0x08;
  66. }
  67. void loop() {
  68. if(Serial.available()){
  69. char First = Serial.read();
  70. // Serial.println(First); Debugging for serial communication
  71. if(First >= ''0'' && First <= ''9''){
  72. command = (command*10)+(First-48);
  73. } /*code for debugging the serial communication
  74. else if(First == 10){
  75. Serial.print("Command received: ");
  76. Serial.println(command);
  77. }
  78. Serial.print("Command received: ");
  79. Serial.println(command);*/
  80. }
  81. int commandClass = command/100;
  82. int SubCommand = command-(commandClass*100);
  83. if(commandClass == 1){
  84. //1xx commands turn on digital pins
  85. switch(SubCommand){
  86. case 02:
  87. PORTE += 0x10;
  88. command = 0;
  89. break;
  90. case 03:
  91. PORTE += 0x20;
  92. command = 0;
  93. break;
  94. case 04:
  95. PORTG += 0x20;
  96. command = 0;
  97. break;
  98. case 05:
  99. PORTE += 0x08;
  100. command = 0;
  101. break;
  102. case 06:
  103. PORTH += 0x08;
  104. command = 0;
  105. Serial.println("Received");
  106. break;
  107. //Skipping 107-117 because those are input pins
  108. case 18:
  109. PORTD += 0x08;
  110. command = 0;
  111. break;
  112. case 19:
  113. PORTD += 0x04;
  114. command = 0;
  115. break;
  116. case 20:
  117. PORTD +=0x02;
  118. command = 0;
  119. break;
  120. case 21:
  121. PORTD += 0x01;
  122. command = 0;
  123. break;
  124. case 22:
  125. PORTA += 0x01;
  126. command = 0;
  127. break;
  128. case 23:
  129. PORTA +=0x02;
  130. command = 0;
  131. break;
  132. case 24:
  133. PORTA += 0x04;
  134. command = 0;
  135. break;
  136. case 25:
  137. PORTA += 0x08;
  138. command = 0;
  139. break;
  140. case 26:
  141. PORTA += 0x10;
  142. command = 0;
  143. break;
  144. case 27:
  145. PORTA += 0x20;
  146. command = 0;
  147. break;
  148. case 28:
  149. PORTA += 0x40;
  150. command = 0;
  151. break;
  152. case 29:
  153. PORTA += 0x80;
  154. command = 0;
  155. break;
  156. case 30:
  157. PORTC += 0x80;
  158. command = 0;
  159. break;
  160. case 31:
  161. PORTC += 0x40;
  162. command = 0;
  163. break;
  164. case 32:
  165. PORTC += 0x20;
  166. command = 0;
  167. break;
  168. case 33:
  169. PORTC += 0x10;
  170. command = 0;
  171. break;
  172. case 34:
  173. PORTC += 0x08;
  174. command = 0;
  175. break;
  176. case 35:
  177. PORTC += 0x04;
  178. command = 0;
  179. break;
  180. case 36:
  181. PORTC +=0x02;
  182. command = 0;
  183. break;
  184. case 37:
  185. PORTC += 0x01;
  186. command = 0;
  187. break;
  188. case 38:
  189. PORTD += 0x80;
  190. command = 0;
  191. break;
  192. case 39:
  193. PORTG += 0x04;
  194. command = 0;
  195. break;
  196. case 40:
  197. PORTG +=0x02;
  198. command = 0;
  199. break;
  200. case 41:
  201. PORTG += 0x01;
  202. command = 0;
  203. break;
  204. case 42:
  205. PORTL += 0x80;
  206. command = 0;
  207. break;
  208. case 43:
  209. PORTL += 0x40;
  210. command = 0;
  211. break;
  212. case 44:
  213. PORTL += 0x20;
  214. command = 0;
  215. break;
  216. case 45:
  217. PORTL += 0x10;
  218. command = 0;
  219. break;
  220. case 46:
  221. PORTL += 0x08;
  222. command = 0;
  223. break;
  224. case 47:
  225. PORTL += 0x04;
  226. command = 0;
  227. break;
  228. case 48:
  229. PORTL +=0x02;
  230. command = 0;
  231. break;
  232. case 49:
  233. PORTL += 0x01;
  234. command = 0;
  235. break;
  236. case 50:
  237. PORTB += 0x08;
  238. command = 0;
  239. break;
  240. case 51:
  241. PORTB += 0x04;
  242. command = 0;
  243. break;
  244. case 52:
  245. PORTB +=0x02;
  246. command = 0;
  247. break;
  248. case 53:
  249. PORTB += 0x01;
  250. command = 0;
  251. break;
  252. }
  253. } else if(commandClass==2){
  254. //2xx commands turn off digital pins
  255. switch(SubCommand){
  256. case 02:
  257. PORTE -= 0x10;
  258. command = 0;
  259. break;
  260. case 03:
  261. PORTE -= 0x20;
  262. command = 0;
  263. break;
  264. case 04:
  265. PORTG -= 0x20;
  266. command = 0;
  267. break;
  268. case 05:
  269. PORTE -= 0x08;
  270. command = 0;
  271. break;
  272. case 06:
  273. PORTH -= 0x08;
  274. command = 0;
  275. break;
  276. //Skipping 207-217 because those are input pins
  277. case 18:
  278. PORTD -= 0x08;
  279. command = 0;
  280. break;
  281. case 19:
  282. PORTD -= 0x04;
  283. command = 0;
  284. break;
  285. case 20:
  286. PORTD -=0x02;
  287. command = 0;
  288. break;
  289. case 21:
  290. PORTD -= 0x01;
  291. command = 0;
  292. break;
  293. case 22:
  294. PORTA -= 0x01;
  295. command = 0;
  296. break;
  297. case 23:
  298. PORTA -=0x02;
  299. command = 0;
  300. break;
  301. case 24:
  302. PORTA -= 0x04;
  303. command = 0;
  304. break;
  305. case 25:
  306. PORTA -= 0x08;
  307. command = 0;
  308. break;
  309. case 26:
  310. PORTA -= 0x10;
  311. command = 0;
  312. break;
  313. case 27:
  314. PORTA -= 0x20;
  315. command = 0;
  316. break;
  317. case 28:
  318. PORTA -= 0x40;
  319. command = 0;
  320. break;
  321. case 29:
  322. PORTA -= 0x80;
  323. command = 0;
  324. break;
  325. case 30:
  326. PORTC -= 0x80;
  327. command = 0;
  328. break;
  329. case 31:
  330. PORTC -= 0x40;
  331. command = 0;
  332. break;
  333. case 32:
  334. PORTC -= 0x20;
  335. command = 0;
  336. break;
  337. case 33:
  338. PORTC -= 0x10;
  339. command = 0;
  340. break;
  341. case 34:
  342. PORTC -= 0x08;
  343. command = 0;
  344. break;
  345. case 35:
  346. PORTC -= 0x04;
  347. command = 0;
  348. break;
  349. case 36:
  350. PORTC -=0x02;
  351. command = 0;
  352. break;
  353. case 37:
  354. PORTC -= 0x01;
  355. command = 0;
  356. break;
  357. case 38:
  358. PORTD -= 0x80;
  359. command = 0;
  360. break;
  361. case 39:
  362. PORTG -= 0x04;
  363. command = 0;
  364. break;
  365. case 40:
  366. PORTG -=0x02;
  367. command = 0;
  368. break;
  369. case 41:
  370. PORTG -= 0x01;
  371. command = 0;
  372. break;
  373. case 42:
  374. PORTL -= 0x80;
  375. command = 0;
  376. break;
  377. case 43:
  378. PORTL -= 0x40;
  379. command = 0;
  380. break;
  381. case 44:
  382. PORTL -= 0x20;
  383. command = 0;
  384. break;
  385. case 45:
  386. PORTL -= 0x10;
  387. command = 0;
  388. break;
  389. case 46:
  390. PORTL -= 0x08;
  391. command = 0;
  392. break;
  393. case 47:
  394. PORTL -= 0x04;
  395. command = 0;
  396. break;
  397. case 48:
  398. PORTL -=0x02;
  399. command = 0;
  400. break;
  401. case 49:
  402. PORTL -= 0x01;
  403. command = 0;
  404. break;
  405. case 50:
  406. PORTB -= 0x08;
  407. command = 0;
  408. break;
  409. case 51:
  410. PORTB -= 0x04;
  411. command = 0;
  412. break;
  413. case 52:
  414. PORTB -=0x02;
  415. command = 0;
  416. break;
  417. case 53:
  418. PORTB -= 0x01;
  419. command = 0;
  420. break;
  421. }
  422. } else if(commandClass==3){
  423. //3xx commands control pumps (302 & 303) and activate and deactivate water change (318-389)
  424. switch(SubCommand){
  425. case 02:
  426. ActivePump = 1;
  427. command = 0;
  428. break;
  429. case 03:
  430. ActivePump = 2;
  431. break;
  432. case 18:
  433. int errorCheck = ActivatePump();
  434. if(errorCheck == 0){
  435. OpenMains();
  436. PORTD += 0x08;
  437. command = 0;
  438. break;
  439. } else {
  440. command = 0;
  441. break;
  442. }
  443. case 54:
  444. PORTD -= 0x08;
  445. CloseMains();
  446. StopPump();
  447. break;
  448. }
  449. } else if(commandClass == 4){
  450. //4xx commands read analog inputs
  451. switch(SubCommand){
  452. }
  453. } else if(commandClass == 5){
  454. //5xx commands read digital inputs
  455. switch(SubCommand){
  456. }
  457. }/*case 400:
  458. int initalRead;
  459. initialRead = analogRead(A0);
  460. Serial.println(initialRead);
  461. command = 0;
  462. break;*/
  463. }

编辑:我想通了。显然 ser.readline() 命令抛出了一个异常,该异常在我将监控程序连接到串行端口之前由于某种原因没有打印出来,然后它抛出了异常。我注释掉了那行,现在它完美无缺。

编辑 2: 好吧,我说得太早了。如果没有连接串行监视器程序,脚本仍然无法运行。

Arduino + RFID 读取 IC 卡 Arduino uno中获得RFID的UID 并通过串口转发RFID卡号

Arduino + RFID 读取 IC 卡 Arduino uno中获得RFID的UID 并通过串口转发RFID卡号

RFID简介:射频识别即RFID(Radio Frequency IDentification)技术,又称无线射频识别,是一种通信技术,可通过无线电讯号识别特定目标并读写相关数据,而无需识别系统与特定目标之间建立机械或光学接触。常用的有低频(125k~134.2K)、高频(13.56Mhz)、超高频,微波等技术。RFID读写器也分移动式的和固定式的,目前RFID技术应用很广,如:图书馆,门禁系统,食品安全溯源等。

硬件准备

(基于Arduino的开发板、MFRC522读卡器模块)
Arduino Uno * 1
在这里插入图片描述
RFID-RC522 模块 * 1
在这里插入图片描述
IC卡 * 1-2
在这里插入图片描述
RFID技术现在都非常成熟和应用广泛,今天我们就来看看这个RFID如何实现读取里面的数据

接线

Arduino Uno <—> RFID-RC522
10 <—> SDA
13 <—> SCK
11 <—> MOSI
12 <—> MISO
null <—> IRQ
GND <—> GND
9 <—> RST
3.3V <—> 3.3V

需要用到RFID-RC522的库

法一、下载:https://github.com/miguelbalboa/rfid
下载解压到Arduino IDE的安装路径里的库文件夹libraries
https://download.csdn.net/download/v86337286/11813061

法二、点开管理库,在搜索栏里输入RC522,找到图中的库,
在这里插入图片描述
在这里插入图片描述
点击安装(我这图是已经安装过)
在这里插入图片描述

示例代码 .

Arduino + RFID 读取 IC 卡信息

读取 IC 卡信息后并通过串口将卡号及0扇区卡号数据打印出来,其他15个扇区不显示扇区内容
代码如下

/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 * 
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 * 
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 * 
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 * 
 * @license Released into the public domain.
 * 
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */
 
#include <SPI.h>
#include <MFRC522.h>
 
#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above
 
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
 
void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}
 
void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
 
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
 
    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

运行此代码并将其中一张卡放入RFID卡时,很多信息显示在Arduino IDE的串行监视器上
在这里插入图片描述

看完了上面那如何在Arduino中获得RFID的UID?

Arduino uno中只获得RFID的UID 并通过串口转发

法一

创建了另一个函数: PICC_DumpDetailsToSerialUid(Uid *uid)


函数如下

//This is just for read UID!
void MFRC522::PICC_DumpDetailsToSerialUid(Uid *uid){
Serial.print(F(“Card JUST UID :”));
for (byte i = 0; i < uid->size; i++) {
if(uid->uidByte[i] < 0x10)
Serial.print(F(" 0"));
else
Serial.print(F(" "));
Serial.print(uid->uidByte[i], HEX);
}
Serial.println();
}

可以把它放在你需要的任何地方
示例:
在这里插入图片描述
添加该功能后,您需要进入第410行的 MFRC522.h 库并添加

void PICC_DumpDetailsToSerialUid(Uid *uid);

在该库中进行了这两次编辑后,您可以在任意位置调用该函数 .
示例:
在这里插入图片描述
用Arduino调用它: mfrc522.PICC_DumpDetailsToSerialUid(&(mfrc522.uid)); 只仅且只有一个函数用于uid读取
效果
在这里插入图片描述

法二

返回UID的函数 .

/**
 * mfrc522.PICC_IsNewCardPresent() should be checked before 
 * @return the card UID
 */
unsigned long getID(){
  if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
    return -1;
  }
  unsigned long hex_num;
  hex_num =  mfrc522.uid.uidByte[0] << 24;
  hex_num += mfrc522.uid.uidByte[1] << 16;
  hex_num += mfrc522.uid.uidByte[2] <<  8;
  hex_num += mfrc522.uid.uidByte[3];
  mfrc522.PICC_HaltA(); // Stop reading
  return hex_num;
}

例如这样使用:

if(mfrc522.PICC_IsNewCardPresent()) {
  unsigned long uid = getID();
  if(uid != -1){
    Serial.print("Card detected, UID: "); Serial.println(uid);
  }
}

在这里插入图片描述

Arduino - Raspberry Pi,使用 D-BUS API 的蓝牙连接

Arduino - Raspberry Pi,使用 D-BUS API 的蓝牙连接

如何解决Arduino - Raspberry Pi,使用 D-BUS API 的蓝牙连接

任务是使用基于python脚本的D-BUS API通过蓝牙自动实现Arduino和RaspBerry Pi之间的配对和连接过程。

连接Arduino的蓝牙模块为:Grove - Serial Bluetooth v3.0.

我能够自动化配对过程。配对脚本按顺序执行以下操作:

  1. 它通过创建适配器对象并使用 Startdiscovery 方法查找名为 Slave 的蓝牙模块。(命名在 Arduino 中完成)。
  2. 注册蓝牙代理。
  3. 如果设备尚未配对,则通过Pair方法创建设备对象和配对。

执行上述步骤的代码部分如下:

  1. register_agent()
  2. start_discovery()
  3. time.sleep(10)
  4. for i in range(len(address_list)):
  5. new_dbus_device = get_device(address_list[i])
  6. dev_path = new_dbus_device.object_path
  7. device_properties = dbus.Interface(new_dbus_device,"org.freedesktop.DBus.Properties")
  8. pair_status = device_properties.Get("org.bluez.Device1","Paired")
  9. if not pair_status:
  10. new_dbus_device.Pair(reply_handler=pair_reply,error_handler=pair_error,timeout=60000)

以下是 register_agent() 按要求执行的操作:

  1. def register_agent():
  2. agent = Agent(bus,path)
  3. capability = "NoInputNoOutput"
  4. obj = bus.get_object(BUS_NAME,"/org/bluez");
  5. manager = dbus.Interface(obj,"org.bluez.AgentManager1")
  6. manager.Registeragent(path,capability)

但是,当我尝试调用 Bluez 的 device-api 中记录的 Connect 方法时,它总是失败。我创建了一个自定义串行端口配置文件并尝试了 ConnectProfile 方法,但它再次失败。

如果我使用不推荐使用的 rfcomm 工具,则通过蓝牙进行通信,或者如果我使用 python 套接字模块,它也可以工作。 但是我想避免使用 rfcomm,因为它已被弃用.关于使用python socket库,连接仅在rfcomm channel 1有效,其他通道产生Connection Refused错误。

添加MRE,以更好地阐明问题:

  1. import dbus
  2. import dbus.service
  3. import dbus.mainloop.glib
  4. import sys
  5. import time
  6. import subprocess
  7. from bluezutils import *
  8. from bluetooth import *
  9. from gi.repository import GObject,GLib
  10. from dbus.mainloop.glib import DBusGMainLoop
  11. DBusGMainLoop(set_as_default=True)
  12. path = "/test/agent"
  13. AGENT_INTERFACE = ''org.bluez.Agent1''
  14. BUS_NAME = ''org.bluez''
  15. bus = dbus.SystemBus()
  16. device_obj = None
  17. dev_path = None
  18. def set_trusted(path2):
  19. props = dbus.Interface(bus.get_object("org.bluez",path2),"org.freedesktop.DBus.Properties")
  20. props.Set("org.bluez.Device1","Trusted",True)
  21. class Rejected(dbus.DBusException):
  22. _dbus_error_name = "org.bluez.Error.Rejected"
  23. class Agent(dbus.service.Object):
  24. exit_on_release = True
  25. def set_exit_on_release(self,exit_on_release):
  26. self.exit_on_release = exit_on_release
  27. @dbus.service.method(AGENT_INTERFACE,in_signature="",out_signature="")
  28. def Release(self):
  29. print("Release")
  30. if self.exit_on_release:
  31. mainloop.quit()
  32. @dbus.service.method(AGENT_INTERFACE,in_signature="os",out_signature="")
  33. def AuthorizeService(self,device,uuid):
  34. print("AuthorizeService (%s,%s)" % (device,uuid))
  35. return
  36. @dbus.service.method(AGENT_INTERFACE,in_signature="o",out_signature="s")
  37. def RequestPinCode(self,device):
  38. set_trusted(device)
  39. return "0000"
  40. @dbus.service.method(AGENT_INTERFACE,out_signature="u")
  41. def RequestPasskey(self,device):
  42. set_trusted(device)
  43. return dbus.UInt32("0000")
  44. @dbus.service.method(AGENT_INTERFACE,in_signature="ou",out_signature="")
  45. def RequestConfirmation(self,passkey):
  46. set_trusted(device)
  47. return
  48. @dbus.service.method(AGENT_INTERFACE,out_signature="")
  49. def RequestAuthorization(self,device):
  50. return
  51. @dbus.service.method(AGENT_INTERFACE,out_signature="")
  52. def Cancel(self):
  53. print("Cancel")
  54. def pair_reply():
  55. print("Device paired and trusted")
  56. set_trusted(dev_path)
  57. def pair_error(error):
  58. err_name = error.get_dbus_name()
  59. if err_name == "org.freedesktop.DBus.Error.noreply" and device_obj:
  60. print("Timed out. Cancelling pairing")
  61. device_obj.CancelPairing()
  62. else:
  63. print("Creating device Failed: %s" % (error))
  64. mainloop.quit()
  65. def register_agent():
  66. agent = Agent(bus,capability)
  67. def start_discovery():
  68. global pi_adapter
  69. pi_adapter = find_adapter()
  70. scan_filter = dict({"DuplicateData": False})
  71. pi_adapter.SetdiscoveryFilter(scan_filter)
  72. pi_adapter.Startdiscovery()
  73. def stop_discovery():
  74. pi_adapter.Stopdiscovery()
  75. def get_device(dev_str):
  76. # use [Service] and [Object path]:
  77. device_proxy_object = bus.get_object("org.bluez","/org/bluez/hci0/dev_"+dev_str)
  78. # use [Interface]:
  79. device1 = dbus.Interface(device_proxy_object,"org.bluez.Device1")
  80. return device1
  81. def char_changer(text):
  82. text = text.replace('':'',r''_'')
  83. return text
  84. def slave_finder(device_name):
  85. global sublist_normal
  86. sublist_normal = []
  87. sublist= []
  88. address = []
  89. edited_address = None
  90. sub = subprocess.run(["hcitool scan"],text = True,shell = True,capture_output=True)
  91. print(sub.stdout) #string type
  92. sublist = sub.stdout.split()
  93. for i in range(len(sublist)):
  94. if sublist[i] == device_name:
  95. print(sublist[i-1])
  96. sublist_normal.append(sublist[i-1])
  97. edited_address = char_changer(sublist[i-1])
  98. address.append(edited_address)
  99. return address
  100. def remove_all_paired():
  101. for i in range(len(sublist_normal)):
  102. sub = subprocess.run(["bluetoothctl remove " + sublist_normal[i]],capture_output=True)
  103. time.sleep(1)
  104. if __name__ == ''__main__'':
  105. pair_status = None
  106. address_list = slave_finder(''Slave'') #Arduino bluetooth module named as "Slave",here we are finding it.
  107. time.sleep(2)
  108. remove_all_paired() #rfcomm requires repairing after release
  109. print(sublist_normal)
  110. if address_list:
  111. register_agent()
  112. start_discovery()
  113. time.sleep(10)
  114. for i in range(len(address_list)):
  115. new_dbus_device = get_device(address_list[i])
  116. dev_path = new_dbus_device.object_path
  117. device_properties = dbus.Interface(new_dbus_device,"org.freedesktop.DBus.Properties")
  118. pair_status = device_properties.Get("org.bluez.Device1","Paired")
  119. if not pair_status:
  120. new_dbus_device.Pair(reply_handler=pair_reply,timeout=60000)
  121. mainloop = GLib.MainLoop()
  122. mainloop.run()

sudo btmon 输出:

  1. Bluetooth monitor ver 5.50
  2. = Note: Linux version 5.4.83-v7l+ (armv7l) 0.832473
  3. = Note: Bluetooth subsystem version 2.22 0.832478
  4. = New Index: DC:A6:32:58:FE:13 (Primary,UART,hci0) [hci0] 0.832481
  5. = Open Index: DC:A6:32:58:FE:13 [hci0] 0.832484
  6. = Index Info: DC:A6:32:5.. (Cypress Semiconductor Corporation) [hci0] 0.832487
  7. @ MGMT Open: bluetoothd (privileged) version 1.14 {0x0001} 0.832490
  8. @ MGMT Open: btmon (privileged) version 1.14 {0x0002} 0.832540

所以问题是为什么ConnectConnectProfile方法总是失败,我需要做什么才能在Arduino和RaspBerry Pi之间建立基于D-BUS API的蓝牙通信?

解决方法

我想你已经回答了你自己的问题。 Connect 不起作用的原因是您没有在 Raspberry Pi 上运行串行端口配置文件 (SPP)。如果您运行 btmon,您会看到客户端断开连接,因为没有与 Arduino 提供的配置文件匹配。

Python Socket 连接中使用的端口号需要与 Arduino 蓝牙模块上的端口号匹配。这可能就是只有 1 起作用的原因。

作为参考,我用 Raspberry Pi 和 HC-06 对此进行了测试。我删除了所有扫描代码以尝试获得最小的可运行代码。这是我使用的代码:

  1. import socket
  2. from time import sleep
  3. import dbus
  4. import dbus.service
  5. import dbus.mainloop.glib
  6. from gi.repository import GLib
  7. BUS_NAME = ''org.bluez''
  8. AGENT_IFACE = ''org.bluez.Agent1''
  9. AGNT_MNGR_IFACE = ''org.bluez.AgentManager1''
  10. ADAPTER_IFACE = ''org.bluez.Adapter1''
  11. AGENT_PATH = ''/ukBaz/bluezero/agent''
  12. AGNT_MNGR_PATH = ''/org/bluez''
  13. DEVICE_IFACE = ''org.bluez.Device1''
  14. CAPABILITY = ''KeyboardDisplay''
  15. my_adapter_address = ''11:22:33:44:55:66''
  16. my_device_path = ''/org/bluez/hci0/dev_00_00_12_34_56_78''
  17. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  18. bus = dbus.SystemBus()
  19. class Agent(dbus.service.Object):
  20. @dbus.service.method(AGENT_IFACE,in_signature=''o'',out_signature=''s'')
  21. def RequestPinCode(self,device):
  22. print(f''RequestPinCode {device}'')
  23. return ''0000''
  24. class Device:
  25. def __init__(self,device_path):
  26. dev_obj = bus.get_object(BUS_NAME,device_path)
  27. self.methods = dbus.Interface(dev_obj,DEVICE_IFACE)
  28. self.props = dbus.Interface(dev_obj,dbus.PROPERTIES_IFACE)
  29. self._port = 1
  30. self._client_sock = socket.socket(socket.AF_BLUETOOTH,socket.SOCK_STREAM,socket.BTPROTO_RFCOMM)
  31. def connect(self):
  32. # self.methods.Connect()
  33. self._client_sock.bind((my_adapter_address,self._port))
  34. self._client_sock.connect((self.address,self._port))
  35. def disconnect(self):
  36. self.methods.Disconnect()
  37. def pair(self):
  38. self.methods.Pair(reply_handler=self._pair_reply,error_handler=self._pair_error)
  39. def _pair_reply(self):
  40. print(f''Device trusted={self.trusted},connected={self.connected}'')
  41. self.trusted = True
  42. print(f''Device trusted={self.trusted},connected={self.connected}'')
  43. while self.connected:
  44. sleep(0.5)
  45. self.connect()
  46. print(''Successfully paired and connected'')
  47. def _pair_error(self,error):
  48. err_name = error.get_dbus_name()
  49. print(f''Creating device failed: {err_name}'')
  50. @property
  51. def trusted(self):
  52. return bool(self.props.Get(DEVICE_IFACE,''Trusted''))
  53. @trusted.setter
  54. def trusted(self,value):
  55. self.props.Set(DEVICE_IFACE,''Trusted'',bool(value))
  56. @property
  57. def paired(self):
  58. return bool(self.props.Get(DEVICE_IFACE,''Paired''))
  59. @property
  60. def connected(self):
  61. return bool(self.props.Get(DEVICE_IFACE,''Connected''))
  62. @property
  63. def address(self):
  64. return str(self.props.Get(DEVICE_IFACE,''Address''))
  65. if __name__ == ''__main__'':
  66. agent = Agent(bus,AGENT_PATH)
  67. agnt_mngr = dbus.Interface(bus.get_object(BUS_NAME,AGNT_MNGR_PATH),AGNT_MNGR_IFACE)
  68. agnt_mngr.RegisterAgent(AGENT_PATH,CAPABILITY)
  69. device = Device(my_device_path)
  70. if device.paired:
  71. device.connect()
  72. else:
  73. device.pair()
  74. mainloop = GLib.MainLoop()
  75. try:
  76. mainloop.run()
  77. except KeyboardInterrupt:
  78. agnt_mngr.UnregisterAgent(AGENT_PATH)
  79. mainloop.quit()

Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入

Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入

我修好了,谢谢大家给我指明了正确的方向。问题出在我的 Arduino 代码中。我使用的是静态 JSON,它没有给我一个压缩字符串。

我将其切换为动态,如 https://arduinojson.org/ 文档中所述。

我的 Arduino 更改为以下内容。

#include <ArduinoJson.h>

void setup() {
  // put your setup code here,to run once:
  Serial.begin(9600);
}

void loop() {
  myFunction();
  delay(5000);
}

int myFunction(){
    DynamicJsonDocument doc(260);
    
    int temp = 21;
    int humidity = 99;
    
    doc["day"] = "Monday";
    doc["temperature"] = temp;
    doc["humidity"] = humidity;

    serializeJson(doc,Serial);
    Serial.println();
  }

Arduino Serial.Available() 在 255 个字节后为假

Arduino Serial.Available() 在 255 个字节后为假

由于错误发生在特定字节之后,通常意味着某种溢出。您还没有显示完整的代码,响应数组的大小是多少(或 ARRAYSIZE,因为您正在使用 memset 清除它)。很可能您的 response[index] 导致越界访问

今天关于Raspberry Pi 和 Arduino 不与 Python Serial 通信arduino和raspberry的区别的介绍到此结束,谢谢您的阅读,有关Arduino + RFID 读取 IC 卡 Arduino uno中获得RFID的UID 并通过串口转发RFID卡号、Arduino - Raspberry Pi,使用 D-BUS API 的蓝牙连接、Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入、Arduino Serial.Available() 在 255 个字节后为假等更多相关知识的信息可以在本站进行查询。

本文标签: