Hello everyone,
I'm hoping to get some programming help here for my little project. I'm trying to gain experience with the code and the arduino, so please bear with me.
What I'm trying to accomplish is to have my accelerometer detect movement and then have my stepper motor move accordingly (the bigger the acceleration, the bigger the stepper motor movement). Also, if the accelerometer is experiencing a constant G, then the stepper steps the appropriate number of steps, and holds that position. When there is no acceleration, the stepper motor returns to the original position it started. Hopefully this is clear
The problem that I am experiencing is erattic motor behaviour. It seems like the motor doesn't reliably return to the starting position. Any suggestions would be great! Thanks!
Without further adieu, here is the code I have so far:
//Easydriver pins
int dirPin = 3;
int stepperPin = 12;
//Accelerometer pins (analog)
const int pinx = 1 ;
const int piny = 2 ;
const int pinz = 3 ;
const int SLP = 9;
//variables to store accelerometer output and keep track of stepper position
int valx = 0;
int valy = 0;
int valz = 0;
int last = 0;
int current = 0;
int difference = 0;
//setup
void setup() {
Serial.begin(9600);
pinMode(SLP, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(stepperPin, OUTPUT);
}
//Function for instructing the Easydriver
void step(boolean dir,int steps){
digitalWrite(dirPin,dir); //give Easydriver direction for stepper to move
delay(50);
for(int i=0;i<steps;i++){ //loop through the number of steps that the stepper motor must complete
digitalWrite(stepperPin, LOW);
digitalWrite(stepperPin, HIGH);
delayMicroseconds(1000);
}
}
//Main code body
void loop(){
digitalWrite(SLP, HIGH); //Make sure the accelerometer is "awake"
//Read the values from the accelerometer and assign them to the variables. For this simple program, only the y value will be used for now.
valx = analogRead(pinx);
valy = analogRead(piny);
valz = analogRead(pinz);
if (last == 0) { //For the first time through the loop, set the "last" value to y input from the accelerometer (multiplied by 5 so stepper motor moves more)
last = valy*5;
}
current = valy*5; //Set the "current" value to the y value (multiplied by 5 so stepper motor moves more)
difference = last - current; //Calculate the difference between the last known acceleration and the current acceleration
if (difference > 0) { //If the difference is positive, then it will tell the Easydrive to step the motor counter-clockwise
step(false, difference);
}
if (difference < 0) { //If the difference is a negative number, then it will tell the Easydriver to step the motor clockwise
difference = abs(difference);
step(true, difference);
}
last = current; //Set the last known to acceleration to the current one so it can be compared to the next reading
delay(50);
}