{"id":240981,"date":"2023-11-27T11:41:18","date_gmt":"2023-11-27T10:41:18","guid":{"rendered":"https:\/\/emariete.com\/?p=240981"},"modified":"2023-12-03T21:47:53","modified_gmt":"2023-12-03T20:47:53","slug":"fan-speed-variable-raspberry-pi","status":"publish","type":"post","link":"https:\/\/emariete.com\/en\/ventilador-velocidad-variable-raspberry-pi\/","title":{"rendered":"Tutorial: Temperature-controlled variable speed fan for Raspberry Pi"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Do you want to, like me, <strong>reduce Raspberry Pi fan noise<\/strong> (or even eliminate it)? If so, here is the ultimate solution to our noise problems: the variable speed fan for Raspberry Pi. An easy and cheap solution (a couple of euros).<\/p>\n\n\n\n<p class=\"has-global-color-8-background-color has-background wp-block-paragraph\">This tutorial <strong>is accompanied by a video<\/strong>I'll leave it below, so that you can follow it very easily.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Following this tutorial, you will be able to build, with very few components, a small controller for the Raspberry Pi to regulate the speed of its fan depending on its temperature and we will complete it with a small Python program to do the monitoring and control work.<\/p>\n\n\n<div class=\"gb-container gb-container-f70ece6b\">\n\n<p class=\"wp-block-paragraph\">Whenever I write a blog post, my top priority is always to <strong>that provides value for the reader<\/strong>that actually provides knowledge. Not write empty articles that just skim over a topic with information that is already all over the internet.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why have I written this tutorial on how to set up a temperature-controlled variable speed Raspberry fan, when there are already many on the internet?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because the articles I found seemed too biased, or didn't seem to explain the basics well, in a way that I didn't think they could. <em>understandable<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In addition, I have found that most tutorials for implementing temperature-based PWM speed control on the Raspberry Pi <strong><span style=\"text-decoration: underline;\">THEY DON'T DO IT WELL<\/span><\/strong> (I will explain why later).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This article (and the other articles it links to, which I have written in support of this tutorial), attempt to cover the topic in depth but <em>understandable<\/em>, trying to <strong>that anyone can easily understand it just by reading the blog and with no prior preparation.<\/strong>.<br>I hope you enjoy it!<\/p>\n\n<\/div>\n\n\n<div class=\"wp-block-group has-global-color-8-background-color has-background\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p class=\"wp-block-paragraph\">It seems unbelievable how long it took, both hardware and software, until everything worked perfectly. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The fact that it has taken longer than expected has not discouraged me at all, quite the contrary. This means that the subject is not so simple and that this article will have a lot of value.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The truth is that I have learned a lot along the way. I didn't expect that such an apparently simple subject would give me so many headaches.<\/p>\n<\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I have several Raspberry Pi running at home for different tasks. They are small devices, with low power consumption and very stable in their operation (they can be running continuously for months without needing a reboot).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I have used the original Raspberry Pi (the v1), the Raspberry Pi 2, the Raspberry Pi 3 and its \"in-between\" versions (with the \"B\" or \"+\" added) and temperature has never been an issue. They have all worked great for years with no heat problems.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The last one I added, a Raspberry Pi 4, has much more power and performance than the previous ones and that means that it has some <strong>cooling requirements far above those of their predecessors<\/strong>Can a Raspberry Pi 4 be used without a fan? Yes, but <strong>it is not advisable to run a Raspberry Pi 4 without a fan<\/strong> to refrigerate it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is assumed that if we put a Raspberry Pi 4 it is because we need its power in some moments (if not, why use a Raspberry Pi 4?, better to put one of the previous models, which are cheaper and consume less) and in this case to provide it with <strong>a cooling fan is almost indispensable<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The disadvantage of adding a fan to the Raspberry Pi 4 is that <strong>ceases to be a silent 100% device<\/strong> to become a minor nuisance (especially in a quiet bedroom or office).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-cuanto-ruido-hace-una-raspberry-pi-4\">How loud is a Raspberry Pi 4?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The Raspberry Pi 4 itself does not make noise<\/strong>has no moving parts, what makes noise is its <strong>fan<\/strong>\u2026<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The noise level of a 5V fan for a Raspberry Pi 4 can vary depending on the model and make of the fan, as well as its design and build quality. However, in general, small 5V fans tend to be quite quiet, especially if powered at 3.3V (yes, 5V fans powered at 3.3V so they spin slower and make less noise).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The noise level of a fan is generally measured in decibels (dB), and small 5V fans designed for Raspberry Pi often have a noise level of around 20 to 30 dB. This is relatively quiet and should not be annoying in most situations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is important to note that there are some factors that can influence the noise level, such as the speed at which the fan operates and the quality of the fan's bearing. If you need particularly quiet operation, you can opt for fans with high quality bearings, such as fluid bearings or ball bearings, which tend to generate less noise than simpler bearings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In any case, if noise is a concern for you, you can look for fans designed specifically for low-noise applications or those with speed control options to adjust fan speed as needed, which can help you maintain a balance between temperature and noise.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Taking all of the above into account, we can say that the fan noise of a Raspberry Pi 4, once we have chosen the fan (better or worse, higher or lower quality) and connected it, <strong>will always spin at the same speed, cool in the same way and make the same noise.<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If we want to reduce the noise, taking advantage of the fan always running at maximum (in fact, we don't even need the fan to be always running) the solution is to have a variable speed fan for Raspberry Pi.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why should I put a fan on a Raspberry Pi 4?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">It is good to put a fan on a Raspberry Pi 4 or other similar electronic devices for several reasons:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Refrigeration:<\/strong> The Raspberry Pi 4 can generate heat, especially when running CPU or GPU intensive applications. A fan helps dissipate that heat more efficiently, which prevents the device's temperature from rising too high. Operating at lower temperatures can help prevent overheating, which can negatively affect the Raspberry Pi's performance and lifespan.<\/li>\n\n\n\n<li><strong>Increased performance and stability:<\/strong> Keeping the temperature of the CPU and other components at a lower temperature can allow the Raspberry Pi to run more steadily and without slowdowns caused by overheating.<\/li>\n\n\n\n<li><strong>Damage prevention:<\/strong> Excessive heat can damage electronic components over time. A fan can extend the life of the Raspberry Pi and prevent long-term damage.<\/li>\n\n\n\n<li><strong>Consistent performance under intensive workloads:<\/strong> If you plan to use your Raspberry Pi for intensive tasks, such as game emulation, machine learning or video transcoding, a fan can be essential to maintain consistent performance and avoid thermal throttling.<\/li>\n\n\n\n<li><strong>Reduced fan speed and noise:<\/strong> You don't need the fan to be at full speed all the time. You can set the fan to run only when the temperature reaches a certain threshold, which helps reduce noise and power consumption.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">All of the above confirms what we suspected, putting a fan on a Raspberry Pi 4 is a good idea if you plan to use it for tasks that generate heat or in environments where the ambient temperature is high. It will help keep the Raspberry Pi running efficiently and prolong its lifespan by keeping temperatures under control.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">And since we're putting a fan, we'd better put a variable speed fan for Raspberry Pi.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is the quietest Raspberry Pi 4 fan?<\/h2>\n\n\n\n<div class=\"wp-block-media-text is-stacked-on-mobile\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"500\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-Raspberry-Pi.png\" alt=\"\" class=\"wp-image-240994 size-full\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-Raspberry-Pi.png 500w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-Raspberry-Pi-300x300.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-Raspberry-Pi-150x150.png 150w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"wp-block-paragraph\">I can tell you, without fear of contradiction, that <strong>the quietest fan is the fan that is switched off.<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can put better quality fans, lower voltage, graphene or Kryptonite bearings, but all of them, without exception, make noise.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If we want a fan to be silent, the best way is to <strong>turn it off <\/strong>when it is not necessary and put it to the <strong>minimum speed<\/strong> to keep the temperature of the Raspberry Pi 4 under control (it is not necessary that it is always \"always on\").<em>as cold as possible<\/em>\").<\/p>\n<\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">However, if I have something to tell you: As a general rule, Raspberry 4 fans are very small (usually 40mm) and this means that they have to rotate very fast in order to provide a significant amount of air. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To move the same amount of air, a smaller fan (such as a 40 mm fan) must spin approximately 9 times faster than a larger fan (such as a 120 mm fan).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The speed ratio is calculated as follows:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"353\" height=\"52\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad.png\" alt=\"\" class=\"wp-image-240991\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad.png 353w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad-300x44.png 300w\" sizes=\"auto, (max-width: 353px) 100vw, 353px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Where:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em>D<\/em><sub>large fan<\/sub>is the diameter of the large fan (in this case 120 mm).<\/li>\n\n\n\n<li><em>D<\/em><sub>small fan<\/sub>is the diameter of the small fan (in this case 40 mm).<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If we substitute the values in the formula:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"390\" height=\"38\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad-2.png\" alt=\"\" class=\"wp-image-240992\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad-2.png 390w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Formula-relacion-de-velocidad-2-300x29.png 300w\" sizes=\"auto, (max-width: 390px) 100vw, 390px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">In summary, if we want to have the quietest possible fan, we should look at:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Switch off <\/strong>the fan when it is not needed<\/li>\n\n\n\n<li>Adjust the <strong>fan speed<\/strong> to the minimum necessary at any given time<\/li>\n\n\n\n<li>Mount the <strong>larger fan<\/strong> that it is possible for us to<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">The fan for the Raspberry Pi 4<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For our variable speed fan we are going to use a small 5V DC fan (if you're curious, we're going to use a 5V DC fan), <a href=\"https:\/\/emariete.com\/en\/control-the-speed-of-a-fan-with-pwm\/#tipos-ventiladores\" target=\"_blank\" rel=\"noreferrer noopener\">click here to see the different types of fans that can be used on a Raspberry<\/a>).<\/p>\n\n\n\n<div class=\"wp-block-media-text is-stacked-on-mobile\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" decoding=\"async\" width=\"1000\" height=\"785\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-DC-basico.jpg\" alt=\"\" class=\"wp-image-241004 size-full\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-DC-basico.jpg 1000w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-DC-basico-300x236.jpg 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-DC-basico-768x603.jpg 768w\" sizes=\"auto, (max-width: 1000px) 100vw, 1000px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"wp-block-paragraph\">This is a simple fan that only has a DC motor that moves the blades. In this case, its speed will depend on the voltage we feed it with.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It has only two wires, the positive and negative power wires (which, by the way, you can connect backwards and the fan will rotate in the opposite direction).<\/p>\n\n\n<div class=\"gb-container gb-container-0d0288ec\">\n<span >No products found.<\/span>\n<\/div><\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">If you want more details about why I have chosen this type of fan, why I have decided to vary its speed via PWM and many more details about PWM fan speed control, you will like the following blog article:<\/p>\n\n\n<div class=\"gb-container gb-container-14311298\">\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"sUmmfzDVvP\"><a href=\"https:\/\/emariete.com\/en\/control-the-speed-of-a-fan-with-pwm\/\">Controlling the speed of a fan with PWM<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;Controlling the speed of a fan with PWM&quot; - eMariete\" src=\"https:\/\/emariete.com\/controlar-la-velocidad-de-un-ventilador-con-pwm\/embed\/#?secret=rorxVWkHCH#?secret=sUmmfzDVvP\" data-secret=\"sUmmfzDVvP\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Although it is not obligatory to read this article, it is interesting to do so, as it lays the groundwork for what we will see below.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you find that you get lost in the following explanations, come back here and read the article \"<a href=\"https:\/\/emariete.com\/en\/control-the-speed-of-a-fan-with-pwm\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Controlling the speed of a fan with PWM<\/em><\/a>\".<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-como-vamos-a-regular-la-velocidad-del-ventilador-de-la-raspberry-pi-4\">How do we regulate the fan speed of the Raspberry Pi 4?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We are going to do this by generating a PWM signal and amplifying it, with a small circuit, as the Raspberry Pi cannot directly supply a PWM signal with the power needed to move a fan.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To do this, we are going to write a small Python program that generates a PWM signal that has a <em>Duty cycle<\/em> variable depending on how fast you need the fan to spin to cool the Raspberry Pi 4.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will make the Raspberry Pi 4 run this program automatically and every 15 seconds (configurable) the program will modify, if necessary, the PWM signal to increase or decrease the fan speed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This programme shall have a minimum value of <em>Duty cycle<\/em> PWM signal to ensure that the fan always moves and never blocks because it does not have enough energy to overcome inertia and start moving.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In addition, we are going to write a small auxiliary program that will allow us to find out what is the <em>Minimum duty cycle<\/em> for the fan to start and what is the <em>Minimum duty cycle<\/em> so that the fan does not stop, once it is in motion (both <em>Working cycles<\/em> need not be the same, and they will not be).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For our PWM signal we will use the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Amplitude<\/strong>: 3.3V<\/li>\n\n\n\n<li><strong>Duty cycle<\/strong>It will go from the minimum that allows the fan to start (or not to stop, if it is already moving) to 100%. <\/li>\n\n\n\n<li><strong>Frequency<\/strong>: 25Khz<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Just by feeding the fan with this PWM signal, instead of connecting it directly to 5V (or 3.3V), we will have a variable speed fan on the Raspberry Pi.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The PWM signal amplifier electronic circuit<\/h2>\n\n\n\n<div class=\"wp-block-media-text is-stacked-on-mobile\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"500\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-con-controlador-futurista-500x500-1.jpg\" alt=\"\" class=\"wp-image-241075 size-full\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-con-controlador-futurista-500x500-1.jpg 500w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-con-controlador-futurista-500x500-1-300x300.jpg 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Ventilador-con-controlador-futurista-500x500-1-150x150.jpg 150w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"wp-block-paragraph\">The normal power consumption of small 5V 40x40mm fans is approximately 150mA.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Raspberry Pi can only safely provide 16mA, according to the official Raspberry Pi documentation (and 50mA simultaneously, adding up all its pins).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We are going to add a very simple electronic circuit to our Raspberry Pi 4, with a transistor that, with this small control signal, of limited intensity, is capable of generating an equal signal but that can reach a minimum of 200 or 300mA.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Such circuits are often referred to as <em><strong>\"drivers<\/strong><\/em>.<\/p>\n<\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">There are two main ways of doing it (very similar) and I'll leave you with both, so you can choose the one you prefer (although my recommendation is to use the MOSFET version).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">PWM driver with BJT transistor<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the schematic of our driver with BJT transistor:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Schematic_Driver-PWM-con-transistor-BJT_2023-11-02.png\" alt=\"\" class=\"wp-image-241076\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Unless you already have the components (especially the BJT transistor), <strong>I recommend you to build the PWM driver with MOSFET transistor.<\/strong> below.<\/p>\n\n\n\n<div class=\"wp-block-media-text is-stacked-on-mobile\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Prototype_Driver-PWM_BJT_-transistor-2023-11-02-1024x576.png\" alt=\"\" class=\"wp-image-241084 size-full\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Prototype_Driver-PWM_BJT_-transistor-2023-11-02-1024x576.png 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Prototype_Driver-PWM_BJT_-transistor-2023-11-02-300x169.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Prototype_Driver-PWM_BJT_-transistor-2023-11-02-768x432.png 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Prototype_Driver-PWM_BJT_-transistor-2023-11-02.png 1192w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"wp-block-paragraph\">This is the prototype of the BJT transistor driver I built for testing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, the plate is very dirty (let's say it is very dirty). <em>\"worked\".<\/em>), due to the large number of tests I did with different variations:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Different transistors in configuration <em>high-side<\/em> y <em>low-side<\/em>different resistor values, many measurements, etc...<\/p>\n<\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Even using normal components <em>\"through hole\".<\/em> (not surface mount), as you can see it was a very compact size, so you can fit it inside the Raspberry Pi 4 case.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the following article you have all the information on the <a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt\/\" target=\"_blank\" rel=\"noreferrer noopener\">PWM driver with BJT transistor<\/a>:<\/p>\n\n\n<div class=\"gb-container gb-container-83f81007\">\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"XViJkaKnrP\"><a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt\/\">PWM driver with BJT transistor<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;PWM driver with BJT transistor&quot; - eMariete\" src=\"https:\/\/emariete.com\/driver-pwm-transistor-bjt\/embed\/#?secret=M7V5brnS42#?secret=XViJkaKnrP\" data-secret=\"XViJkaKnrP\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n<\/div>\n\n\n<h3 class=\"wp-block-heading\">PWM driver with MOSFET transistor<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>This is the type of driver I recommend you build.<\/strong>. Among other advantages, it is more efficient in operation than the BJT transistor driver and <strong>it heats up less<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is the schematic of our PWM signal driver with MOSFET transistor:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"550\" height=\"550\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Schematic_Driver-PWM-con-transistor-MOSFET_2023-11-02.png\" alt=\"\" class=\"wp-image-241077\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Schematic_Driver-PWM-con-transistor-MOSFET_2023-11-02.png 550w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Schematic_Driver-PWM-con-transistor-MOSFET_2023-11-02-300x300.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Schematic_Driver-PWM-con-transistor-MOSFET_2023-11-02-150x150.png 150w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, it is very similar to the BJT transistor driver we saw before.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the following article you have all the information on the <a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt\/\" target=\"_blank\" rel=\"noreferrer noopener\">PWM driver with transistor <\/a><a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">BJT<\/a>:<\/p>\n\n\n<div class=\"gb-container gb-container-14320f57\">\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"Rqp7Frfy3t\"><a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt-2\/\">PWM driver with MOSFET transistor<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;PWM driver with MOSFET transistor&quot; - eMariete\" src=\"https:\/\/emariete.com\/driver-pwm-transistor-mosfet\/embed\/#?secret=rdb2ABVlPo#?secret=Rqp7Frfy3t\" data-secret=\"Rqp7Frfy3t\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n<\/div>\n\n\n<h2 class=\"wp-block-heading\">Variable speed fan control software for the Raspberry Pi 4<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the video I have prepared to make it easier for you to follow this tutorial. I recommend that you watch it as you read it.<\/p>\n\n\n<div class=\"gb-container gb-container-9273ec54\">\n<div class=\"gb-container gb-container-d837ac58\">\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Tutorial: Temperature-controlled Raspberry Pi variable speed fan - WELL EXPLained!\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/8tjSm3EvOCQ?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n<\/div>\n<\/div>\n\n<div class=\"gb-container gb-container-68641a62\">\n\n<p class=\"wp-block-paragraph\"><strong>Making these videos takes a lot of work<\/strong>. If you like the video don't forget to \"Like\" and subscribe to the channel. That's&nbsp;<strong>will motivate me to keep making more videos like this one.<\/strong><\/p>\n\n\n\n<p class=\"has-text-align-center wp-block-paragraph\"><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><a href=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-scaled.jpg\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"462\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-1024x462.jpg\" alt=\"\" class=\"wp-image-241245\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-1024x462.jpg 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-300x135.jpg 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-768x347.jpg 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-1536x693.jpg 1536w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Mesa-laboratorio-2048x924.jpg 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n\n<\/div>\n\n<div class=\"gb-container gb-container-1f704b4a\"><\/div>\n\n\n<p class=\"wp-block-paragraph\">Although what we are about to do is very simple and shouldn't cause any problems, the risk is always there, so <strong>I recommend that you make a backup copy<\/strong> (I suggest you directly clone your Micro SD card before touching anything).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Generating a PWM signal with the Raspberry Pi 4<\/h3>\n\n\n<div class=\"gb-container gb-container-7e059c3a\">\n\n<p class=\"wp-block-paragraph\">Generating PWM signal on the Raspberry Pi with Python is not difficult at all, but it is important to know how, because it is, <strong>either I am very wrong, or the vast majority of information on the internet is wrong.<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here's why most of the tutorials for implementing temperature-based PWM speed control on the Raspberry Pi that I've seen on the internet have been for the following reasons <strong><span style=\"text-decoration: underline;\">THEY DON'T DO IT WELL<\/span><\/strong>.<\/p>\n\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Initially, I did this whole project with the RPi.GPIO library (which is the recommended one, and the one 99% people use on the internet) and I noticed some noises in the fan and very little smoothness in its operation. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I attributed the noises and poor running smoothness to the fact that it was not a good quality fan, but, by testing with the oscilloscope, <strong>I saw that something wasn't right...<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The PWM signal generated was horrendous, full of noise, at a frequency that was not the one I had set and both the frequency and duty cycle values were <strong>very unstable<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most curious thing was that <strong>the system worked<\/strong> and if I hadn't tested thoroughly with the oscilloscope I would never have known how bad it was turning out. Surely there are millions of systems like this <em>'functioning'.<\/em> in the world without knowing the problems they have.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I did some research and found that the library <em>RPi.GPIO<\/em> <strong>does not generate the PWM signals by hardware, but by software.<\/strong> (even if you use a hardware pin), and worse, it has problems with signals over a few kilohertz.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Using a PWM signal with a frequency of 1Khz, for example, the system worked, but the fan made a noise, perfectly audible, that was worse than having it running at full power.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An additional important disadvantage is that when the PWM signal is generated by software, it is the CPU of the Raspberry Pi that does all the work (and it is a lot, because it has to be continuously attending and activating and deactivating the pin) so the CPU consumption can be high.<\/p>\n\n\n\n<p class=\"has-global-color-8-background-color has-background wp-block-paragraph\">I am still documenting all this, testing, writing and recording videos so that I can explain it well. I will include the information shortly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The solution was to use a different library, instead of the <em>RPi.GPIO<\/em>. One that supports hardware PWM signal generation.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are a few projects (the fewest) that use some form of hardware PWM control, but most have problems or limitations.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>They are based on obsolete, or under-used, or unsupported projects such as <em>wiringPi<\/em><\/li>\n\n\n\n<li>They need a running demon (like <em>pigpio<\/em>), which complicates installation and architecture.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Generating a hardware PWM signal with Raspberry Pi 4<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can generate a PWM signal on a pin of a Raspberry Pi 4, in a very easy way, using Python and the library <em>\u2018<strong>rpi-hardware-pwm<\/strong>\u2018<\/em>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The first thing to do is to prepare the Raspberry Pi to be able to use the two hardware PWM channels it has.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You have to edit the file <em>\/boot\/config.txt<\/em> and include the line <em>dtoverlay=pwm-2chan<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To do this, from the console run:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano \/boot\/config.txt\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">And after the last line beginning with <em>dtoverlay<\/em> (which is possibly annotated, with a pad <em>\u2018#\u2019<\/em>), includes the line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ndtoverlay=pwm-2chan\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This will enable hardware PWM in the <strong>Default GPIO: GPIO_18 for PWM0 and GPIO_19 for PWM1<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, you can use (instead of the previous line), the line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ndtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This will enable hardware PWM in the <strong>Alternative GPIOs: GPIO_12 for PWM0 and GPIO_13 for PWM1<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now restart the Raspberry Pi, for the changes to take effect, with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo reboot\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">When the Raspberry Pi starts up again, go back into the console and install the library <em>rpi-hardware-pwm<\/em> with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo apt-get update\nsudo pip3 install rpi-hardware-pwm\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"pwm_generator\">Test programme and calibration of the PWM signal for the specific fan<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Raspberry Pi is now ready to generate a hardware PWM signal.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now we need a programme, which allows us to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Prove in an easy way that it does indeed work.<\/li>\n\n\n\n<li>Find out the minimum duty cycles so that our fan does not stall (each one is different).<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For this I have created a very simple script, in the Python programming language, <code>hardware_pwm_generator.py<\/code>which allows us to call it with three parameters on the Raspberry Pi command line:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>0 to use the channel <strong>PWM0<\/strong> at <strong>GPIO_18 PWM0 and PWM1<\/strong> at <strong>GPIO_19<\/strong> (or PWM0 on GPIO_12 PWM0 and PWM1 on GPIO_13, if you have chosen the alternative pins in the file <em>\/boot\/config.txt<\/em>.<\/li>\n\n\n\n<li>The frequency in hertz. For example, 25000 for 25Khz.<\/li>\n\n\n\n<li>The duty cycle (a number between 0 and 100).<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport sys\nfrom rpi_hardware_pwm import HardwarePWM\n\ndef set_pwm(pwm_channel, frequency, duty_cycle):\n    pwm = HardwarePWM(pwm_channel, frequency).\n    pwm.start(duty_cycle)\n    input(\"Press Enter to stop the PWM...\")\n    pwm.stop()\n\nif __name__ == \"__main__\":\n    if len(sys.argv) != 4:\n        print(\"Usage: python pwm_generator.py   \")\n        sys.exit(1)\n\n    pwm_channel = int(sys.argv[1])\n    frequency = float(sys.argv[2])\n    duty_cycle = float(sys.argv[3])\n\n    try:\n        set_pwm(pwm_channel, frequency, duty_cycle)\n    except KeyboardInterrupt:\n        pass\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Save this program in a file called \"hardware_pwm_generator.py\".<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can do this by running this line from the console:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano hardware_pwm_generator.py\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can run the program with the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython hardware_pwm_generator.py   .\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Replaces:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>&lt;canal_pwm&gt;<\/em><\/strong> By the PWM channel you want to use (0 or 1). For example, a <strong>0 to use PWM0 channel<\/strong> of GPIO_18.<\/li>\n\n\n\n<li><strong><em>.<\/em><\/strong> By the frequency in Hertz that you want the PWM signal to have. For example, <strong>25000 for 25Khz<\/strong>.<\/li>\n\n\n\n<li><code><em>&lt;<strong>work_cycle<\/strong><\/em>&gt;<\/code> by the duty cycle you want, e.g. \"50\" for a 50% duty cycle.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For example, to generate on PWM channel 0 (PWM0) on GPIO_18 a signal at 25Khz with a duty cycle of the 80%, you have to run on the console:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\npython hardware_pwm_generator.py 0 25000 80\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">To exit and stop the PWM, just press <em>[Enter]<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can also interrupt and exit the programme with <em>Ctrl-C<\/em>. In this case the PWM signal will not stop.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The code is as follows:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Raspberry Pi CPU temperature readings<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let's see what we have to do to read the temperature of the CPU of the Raspberry Pi in a simple way, to go little by little and to be understandable. Later we will see how to modify the PWM signal based on the temperature.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To read the CPU temperature of a Raspberry Pi you can use the library <strong><code><em>psutil<\/em>.<\/code><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Make sure you have the library <strong><code><em>psutil<\/em>.<\/code><\/strong> installed on your Raspberry Pi. You can install <strong><em><code>psutil<\/code> <\/em><\/strong>with the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo apt-get update\nsudo pip install psutil\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Now that we have the library installed, we can see the temperature by running the following line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nvcgencmd measure_temp\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here is a simple Python program that uses the psutil library to read the CPU temperature and prints it to the console every 5 seconds:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport psutil\nimport time\n\ndef get_cpu_temperature():\n    try:\n        temperature = psutil.sensors_temperatures()['cpu_thermal'][0].current\n        return temperature\n    except Exception as e:\n        print(f \"Error getting CPU temperature: {e}\")\n        return None\n\ndef main():\n    try:\n        while True:\n            temperature = get_cpu_temperature()\n\n            if temperature is not None:\n                print(f \"CPU temperature: {temperature}\u00b0C\")\n\n            time.sleep(5)\n\n    except KeyboardInterrupt:\n        pass\n\nif __name__ == \"__main__\":\n    main()\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can write it in the file <em>temperature_reader.py<\/em> (as we did before with hardware_pwm_generator.py), with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano temperature_reader.py\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Different versions of Raspberry Pi and Linux may call the temperature sensor by a name different from <em>cpu_thermal<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Run it from the console with the line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython temperature_reader.py\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">If you get an error like \"<em>Error getting CPU temperature: 'cpu_thermal'.<\/em>\"probably because your sensor is not called <em>cpu_thermal<\/em> and you will have to find out his name.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once you know the name, you will have to substitute in line 6 the name <em>cpu_thermal<\/em> by the name of your sensor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, on both the Raspberry Pi 3 with which I started testing and the Raspberry Pi, this sensor was named <em>cpu_thermal<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can use this small code to find out by printing out the list of all available sensors to understand which names are present in your system:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nimport psutil\nimport time\n\ndef get_cpu_temperature():\n    try:\n        sensors_data = psutil.sensors_temperatures()\n        if 'coretemp' in sensors_data:\n            temperature = sensors_data['cpu_thermal'][0].current\n            return temperature\n        else:\n            print(\"No data found for sensor 'cpu_thermal'. Sensors available:\", sensors_data.keys())\n            return None\n    except Exception as e:\n        print(f \"Error getting CPU temperature: {e}\")\n        return None\n\ndef main():\n    try:\n        while True:\n            temperature = get_cpu_temperature()\n\n            if temperature is not None:\n                print(f \"CPU temperature: {temperature}\u00b0C\")\n\n            time.sleep(5)\n\n    except KeyboardInterrupt:\n        pass\n\nif __name__ == \"__main__\":\n    main()\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This script will print the list of available sensors on your system if it cannot find the sensor. <em>cpu_thermal<\/em>. By running the script, you will be able to see which sensor names are present, and you can adjust the code accordingly to read the temperature from the correct sensor.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Temperature reading program and fan speed adjustment<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To read the CPU temperature of a Raspberry Pi 4 and generate a PWM signal with a duty cycle proportional to the CPU temperature, we will use, as we have seen before, the library <strong><code><em>psutil<\/em>.<\/code> <\/strong>to obtain the CPU temperature and, again, the library <strong><em>rpi-hardware-pwm<\/em><\/strong> to generate the PWM signal.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n#!\/usr\/bin\/env python3\n\nimport configparser\nfrom rpi_hardware_pwm import HardwarePWM\nimport psutil\nimport time\nimport sys\nimport atexit\nimport syslog\nimport os\nimport signal\n\n#Initialise variables\nchannel_pwm = 0\nfrequency = 25000\nprevious_duty_cycle = 0\ninput_temperature = 0\ntime = 6\nduty_cycle = 0\n\npwm = HardwarePWM(channel_pwm, frequency)\n\ndef print_debug(message):\n    if debug and not as_a_service:\n        print(message)\n    if debug and as_a_service:\n        syslog.syslog(syslog.LOG_INFO, message)\n        \ndef initialize_configuration():\n    # Defaults.\n    defaults = {\n        test_interval': 5,\n        'pwm_channel': 0,\n        'frequency': 25000,\n        'temp_min': 45,\n        'temp_max': 65,\n        'cycle_min': 60,\n        'cycle_max': 100,\n        'hysteresis': 2,\n        'debug': False,\n        'as_a_service': True\n    }\n\n    try:\n        # Load configuration from INI file.\n        config = configparser.ConfigParser()\n        config.read(\"temperature_pwm_controller.ini\")\n\n        # Unpack configuration or use default values\n        test_interval = config.getint(\"config\", \"test_interval\", fallback=defaults['test_interval'])\n        pwm_channel = config.getint(\"config\", \"pwm_channel\", fallback=defaults['pwm_channel'])\n        frequency = config.getint(\"config\", \"frequency\", fallback=defaults['frequency'])\n        temp_min = config.getint(\"config\", \"temp_min\", fallback=defaults['temp_min'])\n        temp_max = config.getint(\"config\", \"temp_max\", fallback=defaults['temp_max'])\n        cycle_min = config.getint(\"config\", \"cycle_min\", fallback=defaults['cycle_min'])\n        cycle_max = config.getint(\"config\", \"cycle_max\", fallback=defaults['cycle_max'])\n        hysteresis = config.getint(\"config\", \"hysteresis\", fallback=defaults['hysteresis'])\n        debug = config.getboolean(\"config\", \"debug\", fallback=defaults['debug'])\n        as_a_service = config.getboolean(\"config\", \"as_a_service\", fallback=defaults['as_a_service'])\n\n        return (test_interval, pwm_channel, frequency, temp_min, temp_max, min_cycle, max_cycle, hysteresis, debug, as_a_service)\n\n    except Exception as e:\n        print(f \"Error loading config: {str(e)}\")\n        syslog.syslog(syslog.LOG_ERR, f \"Error loading configuration: {str(e)}\")\n        # Use defaults if there is an error loading the configuration\n        return tuple(defaults.values())\n\ndef calculate_work_cycle(temp, temp_min, temp_max, cycle_min, cycle_max, current_cycle, hysteresis):\n    try:\n        if temp  temp_max:\n            return 100\n        elif temp_min  (previous_temperature + hysteresis)) or (temp = test_interval and debug is True:\n            message = f \"CPU temperature is {temp:.2f} \u00b0C. Duty cycle is {duty_cycle:.0f}%\"\n            print_debug(message)\n            message = f \"The previous temperature was {previous_temp:.2f} \u00b0C. The previous cycle was {previous_work_cycle:.0f}%\"\n            print_debug(message)\n            mensaje = f\"--------------------------------------------------------------------------------------------\"\n            print_debug(message)\n            time = 0\n        else:\n            time += 1\n\n        if previous_job_cycle == 0 and job_cycle != 0:\n            print_debug(f \"Starting fan.... (temperature {temp:.2f}\u00baC)\")\n            pwm.change_duty_cycle(100)\n            previous_duty_cycle = 100\n            time.sleep(1)\n\n        if duty_cycle != previous_duty_cycle:\n            pwm.change_duty_cycle(duty_cycle).\n            print_debug(f \"New temperature: {temp:.2f}\u00baC. New duty cycle: {duty_cycle: {duty_cycle:.0f}%\")\n            print_debug(f \"Previous temperature change: {previous_temperature: {previous_temp:.2f}\u00baC. Previous_duty_cycle: {previous_duty_cycle:.0f}%\")\n            previous_duty_cycle = previous_duty_cycle\n            previous_temperature = temp\n\n        time.sleep(test_interval)\n\nexcept Exception as e:\n    print(f \"General error: {str(e)}\")\n    syslog.syslog(syslog.LOG_ERR, f \"General error: {str(e)}\")\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can save the programme in a file named <em>temperature_pwm_controller.py<\/em> by means of:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano temperature_pwm_controller.py\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This program reads the CPU temperature every 5 seconds and adjusts the PWM duty cycle according to the temperature. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are several parameters that you can adjust according to your needs and preferences.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em><strong>channel_pwm = 0<\/strong><\/em>: Allows you to choose the PWM channel you want to use.<\/li>\n\n\n\n<li><em><strong>frequency = 25000<\/strong><\/em>The frequency of the PWM signal. Note that a lower frequency signal will cause audible noise which can be annoying.<\/li>\n\n\n\n<li><em><strong>temp_min = 45<\/strong><\/em>The temperature below which the fan will be stopped.<\/li>\n\n\n\n<li><em><strong>temp_max = 60<\/strong><\/em>The temperature you do not want to exceed. From this temperature the duty cycle of the PWM signal will be 100%.<\/li>\n\n\n\n<li><em><strong>cycle_min = 55<\/strong><\/em>PWM signal cycle for your fan and preferences. Do not set too low a signal that may cause the fan not to spin.<\/li>\n\n\n\n<li><em><strong>cycle_max = 100<\/strong><\/em>The maximum duty cycle at which you want the PWM signal to be generated.<\/li>\n\n\n\n<li><strong>hysteresis = 2<\/strong>To ensure that the fan is not continually stopping and starting, this is the \"grey zone\" value. The temperature will have to vary more than this value for the fan to switch between running and stopped.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython temperature_pwm_controller.py\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The script will read the temperature and adjust the PWM signal periodically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Click <code>Ctrl-C<\/code> to interrupt it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-configuracion-del-script\">Script configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you wish, you can create a configuration file to make it easier for you to adapt the programme to your preferences without having to modify the script.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This file is completely optional and if you don't create it (or any line is missing) the script will use the default values that are defined in the code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You just need to create a text file, named <code>temperature_pwm_controller.ini<\/code> in the same folder where you have the script (file <code>temperature_pwm_controller.py<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want, you can create it with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano temperature_pwm_controller.ini\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Inside the file, you only have to include a first line, as a header, with the text <code>[config]<\/code> and then include the lines you want from the ones listed above with the values you want.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n[config]\ntest_interval = 5\npwm_channel = 0\nfrequency = 25000\ntemp_min = 46\ntemp_max = 65\nmin_cycle = 60\ncycle_max = 100\nhysteresis = 2\ndebug = False\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Install the script from GitHub<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can find all updated code at <a href=\"https:\/\/github.com\/melkati\/raspberry-fan\/tree\/main\" target=\"_blank\" rel=\"noreferrer noopener\">my GitHub repository<\/a> and you can download it to your Raspberry Pi directly from there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once in the console I recommend that you create a directory to clone the repository to, and clone it:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\ngit clone https:\/\/github.com\/melkati\/raspberry-fan.git\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Please note that you will have to make the necessary adjustments because the scripts will not be in <code>\/home\/pi <\/code>but in <code>\/home\/pi\/raspberry-fan<\/code><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The archive <code>temperature_pwm_controller.service<\/code> will already be configured to operate from <code>\/home\/pi\/raspberry-fan<\/code><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Make it start automatically when the Raspberry Pi 4 boots up<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It wouldn't make much sense if every time we started the Raspberry Pi we had to go into the console and run a program, so we're going to automate it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are several ways to make the script run automatically when the Raspberry Pi boots up. Here we are going to see how to do it with <em>systemctl<\/em>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Automatic execution with systemctl<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To run a Python script at startup on a Raspberry Pi using systemd, you can follow these steps.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this example the name of the script is <code>temperature_pwm_controller.py<\/code> and the full path where it is is <code>\/home\/pi\/<\/code>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Make sure the script is executable:<\/strong><\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo chmod +x \/home\/pi\/temperature_pwm_controller.py\n<\/pre><\/div>\n\n\n<ol class=\"wp-block-list\" start=\"3\">\n<li><strong>Create a service file for systemd:<\/strong><br>Create a service file in the location <code>\/etc\/systemd\/system\/<\/code>. You can name it, for example, <code>temperature_pwm_controller.service<\/code>.<br><br><code>sudo nano \/etc\/systemd\/system\/temperature_pwm_controller.service<\/code><br><br>The content of the file should be as follows:<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n# This is a service file for the temperature-based PWM controller\n# that will run automatically when the Raspberry Pi boots up.\n\n[Unit]\nDescription=Temperature-based PWM controller\nAfter=multi-user.target\n\n[Service]\nExecStartPre=sleep 30\nExecStart=\/usr\/bin\/python3 \/home\/pi\/temperature_pwm_controller.py\nWorkingDirectory=\/home\/pi\nStandardOutput=syslog\nStandardError=syslog\nRestart=always\nUser=pi\n\n[Install] [Install] [Install] [Install] [Install] [Install] [Install] [Install]\nWantedBy=multi-user.target\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can create the file with the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo nano \/etc\/systemd\/system\/temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Once created, make sure it has the correct permissions. You can give it permissions with the following line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nsudo chmod 777 \/etc\/systemd\/system\/temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Be sure to replace <code>\/home\/pi\/temperature_pwm_controller.py<\/code> with the full path to your Python script, if you have modified it.<\/p>\n\n\n\n<ol class=\"wp-block-list\" start=\"4\">\n<li><strong>Recharge systemd:<\/strong><\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nsudo systemctl daemon-reload\n<\/pre><\/div>\n\n\n<ol class=\"wp-block-list\" start=\"5\">\n<li><strong>Enables and starts the service:<\/strong><\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo systemctl enable temperature_pwm_controller.service\nsudo systemctl start temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The service has a 30-second delay before running to ensure that the Raspberry Pi is fully booted before starting the fan, so it will take some time to run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you restart the Raspberry Pi at this point, the service will start automatically. You can do this from the console with the line:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo reboot\n<\/pre><\/div>\n\n\n<ol class=\"wp-block-list\" start=\"6\">\n<li><strong>Check the status of the service:<\/strong><\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo systemctl status temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can <strong>stop <\/strong>the service with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo systemctl stop temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can <strong>run <\/strong>the service with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo systemctl start temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can <strong>see the status<\/strong> of the service with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n   sudo systemctl status temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">You can <strong>see the log<\/strong> of the service with:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nsudo journalctl -f -u temperature_pwm_controller.service\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Note that we don't need to run the script every fifteen seconds as it is actually always running, doing its job every 15 seconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These steps should set up your script <code>temperature_pwm_controller.py<\/code> to run automatically on startup of your Raspberry Pi using systemd. Be sure to adjust the paths and filenames to suit your specific needs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Connecting the PWM driver to the Raspberry Pi 4 and starting it up<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now we have everything we need and we can put the pieces together, hardware and software, and get our Raspberry Pi variable speed fan up and running.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Although you have a tutorial on a PWM driver with a MOSFET (and another on a PWM driver with a BJT transistor), I have designed a <strong>specific PWM driver for the Raspberry Pi: <a href=\"https:\/\/emariete.com\/en\/mini-hat-pwm-raspberry-pi\/\">The Mini HAT PWM<\/a><\/strong>:<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"MDGrDvmPUa\"><a href=\"https:\/\/emariete.com\/en\/mini-hat-pwm-raspberry-pi\/\">eMariete PWM Mini Hat for Raspberry Pi<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;eMariete PWM Mini Hat for Raspberry Pi&quot; - eMariete\" src=\"https:\/\/emariete.com\/mini-hat-pwm-raspberry-pi\/embed\/#?secret=hgJqPHr3Ee#?secret=MDGrDvmPUa\" data-secret=\"MDGrDvmPUa\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Choose the Raspberry Pi 4 pin to which we are going to connect the driver.<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">All of the Raspberry Pi 4's output pins can output a PWM signal, but it should be noted that not all pins are the same when it comes to generating a PWM signal.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Software PWM pins: They will generate the signal by software. It will be the CPU of the Raspberry Pi 4 in charge of generating the signal and will consume CPU resources, like any other program.<\/li>\n\n\n\n<li>Pins<strong> PWM hardware<\/strong>They will generate the signal by hardware. The CPU of the Raspberry Pi 4 will only have to ask one of its \"hardware PWM generators\" to generate the desired signal and it will be able to ignore it. The hardware specialised in generating PWM signals will take care of its generation and the CPU will not have to do anything, so it will not consume CPU resources, leaving all its capacity and power for other programs.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"588\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-1024x588.png\" alt=\"\" class=\"wp-image-241588\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-1024x588.png 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-300x172.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-768x441.png 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-1536x882.png 1536w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-Pinout-Diagram-2-2048x1176.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Image source: raspberry.org<\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">The pins <strong>12\/13 and 18\/19 generate the PWM signal by hardware<\/strong>while all other pins generate the PWM signal by software.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"359\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-1024x359.png\" class=\"wp-image-241587\" alt=\"1. GPIO input header and pins for Raspberry Pi A+\/B+ and Pi 2\/3\/4.\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-1024x359.png 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-300x105.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO-768x269.png 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Raspberry-Pi-GPIO.png 1200w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/> <\/a><figcaption class=\"wp-element-caption\">Image source: raspberry.org<\/figcaption><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">I recommend that you use one of the pins 12\/13 and 18\/19, unless you have a good reason not to, such as the following:<\/p>\n\n\n\n<p class=\"has-global-color-8-background-color has-background wp-block-paragraph\">The PWM hardware and the headphone jack use the same circuitry as the Raspberry Pi, so the <strong>you will not be able to use them at the same time<\/strong>. In other words, if you use the headphone jack on the Raspberry Pi 4 you will have to use PWM in software, with all its limitations.<\/p>\n\n\n\n<p class=\"has-text-align-center has-global-color-8-background-color has-background has-medium-font-size wp-block-paragraph\"><strong>IMPORTANT: If you do not use pin 18, remember to update the code with the pin you have decided to use.<\/strong>. These examples are set up to use GPIO 18 (pin 12 on the Raspberry Pi 4 expansion port).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">PWM signal calibration for <strong>your <\/strong>fan<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As we saw in detail in the article \"<a href=\"https:\/\/emariete.com\/en\/control-the-speed-of-a-fan-with-pwm\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Controlling the speed of a fan with PWM<\/em><\/a>\"As we mentioned earlier in this article, each fan responds differently to PWM signals.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each fan has a minimum duty cycle for the fan to start spinning from standstill. On some fans it may be 30% and on others 90% so you need to test it yourself with <strong>your fan<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each fan also has a minimum Duty Cycle so that it does not stop when it is already in motion. You will not be able to lower the Duty Cycle to, say, 5%, expecting the fan to run very slowly. With so little power it will stop long before it gets down to that 5%.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To give you an idea, the fan I'm testing right now stops when the duty cycle drops to about 60%.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You have to keep in mind that both Work Cycles do not have to be the same (and they won't be). <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The fan needs more energy (higher duty cycle) to overcome the resistance to start up and will need less energy to keep moving once it is already moving.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All of the above means that you will need to calibrate <strong>your specific fan<\/strong> to find these two Duty Cycle values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can easily calibrate your fan using the programme <a href=\"https:\/\/emariete.com\/en\/fan-speed-variable-raspberry-pi\/#pwm_generator\">pwm_generator.py<\/a> I have left you before (<a href=\"https:\/\/emariete.com\/en\/fan-speed-variable-raspberry-pi\/#programa_basico_pwm\">you can click here to go to it<\/a>). <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You will have to run the programme several times with the fan stopped, <strong>by going to <\/strong>each time the Duty Cycle, <strong>until the fan starts up<\/strong>. Once you have found that \"<em>Minimum duty cycle from standstill<\/em>\"You can use that value, increasing it by a percentage as a safety margin (you can try a 10%).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then, with the fan running, you will have to run the programme several times, <strong>downloading<\/strong> each time the Duty Cycle, <strong>until the fan stops<\/strong>. Once you have found that \"<em>Minimum duty cycle from in motion<\/em>\"You can use that value, increasing it by a percentage as a safety margin (you can try a 10%).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What if my Raspberry Pi is not the 4, what about other models?<\/h2>\n\n\n\n<div class=\"wp-block-media-text is-stacked-on-mobile\"><figure class=\"wp-block-media-text__media\"><img loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"500\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Cartas-Raspberry-Pi-500x500-1.jpg\" alt=\"\" class=\"wp-image-241066 size-full\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Cartas-Raspberry-Pi-500x500-1.jpg 500w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Cartas-Raspberry-Pi-500x500-1-300x300.jpg 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/11\/Cartas-Raspberry-Pi-500x500-1-150x150.jpg 150w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/figure><div class=\"wp-block-media-text__content\">\n<p class=\"wp-block-paragraph\">The Raspberry Pi 5 is too new and I haven't used it yet, so I won't be able to tell you much about it, but I have had all the models before 4 and I can tell you about them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I can tell you that, on the previous Raspberry Pi models, 1, 2, 3 and their variations, the power consumption is much lower than on the Raspberry Pi 4 and I have never needed to use a fan and its temperature has always been kept within very reasonable limits.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, if you want or need to add the fan to one of these models, it won't be difficult.<\/p>\n<\/div><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">I have tested it (and have it running) on the Raspberry Pi 3 and Raspberry Pi 4, so it is well tested on these models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to test it on another version, the software will probably work as is, or with minimal changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All the research and development has been done with a Raspberry Pi 3, only when it was finished I have installed it on the Raspberry Pi 4. The reason is simply that the only Raspberry Pi 4 that I have was occupied for things of home automation, and I could not be removing it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you try it with other versions, especially if it is with the <strong>Raspberry Pi 5<\/strong>I ask you to <strong>leave a message in the comments <\/strong>and then I can update the article with that information.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Raspberry Pi 4<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The software is tested on the Raspberry Pi 4 and works flawlessly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By the way, on the Raspberry Pi 4 I have mounted a special version of the <strong>Mini HAT PWM with SMD components<\/strong> and some longer pins so it can be glued to the outside of the box. In my opinion, it has turned out very well.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"553\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4-1024x553.png\" alt=\"\" class=\"wp-image-241743\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4-1024x553.png 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4-300x162.png 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4-768x415.png 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4-1536x830.png 1536w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-Hat-PWM-V2-en-Raspberry-Pi-4.png 1616w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"461\" src=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4-1024x461.jpg\" alt=\"\" class=\"wp-image-241740\" srcset=\"https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4-1024x461.jpg 1024w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4-300x135.jpg 300w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4-768x346.jpg 768w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4-1536x692.jpg 1536w, https:\/\/emariete.com\/wp-content\/uploads\/2023\/12\/Mini-HAT-PWM-en-Raspberry-Pi-4.jpg 1600w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Raspberry Pi 3<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is the model on which I have done the research and development so it is tested and should work without a problem.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Raspberry Pi 2<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When I can I will try it in this version, although it is not very useful because it doesn't heat up and doesn't need a fan. I don't foresee any problems.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Don't confuse hardware and software on your Raspberry Pi<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">What we have just seen is with respect to the <strong>hardware <\/strong>of the Raspberry Pi, but also the <strong>software <\/strong>can be different.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The specific version of the operating system I had installed on the Raspberry Pi 3 was: \"<code>Raspbian GNU\/Linux 11 (bullseye) armv71<\/code> (32bit) with 32 bit user space.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The operating system that I had installed on the Raspberry Pi 4 was: \"<code>Raspbian GNU\/Linux 11 (bullseye) aarch64<\/code> (64bit) with 32 bit user space.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you have followed the tutorial and found something different or not working, it wouldn't hurt to check your version.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see the version of the operating system installed on your Raspberry Pi, you can use the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncat \/etc\/os-release\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This command will show you the name and version of the operating system running on your device.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to know whether the operating system is 32-bit or 64-bit, you can use the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nuname -m\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This command will show you the processor architecture of your Raspberry Pi. If the output is <code>armv7l<\/code>If the output is aarch64, then you are using a 32-bit operating system. If the output is aarch64, then you are using a 64-bit operating system 12.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see if the user space of your Raspberry Pi is 32-bit or 64-bit, you can use the following command:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code\"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ngetconf LONG_BIT\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">This command will show you the processor architecture of your Raspberry Pi. If the output is <code>32<\/code>If the output is 32-bit, then you are using 32-bit user space, if the output is 64, then you are using 64-bit user space.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this article we have seen what we have to do to control the Raspberry Pi's fan speed depending on the temperature of your CPU. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you have not done so, I suggest you read the following articles, which provide more information on each of the aspects we have summarised here:<\/p>\n\n\n<div class=\"gb-container gb-container-0fef7b32\">\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"6VxOuYVBKo\"><a href=\"https:\/\/emariete.com\/en\/pwm-signal-pulse-width-modulation\/\">What is a PWM (Pulse Width Modulation) signal?<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;What is a PWM (Pulse Width Modulation) signal?&quot; - eMariete\" src=\"https:\/\/emariete.com\/senal-pwm-pulse-width-modulation\/embed\/#?secret=8uZSwOYfCR#?secret=6VxOuYVBKo\" data-secret=\"6VxOuYVBKo\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"XViJkaKnrP\"><a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt\/\">PWM driver with BJT transistor<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;PWM driver with BJT transistor&quot; - eMariete\" src=\"https:\/\/emariete.com\/driver-pwm-transistor-bjt\/embed\/#?secret=M7V5brnS42#?secret=XViJkaKnrP\" data-secret=\"XViJkaKnrP\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"Rqp7Frfy3t\"><a href=\"https:\/\/emariete.com\/en\/driver-pwm-transistor-bjt-2\/\">PWM driver with MOSFET transistor<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;PWM driver with MOSFET transistor&quot; - eMariete\" src=\"https:\/\/emariete.com\/driver-pwm-transistor-mosfet\/embed\/#?secret=rdb2ABVlPo#?secret=Rqp7Frfy3t\" data-secret=\"Rqp7Frfy3t\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-emariete wp-block-embed-emariete\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"MDGrDvmPUa\"><a href=\"https:\/\/emariete.com\/en\/mini-hat-pwm-raspberry-pi\/\">eMariete PWM Mini Hat for Raspberry Pi<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&quot;eMariete PWM Mini Hat for Raspberry Pi&quot; - eMariete\" src=\"https:\/\/emariete.com\/mini-hat-pwm-raspberry-pi\/embed\/#?secret=hgJqPHr3Ee#?secret=MDGrDvmPUa\" data-secret=\"MDGrDvmPUa\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n<\/div>\n\n<div class=\"wp-block-uagb-faq uagb-faq__outer-wrap uagb-block-78fab2f7 uagb-faq-icon-row uagb-faq-layout-accordion uagb-faq-expand-first-false uagb-faq-inactive-other-true uagb-faq__wrap uagb-buttons-layout-wrap uagb-faq-equal-height\" data-faqtoggle=\"true\" role=\"tablist\"><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-e5e47b33\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">Script does not run on Raspberry Pi startup<\/span><\/div><div class=\"uagb-faq-content\"><p>If your script is not running automatically when you boot up the Raspberry Pi as expected, here are a few things you can check and adjust:<br><strong>Location of the Service File:<\/strong> Make sure that the service file (<code>temperature_pwm_controller.service<\/code>) is located in the correct directory, which is typically <code>\/etc\/systemd\/system\/<\/code>. You can use <code>ls<\/code> to check if the file is there:<br>bashCopy code<br><code>ls \/etc\/systemd\/system\/temperature_pwm_controller.service<\/code><br>If it is not there, move the file to that directory and re-enable the service.<br><strong>Enable and Start Service:<\/strong> Check that you have enabled the service correctly and that it has started:<br>bashCopy code<br><code>sudo systemctl enable temperature_pwm_controller.service sudo systemctl start temperature_pwm_controller.service<\/code><br>Make sure there are no errors when executing these commands. You can check the status of the service after starting it:<br>bashCopy code<br><code>sudo systemctl status temperature_pwm_controller.service<\/code><br><strong>Check the System Registry:<\/strong> Use <code>journalctl<\/code> to check the system logs for error messages or information related to the start of the service:<br>bashCopy code<br><code>sudo journalctl -u temperature_pwm_controller.service<\/code><br>This will give you a more detailed picture of what is happening with your service.<br><strong>Restart the Raspberry Pi:<\/strong> After making changes, restart the Raspberry Pi and check if the service starts automatically.<br><strong>Review Permits:<\/strong> Make sure that the script and configuration file have the appropriate permissions to be executed by the user of the service. You can grant the necessary permissions using <code>chmod<\/code>.<br>bashCopy code<br><code>chmod +x \/path\/a\/tu\/script.py<\/code><br><strong>Review the Service File Content:<\/strong> Verify that the service file (<code>temperature_pwm_controller.service<\/code>) have the correct configuration, especially the paths to your script and directory.<br><strong>Script errors:<\/strong> Check your script for errors. You can run your script manually to see if there are any problems.<br>bashCopy code<br><code>\/usr\/bin\/python3 \/path\/to\/your\/script.py<\/code><br>Make sure that all paths and settings within the script are correct.<br><strong>Check the Type of Service Configuration:<\/strong> Make sure that the configuration <code>Type=simple<\/code> is appropriate for your script. In some cases, <code>Type=simple<\/code> may be more appropriate, while in other cases, you may need to <code>Type=forking<\/code> depending on the nature of your script.<br><strong>Verify the Configuration File Permissions:<\/strong> If your script uses a configuration file (<code>temperature_pwm_controller.ini<\/code>), make sure it has the appropriate permissions and can be read by the user of the service.<br><strong>Additional Logs:<\/strong> Add additional logs to your script and service file to get more information about what might be going wrong. You can add print statements to your script, or use the <code>syslog<\/code> to log messages within the script.<br>Inside the Python script:<br>pythonCopy code<br><code>print(\"Starting script...\")<\/code><br>In the service file (<code>temperature_pwm_controller.service<\/code>), you can add the following line below the section <code>Service] [Service].<\/code>:<br>iniCopy code<br><code>StandardOutput=journal+console<\/code><br>This will allow standard output messages from the service to be sent to both the syslog and the console, which may help you identify problems during startup.<br><strong>Verify Permits and Owners:<\/strong> Make sure that all files and directories related to your service have the appropriate permissions and owners so that the service can access them.<br><strong>Try Manual Initiation:<\/strong> Try starting your script manually to make sure there are no direct execution problems. Use the following command line:<br>bashCopy code<br><code>\/usr\/bin\/python3 \/path\/to\/your\/script.py<\/code><br>Make sure that this manual execution does not generate errors.<br><strong>Check the Kernel Log:<\/strong> You can check the kernel log for additional information. Use the following command to view kernel messages:<br>bashCopy code<br><code>dmesg | grep service_name<\/code><br>This could provide additional information if there are problems at the kernel level.<br><strong>Review Log Files:<\/strong> In addition to <code>journalctl<\/code>check other log files that may contain relevant information. For example, if your script writes to a specific log file, check that file for error messages.<br><strong>Check for Blank Spaces in the Service File:<\/strong> Make sure there are no extra blanks or unwanted characters in the service file (<code>temperature_pwm_controller.service<\/code>).<br><strong>Check IP Address Configuration:<\/strong> If your script relies on the network, check that the Raspberry Pi has a network connection established at startup. Some scripts may have problems if they are run before the network connection is established.<br><strong>Check Date and Time Settings:<\/strong> Check that the Raspberry Pi's date and time are set correctly, as some scripts may depend on the current time.<br><strong>Check Selinux Configuration or AppArmor:<\/strong> If you are using Selinux or AppArmor on your system, make sure they are not blocking the service from running.<br><strong>Restart Service and Check Log in Real Time:<\/strong> Restart the service and check the real-time log for any error messages at startup:<br>bashCopy code<br><code>sudo systemctl restart service_name sudo journalctl -fu service_name<\/code><\/p><\/div><\/div><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-38bd00a0\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">Can I automate the start of the script with <em>rc.local<\/em>?<\/span><\/div><div class=\"uagb-faq-content\"><p>Theoretically it is also possible to do so, but <strong>I have not been able to get it to work properly with <em>rc.local<\/em><\/strong>. <br><br>The file is supposed to <em>rc.local<\/em>is executed after all system services are started.<br>To use this method, you have to edit the file <em>rc.local<\/em> and add the command to run your script before the \"exit 0\" line.<br><br>For example, if your script is called <em>temperature_pwm_controller.py<\/em> and it is in the \/home\/pi directory, you would have to put something like this:<br><br>python3 \/home\/pi\/temperature_pwm_controller.py &amp;<br><br>You can edit the file <em>rc.local<\/em> with:<br><br>sudo nano \/etc\/rc.local<br><br>It is important to mention that the use of <code><em>rc.local<\/em>.<\/code> has diminished on newer systems, as many Linux distributions have adopted more advanced boot systems such as systemd. However, it is still possible to find systems that use <code><em>rc.local<\/em>.<\/code>especially in older environments or customised configurations.<\/p><\/div><\/div><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-c7785ad5\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">At what temperature is it recommended to run the fan of a Raspberry Pi 4?<\/span><\/div><div class=\"uagb-faq-content\"><p>The temperature at which you should activate the fan on a Raspberry Pi 4 can depend on a number of factors, including the specific components of your Raspberry Pi, the environment it is in, and the workload it is subjected to.<br><br>In general, the Raspberry Pi 4 has built-in mechanisms to manage temperature and prevent overheating. However, if you want to use a fan for active cooling, you might consider starting the fan when the CPU temperature reaches around 50-55 degrees Celsius. This will provide a margin of safety and help keep the temperature in a safe range.<br><br>Adjusting the fan activation temperature may also depend on your preferences and the balance you want to achieve between performance and fan noise level. Some people prefer to set the fan to activate at higher temperatures if they are willing to tolerate a little more heat before active cooling starts.<br><br>Remember to regularly monitor the temperature of your Raspberry Pi and adjust the settings as necessary to suit your needs and the environment it is in.<\/p><\/div><\/div><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-a72b8fd4\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">My fan only starts from standstill at 100% (or 90%, for example).<\/span><\/div><div class=\"uagb-faq-content\"><p>This is quite normal, don't worry. Most of the fans I have tested did not start up with guarantees until they had a 100% duty cycle.<\/p><\/div><\/div><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-8aafd923\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">My fan makes noise when the duty cycle drops below x %<\/span><\/div><div class=\"uagb-faq-content\"><p>It is normal for fans to be noisy even at high duty cycles.<br>Don't worry and set a lower limit slightly above the point where it runs noiselessly, smoothly and guaranteed not to stall.<br>Even just downgrading from the 100% to the 90% is a significant noise reduction.<\/p><\/div><\/div><div class=\"wp-block-uagb-faq-child uagb-faq-child__outer-wrap uagb-faq-item uagb-block-8081eb10\" role=\"tab\" tabindex=\"0\"><div class=\"uagb-faq-questions-button uagb-faq-questions\">\t\t\t<span class=\"uagb-icon uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M432 256c0 17.69-14.33 32.01-32 32.01H256v144c0 17.69-14.33 31.99-32 31.99s-32-14.3-32-31.99v-144H48c-17.67 0-32-14.32-32-32.01s14.33-31.99 32-31.99H192v-144c0-17.69 14.33-32.01 32-32.01s32 14.32 32 32.01v144h144C417.7 224 432 238.3 432 256z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t\t\t\t<span class=\"uagb-icon-active uagb-faq-icon-wrap\">\n\t\t\t\t\t\t\t\t<svg xmlns=\"https:\/\/www.w3.org\/2000\/svg\" viewbox= \"0 0 448 512\"><path d=\"M400 288h-352c-17.69 0-32-14.32-32-32.01s14.31-31.99 32-31.99h352c17.69 0 32 14.3 32 31.99S417.7 288 400 288z\"><\/path><\/svg>\n\t\t\t\t\t\t\t<\/span>\n\t\t\t<span class=\"uagb-question\">Can I control the fan without all this software?<\/span><\/div><div class=\"uagb-faq-content\"><p><strong>You can, but you won't be able to control its speed, just turn it on and off.<br><\/strong><br>The Raspberry Foundation, knowing that the Raspberry Pi 4 would need a fan, natively included in its operating system the ability to enable temperature control easily from one of the Raspberry Pi's configuration menus.<br><br>The control possibilities are rather limited as only a temperature can be specified, below which the fan will stop and start again, at 100% speed, when the temperature is exceeded. Speed control is not included.<br><br>It is a simple functionality, but <strong>is available natively, without having to install any additional software.<\/strong><br><br>Note that, by not regulating the speed, but only turning the fan on and off (0 or 100%) it can be even noisier than having the fan at full power if these changes occur often. If you are considering doing it this way, I recommend that you try it out to see how it works in your particular case.<\/p><\/div><\/div><\/div><div class=\"essb_break_scroll\"><\/div>","protected":false},"excerpt":{"rendered":"<p>Do you, like me, want to reduce (or even eliminate) the annoying noise of the Raspberry Pi 4 fan? If so, here is the ultimate solution. Easy and cheap.<\/p>","protected":false},"author":1,"featured_media":240986,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[64,63],"tags":[67,46],"class_list":["post-240981","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-electronica","category-raspberry-pi","tag-pwm","tag-raspberry-pi"],"modified_by":"Mariete","uagb_featured_image_src":{"full":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image.png",1080,608,false],"thumbnail":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image-150x150.png",150,150,true],"medium":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image-300x169.png",300,169,true],"medium_large":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image-768x432.png",768,432,true],"large":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image-1024x576.png",1024,576,true],"1536x1536":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image.png",1080,608,false],"2048x2048":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image.png",1080,608,false],"trp-custom-language-flag":["https:\/\/emariete.com\/wp-content\/uploads\/2023\/10\/Ventilador-velocidad-variable-para-Raspberry-4-Featured-Image.png",18,10,false]},"uagb_author_info":{"display_name":"Mariete","author_link":"https:\/\/emariete.com\/en\/author\/admin_xlyz052h\/"},"uagb_comment_info":4,"uagb_excerpt":"\u00bfQuieres, como yo, reducir (o incluso eliminar) el molesto ruido del ventilador de la Raspberry Pi 4? Si es as\u00ed, aqu\u00ed te traigo la soluci\u00f3n definitiva. F\u00e1cil y barata.","_links":{"self":[{"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/posts\/240981","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/comments?post=240981"}],"version-history":[{"count":132,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/posts\/240981\/revisions"}],"predecessor-version":[{"id":241748,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/posts\/240981\/revisions\/241748"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/media\/240986"}],"wp:attachment":[{"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/media?parent=240981"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/categories?post=240981"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/emariete.com\/en\/wp-json\/wp\/v2\/tags?post=240981"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}