iqhtyar2k

SmartPhoneBot

Jan 21st, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import serial
  2. import pygame
  3. import speech_recognition as sr
  4.  
  5. # Buka port serial
  6. ser = serial.Serial("/dev/ttyUSB0", 9600)
  7.  
  8. # Deklarasi variabel
  9. kiri = 0
  10. kanan = 0
  11.  
  12. # Inisialisasi pygame
  13. pygame.init()
  14.  
  15. # Buat layar
  16. layar = pygame.display.set_mode((640, 480))
  17.  
  18. # Tampilkan gambar avatar gif
  19. gambar = pygame.image.load("avatar.gif")
  20.  
  21. # Loop utama
  22. while True:
  23.  
  24.     # Baca data dari serial port
  25.     data = ser.readline().decode("utf-8")
  26.  
  27.     # Jika data adalah "maju", gerakkan motor maju
  28.     if data == "maju":
  29.         kiri = 100
  30.         kanan = 100
  31.  
  32.     # Jika data adalah "mundur", gerakkan motor mundur
  33.     elif data == "mundur":
  34.         kiri = -100
  35.         kanan = -100
  36.  
  37.     # Jika data adalah "belok kiri", gerakkan motor kiri
  38.     elif data == "belok kiri":
  39.         kiri = 100
  40.         kanan = 0
  41.  
  42.     # Jika data adalah "belok kanan", gerakkan motor kanan
  43.     elif data == "stop":
  44.         kiri = 0
  45.         kanan = 0
  46.  
  47.     # Update layar
  48.     pygame.display.update()
  49.  
  50.     # Deteksi suara
  51.     recognizer = sr.Recognizer()
  52.     with sr.Microphone() as source:
  53.         audio = recognizer.listen(source)
  54.  
  55.     # Proses suara
  56.     try:
  57.         hasil = recognizer.recognize_google(audio)
  58.         print(hasil)
  59.  
  60.         # Kontrol robot dengan suara
  61.         if hasil == "maju":
  62.             kiri = 100
  63.             kanan = 100
  64.         elif hasil == "mundur":
  65.             kiri = -100
  66.             kanan = -100
  67.         elif hasil == "belok kiri":
  68.             kiri = 100
  69.             kanan = 0
  70.         elif hasil == "belok kanan":
  71.             kiri = 0
  72.             kanan = 100
  73.         elif hasil == "stop":
  74.             kiri = 0
  75.             kanan = 0
  76.  
  77.     except:
  78.         pass
  79.  
  80.     # Set kecepatan motor
  81.     ser.write(str(kiri) + " " + str(kanan) + "\n")
  82.  
  83.  
Add Comment
Please, Sign In to add comment