Project

General

Profile

Código e implementación » History » Version 11

Version 10 (Vranika Santiago, 12/14/2022 03:24 AM) → Version 11/18 (Vranika Santiago, 12/14/2022 03:29 AM)

*Índice:*
* [[Introducción]]
* [[Organización y planificación]]
* [[Análisis y diseño]]
* [[Código e implementación]]

---

h1. Código e implementación

---

{{collapse(Interfaz gráfica (GUI))
<pre><code class="python">
import tkinter as tk
from tkinter import ttk
from tkinter import *
import socket



#Ventana
ventana = tk.Tk()
ventana.config(width=900, height=700)
ventana.title("Interfaz -> Gorilla-Tank")
ventana.configure(bg="gray25")



#FUNCIONES
def Arriba(event= None):
clientSocket.send(bytes([ord('w')]))

def Abajo(event=None):
clientSocket.send(bytes([ord('s')]))

def Izquierda(event=None):
clientSocket.send(bytes([ord('a')]))

def Derecha(event=None):
clientSocket.send(bytes([ord('d')]))

def Disparar(event=None):
clientSocket.send(bytes([ord('p')]))

def Angulo():
if(opcion.get()=="45"):
clientSocket.send(bytes([ord('i')]))
elif(opcion.get() == "0"):
clientSocket.send(bytes([ord('o')]))

def Luciano():
clientSocket.send(bytes([ord('f')]))

def Distancia():
clientSocket.send(bytes([ord('m')]))
def on_realese(event):
print("click realese")
clientSocket.send(bytes([ord(' ')]))
def Cannon(event):
clientSocket.send(bytes([ord('l')]))

def getAddres():

w_ip = Tk()

w_ip.geometry("300x100")



dato = StringVar(w_ip)

w_ip.title("Configurar Ip")

ip = ttk.Entry(w_ip,textvariable=dato).place(x=10,y=10)

button = Button(w_ip,text =" Aplicar",command=lambda:[conectar(dato.get()),w_ip.destroy()]).place(x=170,y=9)

print(dato.get())

def conectar(adress):

port = 19999

try:

clientSocket.connect((adress,port))

messagebox.showinfo("Mensaje Servido","Cliente conectado al robot: {0} : {1}".format(adress,port))

except socket.error:

messagebox.showwarning("Conexión erronea","No se ha logrado al conexíon, verifique la Ip {0}".format(adress))

getAddres()

clientSocket.close()


#ETIQUETAS


img2 = tk.PhotoImage(file="gorilla.png")
lnl_img2 = tk.Label(ventana,image = img2, bg = "gray25").place(x=80,y=0)



#Angulo
img3 = tk.PhotoImage(file="Angulo.png")
lnl_img3 = tk.Label(ventana,image = img3,bg = "gray25").place(x=600,y=100)
opcion=StringVar()
angulo = Spinbox(ventana,state="readonly",values=("0","45"),textvariable=opcion).place(x=600,y=270)



boton_angulo = Button(ventana, text="Ingresar", command=Angulo,background = "gray25",fg="white",font=("Arial Black",10)).place(x=600, y=300)

img4 = tk.PhotoImage(file="ONOFF.png")
boton_salir = Button(ventana,image=img4, command=ventana.destroy,bg = "gray25").place(x=600, y=390)

img_boton_arri = tk.PhotoImage(file="Arriba.png")
boton_arriba = tk.Button(repeatdelay=50,repeatinterval=50,image=img_boton_arri,command=Arriba, background = "gray25")
boton_arriba.place(x=170, y=340)
boton_arriba.bind('<ButtonRelease-1>',on_realese)

img_boton_abaj = tk.PhotoImage(file="Abajo.png")
boton_abajo = tk.Button(repeatdelay=50,repeatinterval=50,image=img_boton_abaj,command=Abajo, background = "gray25")
boton_abajo.place(x=170, y=450)
boton_abajo.bind('<ButtonRelease-1>',on_realese)

img_boton_izq = tk.PhotoImage(file="Izquierda.png")
boton_izq = tk.Button(repeatdelay=50,repeatinterval=50,image=img_boton_izq,command=Izquierda, background = "gray25")
boton_izq.place(x=60, y=400)
boton_izq.bind('<ButtonRelease-1>',on_realese)

img_boton_derech = tk.PhotoImage(file="Derecha.png")
boton_derech = tk.Button(repeatdelay=50,repeatinterval=50,image=img_boton_derech,command=Derecha, background = "gray25")
boton_derech.place(x=280, y=400)
boton_derech.bind('<ButtonRelease-1>',on_realese)

ventana.mainloop()

</code></pre>

}}

{{collapse(Servidor)
<pre><code class="python">
import socket
from Function import *
s = socket.socket()
print("Socket creado")
port = 19999
s.bind( ("", port) )
print("El socket se creo con puerto:{}".format(port))
s.listen(5)
print("EL socket is listening....")
connect, addr = s.accept()
print("Se conecto a {}".format(addr))
while True:
rawByte = connect.recv(1)
char = rawByte.decode('utf-8')
if (char == 'w'):
moveUp()
if (char == 's'):
moveDown()
if (char == 'd'):
moveRight()
if (char == 'a'):
moveLeft()
if (char == 'p'):
Disparar()
if (char == 'f'):
Luciano()
if (char == 'i'):
Inclinacion45()
if (char == 'o'):
Inclinacion0()
if (char == ' '):
Stop()
if (char == 'm'):
Distancia()
if (char == 'l'):
StopCannon()
</code></pre>
}}

{{collapse(Movimientos del robot)
<pre><code class="python">
#!/usr/bin/env python3
from ev3dev2.motor import LargeMotor, MediumMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank
from ev3dev2.sensor import INPUT_1
from ev3dev2.sensor .lego import UltrasonicSensor
from ev3dev2.sound import Sound
from ev3dev2.led import Leds

motor_angle= LargeMotor(OUTPUT_A)
cannon = MediumMotor(OUTPUT_D)
sonido = Sound()
sensor = UltrasonicSensor(INPUT_1)
sensor.mode = "US-DIST-CM"
tankmoves = MoveTank(OUTPUT_B,OUTPUT_C)
print(sensor.value()/10)

def moveUp():
print("Moving up...")
tankmoves.on(SpeedPercent(100),SpeedPercent(100))
def moveDown():
print("Moving down...")
tankmoves.on(SpeedPercent(-100),SpeedPercent(-100))
def moveRight():
print("Moving right...")
tankmoves.on(SpeedPercent(100),SpeedPercent(-100))
def moveLeft():
print("Moving left...")
tankmoves.on(SpeedPercent(-100),SpeedPercent(100))
def Inclinacion0():
motor_angle.on_for_degrees(7,55,brake=True)
def Inclinacion45():
motor_angle.on_for_degrees(7,-55,brake=True)

def Disparar():
cannon.on(SpeedPercent(-100))
def Apuntar():
sensor.value #valor del sensor en milimetro

def Luciano():
sonido.speak("gorila tank mak two")
def Distancia():

while(sensor.value()/10 <= 100 or sensor.value()/10 >= 110):
print(sensor.value()/10)
if(sensor.value()/10 < 100):
tankmoves.on(SpeedPercent(-40),SpeedPercent(-40))

else:
tankmoves.on(SpeedPercent(40),SpeedPercent(40))
Stop()

def Stop():
tankmoves.stop()

def StopCannon():
cannon.stop()
sonido.play_file("misioncumplida.wav",100,1)

</code></pre>
}}