[英]pySerial and Arduino communication
So far, I was exploring Python with Arduino using pySerial. 到目前为止,我正在使用pySerial和Arduino探索Python。 I made some projects where pySerial reads something from the serial port.
我做了一些项目,其中pySerial从串行端口读取某些内容。
import serial
arduinoSerialData = serial.Serial('com11',9600) #Create Serial port object called arduinoSerialData
while (1==1):
if (arduinoSerialData.inWaiting()>0):
myData = arduinoSerialData.readline()
print (myData)
int trigPin=13; //Sensor Trig pin connected to Arduino pin 13
int echoPin=11; //Sensor Echo pin connected to Arduino pin 11
float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in low state
pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds
pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
targetDistance= speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance= targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile)
Serial.println(targetDistance);
delay(100); //delay tenth of a second to slow things down a little.
}
For now, my code looks something like this. 现在,我的代码看起来像这样。 How can I make use of my ultrasonic sensor in Python and send signals to my Arduino program?
如何使用Python中的超声波传感器并将信号发送到Arduino程序? In other words, can I make my Arduino file read from the Python file that I have or it is only one direction?
换句话说,我可以让我的Arduino文件从我拥有的Python文件中读取还是仅仅是一个方向?
pySerial allows for communication over serial in both directions. pySerial允许双向双向通讯。 On the Arduino side, you need to call
Serial.read
where appropriate to read data stream from Python. 在Arduino端,您需要在适当的地方调用
Serial.read
来从Python读取数据流。 In Python, you just need to send data using the function serial.write
. 在Python中,您只需要使用
serial.write
函数发送数据。 If using Python 3, input to serial.write
needs to be in byte
format. 如果使用Python 3,则
serial.write
输入必须为byte
格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.