0

I am trying to send a 4-digit number, that is a result of two HC-SR04 sensors'measured distance, through UDP and according to almost every command and wireshark on my computer, the Raspberry isn't sending anything. Any idea why that is?

Here's the code I am using:

#Libraries
import RPi.GPIO as GPIO
import time
import math
import socket

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 2
GPIO_ECHO = 3

GPIO_TRIGGER2 = 5
GPIO_ECHO2 = 4

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

GPIO.setup(GPIO_TRIGGER2, GPIO.OUT)
GPIO.setup(GPIO_ECHO2, 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

    distance = math.floor((TimeElapsed * 34300) / 2)

    return distance

def distance2():

    time.sleep(0.003)
    GPIO.output(GPIO_TRIGGER2, True)
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER2, False)
    StartTime = time.time()
    StopTime = time.time()
    while GPIO.input(GPIO_ECHO2) == 0:
    StartTime2 = time.time()

while GPIO.input(GPIO_ECHO2) == 1:
    StopTime2 = time.time()

TimeElapsed2 = StopTime2 - StartTime2
distance2 =math.floor((TimeElapsed2 * 34300) / 2)
return distance2

UDP_IP = "192.168.0.107"
UDP_PORT = 8083
while True:
    dist = distance()
    dist2 = distance2()
    data = (dist*100)+dist2
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.sendto(str(data),(UDP_IP, UDP_PORT))
    time.sleep(0.2)

The Rasp Pi can ping the PC and has internet connection. It is also a fresh install, so shouldn't be a problem with the OS...

  • 1
    In Python indentation matters. Is the code you posted really formatted like this? The function distance2() seems to be broken due to the indentation. Also you should not open a new socket in every iteration of the while loop. – oh.dae.su Jun 3 at 10:10
  • No, I messed it up when transferring. Fixed the socket and the loop, still nothing. – Random41 Jun 3 at 10:42
  • Did you check, if you are stuck in one of your distance functions? – oh.dae.su Jun 3 at 11:00
  • I did put a print in the while loop and it did print until I stopped it – Random41 Jun 3 at 11:01
  • Are you sure you have the correct ip for your computer? And have you tried running as root user with sudo? – Mohammad Ali Jun 3 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.