/*
Code for triggering 5 millisecond pulses
Source: Arduino Forum
Topic: Triggering 5 millisecond pulses part #1
Category: Using Arduino
Subcategory: Programming Questions
Link: https://forum.arduino.cc/t/triggering-5-millisecond-pulses-part-1/1135999/85
*/
// Define analog input pin
#define ainPin A0
// Define constants
#define compareVoltage 2.0f // Voltage level used as a threshold for pulse triggering
#define pulseTime 50ul // Duration of the pulse in milliseconds
#define hiAmplitude 6 // Amplitude value for the high state of the pulse
#define loAmplitude 1 // Amplitude value for the low state of the pulse
// Declare global variables
float input_voltage; // Holds the current input voltage
uint32_t pulseStartAtMs; // Records the start time of the pulse
bool inPulse; // Indicates whether the system is currently in a pulse state
uint8_t Millis; // Stores the amplitude value for the pulse
// Setup function: runs once at the beginning
void setup() {
// Start serial communication
Serial.begin(115200);
// Initialize variables
input_voltage = 0.0f; // Initializing input voltage variable
inPulse = false; // Setting inPulse variable to false initially
}
// Loop function: runs repeatedly
void loop() {
// Read analog input
int analog_value = analogRead(ainPin); // Read analog input from ainPin
// Store previous input voltage
float prevInputVoltage = input_voltage; // Store the previous input voltage
// Calculate input voltage
input_voltage = (analog_value * 5.0) / 1023.0f; // Convert analog value to input voltage
// Check for the condition to start a pulse
if (prevInputVoltage < compareVoltage && input_voltage >= compareVoltage) {
Millis = hiAmplitude; // Set pulse amplitude to high
inPulse = true;
pulseStartAtMs = millis(); // Record pulse start time
}
// Check if the pulse duration has elapsed
if (inPulse && millis() - pulseStartAtMs >= pulseTime) {
inPulse = false; // End the pulse
Millis = loAmplitude; // Set pulse amplitude to low
}
// Print input voltage, pulse amplitude, and compare voltage
Serial.println(
"Input Voltage:= " + String(input_voltage, 2) + "V"
+ ", Pulse Amplitude:= " + String(Millis)
+ ", Compare Voltage:= " + String(compareVoltage, 2) + "V"
);
}