#include <avr/wdt.h> // Include watchdog timer library
#include "HX711.h" // Include HX711 library
// Pin Definitions
const int analogPin = 3; // Potentiometer pin for delay adjustment
const int dtPin = 2; // HX711 Data pin
const int sckPin = 1; // HX711 Clock pin
const int fetPin = 0; // PWM pin for FET control
const int relayPin = 1; // Relay pin
// HX711 Object
HX711 scale;
void setup() {
pinMode(fetPin, OUTPUT);
pinMode(relayPin, OUTPUT);
digitalWrite(fetPin, HIGH); // Set FET to High State (initial state)
digitalWrite(relayPin, LOW); // Set relay to normally closed (initial state)
// Initialize Watchdog Timer
wdt_enable(WDTO_250MS); // Set watchdog timer to 250 milliseconds
// Initialize HX711
scale.begin(dtPin, sckPin);
scale.set_scale(); // Set scale to default (calibrate later if necessary)
scale.tare(); // Reset the scale to 0
// Initialize analog reference and ADC
analogReference(DEFAULT); // Set ADC reference to default (Vcc)
analogRead(analogPin); // Perform a dummy read to initialize the ADC
}
void loop() {
static unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50; // Debounce time in milliseconds
// Read HX711 value
long strainGaugeValue = scale.get_units(); // Read force value from HX711
// Read potentiometer value and map it to delay time
int potValue = analogRead(analogPin);
unsigned long delayTime = map(potValue, 0, 1023, 40, 500); // Map potentiometer value to delay range (40 to 500 ms)
// Check if strain gauge value exceeds the force threshold
if (strainGaugeValue > 512) { // Adjust threshold based on calibration
if ((millis() - lastDebounceTime) > debounceDelay) {
delayMicroseconds(10); // Small delay for sensor stabilization
// Confirm the sensor value is still above the threshold
if (scale.get_units() > 512) { // Confirm force is still above threshold
digitalWrite(relayPin, HIGH); // Activate relay to allow FET operation
digitalWrite(fetPin, LOW); // Cut FET
delay(delayTime); // Wait according to potentiometer value
// Ramp up FET signal
for (int loop = 40; loop <= 255; loop++) {
analogWrite(fetPin, loop); // Start sending signal to FET
digitalWrite(relayPin, HIGH); // Keep relay activated
delayMicroseconds(320); // Loop delay
}
digitalWrite(fetPin, HIGH); // After loop, set FET to full power
digitalWrite(relayPin, LOW); // Turn off relay to allow direct power
// Wait for the sensor to be released with a more efficient debounce
unsigned long sensorReleaseStart = millis();
while (scale.get_units() > 512) { // Confirm force is below threshold
if (millis() - sensorReleaseStart > debounceDelay * 4) { // Timeout after 4x debounceDelay
break;
}
}
lastDebounceTime = millis(); // Update debounce time
}
}
}
wdt_reset(); // Reset watchdog timer
}