I need to set the resolution of a photo taken with SimpleCV using the result returned by a function, this would be the code:
def resolutionselection():
print"""
Ahora tenemos que escoger el formato y resolución de las fotos:
1 - 10x15.
2 - 15x20.
"""
answer = raw_input("→")
if answer == "1":
print("Has seleccionado hacer las fotos en 10x15.\n")
resolution = ['2304', '1536']
return resolution
elif answer == "2":
print("Has seleccionado hacer las fotos en 15x20.\n")
resolution = ['2048', '1536']
return resolution
else:
print("No estamos colaborando...")
exit(0)
px = resolutionselection()
cam = Camera(prop_set={'width':px[0], 'height':px[1]})
But it gives me error:
TypeError: Expected CvCapture for argument 'capture'
EDIT:
I'm posting the full code, to clarify:
# -- coding: utf-8 --
import time
from SimpleCV import Camera
import RPi.GPIO as GPIO
from sys import exit
sequence = 001 # Starts the sequence number for the photos.
event_name = "Event" # Indicates the name of the event, used in the filename of the photos.
kiosk = "./" # Without choosing, same folder as the program.
cam = Camera(prop_set={'width':2304, 'height':1536}) # Initializes the camera with HR 3:2 format.
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def kioskselection():
print"""
Primero, tenemos que escoger el Kiosco que va a imprimir:
1 - Kodak Wedding.
2 - Kodak Voyage.
"""
answer = raw_input("→\t")
if answer == "1":
print("Has seleccionado Kodak Wedding.\n")
kiosk = "/media/kodakwedding/"
return kiosk
elif answer == "2":
print("Has seleccionado Kodak Voyage. \n")
kiosk = "/media/kodakvoyage/"
return kiosk
else:
print("No estamos colaborando...")
exit(0)
def resolutionselection():
print"""
Ahora tenemos que escoger el formato y resolución de las fotos:
1 - 10x15.
2 - 15x20.
"""
answer = raw_input("→\t")
if answer == "1":
print("Has seleccionado hacer las fotos en 10x15.\n")
resolution = [2304, 1536]
print(resolution)
return resolution
elif answer == "2":
print("Has seleccionado hacer las fotos en 15x20.\n")
resolution = [2048, 1536]
return resolution
print(resolution)
else:
print("No estamos colaborando...")
exit(0)
kiosk = kioskselection()
px = resolutionselection()
cam = Camera(prop_set={'width':px[0], 'height':px[1]})
print("PUSH DA BUTTON!")
while True:
input_state = GPIO.input(17)
if input_state == False:
img = cam.getImage()
img.save("%s%s - %d.jpg" % (kiosk, event_name, sequence))
time.sleep(1)
print("Foto '%s - %d.jpg', guardada." % (event_name, sequence))
sequence += 1
Related
I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?
menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar facturacion del mes
(5) Listar todos los clientes
(6) Terminar
"""
lista_nom =[]
list_borra2 = []
ventas = []
while True:
print(menu)
opc = input("Escriba una opcion: ")
opc = int(opc)
if opc == 1:
nombre = input("Escribe el nombre del cliente: ")
cif = input('Escribe el cif de cliente: ')
direccion = input("Escribe el direccion de cliente: ")
lista_nom1 = (nombre,cif,direccion)
lista_nom.append(lista_nom1)
print(lista_nom)
#print(lista_nom1)mismo dato en tupla
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
for nombre in lista_nom[0]:
lista_nom.remove[(nombre)]
else:
print('No existe el cliente con el nombre', nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
I have tried to access the element with nested for but it simply does nothing.
try to create a new list to store the deleted data and then install it in the first list with the main values to be deleted
# list_borra2.append(nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
# lista_nom.remove(nombre)
# list_borra2 += lista_nom
# # print(list_borra2)
# print(list_borra2)
Instead of deleting an element, what is not possible inside of tuples, you could define a new tuple by doing
nom_remove = lista_nom[:nom] + lista_nom[(nom+1):]
At the end I resolved the problem with this, like the other guy tell me the tuples are immutable so I need to go inside the list and i can access to the tuple:
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
vivo = 0
for kilo in ventas:
vivo = ventas[kilo].count(nombre)
if vivo == 0:
for nom in range(len(lista_nom)):
if lista_nom[nom].count(nombre)>0:
del lista_nom[nom:nom+1]
print(lista_nom)
break
I'm creating a GUI and I had an issue. My GUI is supposed to get the user's ID and then show him a button to direct him to another window with some tutorials. If the user has already watched all the tutorials, an input box will appear asking if he wants to watch any tutorial again, if he refuses it (by typing "N") the window will be cleared for another user put his ID.
The code is working, but I noticed that when the user has already watched all tutorials and then refuses to watch again, if the next user has already watched all tutorials too the code doesn't work.
Notice that the input box clears it self, when it was supposed to make the same thing it did in the first picture.
Some curious fact is that if i put the ID of some user that didn't finish the tutorials, it will work fine. And if I put the ID of someone who finished, after puting the ID of someone who didn't, it will work again.
Here is the code, could somone help me?
import pandas as pd
import os
import PySimpleGUI as sg
from window3 import window3
from window2 import window2
from window4 import window4
users_path = r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\Users.csv"
watched_videos_path = r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\watched_videos.csv"
# caminho para a pasta dos videos da 111
path_111 = "D:\\Users\\raulc\\Documents\\AMBIENTES\\videos\\111"
# caminho para a pasta dos videos da 113
path_113 = "D:\\Users\\raulc\\Documents\\AMBIENTES\\videos\\113"
# variavel que armazena o nome dos arquivos que estao na 111
p111 = os.listdir(path_111)
# variavel que armazena o nome dos arquivos que estao na 113
p113 = os.listdir(path_113)
# verifica se o usuario ja esta registrado no banco de dados
def is_registered(ID): #OK
df = read_any_csv(users_path)
x = df.loc[df["ID"] == ID]
if x.empty:
return False
else:
return True
# faz o cadastro do usuario
def register(ID,name,section): # OK
global users_df # need it to add to external variable
# com esse "global" nao precisa ler o csv de novo
data = pd.DataFrame({'NAME': [name], 'ID': [ID], 'SECTION': [section]})
users_df = pd.concat([users_df, data]) # <-- add to original `users_df`
users_df.to_csv(r"D:\Users\raulc\Documents\AMBIENTES\TESTE\21 - Ilha de treinamento\Users.csv", index=False)
# mostrar os videos ja assistidos
def already_watched(ID): #OK
df = read_any_csv(watched_videos_path)
videos = df.loc[df["ID"] == ID,"LINK"]
return videos
# retorna os links que nao foram assistidos ainda
def videos_to_watch(section,ID): #OK
list_already_watched = already_watched(ID).tolist()
if section == 111:
list_to_watch = set(p111)-set(list_already_watched)
elif section == 113:
list_to_watch = set(p113)-set(list_already_watched)
elif section == 000:
list_to_watch = []
return list(list_to_watch)
# retorna setor do usuario
def current_user_section(df,ID):
current_user = df.loc[df["ID"] == ID]
section = int(current_user["SECTION"])
return section
# retorna se a lista de videos a serem assistidos esta vazia ou nao
def is_list_empty(list,section,ID):
list = videos_to_watch(section,ID)
length = len(list)
if length == 0:
return True
else:
return False
# retorna o nome do usuario
def current_user_name(df,ID):
current_user = df.loc[df["ID"] == ID]
name = current_user["NAME"].to_string(index = False)
return name
# retorna os dados do usuario -> nao da para ser essa funcao direto, pois ai o python nao consegue converte o section para int
def current_user_data(df,ID):
name = current_user_name(df,ID)
section = current_user_section(df,ID)
return name,section
# faz a funcao read_csv do pandas
def read_any_csv(path): #OK
df = pd.read_csv(path)
return df
def window():
global users_df
# Definindo o fundo da tela como preto
sg.theme('Black')
# Declarando o logo da mercedes
myImg = sg.Image(filename='logo_meca_pret.png',size=(200,200))
# Declarando os outputs
output = sg.Text(font=("Arial",20),key="output")
output2 = sg.Text(font=("Arial",20),key="output2")
output3 = sg.Text(font=("Arial",20),key="output3")
layout = [
[myImg,sg.Text('PROGRAMA DE TREINAMENTOS',font=("Arial",60),justification="center")],
[sg.Text("Passe o cracha no leitor: ",font=("Arial",20)),sg.InputText(size=(60),key="ID")],
[sg.Text("Escreva seu nome: ",font=("Arial",20),visible=False,key="NAMETEXT"),sg.InputText(size=(60),visible=False,key="NAME")],
[sg.Text("Digite seu setor(111/112/113): ",font=("Arial",20),visible=False,key="SECTIONTEXT"),sg.Input(size=(5),visible=False,key="SECTION")],
[sg.Button('SubmitData', visible=False)],
[output],
[output2],
[output3,sg.InputText(size=(1),key="w_a",visible=False)],
[sg.Text("CLIQUE AQUI E FECHE A JANELA",font=("Arial",20),visible=False,key="BOTAOERROR1"),sg.Text("CLIQUE NO BOTAO PARA ABRIR AS TELAS DOS TUTORIAIS",font=("Arial",20),visible=False,key="BOTAOW3"),sg.Button("W3",visible=False)],
[sg.Text("CLIQUE NO BOTAO PARA ASSISTIR ALGUM TUTORIAL NOVAMENTE",font=("Arial",20),visible=False,key="BOTAOW5"),sg.Button("W5",size=(5),visible=False)],
[sg.Button('Submit', visible=False, bind_return_key=True)],
#[sg.Button("ERROR1",visible=False)],
]
window = sg.Window('PROGRAMA DE TREINAMENTOS MERCEDES BENZ', layout,element_justification="center").Finalize()
window.Maximize()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
#print('You entered ', values[0])
if event == 'Submit':
ID = values["ID"]
ID = ID.upper()
if is_registered(ID) == True:
if ID == "X":
name,section = current_user_data(users_df,ID)
window["BOTAOERROR1"].update(visible=True)
#window["ERROR1"].update(visible=True)
window["W3"].update(visible=True)
else:
name,section = current_user_data(users_df,ID)
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section,ID)
if is_list_empty(videos,section,ID) == True:
output2.update("Nao ha novos tutoriais disponiveis.")
output3.update("Deseja assistir algum tutorial novamente (S/N)?")
window['w_a'].update(visible = True)
w_a = values["w_a"]
if w_a == "s" or w_a == "S":
# abre a tela com todos os tutoriais da pasta daquela secao
window2(ID,section)
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window.find_element("w_a").update("")
window['w_a'].update(visible = False)
if w_a == "n" or w_a == "N":
# usa esses comandos para limpar a tela, para que um novo usuario use
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window['w_a'].update(visible = False) # deixa o input do w_a invisivel de novo
else:
# se tiverem videos a serem assistidos abrir a WINDOW3
window["BOTAOW3"].update(visible = True)
window["W3"].update(visible = True)
if section == 113:
folder = p113
elif section == 111:
folder = p111
if len(videos_to_watch(section,ID)) != len(folder):
window["BOTAOW5"].update(visible = True)
window["W5"].update(visible=True)
else:
window["NAMETEXT"].update(visible = True)
window["NAME"].update(visible = True)
window["SECTIONTEXT"].update(visible = True)
window["SECTION"].update(visible = True)
window["SubmitData"].update(visible = True)
if event == "W5":
window2(ID,section)
# if event == "ERROR1":
# window3(ID,section)
# window.find_element("ID").update("")
# window['BOTAOERROR1'].update(visible=False)
# window['ERROR1'].update(visible=False)
if event == 'SubmitData' :
name = values["NAME"]
name = name.title()
section = values["SECTION"]
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
register(ID,name,section)
users_df = pd.read_csv(users_path)
window["BOTAOW3"].update(visible = True)
window["W3"].update(visible = True)
if event == "W3":
window3(ID,section)
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window.find_element("w_a").update("")
window["W3"].update(visible = False)
window["BOTAOW3"].update(visible = False)
window["NAME"].update(visible = False)
window["SECTION"].update(visible = False)
window["NAMETEXT"].update(visible = False)
window["SECTIONTEXT"].update(visible = False)
window["SubmitData"].update(visible = False)
window["W5"].update(visible = False)
window["BOTAOW5"].update(visible = False)
window["BOTAOERROR1"].update(visible=False)
window.close()
users_df = pd.read_csv(users_path)
watched_videos_df = pd.read_csv(watched_videos_path)
window()
I'm trying to make a graphic novelwith Object-oriented programming.
Actually, I'm focused on the battle part.
For some reason, the part where it's suppose to print a specific line it does not work, it would pass without doing anything, or I would get an error.
#Error:
Traceback (most recent call last):
File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 128, in <module>
batalla_f1()
File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 94, in batalla_f1
monstruo_escogido.frase_entre_atzar(7,9)
File "C:\Users\Ester\Desktop\Mercy or kill\mercy_kill_classes.py", line 51, in frase_entre_atzar
entre_atzar = self.frases.random.randrange (a,b)
AttributeError: 'list' object has no attribute 'random'
#Code:
Drah_krow=Personaje("Drah Krow","monstruo",12,12,5,1,1)
Drah_krow.mostrar_todo()
Drah_krow.afegeix_frase("Señor de mediana edad con un cuchillo clavado bajo el cuello... Parece desorientado.")
Drah_krow.afegeix_frase("Drah Krow- Echo de menos a alguien...")
Drah_krow.afegeix_frase("Drah Krow- ¿Quien era? ¿Eras tú?.")
Drah_krow.afegeix_frase("Drah Krow- Mi jefe me ordena cosas extrañas...")
Drah_krow.afegeix_frase("Drah Krow- Quiere que te mate...")
Drah_krow.afegeix_frase("Drah Krow- Oh, ya me acordé...¿Dondè estarà mi hija?")
Drah_krow.afegeix_frase("Drah Krow- Me siento tan perdido que podría morir...")
Drah_krow.afegeix_frase("Drah Krow- Me gustaria ir a la playa con el... ¿O era ella?")
Drah_krow.afegeix_frase("Drah Krow- ¿Me conoces?")
Drah_krow.afegeix_frase("Drah Krow- No se donde estoy...")
Drah_krow.mostra_frases()
prota = Humano("Prota")
def batalla_f1():
Drah_krow=Personaje("Drah Krow","fantasma",20,1,0)
monstruo_escogido=Drah_krow
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
print("")
z=0
d=0
q=0
inici_hp = prota.hp
inicim_hp = monstruo_escogido.hp
while not((prota.hp<=0) or (monstruo_escogido.hp<=0)):
print("Es tu turno:")
z=z+1
i = input("1.atacar 2.defender 3.Comprender")
if(i=="1"):
print("Tu- Atacas:")
a = (prota.atk - monstruo_escogido.defe)
if (prota.atk < monstruo_escogido.defe): # Ataque del prota es mas pequeño que la defensa del monstruo = anular ataque del prota
a = 0
if (a > monstruo_escogido.hp): # Vida del monstruo = 0 (Evitar numeros negativos en la vida del monstruo)
a = monstruo_escogido.hp
print ("Haces",a," de daño.")
monstruo_escogido.hp = (monstruo_escogido.hp-a)
print("La vida del mosntruo se reduce a",monstruo_escogido.hp)
d=d+1
prota.mostrar_todo()
monstruo_escogido.mostrar_todo()
elif(i=="2"):
print ("prota defiende")
a= random.randrange(5,50)
if(prota.hp == inici_hp):
print("Tu hp ya está al máximo.")
elif (prota.hp < inici_hp):
print (a)
if((a+prota.hp)> inici_hp):#si la suma del hp mas lo que se cura es mas grande que el hp original:
aa=(inici_hp -(a+prota.hp)) #restas el nuevo hp - hp original
prota.hp = inici_hp
print ("Te curas:",aa,"hp")
print("Tu hp sube a",prota.hp)
print("")
elif((a+prota.hp)<inici_hp):
print ("Te curas",a,"hp")
prota.hp = (prota.hp + a)
print("Tu hp sube a",prota.hp)
print("")
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
elif(i=="3"):
print("Prota actua:")
a=input("1.Observar 2.Hablar 3.Llorar")
if(a=="1"):
print("Tu- Observas detalladamente:")
monstruo_escogido.digues_frase_concreta(0)
elif(a=="2"):
print("Tu- Le dice que no quieres pelear...")
if((z==0) and (d==0)):
monstruo_escogido.digues_frase_concreta(1)
if((z==0) and (d!=0)):
monstruo_escogido.digues_frase_concreta(3)
if((z==2) and (d==0)):
monstruo_escogido.digues_frase_concreta(2)
q=1
if((z==2) and (d!=0)):
monstruo_escogido.digues_frase_concreta(4)
elif((z!=0) or (z!=2)):
monstruo_escogido.frase_entre_atzar(7,9)
if(q==1):
monstruo_escogido.digues_frase_concreta(5)
elif(a=="3"):
print ("Drah Krow parece confundido...")
prota.incrementa_hp(5)
print ("Te recuperas por 5 hp.")
if not((prota.hp<=0) or (monstruo_escogido.hp<=0) or (q==1)):
print("")
print("Es el turno del monstruo:")
print("")
print("Monstruo ataca:")
b= (monstruo_escogido.atk - prota.defe)#Daño real producido al final
if (monstruo_escogido.atk < prota.defe ): # Anular ataque del monstruo
b = 0
if (b > prota.hp):
b = prota.hp
print ("Monstruo hace",b," de daño.")
prota.hp = (prota.hp-b)
print("")
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
print ("")
if (prota.hp >0):
print ("Tu ganas.")
prota.kill =(prota.kill+1)
elif (q==1):
print ("Drah Krow parece volver un poco en si.")
print ("Drak Krow desaparece tras un destello de luz blanca.")
prota.mercy = (prota.mercy +1)
elif(prota.hp == 0):
print("Game Over")
batalla_f1()
#Class:
import random
class Personaje():
def __init__(self, nom, especie="desconeguda", hp=0, atk=0, defe=0,mercy=0, kill=0):
self.nom= nom
self.especie= especie
self.hp = hp
self.atk = atk
self.defe = defe
self.mercy=mercy
self.kill=kill
self.frases=[]
def mostrar_todo(self): #mostra tots els atributs d'un personatge excepte frases
print("Nom: ", self.nom)
print("Especie:", self.especie)
print("Hp:",self.hp)
print("Atk:",self.atk)
print("Def:",self.defe)
def mostrar_todo_prota(self):
print("Nom: ", self.nom)
print("Especie:", self.especie)
print("Hp:",self.hp)
print("Atk:",self.atk)
print("Def:",self.defe)
print("Mercy:",self.mercy)
print("Kill:",self.kill)
def incrementa_hp(self, quantitat): #mètodes per incrementar els diferents atributs
self.hp = self.hp + quantitat
def incrementa_atk(self, quantitat):
self.atk = self.atk + quantitat
def incrementa_defe(self, quantitat):
self.defe = self.defe+ quantitat
def incrementa_mercy(self, quantitat):
self.mercy = self.mercy + quantitat
def incrementa_kill(self, quantitat):
self.kill = self.kill + quantitat
def afegeix_frase(self, frase): #mètode per afegir frases a la llista del personatge en concret
self.frases.append(frase)
def mostra_frases(self): #mètode per mostrar totes les frases del personatge
for frase in self.frases:
print(frase)
def digues_frase(self): #dir una frase de la llista a l'atzar
if (len(self.frases)!= 0):
frase = random.choice(self.frases)
else:
frase= ("...")
print(frase)
def digues_frase_concreta(self, ordre):
if(ordre<(len(self.frases))):
print(self.frases[ordre])
def frase_entre_atzar(self,a,b):
entre_atzar = self.frases.random.randrange (a,b)
print (entre_atzar)
def ataca(self,oponent):
print(self.nom,"ATACA A", oponent.nom)
if (self.atk > oponent.defe):
oponent.hp = (oponent.hp-1)
print("Li has fet mal a", oponent.nom)
else:
print("No li has fet mal a", oponent.nom)
class Humano(Personaje):
def __init__(self, nom):
super().__init__(nom) #hereda el nom de la classe Personatge
self.especie="humano" #fixa els atributs propis de la classe Humano
self.hp=30
self.atk=15
self.defe=15
self.mercy=0
self.kill=0
class Bestia(Personaje):
def __init__(self, nom):
super().__init__(nom)
self.especie="bestia"
self.hp=15
self.atk=30
self.defe=15
self.mercy=0
self.kill=0
class DemiHumano(Personaje):
def __init__(self, nom):
super().__init__(nom)
self.especie="demi-humano"
self.hp=15
self.atk=15
self.defe=30
self.mercy=0
self.kill=0
I can't understand why it wok the part of "1.atacar 2.defender", but not the part of "3.Comprender".
Could you help me, please?
Also, Do you know any way to count the turns while the battle is going on, to say a different phrase each time the loop is restarted before one of the two characters dies?
(Sorry if some parts are in Spanish, if there something you don't understand, feel free to ask.)
As the error message states, here's the line giving you error:
entre_atzar = self.frases.random.randrange (a,b)
random is not a data member of the the class of which frases is a member (which appears to a list) so you cannot use the dot operator to call a data member of the class that simply doesn't exist.
Normally, random.randrange(a,b) will return a random number in the range between a and b.
So you have two options:
1) Get a number in a random range between a and b and then use that get the value at that index in the list:
entre_atzar = self.frases[random.randrange(a,b)]
2) Simply get a random value from a sub-list of the original list in that range:
entre_atzar = random.choice(self.frases[a:b])
I recommend the latter method, since I consider it to be cleaner and more intuitive, but both will yield the same result.
I am trying to measure a distance with ultrasonic sensor and everything looks well but when I leave the program for a some minutes (3-4 minutes) working, the program stops the measure of distance.
I need that the program dont stops because I need it to a security alarm. The program collects every one second a distance and show it in scree. But if distance is more than 10, the program shows a alert message and dont show the distance until it is less of 10. Following you can see the code:
import time
import RPi.GPIO as GPIO
# Usamos la referencia BOARD para los pines GPIO
GPIO.setmode(GPIO.BOARD)
# Definimos los pines que vamos a usar
GPIO_TRIGGER = 11
GPIO_ECHO = 13
GPIO_LED = 15
# Configuramos los pines como entradas y salidas
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
GPIO.setup(GPIO_LED ,GPIO.OUT) #Led
# -----------------------
# Definimos algunas funciones
# -----------------------
def medida():
# Esta funcion mide una distancia
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
elapsed = stop-start
distancia = (elapsed * 34300)/2
return distancia
def media_distancia():
# Esta funcion recoge 3 medidas
# y devuelve la media de las 3.
distancia1=medida()
time.sleep(0.1)
distancia2=medida()
time.sleep(0.1)
distancia3=medida()
distancia = distancia1 + distancia2 + distancia3
distancia = distancia / 3
return distancia
# -----------------------
# Programa principal
# -----------------------
print ("Medida con sensor de ultrasonidos")
# Ponemos el Trigger en falso (low)
GPIO.output(GPIO_TRIGGER, False)
# Ponemos el Led en falso (low)
GPIO.output(GPIO_LED, False)
# Metemos el bloque principal en un Try para asi poder
# comprobar si el usuario presiona Ctrl + C
# y poder ejecutar una limpieza del GPIO, esto tambien
# evita el usuario tener que ver muchos mensajes de error
try:
while True: # Este bucle se repite siempre
# Lo primero que hago es medir la distancia
distancia = media_distancia()
# Compruebo si la distancia es menor que 10
# Si es menor que 10 muestro la distancia por pantalla
if distancia < 10:
distancia = media_distancia() # Medidos la distancia
print ("Distancia: %.1f" % distancia, " - " , "Fecha:", time.strftime("%c")) # Mostramos la distancia por pantalla
GPIO.output(GPIO_LED, False)
time.sleep(1) # Esperamos 1 segundo
distancia = media_distancia()
a = 0 # Utilizo la variable a para poder para el proceso mas adelante
# Pregunto si la variable a es igual a 1
# Si lo es no hago nada y repito el if anterior
if a == 1:
pass
# Pero si no es 1 le asigno el valor 0
# Para poder seguir con el IF siguiente
else:
a = 0
if distancia > 10 and a == 0: # Si la distancia es mayor que 10cms
print ("La distancia es mayor de 10 cms. Alarma activada!!", " - ", "Fecha:", time.strftime("%c")) # Se interrumpe el bucle y se muestra un aviso
GPIO.output(GPIO_LED, True)
a = 1 # Pongo la variable en 1 para parar el proceso y que no se repita
distancia = media_distancia() # Seguimos midiento la distancia
while distancia < 10: # Pero si la distancia vuelve a ser menor de 10
break # Se termina este bucle y volvemos al principio nuevamente
except KeyboardInterrupt: # Si el usuario presiona crtl + C
# Limpiamos los pines GPIO y salimos del programa
print ("Apagando LED")
time.sleep(1)
GPIO.output(GPIO_LED, False)
print ("Limpiando GPIO")
GPIO.cleanup()
print ("GPIO limpio")
print ("Saliendo...")
time.sleep(1)
Why does the program stops after some minutes?
In your function medida(): you are triggering the sensor using:
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
Then waiting that the ECHO sets to 0 to start counting time and finally waiting the ECHO to set to 1 to stop counting time
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
Now imagine that any of this two transitions doesn't happen:
maybe the ECHO never gets to 1 because there's no ECHO returned at all (no object, misbehavior of the sensor, misconnection...)
or maybe the ECHO is already 1 when you wait for it to get to 0 (you are doing a time.sleep(0.00001) after the rising edge of TRIGGER. In this time maybe the ECHO already gets to 0 in some cases...
If any of this two things happen, your program will wait forever, which is probably what is happening.
You should include a timeout in your loops, so if thins "hang" you can call the function to trigger the sensor again.
My best guest is that there is an exception somewhere on your code. Please, try this version and add an example of the output:
import time
import RPi.GPIO as GPIO
# Usamos la referencia BOARD para los pines GPIO
GPIO.setmode(GPIO.BOARD)
# Definimos los pines que vamos a usar
GPIO_TRIGGER = 11
GPIO_ECHO = 13
GPIO_LED = 15
# Configuramos los pines como entradas y salidas
GPIO.setup(GPIO_TRIGGER,GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN) # Echo
GPIO.setup(GPIO_LED ,GPIO.OUT) #Led
# -----------------------
# Definimos algunas funciones
# -----------------------
def medida():
# Esta funcion mide una distancia
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
elapsed = stop-start
distancia = (elapsed * 34300)/2
return distancia
def media_distancia():
# Esta funcion recoge 3 medidas
# y devuelve la media de las 3.
distancia1=medida()
time.sleep(0.1)
distancia2=medida()
time.sleep(0.1)
distancia3=medida()
distancia = distancia1 + distancia2 + distancia3
distancia = distancia / 3
return distancia
# -----------------------
# Programa principal
# -----------------------
print ("Medida con sensor de ultrasonidos")
# Ponemos el Trigger en falso (low)
GPIO.output(GPIO_TRIGGER, False)
# Ponemos el Led en falso (low)
GPIO.output(GPIO_LED, False)
# Metemos el bloque principal en un Try para asi poder
# comprobar si el usuario presiona Ctrl + C
# y poder ejecutar una limpieza del GPIO, esto tambien
# evita el usuario tener que ver muchos mensajes de error
continuar = True
while continuar: # Este bucle se repite siempre
try:
# Lo primero que hago es medir la distancia
distancia = media_distancia()
# Compruebo si la distancia es menor que 10
# Si es menor que 10 muestro la distancia por pantalla
if distancia < 10:
distancia = media_distancia() # Medidos la distancia
print ("Distancia: %.1f" % distancia, " - " , "Fecha:", time.strftime("%c")) # Mostramos la distancia por pantalla
GPIO.output(GPIO_LED, False)
time.sleep(1) # Esperamos 1 segundo
distancia = media_distancia()
a = 0 # Utilizo la variable a para poder para el proceso mas adelante
# Pregunto si la variable a es igual a 1
# Si lo es no hago nada y repito el if anterior
if a == 1:
pass
# Pero si no es 1 le asigno el valor 0
# Para poder seguir con el IF siguiente
else:
a = 0
if distancia > 10 and a == 0: # Si la distancia es mayor que 10cms
print ("La distancia es mayor de 10 cms. Alarma activada!!", " - ", "Fecha:", time.strftime("%c")) # Se interrumpe el bucle y se muestra un aviso
GPIO.output(GPIO_LED, True)
a = 1 # Pongo la variable en 1 para parar el proceso y que no se repita
distancia = media_distancia() # Seguimos midiento la distancia
while distancia < 10: # Pero si la distancia vuelve a ser menor de 10
break # Se termina este bucle y volvemos al principio nuevamente
except KeyboardInterrupt: # Si el usuario presiona crtl + C
continuar = False
except (Exception) as error:
print (str(error))
# Limpiamos los pines GPIO y salimos del programa
print ("Apagando LED")
time.sleep(1)
GPIO.output(GPIO_LED, False)
print ("Limpiando GPIO")
GPIO.cleanup()
print ("GPIO limpio")
print ("Saliendo...")
time.sleep(1)
The correct way to find the reason of such is simple USE A LOGGER!
without blackbox you will hardly find the reason why your place crash!!
python has one ready to use, check the doc
import the logger module:
import logging
configure it to create a file...
logging.basicConfig(filename='example.log',level=logging.DEBUG)
and begging to log on every spot you find suspicious
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
I'm fairly new to python, and I'm with some problems with encoding.
Please see the code:
# -*- coding: utf-8 -*-
import config # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
import feedparser
class TwitterC:
def logToDatabase(self, tweet, timestamp):
# Will log to the database
database = sqlite3.connect('database.db') # Create a database file
cursor = database.cursor() # Create a cursor
cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
# Assign the values for the insert into
msg_ins = tweet
timestamp_ins = timestamp
values = [msg_ins, timestamp_ins]
# Insert data into the table
cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
database.commit() # Save our changes
database.close() # Close the connection to the database
def shortUrl(self, url):
bit = bitly_api.Connection(config.bitly_username, config.bitly_key) # Instanciar a API
return bit.shorten(url) # Encurtar o URL
def updateTwitterStatus(self, update):
short = self.shortUrl(update["url"]) # Vou encurtar o URL
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
# I will see how much characters have the message, if more than 140, delete some chars
length_message = len(update_str)
if length_message > 140:
length_url = len(short['url'])
count_message = 136 - length_url
shorten_msg = update["msg"][0:count_message] + '... '
update_str = shorten_msg + short['url']
# Will post to twitter and print the posted text
api = twitter.Api(consumer_key=config.consumer_key,
consumer_secret=config.consumer_secret,
access_token_key=config.access_token_key,
access_token_secret=config.access_token_secret)
status = api.PostUpdate(update_str) # Fazer o update
msg = status.text # Vou gravar o texto enviado para a variavel 'msg'
# Vou gravar p a Base de Dados
self.logToDatabase(msg, time.time())
print msg # So p mostrar o texto enviado. Comentar esta linha de futuro.
# Exemplo base
#x = TwitterC()
#x.updateTwitterStatus({"url": "http://xyz.com/?cat=28", "msg": "Some tips about PostgreSQL Administration?"})
# Solucao para um misto de feeds e frases feitas
# Vou escolher uma fonte ao acaso
p = range(2) # tem o 0 e o 1
p = random.choice(p)
if p == 0: # Escolhe TEXT UPDATES
# Vou escolher um text update ao acaso
text_a_enviar = random.choice(config.text_updates)
update_to_send = text_a_enviar
elif p == 1: # Escolhe FEEDS UPDATES
'''# Vou escolher um feed ao acaso
feed_a_enviar = random.choice(config.feeds_updates)
# Vou apanhar o conteudo do feed
d = feedparser.parse(feed_a_enviar["feedurl"])
# Vou definir quantos feeds quero ter no i
i = range(8)
# Vou meter para "updates" 10 entradas do feed
updates = []
for i in range(8):
updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].summary + ", "}])
# Vou escolher ums entrada ao acaso
update_to_send = random.choice(updates)'''
# Vou postar p o Twitter
x = TwitterC()
x.updateTwitterStatus({"url": "http://xyz.com/", "msg": "favoritos à distancia"})
The code have some lines but the problem is in this line:
x.updateTwitterStatus({"url": "http://xyz.com/", "msg": "favoritos à distancia"})
This line have a character with an accent "à" and this causes the problem here:
def updateTwitterStatus(self, update):
short = self.shortUrl(update["url"]) # Vou encurtar o URL
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
...
More precisely in this line:
update_str = update["msg"] + " " + short['url'] # Mensagem em bruto, sem tratamento de contagem de caracteres
The output of the error is this:
x.updateTwitterStatus({"url": "http://xyz.com", "msg": "favoritos à distancia"})
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 48: ordinal not in range(128)
Any clues on how to solve this?
Try adding from __future__ import unicode_literals at the top if your file. Alternatively you can prefix every string with a ´u´, ie u"favoritos à distancia"
Make sure your file is actually saved as utf-8 too!