commit 1c0ecea038ca809b712310fae539b2ae16c7a5c7 Author: Mark van Renswoude Date: Thu Aug 31 21:55:23 2017 +0200 Implemented Arduino code diff --git a/SimulatorFans.ino b/SimulatorFans.ino new file mode 100644 index 0000000..1eb2759 --- /dev/null +++ b/SimulatorFans.ino @@ -0,0 +1,224 @@ +/* + * SimulatorFans + * Copyright (c) 2017 Mark van Renswoude + * https://git.x2software.net/pub/SimulatorFans + * + * + * Accepts serial commands to control one or more fans using PWM. + * + * All commands are terminated with a #10 character and are case sensitive. + * Values are passed as ASCII text. This makes it easy to test it using the + * Arduino's Serial Monitor. + * + * Baud rate is 19200 by default. + * + * + * Commands: + * >Info + * Used for validating that the device is actually a SimulatorFans device. + * Returns the number of connected fans. + * + * Example response: + * GetFans + * Returns the currently set values for all fans. + * + * Example response: + * SetFans:v1,v2,v... + * Updates the fan values. Each value ranges from 0 to 255. + * + * Example response: + * 0) + { + // Try to read a serial command + memset(command, 0, sizeof(command)); + commandLength = Serial.readBytesUntil('\n', command, sizeof(command) - 1); + if (commandLength > 0 && commandLength < sizeof(command)) + { + token = strtok(&command[0], ":"); + if (token != NULL) + { + if (strcmp(token, ">Info") == 0) + handleInfoCommand(); + else if (strcmp(token, ">GetFans") == 0) + handleGetFansCommand(); + else if (strcmp(token, ">SetFans") == 0) + handleSetFansCommand(); + else + handleUnknownCommand(); + } + } + } +} + + +void handleInfoCommand() +{ + Serial.write(" 0) + Serial.write(","); + + Serial.print(fanStatus[fan].value); + } + + Serial.write("\n"); +} + + +void handleSetFansCommand() +{ + for (byte fan = 0; fan < FanCount; fan++) + { + token = strtok(NULL, ","); + if (token == NULL) + break; + + int value = atoi(token); + + if (value < 0) value = 0; + if (value > 255) value = 0; + + setFan(fan, value); + } + + Serial.write(" 0) && + (currentTime - fanStatus[fan].startTime >= StartingFansTime)) + { + fanStatus[fan].startTime = 0; + setFan(fan, fanStatus[fan].value); + } + } +} + +void setFan(byte fan, byte value) +{ + if ((fanStatus[fan].value == 0 || fanStatus[fan].startTime > 0) && value > 0) + { + // Fan was off or still starting up, start with full power to kick it off + analogWrite(FanPin[fan], 255); + + if (fanStatus[fan].startTime == 0) + { + fanStatus[fan].startTime = currentTime; + } + } + else + { + // Already running, simply change the speed and reset the start time if necessary + fanStatus[fan].startTime = 0; + analogWrite(FanPin[fan], value); + } + + fanStatus[fan].value = value; +} +