mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Python vs arduino question

Sun Jan 28, 2018 2:25 pm

Hi Everyone,

I have been using arduino for a few years and have decided to learn python. I have made some simple scripts but am having trouble wrapping my mind around how python actually works through the scripts.
For example, in arduino you generally have a setup loop that arduino will go through only once. You will then have a void loop that will then be run repeatedly from top to bottom as the code is written.

I can't seem to find a good explanation for this on python. All I can seem to find is information on "for loops" which isn't what I think I need.

The main reason I am stuck on this is that I have some arduino code I want to convert to python and run on my raspberry pi, but I can't seem to figure out a way to re-create the void loop in python.

Thanks for any help!

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 13098
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: Python vs arduino question

Sun Jan 28, 2018 2:44 pm

an arduino is a micro controller, so if you write code for it (in c++) that code is the only thing that runs, there is no code that uses a procedure call to run your code, and your code cannot return to the code that called it (with return parameters) because such code doesn't exist.

not so with python code, which is "called" by the operating system, and so can "return" with a parameter.
so python generally has no unending "void loop".

ghans
Posts: 7882
Joined: Mon Dec 12, 2011 8:30 pm
Location: Germany

Re: Python vs arduino question

Sun Jan 28, 2018 2:49 pm

I think what OP needs is an endless loop:

Code: Select all

import sys

while True:
    try:
       blabla
    except KeyboardInterrupt:
       sys.exit()
Without the try ... except the script wouldn't even stop when youboress Ctrl-C.

ghans
• Don't like the board ? Missing features ? Change to the prosilver theme ! You can find it in your settings.
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: Python vs arduino question

Sun Jan 28, 2018 8:30 pm

mahjongg wrote:
Sun Jan 28, 2018 2:44 pm
an arduino is a micro controller, so if you write code for it (in c++) that code is the only thing that runs, there is no code that uses a procedure call to run your code, and your code cannot return to the code that called it (with return parameters) because such code doesn't exist.

not so with python code, which is "called" by the operating system, and so can "return" with a parameter.
so python generally has no unending "void loop".
Thanks for the reply and the info!

I am using a tkinter GUI for my project, and was worried that if I had any other while or for loops in my program they would interfere with the main.loop.
Would something like this be valid?

Code: Select all

import tkinter 
import Tk

class GUI:
    def __init__(self, master):
       #GUI Attributes

    def GuiMethods(self):
        #GUI Methods

root = Tk()
my_gui = GUI(root)
root.mainloop()

For
#some code to run a for loop

While
#some code to run a while loop

User avatar
Paeryn
Posts: 2966
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Python vs arduino question

Sun Jan 28, 2018 11:11 pm

Any code after root.mainloop() won't execute until the Tkinter window is closed as root.mainloop() doesn't return until root is destroyed with root.destroy(). The close button window decoration usually defaults to calling root.destroy() for you.

Note:
Not strictly true as root.quit() will exit the mainloop without destroying the window (so the window will still be there but won't respond to anything until you start the mainloop again) but if you try doing this when running from IDLE it doesn't work as IDLE keeps the mainloop running.
She who travels light — forgot something.

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Python vs arduino question

Mon Jan 29, 2018 10:05 am

To add to Paeryn's answer, yes adding an infinite loop to a GUI is generally a bad idea.

In order to repeat the same actions again and again in a tkinter application, the easiest method is to use the .after method to schedule a function to be run. At the end of that function, the .after method is used again to run the function in another x milli-seconds.

For example

Code: Select all

from tkinter import *

# define a variable as a counter
counter = 1

def loop():
    """ This function will run every 1 second """
    global counter
    txtCounter.set(str(counter))
    counter += 1                    #Increment our counter
    root.after(1000,loop)           #Schedule this function again.

    
root = Tk()                 
txtCounter = StringVar()    #This is how text is displayed
txtBox = Entry(root,textvariable=txtCounter)
txtBox.grid()
root.after(1000,loop)       #Schedule the loop to begin after 1 second

#begin the tkinter mainloop
root.mainloop()
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: Python vs arduino question

Mon Jan 29, 2018 10:56 am

Thanks! @Paeryn and @scotty101

@scotty101 that is exactly what I need! Thank's for taking the time to reply guys, helps me a ton.

Matt

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: Python vs arduino question

Thu Feb 08, 2018 3:27 am

Code: Select all

from tkinter import *

# define a variable as a counter
counter = 1

def loop():
    """ This function will run every 1 second """
    global counter
    txtCounter.set(str(counter))
    counter += 1                    #Increment our counter
    root.after(1000,loop)           #Schedule this function again.

    
root = Tk()                 
txtCounter = StringVar()    #This is how text is displayed
txtBox = Entry(root,textvariable=txtCounter)
txtBox.grid()
root.after(1000,loop)       #Schedule the loop to begin after 1 second

#begin the tkinter mainloop
root.mainloop()
With regards to code above. This works great for most of my sensors that I am using, except 1...
I am using a piezo film to sense vibrations, and am missing the signals.
The problem is obviously the frequency I am calling the root.after loop (1000 ms), the frequency is too low at 1 second.

Is there a method to make this loop run as fast as the processor can make it happen? and if so, what are the negative consequences to increasing the frequency of this .after loop?

Thanks in advance for the help!

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Python vs arduino question

Thu Feb 08, 2018 9:41 am

You could just change the number 1000 for something smaller...

If reading this sensor is time critical, you may have to move this to a separate thread. I do have an example of a Tkinter GUI and a seperate thread but i'll need to find where I posted it.

EDIT: Found it!
This example is split across two files, the first contains the threaded task (your sensor the needs to be run quickly) and the second contains the GUI code. The GUI code starts the threaded task and passes it the 'progress' object so that the thread can update the value displayed on the GUI. For you this could be an IntVar that contains the result of your sensor processing

threaded_task.py

Code: Select all

import threading
import time

class ThreadedTask(threading.Thread):
    def __init__(self, progress):
        threading.Thread.__init__(self)
        self.progress = progress
    def run(self):
        for i in range(100):
            self.progress.step(1)  # Update progress bar
            time.sleep(1)  # Simulate long running process
main.py

Code: Select all

from tkinter import *
from tkinter import ttk
from threaded_task import ThreadedTask

root = Tk()
progcomp = ttk.Progressbar(root, orient='horizontal', length=200, mode = 'determinate', maximum=100)
progcomp.grid()

task = ThreadedTask(progcomp)
task.start()

root.mainloop()
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

mattg31
Posts: 79
Joined: Fri Jan 05, 2018 9:55 pm

Re: Python vs arduino question

Thu Feb 08, 2018 10:26 am

Nice!!
Thanks a million @scotty101!
I didn't know you could do this, I'm sure this will come in handy often

Thanks again

Return to “Python”