Using OPEN HARDWARE MONITOR to get Cpu temperature in C# and make a fan cooling system

A place to showcase LattePanda creations!
Post Reply
User avatar
Kellman616
Posts: 42
Joined: Fri Feb 24, 2017 7:11 am

Mon Jan 29, 2018 3:34 am

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).

Image

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) :D

Hardware:
Software: 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 Openhardwaremonitor software here.

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

Image

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

Image

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

Image

The OpenHardwareMonitorLib.dll is in the OpenHardwareMonitor folder.

Image

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

Code: Select all

using System;
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();
           }
       }
   }
}
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".

Image

Change the
<requestedExecutionLevel>
element to:

Code: Select all

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

5. Click Run

There you go!! Here's the Temperature of my CPU. What about yours? 8-)

Image

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!

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.

Code: Select all

using System;
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");
       }
   }
}
My LattePanda doesn't support this demo. :cry:

Image

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

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 below.

(Change the threshold value according to your actual situation)

Image

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.

Image

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:

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

Image

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

Right Click on References>Add Reference>Browse

Image

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

Code: Select all

using System;
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);//
           }
       }
   }
}
7. Force your application to run as administrator.

Right click on Project > Add New Item, select "Application Manifest File".

Image

Change the
<requestedExecutionLevel>
element to:

Code: Select all

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

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

Image

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

If you have any questions, please let me know!

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.

Image

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. :P 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! ;)

User avatar
LattePanda
Site Admin
Posts: 2425
Joined: Wed Jan 20, 2016 9:09 am

Thu Feb 01, 2018 3:17 am

Nice! Thanks for the sharing! :lol:
Enjoy Tinkering with LattePanda ! :lol:

User avatar
justjim1220
Posts: 1
Joined: Thu Nov 01, 2018 5:19 am

Thu Nov 01, 2018 5:40 am

OK, I am fairly new to C#, but have a pretty decent underlying understanding of coding and programming...

I love this article, but I need it to do a little bit more...

First off, I need the output results to go to a text or json file.
I basically need to know how to get the results to a file and not to the console.

I am also trying to figure out how to change the results from this:

CPU Core #1:50
CPU Core #2:54
CPU Core #3:49
CPU Core #4:52
CPU Package:54

to this:

Core 0 : 50
Core 1 : 54
Core 2 : 49
Core 3 : 52

The spacing is not a problem, that I can figure out.
It's the changing of the result from CPU Core # to just Core and starting with 0 and not 1
I don't need the Core Package result, but I am sure that is probably an easy fix.

Next, I see that the results are coming up every second, can that be changed to, say like every 15 seconds or so.

I also need to understand how the result file isn't going to continue adding to the file as I don't need to save each result. Meaning, is it possible to just overwrite the file with each 15 second result being written to it?

I have been searching, and have not been able to find any direct answers, they all are either too vague, or I just plain don't get it.

Any help, hints, or explanations you can give will be greatly appreciated!

Thanks in advance!

User avatar
Lutz
Posts: 209
Joined: Mon Apr 18, 2016 4:30 am
Location: Germany, NRW

Thu Nov 01, 2018 7:24 am

"C# write print to file"
"C# string manipulation"
should give many examples
If you are using Visual Studio there should also be many examples at Microsoft by "F1"... but maybe not für every VS version.

In the past you were coding 1000 lines during a week for your needed function.
Today you are reading documentation for a whole day to find ONE simple line at last...

(string manipulation : Doing this a always wish to go back to good old BASIC times)

User avatar
LNC-SPN
Posts: 28
Joined: Thu May 19, 2016 7:04 pm
Location: Valencia, Spain
Contact:

Wed Nov 14, 2018 7:46 pm

'm glad to see you got it @Kellman616! , I was OFF, sorry for not answer your reply. Finally you got it by running your program with Administrator privileges?
Kellman616 wrote:
Mon Jan 29, 2018 3:34 am
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! ;)
To power the Fan you have to connect it to the CN2 header (5v- GND), to turn ON and OFF the fan you need to use a Relay or a NPN Transistor.
If you use a Relay, connect it to the GPIOs, and control the Relay by using the digital Pin, cut the 5v cable of the fan and connect one side to COM and the other side to NO (Normally Open).
Image
Kellman616 wrote:
Mon Jan 29, 2018 3:34 am
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.
That's the reason why I used OHM to get the CPU temperature. :)

Post Reply