Hi all,
I'm having issues with analogRead values I'm getting out from a position sensor and I wanted to see if it was an issue with my code.
Staes 1, 2, and 5 work as they should, but in states "3" and "4" I get significantly larger analog values than what should be there. With other similar codes I get values ranging from 10 to 300, but whenever the "EmergencyOpen/Close" inputs are set to HIGH the analogRead values go out of whack in the serial Monitor
float val;
int EnableA = 2; //Designate functions to Arduino IO pins.
int Input1 = 3;
int Input2 = 4;
int EmergencyClose = 6;
int EmergencyOpen = 7;
void setup() {
Serial.begin(9600);
pinMode(EnableA, OUTPUT); //Pins 2,3,4 made OUTPUT pins
pinMode(Input1, OUTPUT);
pinMode(Input2, OUTPUT);
pinMode(EmergencyClose, INPUT); // Pins 6,7 made INPUT pins
pinMode(EmergencyOpen, INPUT);
}
void loop() {
//state 1
int analogPin = analogRead(A0); // Reads feedback from
val = analogPin;
if (val < 22) // Checks if the motor is within the 22-42 range that
{ // I'm trying to operate in.
// If the read is outside the range it goes CLOCKWISE or
Serial.println("Check1");
Serial.println(val); // COUNTERCLOCKWISE as necessary to get back within the
digitalWrite(EnableA, HIGH);
digitalWrite(Input1, HIGH);
digitalWrite(Input2, LOW);
val = analogRead(A0);
}
else if (val > 42) //Same as comments above
//state 2
{
Serial.println("Check2");
Serial.println(val);
digitalWrite(EnableA, HIGH);
digitalWrite(Input1, LOW);
digitalWrite(Input2, HIGH);
val =analogRead(A0);
}
//This part was buggy as hell, planned on revising this.
//The "If out of range, get back in range" functionality works fine,
//but I'm having problems getting the analogRead to keep reading when the
//motor needs to go to emergency open/close positions.
//state 3
else if (digitalRead(EmergencyClose) == HIGH && (val < 42))
{
while(val < 42)
{
Serial.println("Check3");
digitalWrite(EnableA, HIGH);
digitalWrite(Input1, HIGH);
digitalWrite(Input2, LOW);
val = analogRead(A0);
Serial.println(val);
}
}
else if (digitalRead(EmergencyOpen) == HIGH && (val > 22))
{
while(val > 22)
//state 4
{
Serial.println("Check4");
digitalWrite(EnableA, HIGH);
digitalWrite(Input1, LOW);
digitalWrite(Input2, HIGH);
val = analogRead(A0);
Serial.println(val);
}
}
else; // Arbitrary, just needed to close the loop.
//state 5
{
Serial.println("Check5");
digitalWrite(EnableA, LOW);
digitalWrite(Input1, LOW);
digitalWrite(Input2, LOW);
val = analogRead(A0);
Serial.println(val);
}
}
And this is a small sample of shows up on the serial monitor.
Check5
23.00
Check3
924.00
Check5
23.00
Check3
925.00
Check 4 shows the same 900+ values, but because of how the code is written it stays in that part of the loop indefinitely.
Thank you in advance!