chachi420
chachi420

Reputation: 13

Run something only once in while loop without breaking the loop

import RPi.GPIO as g
import time
g.setmode(g.BOARD)
g.setup(33, g.OUT)



while True:
  tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave")
  thetext = tempfile.read()
  tempfile.close()
  tempdata = thetext.split("\n") [1].split(" ")[9]
  temperature = float(tempdata[2:])
  finaltemp = temperature / 1000
  time.sleep(1)

  if finaltemp > 22:
    g.output(33,g.LOW)
    time.sleep(0.3)
    g.output(33,g.HIGH)
  else:
    g.output(33,g.LOW)
    time.sleep(0.3)
    g.output(33,g.HIGH)

I have searched numerous sites including this one, but never found my solution.

As you can see, the code currently grabs the temperature from the system file and stores the temperature in the variable "finaltemp".
The way I have my hardware setup is so that my relay switch is connected to the push button on AC remote control, which is why I have my GPIO set up to turn on and off very quickly (0.3 seconds), to mimic the push of the button on the remote.

My goal is to 'blink' (push the button) the GPIO only once(!) when the temperature changes according to the condition.

For example:

The temperature in room is 20 and the AC is off at the moment. Therefore, the temperature is slowly rising, and right when the temperature goes above 22, I want to run the 3 lines of code to run. What is happening however, is that it keeps checking it every time. Since the condition meets everytime the while loop starts over, it keeps running the code over and over, so essentially what's happening is that my AC keeps turning on and off and on and off.

Upvotes: 0

Views: 1650

Answers (2)

VPfB
VPfB

Reputation: 17352

You need to add both state and hysteresis.

Pseudo-code for the on/off logic:

LIMIT_LOW = 21.5
LIMIT_HIGH = 22.5
AC_running = False  # False or True, you need to know exactly
while True:
  temp = ....
  if temp < LIMIT_LOW and AC_running:
      # turn AC off
      AC_running = False
  elif temp > LIMIT_HIGH and not AC_running:
      # turn AC on
      AC_running = True
  sleep(...)

Upvotes: 1

Brandon Jones
Brandon Jones

Reputation: 31

What you're currently doing is just checking the temperature and using a condition to keep switching the AC on and off, which as you have already figured out will not work.

This is because your condition statements only look at the temperature and not and the current state of the AC, for example if you want the AC to turn on when the temperature is above 22C you're if should be something along the lines of :

if temperature > 22 && AC == off
    // turn on AC

Upvotes: 1

Related Questions