conveyer belt programme.

Hey everyone,
Im quiet new to the programming side of this and im trying to get a conveyer belt going using a ultrasound HR-SR04 sensor and im trying to get it to shut off after it counts three unfortunately im still trying to get the hang of programming and im stuck as i dont actually know how to get it to turn off using an else if statement .i know its something really small but i just get running into a deadend :frowning: any help greatly appreciated.

#define trigPin 10
#define echoPin 8
 // initialize the library with the numbers of the interface pins

// named constants for the switch and motor pins
const int switchPin = 2; // the number of the switch pin
const int motorPin =  9; // the number of the motor pin
int counter = 0;
int currentState = 0;
int previousState = 0;
int switchState = 0;  // variable for reading the switch's status

void setup() {
  Serial.begin (9600);
 // initialize the motor pin as an output:
 pinMode(motorPin, OUTPUT);
 // initialize the switch pin as an input:
 pinMode(switchPin, INPUT); 
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);

void loop() {
  long duration, distance;
 digitalWrite(trigPin, LOW);
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 if (distance <= 10){
 currentState = 1;
 else {
 currentState = 0;
 if(currentState == 1 && previousState == 0)
   counter = counter + 1;
 previousState = currentState;
  // read the state of the switch value:
  switchState = digitalRead(switchPin);

  // check if the switch is pressed.
  if (switchState == HIGH) {
    // turn motor on:
    digitalWrite(motorPin, HIGH);
  else if (counter == 3 && switchState == LOW){
    digitalWrite(motorPin == LOW);

digitalWrite(motorPin == LOW); The compiler barfed on that, didn’t it?

Did you mean digitalWrite(motorPin, LOW);

How do you have your switch wired up? You have it declared as an INPUT and your code expects it to be HIGH when pressed which means you need a pull-down resistor. Do you have that installed?

A more typical approach is to wire one side of a switch to ground and the other to you input pin. You then declare the pin to be INPUT_PULLUP. This inverts the logic such that LOW = pressed and HIGH = not pressed.

 // initialize the library with the numbers of the interface pins

What library?

Have you tried a simple test sketch to display the resulting values that you are calculating for variable 'distance'?