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()
HeatfanJohn
  • 3,125
  • 3
  • 24
  • 36
Coderboy
  • 61
  • 1
  • 1
  • 2

2 Answers2

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()
HeatfanJohn
  • 3,125
  • 3
  • 24
  • 36
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/

Ashbay
  • 373
  • 1
  • 2
  • 9