I have a problem with my code, I want it to detect the reed switch, once it detects the reed switch from that point to the point where it can’t detect the reed switch. It should stop and take the revolutions and divide those revolutions by 2.
Can someone help me to fix this code for me
//Define pin setup
#define motor_in1 7
#define motor_in2 8
#define motor_enA 9
#define sensorPin 2
#define reedPin 2
#define ledPin 13
int half_revolutions = 0;
int revolutions_per_pos;
int pos = 0;
void setup() {
// Set pin mode
pinMode(motor_enA, OUTPUT);
pinMode(motor_in1, OUTPUT);
pinMode(motor_in2, OUTPUT);
pinMode(reedPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
// Since the other end of the reed switch is connected to ground, we need
// to pull-up the reed switch pin internally.
}
void loop() {
// Hallsensor connected to the interrupt pin (Pin 2 on Arduino Uno)
attachInterrupt(digitalPinToInterrupt(sensorPin), magnet_detect, RISING);
// Run full cycle to each position and back to 07
// Position 1
revolutions_per_pos = 706;
move_amount(3);
delay (2000);
return_to_zero(true);
}
void reed_detect()
{
analogWrite(motor_enA, 0);
}
void magnet_detect() {
half_revolutions++;
}
void move_amount(int no_pos)
{
unsigned int hr_local_copy;
unsigned int count;
unsigned int motor_speed;
// Set rotation direction
if (no_pos < 0) {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
no_pos = -no_pos;
motor_speed = 255;
} else {
// Set rotation direction
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
motor_speed = 255;
}
count = no_pos * 2 * revolutions_per_pos;
noInterrupts();
half_revolutions = 0;
hr_local_copy = 0;
interrupts();
// start motor
analogWrite(motor_enA, motor_speed);
while (hr_local_copy < count) {
noInterrupts();
Serial.println(hr_local_copy);
hr_local_copy = half_revolutions;
interrupts();
}
// stop motor
analogWrite(motor_enA, 0);
noInterrupts();
hr_local_copy = half_revolutions;
interrupts();
Serial.println(hr_local_copy);
}
void return_to_zero(boolean clockwise)
{
if(clockwise){
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
else {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
int motor_speed = 255;
analogWrite(motor_enA, motor_speed);
Serial.println("Turning back...");
boolean detected = false;
while(!detected){
half_revolutions = 0;
while(digitalRead(reedPin) == HIGH){
interrupts();
Serial.println("Reed Detected");
detected = false;
}
}
Serial.println("Half revolutions: " + half_revolutions);
int return_half_revolutions = half_revolutions / 2;
analogWrite(motor_enA, 0);
analogWrite(motor_enA, 0);
analogWrite(motor_enA, 0);
if(clockwise){
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
else {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
analogWrite(motor_enA, motor_speed);
while(return_half_revolutions < half_revolutions){}
}