// This code generated using ChatGPT
// Pin definition
const int brakePin = 5; // BRAKE SIGNAL input pin (can be any digital pin)
const int pwmPin = 12; // PWM output pin (can be any digital pin)
const int sensorPin = A1; // Sensor connected to analog pin 1
// Variables
int pwmFrequency = 10; // Default frequency (Hz)
int dutyCycle = 50; // Default duty cycle (percent)
unsigned long previousMicros = 0; // Stores the last time the PWM state changed
unsigned long period = 100000; // Period for PWM signal in microseconds (default 100Hz)
int highTime = 0; // Duration of the HIGH state for PWM (based on duty cycle)
int lowTime = 0; // Duration of the LOW state for PWM
bool pwmState = false; // Tracks the current state of PWM (HIGH or LOW)
bool Apply_brake = false; // Track whether brake applied (HIGH or LOW)
void setup() {
// Initialize the PWM pin as an output
pinMode(brakePin, INPUT);
pinMode(pwmPin, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the sensor value (0 to 1023)
int sensorValue = analogRead(sensorPin);
//delayMicroseconds(10);
Apply_brake = digitalRead(brakePin);
//delayMicroseconds(10);
// Map sensor value (0-1023) to a duty cycle percentage (0-100)
dutyCycle = map(sensorValue, 0, 1023, 0, 100);
// Calculate the period (in microseconds) for the desired PWM frequency
period = 1000000 / pwmFrequency; // period = 1 / frequency, in microseconds
// Calculate the high and low time for the duty cycle
highTime = (dutyCycle * period) / 100; // high time based on duty cycle
lowTime = period - highTime; // low time is the remainder of the period
// Get the current time in microseconds
unsigned long currentMicros = micros();
// Check if it's time to change the state of the PWM pin
if (currentMicros - previousMicros >= (pwmState ? highTime : lowTime)) {
// Toggle the PWM state
pwmState = !pwmState; // Change state from HIGH to LOW or vice versa
// Update the last time the state was changed
previousMicros = currentMicros;
// Set the PWM pin to the new state (HIGH or LOW)
if(Apply_brake)
{
digitalWrite(pwmPin, pwmState ? HIGH : LOW);
//Serial.print(" Output: ");
//Serial.print( pwmState );
//Serial.println(" ");
}
else
{
digitalWrite(pwmPin,LOW);
}
}
// Optional: Monitor and change the frequency through Serial Monitor
if (Serial.available() > 0) {
pwmFrequency = Serial.parseInt(); // Read the frequency from serial input
pwmFrequency = constrain(pwmFrequency, 10, 500); // Ensure it's within the range of 1-500 Hz
Serial.print("New PWM Frequency: ");
Serial.println(pwmFrequency);
Serial.readString();// TO DELETE ANY SERIAL IN DATA
previousMicros = currentMicros;// TO UPDATE LAST TIME
}
// Debugging output to monitor duty cycle and sensor values
//Serial.print(" Brake sensor: ");
//Serial.print(Apply_brake);
//Serial.print(" Sensor Value: ");
//Serial.print(sensorValue);
//Serial.print(" => Duty Cycle: ");
//Serial.println(dutyCycle);
// No delay, just efficient non-blocking execution
}