我的电路中有一个力敏电阻(FSR),我希望我的 Arduino 将此数据传递到我的 PC,通过蓝牙运行 python 脚本。
这是我在这个项目中使用的蓝牙盾:Bluetooth Shield
我尝试模仿此处的示例,但两种情况都没有涉及 Arduino 蓝牙与 PC 的蓝牙交互的情况,并且当我使用他们的草图时代码甚至无法上传。
操作系统:Windows 10
这是我的 FSR 的代码:
const int fsrAnalogPin = A0;
int fsrReading;
void setup(void) {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop(void) {
// put your main code here, to run repeatedly:
fsrReading = analogRead(fsrAnalogPin);
int num = fsrReading/3;
Serial.print("Analog reading = ");
Serial.println(num);
delay(50);
}
这是我的 Python 脚本代码(蓝牙尚未实现):
import serial
serialArduino = serial.Serial('COM4', 9600)
while True:
while (serialArduino.inWaiting() == 0):
pass
valueRead =(serialArduino.readline())
print(valueRead)
我可以在 FSR 代码和 Python 代码中更改哪些内容来通过蓝牙发送和接收数据?
最佳答案
在您的代码中,您没有初始化与您的扩展板的串行连接。
根据使用的Arduino板,您应该选择被屏蔽使用的串行端口。
如果您使用 Uno,则必须使用 SoftwareSerial Library 与您的代码进行通信,如此例所示
#include <SoftwareSerial.h>
#define RxD 7
#define TxD 6
SoftwareSerial BlueToothSerial(RxD,TxD);
void setup()
{
Serial.begin(38400);
BlueToothSerial.begin(38400);
delay(500);
}
void loop()
{
if(BlueToothSerial.available())
{
Serial.print(char(BlueToothSerial.read()));
}
if(Serial.available())
{
BlueToothSerial.print(char(Serial.read()));
}
}
如果您使用 Mega - 检查防护罩使用的序列号并修改上面的代码。
您没有说明您的 PC 上运行哪个操作系统,具体取决于操作系统,您必须选择通信方法。对于 Windows,如果您想使用 COM 端口,则必须首先与 arduino 配对。然后为屏蔽提供的服务添加COM口(曾经是SPP)。
一旦获得 COM 编号,您就可以在 PC 端的脚本中使用它并从 Arduino 读取数据。
更好的方法是与没有 COM 端口的蓝牙设备通信。如果您使用 Windows,可以使用 Bluetooth Framework 来完成
关于python - 如何通过 Arduino 蓝牙模块将数据实时传递到运行 python 脚本的 PC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575239/