Thanks for the info guys. Dave, I've set up a little piece of code using your functions, and I'm having a separate issue. The code I wrote uses an accelerometer to drive a stepper motor (it will eventually drive 2... but for now, just 1) and looks like this:
int xIn=A4;
int yIn=A3;
int xbl;
int ybl;
int i = 0;
int j = 0;
int oneRev = 4076; // Total number of half-steps per revolution
// or whatever your gear train is.
int pause = 3000; // Pause between steps in microseconds.
const int pin[] = {5,4,2,5,3,2,4,3}; // A progressive array of pin numbers to drive motor.
const int pinState[] = {HIGH,LOW,HIGH,LOW,HIGH,LOW,HIGH,LOW};
void setup()
{
for (j = 1; j < 5; j++) // Set the digital pins as outputs.
{
pinMode(pin[j], OUTPUT); // Set up 4 digital pins motor.
}
for (j = 8; j < 12; j++) // Set the digital pins as outputs. **DISREGARD THIS LOOP FOR NOW**
{ //**WILL BE USED FOR SECOND MOTOR**
pinMode(pin[j], OUTPUT); // Set up 4 digital pins motor.
}
Serial.begin(9600);
pinMode(xIn, INPUT);
pinMode(yIn, INPUT);
xbl = analogRead(xIn);
ybl = analogRead(yIn);
}
void loop()
{
int xPos=analogRead(xIn);
int yPos=analogRead(yIn);
int offset=50;
Serial.print("xbl ");
Serial.print(xbl);
Serial.print(" X: ");
Serial.print(xPos);
Serial.print(" ybl ");
Serial.print(ybl);
Serial.print(" Y: ");
Serial.println(yPos);
if (xPos>xbl+offset)//LEFT
{
Serial.print("L ");
motorStepReverseL();
}
if (xPos<xbl-offset)//RIGHT
{
Serial.print("R ");
motorStepForwardL();
}
if (yPos>ybl+offset)//DOWN
{
Serial.print("D ");
motorStepReverseL();
}
if (yPos<ybl-offset)//UP
{
Serial.print("U ");
motorStepForwardL();
}
}
void motorStepForwardL()
{
digitalWrite(pin[j],pinState[j]);
j++; // Keeps permutating the pins in forward direction.
if(j > 7) // Reset j if it has exceeded array size.
{
j = 0;
}
}
void motorStepReverseL()
{
j--; // Keeps permutating the pins in reverse direction.
if(j < 0) // Reset j if it has exceeded array size.
{
j = 7;
}
digitalWrite(pin[j],pinState[j]);
}
Without the motor functions included, the accelerometer portion of the code works fine, and I can see my xPos, yPos xbl, ybl, and U, D L, R in the serial monitor. As soon as I add the motorStepForward
or motorStepReverse
, I get crazy values from the accelerometer and it no longer works. I had an issue like this in the past which was caused by having the SL pin on the accelerometer hooked up to a digital out, but the current set up has it connected to a straight 5VDC pin. Any ideas what would cause this interference?