Code: Alles auswählen
#!/usr/bin/python
import spidev
import time
import os
import thread
import threading
# Open SPI bus
spi = spidev.SpiDev()
spi.open(0,0)
# Function to read SPI data from MCP3008 chip
# Channel must be an integer 0-7
def ReadChannel(channel):
adc = spi.xfer2([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data
class thread1 (threading.Thread):
def RundenBahn1():
f1 = open('runden1.txt', 'r+')# just put 'w' if you want to write to the file
x1 = f1.readline() #this command will read file lines
f1.close()
open("runden1.txt","w").close()
y1 = int(x1)+1
z1 = str(y1) #making data as string to avoid buffer error
#print ("Light1: ",z1)
f1 = open('runden1.txt', 'r+')# just put 'w' if you want to write to the file
f1.write(z1)
f1.close()
time.sleep(10)
print ("thread1 fertig")
return
RundenBahn1()
class thread2 (threading.Thread):
def RundenBahn2():
f2 = open('runden2.txt', 'r+')# just put 'w' if you want to write to the file
x2 = f2.readline() #this command will read file lines
f2.close()
open("runden2.txt","w").close()
y2 = int(x2)+1
z2 = str(y2) #making data as string to avoid buffer error
#print ("Light2: ",z2)
f2 = open('runden2.txt', 'r+')# just put 'w' if you want to write to the file
f2.write(z2)
f2.close()
time.sleep(5)
print ("thread2 fertig")
return
RundenBahn2()
# Define sensor channels
light1_channel = 0
light2_channel = 1
schwellwert = 600
runden1 = 0
runden2 = 0
# Define delay between readings
delay = 5
runden = 0
thread1 = thread1()
thread2 = thread2()
while True:
# Read the light sensor data
light1_level = float(ReadChannel(light1_channel))
light2_level = float(ReadChannel(light2_channel))
if light1_level <= schwellwert:
if not thread1.is_alive():
thread1.start()
if light2_level <= schwellwert:
if not thread2.is_alive():
thread2.start()
Readchannel() ist zum auslesen von alalogen sensoren mit dem raspberry pi.
für mein Problem eher uninteressant.
Die beiden Classes sollen unabhängig von der while-schleife laufen.
in den classes wird eine txt datei geöffnet und die zahl von dort ausgelesen und +1 gerechnet und wieder gespeichert.
und danach wird eine bestimmte zeit gewartet.
In der while-schleife wird der analoge wert ausgelesen und wenn dieser einen bestimmten schwellwert unterschreitet, soll der thread gestartet werden. die while-schleife soll aber nebenbei weiterlaufen.
Wenn aber der eine thread noch läuft soll er nicht noch einmal gestartet werden. das habe ich mit der If-schleife versucht.
wenn ich das script ausführe kommt folgender Fehler:
Traceback (most recent call last):
File "analogread.py", line 71, in <module>
thread1.start()
File "/usr/lib/python2.7/threading.py", line 489, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Kann mir einer helfen?