// Forum: https://forum.arduino.cc/t/reading-5-digital-input-pins-5-bit-to-change-clock-frequency/1109064
// Original sketch by: JB8256
// This Wokwi project: https://wokwi.com/projects/360706483828795393
// Changes by: Koepel, 31 March 2023
//
// Changes:
// Changed 'pins' to 'inPins'
// Added a unknownPin for pin 8
// Changed the for-loop in setup()
// Added a function that reads the inputs and returns an integer 0...31
// Moved global variables to local variables where appropriate
// Pin 2 has now the switch for the lowest bit
// Lowered the frequency for a blinking led
#define LENGTH 5
const int inPins[LENGTH] = {2, 3, 4, 5, 6};
const int clockPin = 9;
const int unknownPin = 8;
int clockState = LOW;
unsigned long previousMillis = 0;
unsigned long interval;
int lastInputValue;
void frequencySet()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (clockState == LOW) {
clockState = HIGH;
} else {
clockState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(clockPin, clockState);
}
}
void setup() {
Serial.begin(9600);
for (int i = 0; i < LENGTH; i++) {
pinMode(inPins[i], INPUT);
}
pinMode(unknownPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop() {
int inputValue = readInputs();
// Convert 0...31 to a interval of 1000...100
// That is a offset of 100.
// The input range of 31 should match the output range of 900
interval = 100UL + (900UL - ((unsigned long) inputValue * 900UL / 31UL));
// run the millis-timer
frequencySet();
if (inputValue != lastInputValue) {
Serial.print("Input Value: ");
Serial.print(inputValue);
lastInputValue = inputValue;
Serial.print(", interval: ");
Serial.print(interval);
Serial.println();
}
}
// Read the 5 inputs and create an integer 0...31
int readInputs()
{
int result = 0;
for (int i = 0; i < LENGTH; i++) {
int pinState = digitalRead(inPins[i]);
if (pinState == HIGH) {
result |= 1 << i;
}
}
return(result);
}