User avatar
coskukoz
Posts: 34
Joined: Sun May 31, 2015 4:01 pm
Location: Balıkesir, Turkey

If Status Change Print

Fri May 13, 2016 5:36 am

Hello guys,
It's easy but I didn't find a code exactly what I want. That's why I post a topic. I'm trying to write a code like: if status change print as you can see on the topic.

For example;
If status ON: print ON to the screen once,
If status change with OFF: print OFF to the screen once.

My code prints ON in the per second so I see so many ON on the screen. Hope I explain well.

Now my code is:

Code: Select all

import spidev
import time
import os
import urllib
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

spi=spidev.SpiDev()
spi.open(0,0)

def ReadChannel (channel):
 adc = spi.xfer2([1,(8+channel)<<4,0])
 data = ((adc[1]&3)<<8) + adc[2]
 return data

def ConvertVolts(data,places):
 volts = (data*3.1815)/float(1023)
 volts = round(volts,places)
 return volts

sensor1_channel = 1

while True:

 foldtime = time.time()
 fnewtime = time.time()
 fstore = 0.1

 while True:
  fnewtime = time.time()
  fdtime = fnewtime-foldtime

  sensor1_level = ReadChannel(sensor1_channel)
  sensor1_volts = ConvertVolts(sensor1_level,9)

  if sensor1_volts > 1.60:
   Durum = 'ON'
  else:
   Durum = 'OFF'

  if fdtime >= fstore:
   foldtime=fnewtime
   print('------------------------')
   print("Sensor1 : {} V,     {}".format(sensor1_volts,sensor1_level))
   print("Durum : {}".format;(Durum))

time.sleep(delay)
Thanks for helps!
Coskun.

----
EDIT:
I solved the issue with the code below:

Code: Select all

import spidev
import time
import os
import urllib
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

spi=spidev.SpiDev()
spi.open(0,0)

def ReadChannel (channel):
 adc = spi.xfer2([1,(8+channel)<<4,0])
 data = ((adc[1]&3)<<8) + adc[2]
 return data

def ConvertVolts(data,places):
 volts = (data*3.1815)/float(1023)
 volts = round(volts,places)
 return volts

sensor1_channel = 1

previous_Status = None

foldtime = time.time()
fnewtime = time.time()
fstore = 3.0

while True:
 fnewtime = time.time()
 fdtime = fnewtime-foldtime

 if fdtime >= fstore:
  foldtime = fnewtime
  sensor1_level = ReadChannel(sensor1_channel)
  sensor1_volts = ConvertVolts(sensor1_level,9)

  if sensor1_volts > 1.60:
   Status = 'ON'
  elif sensor1_volts <= 1.60:
   Status = 'OFF'

  if Status != previous_Status:
   print('------------------------')
   print("Sensor1 : {} V,     {}".format(sensor1_volts,sensor1_level))
   print("Status : {}".format;(Status))
   previous_Status = Status

time.sleep(delay)
cactiapps.blogspot.com

Return to “Beginners”