6

I want to make a simple thread that listens if a Button is pressed or not.

I receive the error ImportError No module named thread.

import RPi.GPIO as GPIO
import time
import thread 

GPIO.setmode(GPIO.BCM)
GPIO.setup(2,GPIO.OUT)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(17,GPIO.IN)



def pushButton():
    while True:
        if GPIO.input(17) == 1:
            print("on")
        else:
            print("of")


while True:
    GPIO.output(2,1)
    GPIO.output(3,1)
    time.sleep(1);
    GPIO.output(2,0)
    GPIO.output(3,0)
    time.sleep(1)

thread.start(pushButton,())


GPIO.cleanup()
7
  • 3
    What version of python are you using? Enter python --version to see. FYI, the thread module was renamed _thread in version 3 of python. Commented Jul 29, 2014 at 20:35
  • thx for answering
    – Coderboy
    Commented Jul 29, 2014 at 21:16
  • when i change it to import _thread i doesnt't work too
    – Coderboy
    Commented Jul 29, 2014 at 21:25
  • Do you get the same error message? Are you using version 3 of python? Commented Jul 29, 2014 at 21:27
  • 1
    Could you post the full error message, starting from the line which says Traceback
    – PiBorg
    Commented Jul 30, 2014 at 8:30

2 Answers 2

11

Your original problem is that you are using Python version 3 and according to this posting the thread module has been renamed _thread in Python 3.

After correcting that issue you state in your comments that the program still doesn't work.

I suspect that is because you never execute the thread.start(pushButton,()) line of code because the previous block of code is an infinite loop, while True: will run the subsequent block of code forever and the thread.start will never get executed.

I recommend that you move the tread.start line of code before the while True block. I also recommend that you put some sort of time.sleep into your pushButton routine otherwise your will continuously output either "on" or "off" very quickly.

I would try:

import RPi.GPIO as GPIO
import time
import _thread 

GPIO.setmode(GPIO.BCM)
GPIO.setup(2,GPIO.OUT)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(17,GPIO.IN)

def pushButton():
    while True:
        time.sleep(1)
        if GPIO.input(17) == 1:
            print("on")
        else:
            print("of")

_thread.start(pushButton,())

while True:
    GPIO.output(2,1)
    GPIO.output(3,1)
    time.sleep(1);
    GPIO.output(2,0)
    GPIO.output(3,0)
    time.sleep(1)

GPIO.cleanup()
0

I'm currently learning Python and setting up a server. In the tutorial I'm reading the guy import the thread module this way :

from thread import *

I'm not telling this is the solution for your problem but we never know. Hope it will help.

Source : http://www.binarytides.com/python-socket-server-code-example/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.