我正在raspberry
中开发一个控制系统。不幸的是,raspberry
没有任何模拟端口。我可以使用arduino
进行转换吗
信号从模拟信号转换为数字信号,然后将此信号从anduino
发送到I / O数字端口到`raspberry?有可能吗?
答案 0 :(得分:0)
您不能通过Raspberry Pi上的数字引脚发送模拟值,但是可以在两者之间使用串行通信。
在Arduino端,您需要首先读取模拟数据(电位计的值),将其串行化(例如将其转换为字符串),然后通过串行端口将其发送到Pi。在Pi端,只需接收值并将其转换为浮点值即可。
按照here中的说明进行连接,并记住根据您的连接更改引脚名称。
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);
}
Pi码:
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)