I am making a project using IR sensor,servomotor and Push button. I am not able write code for the logic as stated: it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

  • 1
    I am not able write code for the logic - so, you want someone to do it for you for free? Sounds fair – Jaromanda X Mar 9 '19 at 6:46
  • logic as stated .... you have not clearly stated the desired behavior – jsotola Mar 9 '19 at 17:59

My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.

Such an approach helps you in creating code easy to maintain and change to new requirements

enter image description here

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.

Switch(state) {
  case 00:
  // if IR set state = 10;
  case 10:
  // if button was pressed set state = 11
  case 11:
  // turn motor
  // if treshold set state = 12


Not the answer you're looking for? Browse other questions tagged or ask your own question.