I’m trying to live stream ultrasonic data from my ardunio to my Mac laptop and hitting a bit of a roadblock. The data the python script recovers does not change even when I move the sensor. I have verified the sensor is functioning by the serial monitor with the ardunio running. Any idea on what I need to do here to get the updated output from the ardunio? The code is below.
// defines pins numbers
const int trigPin = 7;
const int echoPin = 8;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
delayMicroseconds(50);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance in CM
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor in CM
Serial.println(distance);
}
import numpy
import serial
import time
import sys
import cv2
import pickle
#set up the camera stuff
cap = cv2.VideoCapture(1)
#container for images
images=[]
#container for distances
distances=[]
#first frame number
frame_num=1
#setup the serial connection and pause to establish it
ser = serial.Serial('/dev/cu.usbmodem1421', 9600,timeout=1)
time.sleep(5)
while True:
try:
#grab and image
ret,frame=cap.read()
#grab the distance
distance=ser.readline()
#process the image to a gray and 1241,376
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_resized=cv2.resize(gray,(1241,376))
cv2.imshow("FRAME",gray_resized)
print(distance)
images.append([frame_num,gray_resized])
distances.append([frame_num,distance])
except KeyboardInterrupt:
#pickle.dump( images, open( "save.p", "wb" ) )
#pickle.dump( distances, open( "save.p", "wb" ) )
sys.exit()