May-21-2018, 05:43 PM
It is better always to keep the code in a single point (don't repeat yourself) in python you can always use the import machinery to do this.
The only problem is that when you "import" the scripts is executed, so it is common to guard the run part with the __main__ trick.
In your case, there is some mix between proper functions and data, but if you modify the read_MCP to request the spi from the arguments you can store the 2 functions in a separate file:
Now your main script will be:
If you finish having too many small functions and want to organise them properly. you can create easily a package... but that is more advanced python.
The only problem is that when you "import" the scripts is executed, so it is common to guard the run part with the __main__ trick.
In your case, there is some mix between proper functions and data, but if you modify the read_MCP to request the spi from the arguments you can store the 2 functions in a separate file:
#!/usr/bin/env python # This shall be in a file at the same folder as all your programs # I used low_level.py, but you can have more imagination than me... import RPi.GPIO as GPIO def read_MCP(spi, sensorid): #Function reads MCP3008. adc = spi.xfer2([1,(8+sensorid)<<4,0],20000) adcread = ((adc[1]&3) << 8) + adc[2] return adcread def read_ds18b20(sensorid): #Function reads DS18B20 sensor. device="/sys/bus/w1/devices/"+ sensorid +"/w1_slave" try: with open (device) as tfile: text=tfile.read() except FileNotFoundError: GPIO.output(25,True) notemp = 9999 return notemp sensor_data =text.split(" ")[20] #Select 21st word start with zero. # Haal 't=' weg en maak floating temp_raw = float(sensor_data[2:]) #Remove 'T="and make floating. #print (temp_raw) temp = temp_raw digitemp = '%.1f' % temp #Round to one decimal. return digitemp def _test(): # Define here if you want some simple tests to check your functions # You can run it as python low_level.py pass if __name__ == '__main__': # This part runs only when this script is the main script, not when imported from other _test()Then in your other scripts can import from this other -imagine you call it low_level.py) with
from low_level import read_MCP, read_ds18b20
Now your main script will be:
#!/usr/bin/env python #Versie 2.3; 21mei2018 #Dit programma leest elke sensor apart uit en slaat aan het einde #de resultaten op in een csv file. #Importeer benodigde libraries. #21/05File not found opgelost. import sys import time import csv import os import spidev import RPi.GPIO as GPIO from low_level import read_MCP, read_ds18b20 spi = spidev.SpiDev() spi.open(0,0) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(22,GPIO.IN) GPIO.setup(27,GPIO.OUT) GPIO.setup(23,GPIO.OUT) GPIO.setup(24,GPIO.OUT) GPIO.setup(25,GPIO.OUT) datum = (time.strftime('%d/%m/%Y')) # Define date/time variables. tijd = (time.strftime('%H:%M:%S')) GPIO.output(25,False) #reset FileNotFound LED while True: while True: time.sleep(1) if GPIO.input(22): #Contact key is ON GPIO.output(27,True) #Turn on LED indicator. break else: #Contact key is dus OFF GPIO.output(27,False) #LED indicator OFF print ('Schakelaar is UIT') # Checked water level BB with key OFF #Check watersensor SB, channel0 of ADC. level = read_MCP(spi, 0) level_SB = round(level,1) print (level_SB) # Turn on the SB pump if value > 510. if (level_SB) > 510: GPIO.output(23,GPIO.HIGH) #LED/pomprelais SB ON. else: GPIO.output(23,GPIO.LOW) #LED/pomprelais SB OFF. #Check watersensor BB, channel1 of ADC. level =read_MCP(1) level_BB= round(level,1) print (level_BB) # Turn on the BB pump if value > 510 if (level) > 510: GPIO.output(24,GPIO.HIGH) #LED/pomprelais BB ON. else: GPIO.output(24,GPIO.LOW) #LED/pomprelais BB OFF. # Exec DS18B20 function for sensorID's below. temp1 = float(read_ds18b20('28-000009aeba12')) #Motor 1 temp2 = float(read_ds18b20('28-000009aeba12')) #Motor 2 temp3 = float(read_ds18b20('28-000009adc801')) #Buitentemperatuur # Define 'lijst'. lijst = [0,0,0,0,0,0,0,0] # Exec function 'read_temp36' for each ADC channel. for offset in range(0,8): adcread = read_MCP(spi, offset) print (adcread) result = (adcread*330)/float(1024) lijst[offset] = adcread offset +=1 #Decrease offset by 1 data = [datum,tijd,temp1,temp2,temp3,round(lijst[0],1),round(lijst[1],1),round((((lijst[2]*3.3/1024)-0.52)/0.08),1),round((((lijst[3]*3.3/1024)-0.52)/0.08),1)] # lijst 0 is watersensor SB, lijst 1 is idem BB, lijst 3 is stroom SB, lijst 4 is stroom BB # Turn on the SB pump if value > 510. if (lijst[0]) > 510: GPIO.output(23,GPIO.HIGH) #LED/pomprelais SB ON else: GPIO.output(23,GPIO.LOW) #LED/pomprelais SB ON # Turn on the BB pump if value > 510. if (lijst[1]) > 510: GPIO.output(24,GPIO.HIGH) #LED/pomprelais BB ON else: GPIO.output(24,GPIO.LOW) #LED/pomprelais BB ON print (data) #Output naar csv file #csvfile = "/home/pi/programs/testdata.csv" #with open (csvfile,'a') as output: # writer = csv.writer(output, delimiter = ',' ,lineterminator = '\n') # writer.writerow(data) time.sleep(0.5)You now can re-use that functions from other scripts. In general is always better to keep the things in a single part than abuse from the copy-paste or create a gargantuous script that tries to do everything and each time you try to fix one of the functions you break other three (Keep it simple....)
If you finish having too many small functions and want to organise them properly. you can create easily a package... but that is more advanced python.