What's going on here is I combined two working sketches.
One sketch put out a variable duty cycle dependent on A0v.
The other put out constant duty cycle on pins 4, 5, and 6. They each had a v threshold to start sequentially.
THE problem is 4, 5, and 6 are outputing even when voltages are applied to A0.
For simplification it should be:
Sketch 1, A0
Sketch 2, A1
#define INPUT_PIN_A0 A0
#define INPUT_PIN_A1 A1
#define OUTPUT_PIN_PWM 3
#define PIN4 4
#define PIN5 5
#define PIN6 6
// Voltage thresholds for Sketch 2
#define VOLTAGE_THRESHOLD_PIN4 1.7
#define VOLTAGE_THRESHOLD_PIN5 2.6
#define VOLTAGE_THRESHOLD_PIN6 3.5
// Analog reference voltage (for Arduino Uno, Nano, etc., it's typically 5V)
#define REF_VOLTAGE 5.0
// Frequency and period for Sketch 2
#define FREQUENCY 100
#define PERIOD (1000000L / FREQUENCY) // Period in microseconds
void setup() {
// Setup for Sketch 1
Serial.begin(9600); // Initialize serial communication at 9600 bits per second
pinMode(OUTPUT_PIN_PWM, OUTPUT); // Configure the OUTPUT_PIN as an output
// Setup for Sketch 2
pinMode(PIN4, OUTPUT);
pinMode(PIN5, OUTPUT);
pinMode(PIN6, OUTPUT);
pinMode(INPUT_PIN_A1, INPUT);
}
void loop() {
// Loop for Sketch 1
int sensorValue = analogRead(INPUT_PIN_A0); // Read the input on analog pin A0
float voltage = sensorValue * (REF_VOLTAGE / 1023.0); // Convert the analog reading to a voltage
int dutyCycle;
if (voltage >= 2.5) {
dutyCycle = 255; // 100% duty cycle if voltage is 2.5V or above
} else {
// Linear interpolation between 0.35V (20% duty cycle) and 2.5V (100% duty cycle)
float slope = (255 - 51) / (2.5 - 0.35);
dutyCycle = (int)(51 + slope * (voltage - 0.35));
}
analogWrite(OUTPUT_PIN_PWM, dutyCycle); // Output the PWM signal
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.print(" V, Duty Cycle: ");
Serial.print(dutyCycle * 100 / 255);
Serial.println("%");
// Loop for Sketch 2
unsigned long currentTime = micros();
static unsigned long lastToggleTime[3] = {0, 0, 0}; // Separate last toggle time for each pin
float voltageA1 = analogRead(INPUT_PIN_A1) * (REF_VOLTAGE / 1023.0); // Convert analog reading to voltage
// Toggle pins based on voltage and ensure 100Hz frequency
if (currentTime - lastToggleTime[0] >= PERIOD) {
lastToggleTime[0] = currentTime;
if (voltageA1 > VOLTAGE_THRESHOLD_PIN4) {
digitalWrite(PIN4, !digitalRead(PIN4));
} else {
digitalWrite(PIN4, LOW);
}
}
if (currentTime - lastToggleTime[1] >= PERIOD) {
lastToggleTime[1] = currentTime;
if (voltageA1 > VOLTAGE_THRESHOLD_PIN5) {
digitalWrite(PIN5, !digitalRead(PIN5));
} else {
digitalWrite(PIN5, LOW);
}
}
if (currentTime - lastToggleTime[2] >= PERIOD) {
lastToggleTime[2] = currentTime;
if (voltageA1 > VOLTAGE_THRESHOLD_PIN6) {
digitalWrite(PIN6, !digitalRead(PIN6));
} else {
digitalWrite(PIN6, LOW);
}
}
// Delay to avoid spamming the serial monitor for Sketch 1
delay(1);
}
Any clues?
(I don't need serial monitor. I want to delete those parts.)