DC Motor Control w/ Reed Switch

const int switchPin = 2;       // Reed Switch
int enA = 9;
const int motorPinF =  7;      // Motor forward rotation
const int motorPinB =  8;      // Motor backward rotation
int potentiometerIn;


//Reed switch
int magneticField = LOW;
int magneticFieldLast = LOW;
int count = 0;

//Initializing Motor Outputs/Pins
void setup() {
     pinMode(enA, OUTPUT);
     pinMode(switchPin, INPUT_PULLUP);
     pinMode(motorPinF, OUTPUT);
     pinMode(motorPinB, OUTPUT);
    Serial.begin(9600);
}

//Drive Motor Forward
void forwardLoop(){
  
  digitalWrite(motorPinF, HIGH);
  digitalWrite(motorPinB, LOW);
  analogWrite(enA, 20);
}

//Drive Motor Backward
void backwardLoop() {
  digitalWrite(motorPinF, LOW);
  digitalWrite(motorPinB, HIGH);
  analogWrite(enA, 20);
}


void loop() {

//Reed Switch Counter
  int magneticField = digitalRead(switchPin);
  if (magneticField == LOW && magneticFieldLast == LOW) {
  count = count + 1;
  }
  magneticFieldLast = magneticField;
  
//If count is even, drive motor forward
  if (count % 2 == 0){
    forwardLoop();
    delay(250);  
  }

//If count is odd, drive motor backwards
  else if (count & 0x01 == 0) {
    backwardLoop();
    delay(250);
  }
  Serial.println(count);
}

I am having issues with dc motor control using a reed switch. I want to use the reed switch as a counter to run the motor forward if the reed switch is even, and run the motor backward if the reed switch counter is odd. I am running a magnet past the reed switch and am able to get the counter to work but cannot figure out how to change the direction of the motor based on the value of the reed switch counter. I was hoping someone could help with the logic or the syntax of the code :smiley:

Why isn't this

 else if (count & 0x01 == 0) {

a simple

else {

If the number is not even the only alternative is odd.

You don't have any code to print when an even or an odd value is detected

...R

What voltage does the motor run at and how much current does it take ?

UKHeliBob:
What voltage does the motor run at and how much current does it take ?

Hi UKHeliBob, our motor runs at 6 - 12V and takes 1A of current.

zijianz1:
Hi UKHeliBob, our motor runs at 6 - 12V and takes 1A of current.

What is there between the Arduino and the motor ?