运行C++在Arduino上,仅当树莓派请求时

2024-10-03 06:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把数据从raspberry pi发送到arduino,给我发送一次传感器值,然后继续不做任何事情并通过。目前,我发送一个值,然后我收到一个无限循环,我不想。代码如下:

void loop() {
  if (Serial.available() > 0) {
    unsigned long startTime=millis();  
    int phValue = analogRead(sensorPin);
    float voltage = phValue * (5/1023.0);
    float ph = (-5.6548 * voltage) + 15.509;
    int dis=SharpIR.distance();
    float humidity = dht.readHumidity();
    float outside_temp = dht.readTemperature();
    float h = dht.readHumidity();
    float f = dht.readTemperature(true);
    float hif = dht.computeHeatIndex(f,h);
    Serial.print(ph); //ph
    Serial.print(' ');
    Serial.print(dis);
    Serial.print(' ');
    Serial.print(h); //humidity
    Serial.print(' ');
    Serial.print(f); //outside temp in farenheit
    Serial.print(' ');
    Serial.println(hif);
  } else {
    ;
  }

}

Tags: serialfloattempphintprintdisvoltage
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:46

您的Arduino板和Raspberry Pi板应该通过UART相互通信。你应该只在你的设备上设置波特率。你知道吗

例如,在Arduino侧,您可以通过以下方式设置串行连接:

void setup() {
    Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  if (Serial.available() > 0) {
    // read the incoming string:
    incomingString = Serial.readString();
    Serial.write("Hello Raspberrry");
  }
}

在Raspberry方面,您应该首先使用this教程配置您的电路板。然后需要使用pip3 install pyserial在raspberry上安装PySerial包。然后你的董事会可以通过以下方式与Arduino对话:

import serial
import time

port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=2.0)

while True:
    port.write("Hello Arduino")
    string = port.readline()
    print(string)

    time.sleep(10)

相关问题 更多 >