samuel_john64
Posts: 17
Joined: Wed Mar 15, 2017 9:55 am

Store Result from Sensor

Fri Mar 17, 2017 3:30 pm

Hi, i just would like to know how to write a coding that would able me to store the result in a period of time to a text or excel file?i have attached the coding i been trying to do.thanks im now to python codes.

import spidev
import datetime
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)


# Open up SPI bus
spi = spidev.SpiDev()
spi.open(0,1)

# Initialize Sensor
SoilSensor = 5
Pump = 22
sleepTime = 2

# Setup the pin that pump connected to
GPIO.setup(Pump, GPIO.OUT)


def getReading(channel):
# Get Raw Data from chip
rawData = spi.xfer([1, (8 + channel) << 4, 0])
# Process Data to Understandable
processedData = ((rawData[1]&3) <<8) + rawData[2]
return processedData

def convertVoltage(bitValue, decimalPlaces=2):
voltage = (bitValue * 3.3) / float(1023)
voltage = round(voltage, decimalPlaces)
return voltage


try:
while True:
delta = datetime.timedelta(minutes=30)
next_time = datetime.datetime.now()
dt = datetime.datetime.now()
SoilData = getReading(SoilSensor)
SoilVoltage = convertVoltage(SoilData)

#Print Values
print("Soil Moisture bitValue = {} ; Voltage = {} V".format(SoilData, SoilVoltage))
sleep(sleepTime)

#Save Result Every One Hour
if dt > next_time:

file = open("/home/pi/FYP/result/result.txt", "w")
file.write("{};Soil Moisture bitValue = {} ; Voltage = {} V\n".format(strftime("%Y-%m-%d %H:%M:%S"),SoilData, SoilVoltage))
file.close()
next_time = dt + delta

if SoilData < 40:
GPIO.output (Pump, True)
else:
GPIO.output (Pump, False)

finally:
# Reset the GPIO Pins to a safe state
GPIO.output (Pump, False)
GPIO.cleanup()

gordon77
Posts: 5075
Joined: Sun Aug 05, 2012 3:12 pm

Re: Store Result from Sensor

Fri Mar 17, 2017 3:35 pm

Could you show your code using the Code button, this will preserved the layout.

eg

Code: Select all

import spidev
import datetime
import RPi.GPIO as GPIO
from time import sleep
....

When you say "store the result in a period of time" could you explain a bit more what you mean ?

samuel_john64
Posts: 17
Joined: Wed Mar 15, 2017 9:55 am

Re: Store Result from Sensor

Fri Mar 17, 2017 5:23 pm

what i mean for store the result in a period of time is. every 30 minutes the program will store result of sensor into a text file with the real-time timing.

Code: Select all

import spidev
import datetime
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)


# Open up SPI bus
spi = spidev.SpiDev()
spi.open(0,1)

# Initialize Sensor
SoilSensor = 5
Pump = 22
sleepTime = 2

# Setup the pin that pump connected to
GPIO.setup(Pump, GPIO.OUT)


def getReading(channel):
	# Get Raw Data from chip
	rawData = spi.xfer([1, (8 + channel) << 4, 0])
	# Process Data to Understandable
	processedData = ((rawData[1]&3) <<8) + rawData[2]
	return processedData

def convertVoltage(bitValue, decimalPlaces=2):
	voltage = (bitValue * 3.3) / float(1023)
	voltage = round(voltage, decimalPlaces)
	return voltage


try:
	while True:
		delta = datetime.timedelta(minutes=30)
		next_time = datetime.datetime.now()
		dt = datetime.datetime.now()
		SoilData = getReading(SoilSensor)
		SoilVoltage = convertVoltage(SoilData)
	
		#Print Values
		print("Soil Moisture bitValue = {} ; Voltage = {} V".format(SoilData, SoilVoltage))
		sleep(sleepTime)

		#Save Result Every One Hour
		if dt > next_time:
			
			file = open("/home/pi/FYP/result/result.txt", "w")
			file.write("{};Soil Moisture bitValue = {} ; Voltage = {} V\n".format(strftime("%Y-%m-%d %H:%M:%S"),SoilData, SoilVoltage))
			file.close()
			next_time = dt + delta

		if SoilData < 40:
			GPIO.output (Pump, True)
		else:
			GPIO.output (Pump, False)

finally:
	# Reset the GPIO Pins to a safe state
	GPIO.output (Pump, False)
	GPIO.cleanup()

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

Re: Store Result from Sensor

Fri Mar 17, 2017 6:28 pm

Do you mean that you would like to do something like this? Your wording isn't clear

1. Read Sensor
2. Write to file
3. Wait 30 minutes
4. Go to step 1


If so you need to use datetime to get the current time, add a time delta of 30 minutes to that and then wait until that time has elapsed. Can provide an example if this is what you want and you are stuck.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

ghp
Posts: 1517
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Store Result from Sensor

Fri Mar 17, 2017 6:44 pm

Hello,
the problem is that in each iteration, you set the date- and delta values.
Proposal is:

Code: Select all

while true:
    calculate nexttime of file write
    while true:
        sleep 2 secs
        if currentdate > nexttime of file write:
            write file
            break (inner loop)
To make it clear, here the changed code. All gpio, data aquisition is commented away as this is tested not on a pi.

Code: Select all

try:
   while True:
      # changed time to 1 minutes for my tests
      delta = datetime.timedelta(minutes=1)
      next_time = datetime.datetime.now()  + delta
      # changed data aquisition to constant values
      SoilData = 0x0100
      SoilVoltage = 22.2
      while True:
          #Print Values
          #print("Soil Moisture bitValue = {} ; Voltage = {} V".format(SoilData, SoilVoltage))
          print("sleep(sleepTime)")
          sleep(sleepTime)
          
          dt = datetime.datetime.now()
          print("delta", delta, "next_time", next_time, "dt", dt )
      
          #Save Result Every One Hour
          if dt > next_time:
             print("---------------  write file -----------------------")
             file = open("result.txt", "w")
             file.write("{};Soil Moisture bitValue = {} ; Voltage = {} V\n".format(time.strftime("%Y-%m-%d %H:%M:%S"),SoilData, SoilVoltage))
             file.close()
             next_time = dt + delta
             # leave inner loop
             break
      #if SoilData < 40:
      #   print("GPIO.output (Pump, True)")
      #else:
      #  print("GPIO.output (Pump, False)")

finally:
   # Reset the GPIO Pins to a safe state
   print("GPIO.output (Pump, False)")
   print("GPIO.cleanup()")
Hope this helps,
Gerhard

samuel_john64
Posts: 17
Joined: Wed Mar 15, 2017 9:55 am

Re: Store Result from Sensor

Sat Mar 18, 2017 6:50 am

scotty101 wrote:Do you mean that you would like to do something like this? Your wording isn't clear

1. Read Sensor
2. Write to file
3. Wait 30 minutes
4. Go to step 1


If so you need to use datetime to get the current time, add a time delta of 30 minutes to that and then wait until that time has elapsed. Can provide an example if this is what you want and you are stuck.
What i mean is

1. Read Sensor every 2 second
2. Write sensor reading result to file every 30 minutes
4. If the reading of soil sensor lower than 40
5.activate water pump

Im stuck with the timing and also to include the current time with the sensor reading to a file

samuel_john64
Posts: 17
Joined: Wed Mar 15, 2017 9:55 am

Re: Store Result from Sensor

Sat Mar 18, 2017 7:26 am

ghp wrote:Hello,
the problem is that in each iteration, you set the date- and delta values.
Proposal is:

Code: Select all

while true:
    calculate nexttime of file write
    while true:
        sleep 2 secs
        if currentdate > nexttime of file write:
            write file
            break (inner loop)
To make it clear, here the changed code. All gpio, data aquisition is commented away as this is tested not on a pi.

Code: Select all

try:
   while True:
      # changed time to 1 minutes for my tests
      delta = datetime.timedelta(minutes=1)
      next_time = datetime.datetime.now()  + delta
      # changed data aquisition to constant values
      SoilData = 0x0100
      SoilVoltage = 22.2
      while True:
          #Print Values
          #print("Soil Moisture bitValue = {} ; Voltage = {} V".format(SoilData, SoilVoltage))
          print("sleep(sleepTime)")
          sleep(sleepTime)
          
          dt = datetime.datetime.now()
          print("delta", delta, "next_time", next_time, "dt", dt )
      
          #Save Result Every One Hour
          if dt > next_time:
             print("---------------  write file -----------------------")
             file = open("result.txt", "w")
             file.write("{};Soil Moisture bitValue = {} ; Voltage = {} V\n".format(time.strftime("%Y-%m-%d %H:%M:%S"),SoilData, SoilVoltage))
             file.close()
             next_time = dt + delta
             # leave inner loop
             break
      #if SoilData < 40:
      #   print("GPIO.output (Pump, True)")
      #else:
      #  print("GPIO.output (Pump, False)")

finally:
   # Reset the GPIO Pins to a safe state
   print("GPIO.output (Pump, False)")
   print("GPIO.cleanup()")
Hope this helps,
Gerhard
thank you very much.this code helped me alot

User avatar
bensimmo
Posts: 4654
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Store Result from Sensor

Sat Mar 18, 2017 7:58 am

If you have a search for SenseHat Datalogging in the RaspberryPi tutorials, you'll see a nice layout of logging, time periods and CSV file writing.

samuel_john64
Posts: 17
Joined: Wed Mar 15, 2017 9:55 am

Re: Store Result from Sensor

Sat Mar 18, 2017 11:17 am

bensimmo wrote:If you have a search for SenseHat Datalogging in the RaspberryPi tutorials, you'll see a nice layout of logging, time periods and CSV file writing.

Thanks

Return to “Python”