pythonraspberry-pitranslatearduino-ultra-sonic

C++ to Python Code (Arduino to Raspberry Pi) - Using Ultrasonic


I have a Ultrasonic (HCSR04) connected to a Raspberry PI 2015. I have the code for the Ultrasonic using C++ which I previously did in Arduino but I am having trouble translating it into Python code in order to use it in Raspberry PI. Could someone help me with this? Here are my code that are written in Arduino C++:

#include <math.h>

const int trigPin = 10;
const int echoPin = 9;
int g = 12; //green led
int r = 13; //red led

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);

  pinMode(g, OUTPUT);
  pinMode(r, OUTPUT);
  
}

void loop() {
  digitalWrite(trigPin, LOW);  // Clears the trigPin
  delayMicroseconds(2);  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  // Reads the echoPin, returns the ultrasound wave travel time in microsec
  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;  // Calculating the distance

  // Prints the distance on the Serial Monitor
  Serial.print ("Distance(cm): ");
  Serial.println(distance);
  delay(1000);

  if(distance > 10)
  {
    digitalWrite(r, LOW);
    digitalWrite(g, HIGH);
    delay(250);
  }
  else
  {
    digitalWrite(g, LOW);
    digitalWrite(r, HIGH);
    delay(100);
  }
}

Solution

  • You don't need this void setup() Linux is take a care of this. Here is Python code:

    import RPi.GPIO as GPIO
    import time
     
    #GPIO Mode (BOARD / BCM)
    GPIO.setmode(GPIO.BCM)
     
    #set GPIO Pins
    GPIO_TRIGGER = 18
    GPIO_ECHO = 24
     
    #set GPIO direction (IN / OUT)
    GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
    GPIO.setup(GPIO_ECHO, GPIO.IN)
     
    def distance():
        # set Trigger to HIGH
        GPIO.output(GPIO_TRIGGER, True)
     
        # set Trigger after 0.01ms to LOW
        time.sleep(0.00001)
        GPIO.output(GPIO_TRIGGER, False)
     
        StartTime = time.time()
        StopTime = time.time()
     
        # save StartTime
        while GPIO.input(GPIO_ECHO) == 0:
            StartTime = time.time()
     
        # save time of arrival
        while GPIO.input(GPIO_ECHO) == 1:
            StopTime = time.time()
     
        # time difference between start and arrival
        TimeElapsed = StopTime - StartTime
        # multiply with the sonic speed (34300 cm/s)
        # and divide by 2, because there and back
        distance = (TimeElapsed * 34300) / 2
     
        return distance
     
    if __name__ == '__main__':
        try:
            while True:
                dist = distance()
                print ("Measured Distance = %.1f cm" % dist)
                time.sleep(1)
     
            # Reset by pressing CTRL + C
        except KeyboardInterrupt:
            print("Measurement stopped by User")
            GPIO.cleanup()