I have a problem that I cant see in my code.
I am using a HAL sensor to get some values and put them in to an array.
When this is done I pick the largest value and the index of that value in the array. I have a stepper motor that I set the new zero to be the index of the largest value in the array.
So if the largest value is 500 and the index is 53 I move to step 53 and get new values from that position.
Now when I am ready to print the new values from the array it does not match. Is the analogRead still running even its not called?
Here is the code.
// Name: HALsteppingReader_v2
// Date: 2014-08-07
// Files: AccelStepper.h, AFMotor.h, HALsteppingReader_v2.ino
// Programmer: Alexander Mogren
// Description:
#include <AccelStepper.h>
#include <AFMotor.h>
AF_Stepper motor1(200, 1);
int HALsensorPin_1 = A0;
int HALsensorPin_2 = A2;
int HALsensorValue_1 = 0;
int HALsensorValue_2 = 0;
int HALarray[200];
int HALarray_r[200];
int h=0,maxi,i=0,x=0,serpos=0;
void forwardstep() {
motor1.onestep(FORWARD, SINGLE);
}
void backwardstep() {
motor1.onestep(BACKWARD, SINGLE);
}
AccelStepper stepper(forwardstep, backwardstep); // use functions to step
void HALsensor(int i)
{
//Analog ports for sensor 1 and 2;
HALsensorValue_1 = analogRead(HALsensorPin_1);
HALsensorValue_2 = analogRead(HALsensorPin_2);
HALarray[i]=HALsensorValue_1;
HALarray_r[i]=HALsensorValue_2;
}
void HALarrayCheck()
{
maxi=0;
//delay(1000);
for(i=0;i<=200;i++)
{
if(maxi < HALarray[i])
{
maxi = HALarray[i];
serpos = i;
}
}
Serial.print("Largest value ");
Serial.print(maxi);
Serial.print("\n");
Serial.print("Moving motor to step ");
Serial.print(serpos);
Serial.print("\n");
}
void getHALvalue()
{
int i = 0;
while (i != 201)
{
if(stepper.distanceToGo()==0)
{
HALsensor(i);
stepper.moveTo(i);
i++;
}
stepper.run();
}
}
void setup()
{
Serial.begin(9600); // set up Serial library at 9600 bps
// stepper.setSpeed(10); // 0 is no speed 254 i full speed.
}
void loop()
{
stepper.setMaxSpeed(200);
stepper.setAcceleration(200);
Serial.println("Initializing HAL sensor");
getHALvalue();
Serial.println("HAL sensor reading complete.");
Serial.println("Getting HAL sensor largest value.");
HALarrayCheck();
stepper.setCurrentPosition(serpos);
Serial.println("Stepper movment complete");
Serial.println("Run from new position");
getHALvalue();
Serial.println("Printing HAL sensor values");
for(x=0;x<200;x++)
{
Serial.print("#");
Serial.print(x);
Serial.print("\t");
Serial.print(HALarray[x]);
Serial.print("\t");
Serial.print(HALarray_r[x]);
Serial.print("\n");
}
}