xnoodles1
Posts: 1
Joined: Thu May 12, 2016 1:48 pm

LED dynamically changing colors based on sensor values

Thu May 12, 2016 5:36 pm

Hey there everyone, this is my first post on the forums here but I have been lurking the forums for awhile and thought how awesome of a community this is. My current project is a motion sensor and weather monitor that has a UPS Pico attached to it for reserve power. Everything is working very well but I'm planning expanding the functions of the Pi Sense HAT.


My problem right now is that I am trying to make a code that will change the LED visualizer colour based on how the humidity sensor changes in value. Im messing around with experimental if statements but no luck. Here is the code:

Code: Select all

from sense_hat import SenseHat  
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from ISStreamer.Streamer import Streamer
import time  
import sys  
import datetime
import smbus
import smtplib
i2c = smbus.SMBus(1)
  
# --------- User Settings ---------
CITY = "Hamilton"
BUCKET_NAME = ":partly_sunny: " + CITY + " Weather"
BUCKET_KEY = "sense-hat"
ACCESS_KEY = ""
SENSOR_LOCATION_NAME = "Net Access Office"
MINUTES_BETWEEN_SENSEHAT_READS = 0.1
# ---------------------------------

streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
sense = SenseHat()
sense.clear()

g = (0, 255, 0) #Green
r = (255, 0, 0) #Red
y = (255, 255, 0) #yellow

#humidity sensor will change color dynamically according to different values
if sense.get_humidity >=45:
     hawt = [
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r,
      r, r, r, r, r, r, r, r
   ]
     sense.clear()
     sense.set_pixels(hawt)
        

elif sense.get_humidity <= 40:
     mild = [
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y,
       y, y, y, y, y, y, y, y
   ]
     sense.clear()
     sense.set_pixels(mild)
     
elif sense.get_humidity == 35:
      cool = [
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g,
           g, g, g, g, g, g, g, g
    ]
      sense.clear()
      sense.set_pixels(cool)

else:
   print "error"

def bat_level():
   time.sleep(0.1)
   data = i2c.read_word_data(0x69, 0x01)
   data = format(data,"02x")
   return (float(data) / 100)

def pwr_mode():
   data = i2c.read_byte_data(0x69, 0x00)
   data = data & ~(1 << 7)
   if (data == 1):
      return "1 Fully Powered" #Power mode on RPi
   elif (data == 2):
      return "2 Backup Battery" #Power mode on Battery
   else:
      return "0 Error!" #Error

def rpi_level():
   time.sleep(0.1)
   data = i2c.read_word_data(0x69, 0x03)
   data = format(data,"02x")
   return (float(data) / 100)

def sot23_temp():
   time.sleep(0.1)
   data = i2c.read_byte_data(0x69, 0x0C)
   data = format(data,"02x")
   return data

        
while True:
   
  # Read the sensors
  temp_c = sense.get_temperature()
  humidity = sense.get_humidity() 
  pressure_mb = sense.get_pressure()
  battery_level = bat_level()
  power_mode = pwr_mode()
  raspberryPi_level = rpi_level()
  UPS_Pico_temp = sot23_temp()
 
  
  # Format the data
  temp_c = float("{0:.2f}".format(temp_c))
  humidity = float("{0:.2f}".format(humidity))
  pressure_mb = float("{0:.2f}".format(pressure_mb))
  battery_level = float("{0:.1f}".format(battery_level))
  raspberryPi_level = float("{0:.1f}".format(raspberryPi_level))
  
  # Print and stream
  print " "
  print "      Weather Monitor Status"
  print "***********************************"
  print SENSOR_LOCATION_NAME + " Temperature(C): " + str(temp_c)
  print SENSOR_LOCATION_NAME + " Humidity(%): " + str(humidity)
  print SENSOR_LOCATION_NAME + " Pressure(IN): " + str(pressure_mb)
  print SENSOR_LOCATION_NAME + " Battery(V): " + str(battery_level)
  print SENSOR_LOCATION_NAME + " Power Mode(M): " + str(power_mode)
  print SENSOR_LOCATION_NAME + " Raspberry Pi(V): " + str(raspberryPi_level)
  print SENSOR_LOCATION_NAME + " UPS Pico Temperature(C): " + str(UPS_Pico_temp)
  print "***********************************"
  print " "
  
  streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)", temp_c)
  streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity)
  streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure(IN)", pressure_mb)
  streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Battery(V)", battery_level)
  streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Power Mode(M)", power_mode)
  streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Raspberry Pi(V)", raspberryPi_level)
  streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " UPS Pico Temperature(C)", UPS_Pico_temp)
  
  streamer.flush()
  time.sleep(60*MINUTES_BETWEEN_SENSEHAT_READS)


alphanumeric
Posts: 2528
Joined: Tue Jan 19, 2016 2:17 pm
Location: Sydney, Nova Scotia, Canada

Re: LED dynamically changing colors based on sensor values

Tue May 17, 2016 12:20 pm

This is how I did it, for temp, humidity and pressure. Each one has its own color based on conditions and it changes with the conditions. My display shows date, time, temp, humidity, and pressure in a repeating scrolling message. I can adjust the brightness with the joystick, and shut it down with the joystick. My display is flipped 180 degrees. Keep that in mind when reading the code or you'll get confused. The b= is just so I can make one edit to set the default brightness for the display. The joystick dim will be one half of that. same deal with the s=, it lets me set the scroll speed with one simple edit.

Code: Select all

import os
import time, datetime
from sense_hat import SenseHat
from evdev import InputDevice, ecodes,list_devices
from select import select

devices = [InputDevice(fn) for fn in list_devices()]
for dev in devices:
    if dev.name == "Raspberry Pi Sense HAT Joystick":
        js = dev
        
sense = SenseHat()
sense.set_rotation(180)
sense.set_imu_config(False, False, False)
sense.low_light = True

b=(200) # brightness
s=(0.065) # scroll speed

def joy():
    r, w, x = select([dev.fd], [], [],0.01)
    for fd in r:
        for event in dev.read():
            if event.type == ecodes.EV_KEY:# and event.value == 1:
                if event.code == ecodes.KEY_UP: # is really stick down
                    sense.low_light = True
                elif event.code == ecodes.KEY_DOWN: # is really stick up
                    sense.low_light = False                                  
                elif event.code == ecodes.KEY_RIGHT: # is really stick left
                    raise SystemExit
                elif event.code == ecodes.KEY_ENTER: # center press
                    os.system("sudo shutdown now -P")
                    
while True:
    t = sense.get_temperature()
    p = sense.get_pressure()
    h = sense.get_humidity()

    t = round(t)
    p = round(p)
    h = round(h)

    dateString = "%a %b %-d %-I:%M %p"
    msg = "Today is %s" % (datetime.datetime.now().strftime(dateString))
    sense.show_message(msg, scroll_speed=s, text_colour=(b, b, b)) # white
          
    joy()        

    if t < 13: 
        tc = [0, 0, b]  # blue  
    elif t >= 13 and t <= 27:
        tc = [0, b, 0]  # green
    elif t > 26:
        tc = [b, 0, 0]  # red                 
    msg = "Temperature is %sc" % (t)
    sense.show_message(msg, scroll_speed=s, text_colour=tc)

    joy()

    if h > 30 and h < 60:
        hc = [0, b, 0]  # green
    else:
        hc = [b, 0, 0]  # red
    msg = "Humidity is %s%%" % (h)
    sense.show_message(msg, scroll_speed=s, text_colour=hc)

    joy()

    if p < 985:
        pc = [b, 0, 0]  # red    
    elif p >= 985 and p < 1005:
        pc = [b, b, 0]  # yellow
    elif p >= 1005 and p <= 1025:
        pc = [0, b, 0]  # green
    elif p > 1025 and p <= 1050:
        pc = [0, 0, b]  # blue
    elif p > 1050:
        pc = [b, 0, 0]  # red
    msg = "Barometer is %smb" % (p)    
    sense.show_message(msg, scroll_speed=s, text_colour=pc)

    joy()

    if p < 985:
        pc = [b, 0, 0]  # red
        msg = "Storm Warning"
        sense.show_message(msg, scroll_speed=s, text_colour=pc)
    elif p >= 985 and p < 1005:
        pc = [b, b, 0]  # yellow
        msg = "Possible Percipitation"
        sense.show_message(msg, scroll_speed=s, text_colour=pc)
    elif p >= 1005 and p <= 1025:
        pc = [0, b, 0]  # green
        msg = "Changing Conditions"
        sense.show_message(msg, scroll_speed=s, text_colour=pc)
    elif p > 1025 and p <= 1050:
        pc = [0, 0, b]  # blue
        msg = "Clear Skies"
        sense.show_message(msg, scroll_speed=s, text_colour=pc)
    elif p > 1050:
        pc = [b, 0, 0]  # red
        msg = "Very Dry"
        sense.show_message(msg, scroll_speed=s, text_colour=pc)

    joy()
 

Return to “Astro Pi”