Home > database >  Need to take the whole python code into a function that can be access from another python file
Need to take the whole python code into a function that can be access from another python file

Time:06-08

import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time


def privacyfunc():

    # Pin Definitions:
    led_pin_1 = 7
    led_pin_2 = 21
    but_pin = 18

# blink LED 2 quickly 5 times when button pressed
def blink(channel):
    x=GPIO.input(18)
    print("blinked")
    for i in range(1):
        GPIO.output(led_pin_2, GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(led_pin_2, GPIO.LOW)
        time.sleep(0.5)
    mqttBroker="mqtt.fluux.io"#connect mqtt broker
    client=mqtt.Client("privacybtn") #create a client and give a name
    client.connect_async(mqttBroker)#from the client -connect broker

    while True:

        client.publish("privacy", x)#publish this random number to the topic called temparature
        print("Just published" str(x) "to Topc to privacy")#just print random no to topic temparature
        break

def main():
    # Pin Setup:
    GPIO.setmode(GPIO.BOARD)  # BOARD pin-numbering scheme
    GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT)  # LED pins set as output
    GPIO.setup(but_pin, GPIO.IN)  # button pin set as input

    # Initial state for LEDs:
    GPIO.output(led_pin_1, GPIO.LOW)
    GPIO.output(led_pin_2, GPIO.LOW)

    GPIO.add_event_detect(but_pin, GPIO.FALLING, callback=blink, bouncetime=10)
    print("Starting demo now! Press CTRL C to exit")
    try:
        while True:
            x=GPIO.input(18)
            print(x)
            # blink LED 1 slowly   
            GPIO.output(led_pin_1, GPIO.HIGH)
            time.sleep(2)
    finally:
        GPIO.cleanup()  # cleanup all GPIOs

if __name__ == '__main__':
    main()

need to take this whole code into a function that can be accessed from another python file.plz, help me with this coding part.

CodePudding user response:

In the new python file call import module where module is the name of the file. Like led_blink.py would be import led_blink

Then you can call the methods like so:

led_blink.blink(channel)

This is assuming the files are in the same folder.

CodePudding user response:

Easiest way that I do this is to take a .py file and put it in the same directory you created the python script you are working with. From there you can do the following code from The_Python_File import *

Additionally note that the "The_Python_File" is the name of the .py file that contains the function you are trying to call, but you do not include .py when importing the file.

  • Related