首页 > 解决方案 > 如何使用像 A/D 转换器这样的 arduino 将 3 个模拟信号从 3 个电位计转换为覆盆子?

问题描述

我正在开发我的控制系统raspberry。不幸的是,raspberry没有任何模拟端口。我可以使用arduino将信号从模拟转换为数字,并将此信号发送到 I/O 数字端口,从anduino到 `raspberry?那可能吗?

标签: arduinoraspberry-pi

解决方案


您无法通过 Raspberry Pi 上的数字引脚发送模拟值,但您可以在两者之间使用串行通信。

在 Arduino 端,您需要先读取模拟数据(电位器的值),将它们序列化(如将其转换为字符串),然后通过串行端口将其发送到 Pi。在 Pi 方面,只需接收该值并将其转换为浮点值。

按照此处的连接进行操作,并记住根据您的连接更改引脚名称。

Arduino代码:

// definition of analog pins
int analogPin1 = A0;
int analogPin2 = A1;
int analogPin3 = A2;

void setup()
{
  Serial.begin(9600);
}

// a function to read values and convert them to String
String read()
{
  // a variable to hold serilize data of values that need to be sent
  String result = "";
  // convert each value to string
  String analogPin1_value = String(analogRead(analogPin1), 3);
  String analogPin2_value = String(analogRead(analogPin2), 3);
  String analogPin3_value = String(analogRead(analogPin3), 3);
  // result would become something like "1.231,59.312,65.333"
  result = analogPin1_value + "," + analogPin2_value + "," + analogPin3_value;
  return result;
}

void loop()
{
  // send values with one second delay
  Serial.println(read());
  delay(1000);
}

皮码:

import serial

# remember to set this value to a proper serial port name
ser = serial.Serial('/dev/ttyUSB0', 9600)
ser.open()
# flush serial for unprocessed data
ser.flushInput()
while True:
    result = ser.readline()
    if result:
        # decode result
        result = result.decode()
        print("new command:", result)
        # split results
        values = list(map(float, result.split(",")))
        print("Converted results:", values)

推荐阅读