Uncategorized

RPI Servo – Raspberry Pi Forums


Ok my first Idea wasn’t right!. this is a socket problem.

First you could emulate your voice command using telnet or putty in raw mode.

SocketServo.jpeg
SocketServo.jpeg (86.57 KiB) Viewed 12 times

N.B. To escape from telnet CTRL + ] then type close

I cleanup a little your code

Code: Select all

import time
import RPi.GPIO as GPIO
import socket

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
servo_pin = 3  # Change this to the GPIO pin connected to the servo
GPIO.setup(servo_pin, GPIO.OUT)
servo = GPIO.PWM(servo_pin, 50)  # PWM frequency = 50 Hz
servo.start(0)

def move_servo(angle):
    print("Move to angle", angle)
    duty_cycle = (angle / 18) + 2
    GPIO.output(servo_pin, True)
    servo.ChangeDutyCycle(duty_cycle)
    time.sleep(1)
    GPIO.output(servo_pin, False)
    servo.ChangeDutyCycle(0)

def voice_control():
    global server_socket
    runFlag=True;
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    server_socket.bind(('0.0.0.0', 12345))  # Choose a port
    server_socket.listen(1)

    print("Waiting for connection...")
    client_socket, client_address = server_socket.accept()
    print(f"Connection from {client_address}")


    with client_socket:
        while True:
                data = client_socket.recv(1024).decode('utf-8')
                if not data:
                    break

                print("Received command:", data)

                if "stop" in data.lower():
                    runFlag=False
                    break
                elif "move" in data.lower():
                    try:
                        angle = int(data.split()[-2])
                        move_servo(angle)
                    except ValueError:
                        print("Invalid angle value")
        server_socket.shutdown(socket.SHUT_WR )
        server_socket.close()
        server_socket=None
    return runFlag



if __name__ == "__main__":
    try:
      while voice_control():
          pass
    except KeyboardInterrupt:
        if server_socket!= None:
            server_socket.shutdown(socket.SHUT_WR)
            server_socket.close()
    finally:
        GPIO.cleanup()



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *