Skip to content

Instantly share code, notes, and snippets.

@smirgol
Created February 17, 2021 11:19
Show Gist options
  • Save smirgol/a4611f9f50de123014b82facefef4e48 to your computer and use it in GitHub Desktop.
Save smirgol/a4611f9f50de123014b82facefef4e48 to your computer and use it in GitHub Desktop.
Arduino Uno code for controlling two PWM fans
#include <TimerOne.h>
// PWM Pins
#define PIN_FAN1_OUTPUT_PWM 9 // PWM Signal to fan 1 - OUTPUT FAN
#define PIN_FAN2_OUTPUT_PWM 10 // PWM Signal to fan 2 - INPUT FAN
#define PWM_MAX_VALUE 1023 // maximum value of analog pwm throttle signal
// Set these to the defaults that you want on startup (0-255)
int pwm_value_fan1 = 220;
int pwm_value_fan2 = 0;
bool debug = false;
void setup() {
Serial.begin(9600);
Timer1.initialize(25000);
Timer1.pwm(PIN_FAN1_OUTPUT_PWM, pwm_value_fan1); // 1023 max
Timer1.pwm(PIN_FAN2_OUTPUT_PWM, pwm_value_fan2); // 1023 max
}
int toDuty(int in) {
float throttle = in / 255.0;
throttle = round(throttle * PWM_MAX_VALUE);
int pwm_value = max(min(throttle, PWM_MAX_VALUE), 0);
return pwm_value;
}
void loop() {
// Read and execute commands from serial port
if (Serial.available()) { // check for incoming serial data
String data = Serial.readString(); // read command from serial port
data.trim();
if (data == "get_fan_1") {
Serial.println(pwm_value_fan1);
} // eo get_fan_1
if (data == "get_fan_2") {
Serial.println(pwm_value_fan2);
} // eo get_fan_2
int divider_pos = data.indexOf("===");
if (divider_pos != -1) {
String command = data.substring(0, divider_pos);
String value = data.substring(divider_pos+3);
if (debug) {
Serial.print("Command: ");
Serial.print(command);
Serial.print(" Value: ");
Serial.println(value);
}
if (command == "set_fan_1") {
pwm_value_fan1 = value.toInt();
// bounds limiter 0-255;
pwm_value_fan1 = min(max(0,pwm_value_fan1),255);
if (debug) {
Serial.print("Set Fan 1 Speed: ");
Serial.print(pwm_value_fan1);
Serial.print(" Duty: ");
Serial.println(toDuty(pwm_value_fan1));
}
Timer1.setPwmDuty(PIN_FAN1_OUTPUT_PWM, toDuty(pwm_value_fan1));
} // eo set_fan_1
if (command == "set_fan_2") {
pwm_value_fan2 = value.toInt();
// bounds limiter 0-255;
pwm_value_fan2 = min(max(0,pwm_value_fan2),255);
if (debug) {
Serial.print("Set Fan 2 Speed: ");
Serial.print(pwm_value_fan2);
Serial.print(" Duty: ");
Serial.println(toDuty(pwm_value_fan2));
}
Timer1.setPwmDuty(PIN_FAN2_OUTPUT_PWM, toDuty(pwm_value_fan2));
} // eo set_fan_2
} // eo if divider_pos
} // eo Serial.available
} // eo loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment