Skip to content

Instantly share code, notes, and snippets.

@Brockhold
Last active June 15, 2023 22:44
Show Gist options
  • Save Brockhold/14143c5a8dc26b69261c691372814ce3 to your computer and use it in GitHub Desktop.
Save Brockhold/14143c5a8dc26b69261c691372814ce3 to your computer and use it in GitHub Desktop.
/*
Simple serial fan control to go along with a PWM-capable fan and host side software which prints (ascii) integers in the range
0-255 inclusive. Perhaps those integers can be given by a fan control curve on the host.
If no serial interface is connected within two seconds, we simply turn the fan on at maximum and keep waiting.
This firmware will accept numeric characters, which are interpreted as integers. Any other type of character marks the end of the value.
It responds with the interpreted value, constrained to the acceptable PWM range (0-255).
*/
int controlPin = 5; // Any PWM capable output pin
String inString = "";
unsigned long val = 0;
void(* resetFunc) (void) = 0;//declare reset function at address 0
void setup() {
pinMode(controlPin, OUTPUT); //noted as not required in docs, but used in examples?
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
analogWrite(controlPin, 0);
unsigned long currentTime = 0;
Serial.begin(9600);
// wait for serial init, but run anyway after 2 seconds
while (!Serial) {
currentTime = millis();
if (currentTime > 2000) {
//analogWrite(controlPin, 255);
digitalWrite(controlPin, HIGH);
digitalWrite(LED_BUILTIN, HIGH);
}
}
// Once serial becomes available, turn off the fan and wait for requests.
Serial.println("\nFan Control Ready:");
digitalWrite(LED_BUILTIN, LOW);
}
void loop() {
if (!Serial) {
// if we lose serial while running, reset.
resetFunc();
}
while (Serial.available() > 0) {
int inChar = Serial.read();
if (isDigit(inChar)) {
inString += (char)inChar; // convert the incoming byte to a char and add it to the string:
} else {
val = constrain(inString.toInt(), 0, 255);
inString = ""; // clear the string for new input:
Serial.println(val);
analogWrite(controlPin, val);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment