I expected that the servo motor will rotate from 160 to 0 degree when the gas sensor gives the reading of greater than 100 and maintain in the position till I press the switch which is connected in digital pin 7.
But the servo motor rotates from 160 to 0 degree when the gas sensor reading is greater than 100 and it comes back to its original position (160 degrees) when the reading of gas sensor is less than 100.
As I am newbie to arduino, and still learning, I know that I've done some mistake in coding... i will be pleased to know what changes should i do in coding...
i am using an arduino nano with atmega328 (old bootloader)
If remove the break statement the servo motor works as usual and not stops
After appying the break statement, the servo motor stops after moving from 160 to 0 degree which is what I want
But the actual problem is, the servo motor comes to original position when the reading of gas sensor is less than 100, but i need the servo motor to remain in its position until I press the switch
Then you have an open input, and the input level at your digitalRead() will be whatever it chooses to be. You need to either wire the button to ground, and use pinMode(pin,INPUT_PULLUP), and watch for a low pin in your code, OR, you need to provide an external resistor from the input pin to GND. Your choice; your present approach will not work.
A digital input with nothing attached, which is what your button input is when the button is not pressed, is a very high input impedance antenna, and will receive noise from waving your hand over the circuit, the local radio station, and just about any other significant rubbish out there. To receive a proper logic level low or high, it must always have a circuit path to GND or +V. A "pullup resistor" wired from input pin to +5V suffices. So does a "pulldown resistor" wired from input pin to GND. With the '328PB processor in the Nano, you have the option of using a pullup resistor built into the chip itself; very convenient. To do that, you specify pinMode(pin, INPUT PULLUP);
in setup().
What you have now will randomly, but very frequently, get either a high or a low, and that randomness will confound any attempt to build sane logic around the pressing, or not pressing, of a button.
With a pullup in place, external or internal, you can wire your button from input pin to GND, and if(digitalRead(pin) ==LOW)
will test for the button being pressed.