Using Open Hardware Monitor to Get CPU Temperature in C#

18,913

12

6

Introduction: Using Open Hardware Monitor to Get CPU Temperature in C#

About: Green hand in arduino

Introduction

The LattePanda is a full Windows 10 compatible single board computer based on the Intel Cherry Trail CPU. It features an upgraded Z8350 CPU (up to 1.92GHz) and a more stable RTL8723BS Wi-Fi chip (2.4G 802.11n). I brought one 2/32g LattePanda and used as a normal computer, only$89!!! Due to its powerful hardware and small size, heat dissipation inevitably becomes a problem (More details about LattePanda, click here).

These days, I'm trying to make a smart fan cooling system for my baby Lattepanda. In short, just 2 steps:

1.Get the temperature of the CPU.

2.Control the fan ON/OFF.

The most difficult part of this project is getting the CPU temperature. Searching on the Internet for many days. I find many solutions but most of them don't work for me. In this post, I will show you one way that can definitely work on everyone's computer by Openhardwaremonitor. If you have any problems on getting the CPU temperature, feel free to post your questions here!

You can also test these code on your PC. (The WMI way is not working for me, but I will still post the code and you can have a try)

Step 1: What You Need:

Step 2: DEMO 1: Openhardwaremonitor

Introduction

The Open Hardware Monitor is a free open source software that monitors temperature sensors, fan speeds, voltages, load and clock speeds of a computer.

Step 1: Download Open hardware monitor

Download the lastest Open hard waremonitor software here.

You can open the .exe file first to see your hardware information, CPU useage , etc.

Step 2: Install Visual Studio 2017

Download Visual Studio 2017

Step 3 : Create A New Visual Studio Project

1. Create a new Console Application.

Click File > New Project > Visual C# > Console Application > OK (See the picture above)

2. To use the code, you need to include a copy of OpenHardwareMonitorLib.dll in your project, add a reference to it.

Right Click on References>Add Reference>Browse (See the picture above)

The OpenHardwareMonitorLib.dll is in the OpenHardwareMonitor folder.

3. Copy the following code to your Visual Studio program.

<p>using System;<br>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
   class Program
   {
       public class UpdateVisitor : IVisitor
       {
           public void VisitComputer(IComputer computer)
           {
               computer.Traverse(this);
           }
           public void VisitHardware(IHardware hardware)
           {
               hardware.Update();
               foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
           }
           public void VisitSensor(ISensor sensor) { }
           public void VisitParameter(IParameter parameter) { }
       }
       static void GetSystemInfo()
       {
           UpdateVisitor updateVisitor = new UpdateVisitor();
           Computer computer = new Computer();
           computer.Open();
           computer.CPUEnabled = true;
           computer.Accept(updateVisitor);
           for (int i = 0; i < computer.Hardware.Length; i++)
           {
               if (computer.Hardware[i].HardwareType == HardwareType.CPU)
               {
                   for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                   {
                       if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                               Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                   }
               }
           }
           computer.Close();
       }
       static void Main(string[] args)
       {
           while (true)
           {
               GetSystemInfo();
           }
       }
   }
}</p>

4. Force your application to run as administrator

It's very important, or you won't get the data back!!
Right click on Project > Add New Item, select "Application Manifest File". (See the picture above)

Change the <requestedExecutionLevel> element to: (See the picture above)

<p><requestedExecutionLevel level="requireAdministrator" uiAccess="false" /></p>

5. Click Run

There you go!! Here's the Temperature of my CPU (See the picture above). What about yours?

If you just want to get the average temp of the CPU, try to modify the code on your own~ It's very easy!
So far so good? If your have any questions, please let me know!

Step 3: DEMO 2: WMI (No Success)

This WMI demo is not working for me, but it's most of the people suggest me to use. You can have a try.

Create a new Console Application and copy the following code.

<p>using System;<br>using System.Diagnostics;
using System.Management;
class Program
{
   static void Main(string[] args)
   {
       Double CPUtprt = 0;
       System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(@"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature");
       foreach (System.Management.ManagementObject mo in mos.Get())
       {
           CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10;
          Console.WriteLine("CPU temp : " + CPUtprt.ToString() + " °C");
       }
   }
}</p>

My computer doesn't support this demo. (See the picture above)

If somebody can run this demo, please teach me~please~ lol

Step 4: DEMO 3: Cooling Fan Control System Based on CPU Temperature

Introduciton

Since we get the CPU data successfully, we can now easily control the Fan with the logic above.

(Change the threshold value according to your actual situation)

Hardware Step:

1. Connect your Arduino to your PC.

My LattePanda has an ATmega32u4 microcontroller integrated in to it (like you would find in an Arduino Leonardo) with accompanying GPIO. This makes it ideal for physical computing, IoT and embedded applications. (More details about LattePanda)

2. Connect the Fan to A0.

Software Step:

1. Upload StandardFirmata to your Arduino. (See the picture above)

2. Download the LattePanda.Firmata class library

(To find more details and tutorial about LattePanda.Firmata, click here)

3. Open Visual Studio 2017 and create a new console app: (See the picture above)

4. Add the downloaded class library to your project. Open your Solution Explorer and right-click in the blank area, then add existing item. (See the picture above)

5. Include a copy of OpenHardwareMonitorLib.dll in your project, add a reference to it.

Right Click on References>Add Reference>Browse (See the picture above)

6. Copy the following code to your Visual Studio program.

<p>using System;<br>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
using LattePanda.Firmata;
namespace Get_CPU_Temp5
{
   class Program
   {
       static Arduino arduino = new Arduino();
       public class UpdateVisitor : IVisitor
       {
           public void VisitComputer(IComputer computer)
           {
               computer.Traverse(this);
           }
           public void VisitHardware(IHardware hardware)
           {
               hardware.Update();
               foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
           }
           public void VisitSensor(ISensor sensor) { }
           public void VisitParameter(IParameter parameter) { }
       }
       static int GetCpuTemp()
       {
           int Cputemp = 0;
           UpdateVisitor updateVisitor = new UpdateVisitor();
           Computer computer = new Computer();
           computer.Open();
           computer.CPUEnabled = true;
           computer.Accept(updateVisitor);
           for (int i = 0; i < computer.Hardware.Length; i++)
           {
               if (computer.Hardware[i].HardwareType == HardwareType.CPU)
               {
                   for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                   {
                       if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                       {
                           Cputemp += (int)computer.Hardware[i].Sensors[j].Value;
                       }
                   }
               }
           }
           computer.Close();
           return Cputemp;
       }
       static void Main(string[] args)
       {
           arduino.pinMode(0, Arduino.OUTPUT);
           while (true)
           {
               int temp= GetCpuTemp()/4;
               Console.WriteLine(temp);
               if(temp>=70)
                   arduino.digitalWrite(0, Arduino.HIGH);//
               else
                   arduino.digitalWrite(0, Arduino.LOW);//
           }
       }
   }
}</p>

7. Force your application to run as administrator.

Right click on Project > Add New Item, select "Application Manifest File". (See the picture above)

Change the element to: (See the picture above)

<p><requestedExecutionLevel level="requireAdministrator" uiAccess="false" /></p>

8.Finally debug your project Connect your Arduino and click Start.

See, It's nice! (See the picture above) The fan will work when the CPU temperature is above 70 degree.

If you have any questions, please let me know!

Step 5: DEMO 4: Arduino Mod for Open Hardware Monitor

I find a really nice software in the LattePanda forum that can easily control the GPIO output according to the CPU temperature. The function is integrated in the Openhardwaremonitor software. It's really easy to use. See the original post and download the software here.

Step 6: Summary

It really takes me a lot of time to find the solution, I holp this post is useful for you and save your time. Even if you are just start with C# or start with Arduino, this tutorial is good for you to study. Modify the code, you can do a lot of thing.

Sadly, the output of the Arduino GPIO is about 5v 30mA. Fan really works slow :-< Is somebody interested in making a Arduino Fan control Shield? LOL. So we can have a more powerful GPIO output! If you have any questions, please let me know!

Be the First to Share

    Recommendations

    • First Time Author Contest

      First Time Author Contest
    • Make it Fly Challenge

      Make it Fly Challenge
    • DIY Summer Camp Contest

      DIY Summer Camp Contest

    6 Comments

    0
    DeroK1
    DeroK1

    Question 9 months ago on Step 2

    I'm trying to follow #1. I've found it on several pages throughout Google.

    I'm able to get the majority of it done, but it fails while executing with:

    "System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.'"

    I have added the OpenHardware library and its reference. I googled around and found people saying it may be a powershell issue going back to powershell 2,0.H However I'm on Powershell 5,1. Furthermore, the OpenHardware program works fine using the same exact references. That just makes me more confused.

    Any ideas on what to do??

    I'm using:
    Win 10
    OpenHardware 0.9.5
    VS 2019

    0
    keys4anyone
    keys4anyone

    Answer 3 months ago

    Got the same problem. Did you solve it?

    0
    keys4anyone
    keys4anyone

    Reply 3 months ago

    Ok, i solved this problem. Just use Tools > NuGet Packed Menager > Menage Packet Solution and there browse for "LibreHardwareMonitorLibCore" ver 1.0.3. Install it and should work fine with VS2019.

    0
    oet300mail
    oet300mail

    Question 4 months ago on Step 2

    I cant add a Manifest file from my visual studio. There simply isnt such module. I have the newest visual studio 2019. I tried making my own manifest file and selecting it from properties but it crashes.

    0
    billing.indiaaccess

    Very helpful tips,
    I will use the same to solve issues of my company Indiaaccess Servers and Hostasp Servers
    Thanks for your info

    0
    King_Dinesh
    King_Dinesh

    2 years ago

    Hi, nice tutorial! This is what I needed but too sad it doesn't work for me. So I followed the instructions but what's confusing is the tutorial says: connect to the fan to pin A0, while the demonstration picture shows the fan is connected to the normal 5V Ground pins instead of A0... and on the A0 I presume you mean the 5v and the ground pin? Sorry I am very new to arduino.
    Also I followed everything and the console app is working but the fan doesn't slow down or stop.. I don't understand this step:

    Step 8: Finally debug your project and connect to your arduino and click start.

    How do I connect to my arduino before I start? What do you mean by that?

    So far when I hit debug the console app starts, I see the temperatures and the white arduino led is on steadily, while the blue one is blinking every time a temperature is meassured. So it looks like the arduino is receiving something.. This stops when I stop debugging. The fan keeps spinning at full speed. Please help because the fan is driving me crazy :(

    15640971749096588974154181532111.jpg