Hello,
I wrote a code that send UDP,print to terminal \ save to log file whenever I press a button on PI,
and when I press ENTER in the terminal it exit the code.
the code is working - but I can't seem to understand the logic - hope you can help me with this
this is the code:
2. I cant seem to understand this line
3. why the code is in loop? (it's a good thing - but I don;t understand why)
4. why does only "Enter" exit the program ?
5. how does callback work ?
6. what does this line do? what is channel ?
Thanks ,
I wrote a code that send UDP,print to terminal \ save to log file whenever I press a button on PI,
and when I press ENTER in the terminal it exit the code.
the code is working - but I can't seem to understand the logic - hope you can help me with this
this is the code:
import socket #Import udp library import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library import json # import json read\write library import time # import get time option library import logging # import make log option library def button_callback(channel): print("Button was pushed!") CurrentTime = str(time.ctime()) MESSAGE = (CurrentTime + " :User " +str(data['user']) + " -- " + str(data['ID'])) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT)) print (MESSAGE) logging.basicConfig(filename='/home/pi/Desktop/message.log',level=logging.DEBUG) logging.debug(MESSAGE) time.sleep(1) ## - I'm reading this part only 1 time at the startup of the code with open('/home/pi/Documents/config.json') as json_file: data = json.load(json_file) print("user is " + str(data['user']) ) print ("ID is " + str(data['id'])) ## setting of UDP UDP_IP = "10.0.0.51" UDP_PORT = 9051 ## the main code ? GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # pin 10 to be an input pin and set initial value to be pulled low (off) GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge message = input("Press enter to quit\n\n") # Run until someone presses enter GPIO.cleanup() # Clean up1. it the code writting in the correct way? do I need to change the order of the setting?
2. I cant seem to understand this line
GPIO.add_event_detect(10,GPIO.RISING,callback=button_callbackhow does it works?
3. why the code is in loop? (it's a good thing - but I don;t understand why)
4. why does only "Enter" exit the program ?
5. how does callback work ?
6. what does this line do? what is channel ?
def button_callback(channel):is it like a sub function to the main?
Thanks ,