/*
* Example program that fades LED on and off, as if it were "breathing".
* (c) 2022 Nathan "nwb99" Barnett
* MIT License
*/
const float valueRange = 255;
const float conversionFactor = PI / valueRange; // Conversion factor from 0-63 to radians
class OutputState {
private:
int current_pos = 0;
int change_direction = 1;
unsigned long previousMillis = 0;
const int inputPin;
const int outputPin;
public:
OutputState(int inPin, int outPin) : inputPin(inPin), outputPin(outPin) {
// inputPin = inPin;
// outputPin = outPin;
pinMode(inPin,INPUT);
pinMode(outPin,OUTPUT);
}
int timeUpdate(long currentMillis) {
const int potValue = analogRead(inputPin);
const int interval = map(potValue, 0, 1023, 1, 10);
// You can handle the debounce of the button directly
// in the class, so you don't have to think about it
const long intervalDelta = currentMillis - previousMillis;
if (intervalDelta >= interval) {
previousMillis = currentMillis;
current_pos = (current_pos + change_direction*(intervalDelta/interval));
if (current_pos <= 0)
{
change_direction = 1;
}
else if (current_pos >= valueRange)
{
change_direction = -1;
}
const int triangleValue = current_pos;
const float radiansValue = (triangleValue-(valueRange/2)) * conversionFactor;
// Calculate the sine of the radians value
const float sineValue = sin(radiansValue);
// Map the sine value to a PWM range (0-255)
const int pwmValue = (sineValue+1)*(valueRange/2);
const int squareValue = sineValue > 0 ? valueRange : 0;
analogWrite(outputPin, pwmValue);
}
}
}; // don't forget the semicolon at the end of the class
OutputState outputA(3,1);
OutputState outputB(2,0);
void setup() {
// pinMode(1,OUTPUT);
// pinMode(2,OUTPUT);
// pinMode(3,INPUT);
// pinMode(4,INPUT);
}
void loop() {
/*
can connect a 5V LED in series with like a 330 Ohm resistor to pin 6 (P0W)
on the MCP4151. This should cause a "breathing" LED effect.
Furthermore, 'pot.getCurValue()' is reading the value from the IC.
The chip stores the wiper as an 8-bit value at address 00h.
Valid values are 0-255 (or 0x0 to 0xFF, if you prefer).
For my test LED, 87 was basically 'off', given the voltage was too low.
*/
const unsigned long currentMillis = millis();
outputA.timeUpdate(currentMillis);
outputB.timeUpdate(currentMillis);
}