Programming help using button

I am doing a project
function:
1.user press and hold button
2.Turn Green LED On
3.Sensor sense something(Sensorvalue < 100)
4.Turn Green LED Off (continuously until user release the button and press it again)
5.User need release and hold again the button to on Green LED

I need help with achieving function 3 to 5

int button = 2;
int GreenLED = 3;
int Sensor = A1;
int Sensorvalue  = 0;
int buttonstate= 0;
float Sensorvalue;

void setup() 
{
  pinMode(button ,OUTPUT);
  pinMode(GreenLED ,OUTPUT);
  pinMode(Sensor,INPUT);

}

void loop()
{ 
int buttonstate = digitalRead(button);
int Sensorvalue = analogRead(Sensor)
if (buttonstate == High)
 {
   digitalwrite(GreenLED, HIGH)
 }
float Sensorvalue;

void loop()
{
int buttonstate = digitalRead(button);
int Sensorvalue = analogRead(Sensorvalue)

Having two variables with the same name, but different scope AND different types is a recipe for disaster. Do not do that.

Your code won't even compile.

The time/place to read the sensor is after you detect that the switch has been pressed.

You have a global variable named Sensorvalue and a local variable of the same name. NOT a good idea. You seem to be using Sensorvalue as both a pin number and a pin value. Stop doing that.

Some questions to define it better:

  • Led turn on intermediately when the button is pressed?
  • Sensor is read and compared directly?
  • Aka, led on can be short (/not noticeable at all)?
  • If Sensorvalue >= 100, what should happen? Just led on until button is released (so it;s possible to start over)

To define better

septillion:
Some questions to define it better:

  • Led turn on intermediately when the button is pressed?
  • Sensor is read and compared directly?
  • Aka, led on can be short (/not noticeable at all)?
  • If Sensorvalue >= 100, what should happen? Just led on until button is released (so it;s possible to start over)

1.Led turn on intermediately when the button is pressed
2.Sensor is read and compared directly
3 Aka, led on can be short
4. If Sensorvalue >= 100, led off. Only on until button is released and press again (so it;s possible to start over)

Use state change detection to have actions when a button becomes pressed or released. Easy way, use a library like Bounce2 to do the work.

Here a good starting point using Bounce2 after a used a broom to clean your code :wink:

#include <Bounce2.h>

const byte ButtonPin = 2;
const byte GreenLedPin = 3;
const byte SensorPin = A1;

Bounce button;

void setup(){
  //pinMode(ButtonPin, INPUT_PULLUP);
  button.attach(ButtonPin, INPUT_PULLUP);
  pinMode(GreenLedPin, OUTPUT);
}

void loop(){
  button.update();
  
  if(button.fell(){
    //something something
  }
}