Need Help Combining the functions of LED fade with a delay following analog read


Currently I have a simple setup using sample code shown below. (using Arduino UNO)

FSR reading is used to control LED output which works great- (note I inverted the range for brightness so that as load is applied, the LED dims from full brightness to dim

I am wanting expand on this to detect a minimum threshold of force which will dim my LED- then when I remove the force would like to have the LED fade back to bright with a time delay variable. as an example: LED is on - I apply a minimum amount of force, the LED dims, when I release the force I want the LED to fade back up to bright over a 1 to 5 second period.

here is the initial sketch that is working-

int fsrAnalogPin = 0; // FSR is connected to analog 0
int LEDpin = 9;      // connect Red LED to pin 11 (PWM pin)
int fsrReading;      // the analog reading from the FSR resistor divider
int LEDbrightness;
void setup(void) {
  Serial.begin(9600);   // We'll send debugging information via the Serial monitor
  pinMode(LEDpin, OUTPUT);
void loop(void) {
  fsrReading = analogRead(fsrAnalogPin);
  Serial.print("Analog reading = ");
  // we'll need to change the range from the analog reading (0-1023) down to the range
  // used by analogWrite (0-255) with map!
  LEDbrightness = map(fsrReading, 1023, 0, 0, 255);
  // LED gets brighter the harder you press
  analogWrite(LEDpin, LEDbrightness);
Any help would be appreciated  - thanks

LEDbrightness = map(fsrReading, 1023, 0, 0, 255);

That's just about the most expensive way to divide by 4 that there is.

LEDbrightness = 255 - (fsrReading << 2);

Way faster...

When you apply force, fsrReading changes. Without the delay, Serial.print()s, and expensive divide by 4 operation, it might change 10000 in one second. With the delay and other code, it might still change 40+ times per second.

How do you decide that the force applied has been removed? If you plotted the fsrReading values over time, you'd see a relatively steep increase as the force is applied and a relatively steep decrease as the force is removed. But, still, it's not an on/off thing like you'd see with a digital switch. So, you need to decide what constitutes "when I remove the force". When that criteria is met, you can set a flag indicating that the brightness needs to change over time.

Then, you'd add code, based on the blink without delay example, to determine, periodically (otherwise known as "on every pass through loop") if it was time to change the brightness level.

You'd need to record when each change took place. When the LED gets to the desired brightness, clear the flag that indicates that it needs to change.

Remember to clear the flag when a new force is applied, too. Again, the issue of what constitutes a new force needs to be determined.

Thanks for that feedback - I will keep plowing ahead - very new to this