Main Menu

search

You are here

Python: Programming

[last updated: 2024-09-21]
Python home page
-----

This is pretty rough, incomplete at least, surely inaccurate in places, but it's evolving...

    ======================================================================================

  • GPIO: Using rPi inputs and outputs:
    • Setup:
      • import RPi.GPIO as gpio
        the "gpio" in the statement is a variable name that you choose
      • gpio.setmode(...)
        this defines the numbering system you will use in your program

        if you use:
            gpio.setmode(gpio.BOARD), then you specify I/O using connector pin numbers
        if you use:
            gpio.setmode(gpio.BCM) then you specify I/O using GPIO numbers
        eg. connector pin# 12 is GPIO# 18 (see rPi pinout diagram)

    • I/O Designation:
      • gpio.setup([pin# or pinName or variable name], gpio.IN)
        eg:
            gpio.setup(18, gpio.IN)
        or:
            gpio.setup(varName, gpio.OUT)

        if you specify your I/O pin as an input, you can also specify an internal pull-up or pull-down resistor: eg:
            gpio.setup(18, gpio.IN, pull_up_down = gpio.PUD_UP)
        or ... gpio.PUD_DOWN

      • if you specify ... gpio.OUT
        then you can also specify an initial pin state:
            gpio.setup(18, gpio.OUT, initial=gpio.LOW)
    • Reading/Writing to I/O pins:
      • LIMITS:
        • never source or sink more than 16ma from an rPi pin
        • Never exceed 3.3v on an Input
        • Never connect an input to less than 0v
        • TOTAL Max source current is 50ma
        • Do Not drive CAPACITIVE loads without current limiting
      • Reading an input, and set some variable = to the input state:
        pinNumState = gpio.input(18)
      • Writing:
        gpio.output(18, True)
        gpio.output(18, False)
    • Read an input in the background:
      • set up a thread to run in the background that watches/waits for an edge detect on your input pin:
        gpio.add_event_detect([pinNum or varName], gpio.FALLING, callback=[functionName])
        this will run the [functionName] when a FALLING edge detect happens
        you can alternatively specify "gpio.RISING"
      • When the edge is detected and the callback functionName is called, a parameter, the pin number that detected the event, will be passed back to the called function.

        This means that when you define the function, you must specify that your function takes a single parameter:
        def [functionName](pinNum)
        [indent][statements]

    • Handling Switch bounce:
      • Switch bounce is a phenomenon that happens with probably all mechanical switches. When they are 'switched' (whether pushed or toggled), the contact closure does not just happen once. That is, when the mechanical contacts come together, they initially will close, but then open again (ie. 'bounce' apart) for a fraction of a second, and perhaps repeat that several times before 'settling' in their closed position. This can result in multiple switch closures being seen by the controller.
      • To accommodate this, and produce a single switch-closure signal, a delay of some kind is implemented in the program that reads the switch input:
      • ...
  • top
  • ------------------------------------

    Misc statements:

    • Print:
      See: https://realpython.com/python-print/
      print ('this text will print')
    • Comments:
      Lines beginning with "# " (hash + space) are comments and ignored at execution
      Block comments do not exist in python like they do in Arduino ("/*" & "*/"). If you have several consecutive lines you want to comment out, they all must begin with a "# ".
    • Time statements:

    • Input statements:
      • input() will pause program waiting for any keyboard input
      • input("some prompt") will show prompt
  • top
  • ------------------------------------

    Tkinter statements:

    • Setup:
      from tkinter import *
      (note python 2 uses "T", and python 3 uses "t")
    • Create tkinter window:
      root = Tk()
      "root" is your choice of variable name
    • Define widgets like this:
      button1 = Button(root, [other parameters, ...])
      label1 = Label(root, , [other parameters, ...])
      entryField1 = Entry(root, , [other parameters, ...])
    • Place/position the widgets in the window:
      • easiest is 'pack'
        button1.pack()
        but this is less flexible in where the widget ends up.
      • grid is much more flexible, but more time-consuming to set up
    • Button widget parameters:
      • set parameters like this:
        [widgetName]["[parameterName]"] = [parameterValue]
        So for example for first parameter below - command, for button named button1, and for a predefined function named callbackFunction, it would be:
        button1["command"] = callbackFunction
      • command=callbackFunction
        this defines the function that will be executed when the button is pressed
      • bg="blue" for background color
      • activebackground for color when under cursor
      • text="some text"
      • fg="red", or fg=#00aa44
        to specify font color
      • activeforeground for color when under cursor
      • there are other parameters to control formatting of multiple text lines
      • width=40, height=20
        if there's no text in the button (or really if there is no font defined??), these units are in pixels
        if there is text in the button (or a font defined?), these units are in text units
        if these parameters are not used, the button will be big enough to hold the text in it
      • padx=5, pady=5
        add space between contents and button border
      • relief=SUNKEN, or relief=RAISED
      • bd=5, or borderwidth=5
      • image=pathFileName
        however only .png and .gif formats can be used
        this will override text
        if you want text to display on top of the image, set parameter:
        compound = CENTER
      • ...
      • ...
    • Canvas:
      • most flexible for drawing things, as there are built-in methods for lines, points (ovals), rectangles, polygons, other?
      • ...
      • ...
      • ...
    • root.after:
      • In tkinter applications, use this instead of time.sleep (which locks up and slows down cpu while sleeping).
      • syntax: root.after([ms delay], [callback function], [other arguments])
        • an embedded lambda function can be used in place of a callback function def
      • once initiated, a task/event, namely to execute the callback function, is added to the queue/task list that is managed by mainloop in tkinter.

        When the time delay has expired, the task/callback-function is executed.
        The callback function is only executed once for every time root.after is invoked.
        "[other arguments]", if listed, are passed to the callback function.

      • Take note that while time.sleep delays are listed in seconds, root.after delays are in milliseconds.

    ------------------------------------

    read/Write files:

    • [file-object] = open (" [diskFileName] ", " [mode] )
      eg: file01= open("test.txt", "r") #opens file with name of "test.txt"
      this sets the open file to a variable named file01

    • Python will look in home directory by default, so if your file isn't there, you must specify a complete pathname.
    • mode can be "r" to read the file,
      "w" to write to it, (this will create a file if it doesn't already exist)
      or "a" to append, or write to the end of the file

      or "x" to test to see if the file already exists

    • file01.read(n) # reads n number of characters from the file, or if n is blank it reads the entire file.
    • file01.readline(n) # reads an entire line, the nth line, from the file.
      • However it doesn't seem to work this way. It seems to just pull 'n' characters from the first line
    • python keeps track of where you are in the file with a pointer. This means that successive reads (without doing something to change the pointer) will start reading where the last read left off.
    • when done, must:
      file01.close()
    • file01.readlines() will return a comma-separated list, with each element of the list being a line from the file
    • file01.readline() will return a string that is one line of the file, but there will be a CR at the end of the string
    • you can use a for-loop to extract everything line-by-line:
      file01 = open(“testfile.txt”, “r”)
      for line in file:
      [indent]print line, or do whatever
    • $ python main.py >> text.log

    ------------------------------------

    Other stuff, uncategorized...

    • Write/Overwrite to File:
        open('file.txt', 'w') as f:
        print('hello world', file=f)

      Write/Append to File:

        open('file.txt', 'a') as f:
        print('hello world', file=f)
    • make a python file executable: $ chmod +x script.py.
      Now you can start a script by typing in ./script.py to the terminal.
    • [don't know what this is...]
      python setup.py install
      or
      $ sudo easy_install pyserial
      In case you don’t have easy_install installed, you can install it by entering the following command,
      $ sudo apt-get install python-setuptools

    top

.

.

.

eof