Lesson 5

Read Temperature and Humidity

In this lesson, you’ll learn how to write a program that gets temperature and humidity data!

Write Code (Java)

Copy the code below into the project you created. If you don't have a project or forgot how to create one, revisit the Configure section.

Not your programming language? Set your preferences so we can display relevant code examples

  
package gettingstarted;

//Add Phidgets Library | You added a file called phidget22 when configuring your project. Import gives you access to the Phidgets library code inside that file. 
import com.phidget22.*;

public class GettingStarted {
    public static void main(String[] args) throws Exception{

        //Create | Here you've created a HumiditySensor and a TemperatureSensor object for your Humidity Phidget. This allows you to access both temperature and humidity data from your Phidget.
        HumiditySensor humiditySensor = new HumiditySensor();
        TemperatureSensor temperatureSensor = new TemperatureSensor();

        //Open | Open establishes a connection between your object and your physical Phidget. You provide a timeout value of 1000 to give the program 1000 milliseconds (1 second) to locate your Phidget. If your Phidget can't be found, an exception occur.
        humiditySensor.open(1000);
        temperatureSensor.open(1000);

        //Use your Phidgets | This code will print humidity and temperature read by the sensor every 150ms.
        while(true){
            System.out.println("Humidity: " + humiditySensor.getHumidity() +" %RH, Temperature: " + temperatureSensor.getTemperature() + " °C" );
            Thread.sleep(150);
        }
    }
}
  
  
//Add Phidgets Library | You added a file called phidget22 when configuring your project. Import gives you access to the Phidgets library code inside that file. 
import com.phidget22.*;

public class GettingStarted {
    public static void main(String[] args) throws Exception{

        //Create | Here you've created a HumiditySensor and a TemperatureSensor object for your Humidity Phidget. This allows you to access both temperature and humidity data from your Phidget.
        HumiditySensor humiditySensor = new HumiditySensor();
        TemperatureSensor temperatureSensor = new TemperatureSensor();

        //Open | Open establishes a connection between your object and your physical Phidget. You provide a timeout value of 1000 to give the program 1000 milliseconds (1 second) to locate your Phidget. If your Phidget can't be found, an exception occur.
        humiditySensor.open(1000);
        temperatureSensor.open(1000);

        //Use your Phidgets | This code will print humidity and temperature read by the sensor every 150ms.
        while(true){
            System.out.println("Humidity: " + humiditySensor.getHumidity() +" %RH, Temperature: " + temperatureSensor.getTemperature() + " °C" );
            Thread.sleep(150);
        }
    }
}
  
  
//Add Phidgets Library | You added a file called phidget22 when configuring your project. Import gives you access to the Phidgets library code inside that file. 
import com.phidget22.*;

//Define
TemperatureSensor temperatureSensor;
HumiditySensor humiditySensor;

void setup(){
  try{
    
    //Create | Here you've created a DigitalOutput object for your LED. An object represents how you interact with your device. DigitalOutput is a class from the Phidgets library that's used to provide a voltage to things like LEDs. 
     temperatureSensor = new TemperatureSensor();
     humiditySensor = new HumiditySensor();
    
    //Open | Open establishes a connection between your object and your physical Phidget. You provide a timeout value of 1000 to give the program 1000 milliseconds (1 second) to locate your Phidget. If your Phidget can't be found, an exception will be thrown.
    temperatureSensor.open(1000);
    humiditySensor.open(1000);
    
  }catch(Exception e){
    //Handle Exceptions | Exceptions will happen in your code from time to time. These are caused by unexpected things happening. Make sure you’ve surrounded your code with a try-catch.
    e.printStackTrace();
  }
}

void draw(){
  try{
    //Use your Phidgets | Here is where you can have some fun and use your Phidgets! You can turn your LED on/off by setting the state to true/false. The sleep command keeps your LED on by letting 1000 milliseconds pass before turning the LED off.
    println("Humidity: " + humiditySensor.getHumidity() +" %RH, Temperature: " + temperatureSensor.getTemperature() + " °C" );
    delay(150);
    
  }catch(Exception e){
    //Handle Exceptions | Exceptions will happen in your code from time to time. These are caused by unexpected things happening. Make sure you’ve surrounded your code with a try-catch.
    e.printStackTrace();
  }
}
  

Write Code (Python)

Copy the code below into the project you created. If you don't have a project or forgot how to create one, revisit the Configure section.

Not your programming language? Set your preferences so we can display relevant code examples

  
#Add Phidgets Library | You used Python's package manager to install the Phidget libraries on your computer. The import statements below give your program access to that code.
from Phidget22.Phidget import *
from Phidget22.Devices.HumiditySensor import *
from Phidget22.Devices.TemperatureSensor import *
#Required for sleep statement
import time 

#Create | Here you've created a HumiditySensor and a TemperatureSensor object for your Humidity Phidget. This allows you to access both temperature and humidity data from your Phidget.
humiditySensor = HumiditySensor()
temperatureSensor = TemperatureSensor()

#Open | Open establishes a connection between your object and your physical Phidget. You provide a timeout value of 1000 to give the program 1000 milliseconds (1 second) to locate your Phidget. If your Phidget can't be found, an exception occur.
humiditySensor.openWaitForAttachment(1000)
temperatureSensor.openWaitForAttachment(1000)

#Use your Phidgets | This code will print humidity and temperature read by the sensor every 150ms.
while(True):
    print("Humidity: " + str(humiditySensor.getHumidity()) +" %RH, Temperature: " + str(temperatureSensor.getTemperature()) + " ℃" )
    time.sleep(0.15)
  

Write Code (C#)

Copy the code below into the project you created. If you don't have a project or forgot how to create one, revisit the Configure section.

Not your programming language? Set your preferences so we can display relevant code examples

      
using Phidget22; //Add Phidgets Library | You used NuGet to install the Phidget package. The statement below give your program access to that package.

namespace GettingStarted{
    class Progam{
        public static void Main(string[] args){

            //Create | Here you've created a HumiditySensor and a TemperatureSensor object for your Humidity Phidget. This allows you to access both temperature and humidity data from your Phidget.
            HumiditySensor humiditySensor = new HumiditySensor();
            TemperatureSensor temperatureSensor = new TemperatureSensor();

            //Open | Open establishes a connection between your object and your physical Phidget. You provide a timeout value of 1000 to give the program 1000 milliseconds (1 second) to locate your Phidget. If your Phidget can't be found, an exception occur.
            humiditySensor.Open(1000);
            temperatureSensor.Open(1000);

            //Use your Phidgets | This code will print humidity and temperature read by the sensor every 150ms.
            while (true){
                System.Console.WriteLine("Humidity: " + humiditySensor.Humidity + " %RH, Temperature: " + temperatureSensor.Temperature + "°C");
                System.Threading.Thread.Sleep(150);
            }
        }
    }
}
  

Write Code (Swift)

Create two labels in your window and copy the code below into the project you created. If you don't have a project or forgot how to create one, revisit the Configure section.

Not your programming language? Set your preferences so we can display relevant code examples

Create two labels

Add the following to your PrintTemperature file then run your program. Cover the Phidget with your hand to see the temperature change

  
import Cocoa
//Add Phidgets Library | You used cocoapods to install the Phidget library. The statement below give your program access to that code.
import Phidget22Swift

class ViewController: NSViewController {
    
    @IBOutlet weak var temperatureLabel: NSTextField!
    @IBOutlet weak var humidityLabel: NSTextField!
    
    //Create | Here you've created a HumiditySensor and a TemperatureSensor object for your Humidity Phidget. This allows you to access both temperature and humidity data from your Phidget.
    let temperatureSensor = TemperatureSensor()
    let humiditySensor = HumiditySensor()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        do{
            //Subscribe to event
            let _ = temperatureSensor.temperatureChange.addHandler(onTemperatureChange)
            let _ = humiditySensor.humidityChange.addHandler(onHumidityChange)
            
            //Open | Open establishes a connection between your object and your physical Phidget.
            try temperatureSensor.open()
            try humiditySensor.open()
            
        }catch{
            print(error)
        }
    }
    
    func onTemperatureChange(sender:TemperatureSensor, temperature: Double){
        DispatchQueue.main.async { 
            //Use your Phidgets | This code will update the temperature label with the latest temperature data.
            self.temperatureLabel.stringValue = String(temperature) + "°C"
        }
    }
    
    func onHumidityChange(sender:HumiditySensor, humidity: Double){
        DispatchQueue.main.async { 
            //Use your Phidgets | This code will update the humidity label with the latest humidity data.
            self.humidityLabel.stringValue = String(humidity) + " %RH"
        }
    }
}
  

Run Your Program

You will see the temperature and humidity displayed.

I have one Phidget but two sensors?

Smart Phidgets can contain multiple sensors. You get information from these sensors by creating the appropriate object, just like the code above does. You can tell which sensors a Smart Phidget has by looking at it! Check the black enclosure for a list of objects.

Practice

  1. Only print the humidity if it is above 30%. If it is bellow 30% print “Humidity is low”.
  2. Only print the temperature if it is above 21°C (70°F). If the temperature is below 21°C, print "Room is too cold".

Note: Increase the temperature or humidity by holding the sensor tightly in your hand.

Solutions available for educators. Email us for access.
Troubleshoot

I am getting a "Timed Out" exception.

  1. Make sure the USB cable from your VINT Hub to your computer is attached properly.
  2. Make the Phidget cable (the black, red and white one) is connected to your VINT Hub and to your Humidity Phidget properly).
  3. Make sure no other program is running that uses Phidgets. If a Phidget is already in use in another program, it will be busy and won't respond to this one.

Still having issues?

Visit the Advanced Troubleshooting Page or contact us (education@phidgets.com).

What are Phidgets?

Phidgets are programmable USB sensors. Simply plug in your sensor, write code in your favorite language and go!

Phidgets have been used by STEM professionals for over 20 years and are now available to students.

Learn more

Set your preferences

Windows

Mac OS

Raspberry Pi

Java

Python

C#

Swift

NetBeans

Processing

Eclipse

Thonny

PyCharm

PyScripter

Visual Studio

Xcode

Setting your preferred operating system, programming language and environment lets us display relevant code samples for the Getting Started Tutorial, Device Tutorials and Projects

Done