I'm using a Nano driven stepper to tune a capacitor, but I am having a lot of trouble trying to get repeatable positioning.
I also have a 'homing' routine to establish the starting position, but when the system returns home, it 'bounces' against the limit switch.
this is the sketch.....
#include "Arduino.h"
#include "LiquidCrystal_I2C.h"
#include <Wire.h>
#include "BasicStepperDriver.h"
#include <Encoder.h>
#define outputA 2
#define outputB 3
#define button_pin 6
#define upswitch 4
#define dnswitch 5
#define DIR 7
#define STEP 8
#define limitswitch 9
#define SLEEP 10
#define MICROSTEPS 8
#define MOTOR_STEPS 200
#define RPM 5
BasicStepperDriver stepper(MOTOR_STEPS, DIR, STEP, SLEEP);
Encoder myEnc(2, 3);
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4);
int button;
int position;
int stepcount = 0;
int limit = 0;
int currpos;
long oldPosition = 0;
long newPosition = 0;
void setup() {
lcd.begin(20, 4);
lcd.display();
lcd.backlight();
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(10,OUTPUT);
pinMode (3, INPUT_PULLUP);
pinMode (2, INPUT_PULLUP);
pinMode (6, INPUT_PULLUP);
pinMode (9, INPUT_PULLUP);
pinMode (4, INPUT_PULLUP);
pinMode (5, INPUT_PULLUP);
stepper.begin(RPM, MICROSTEPS);
Serial.begin (9600);
}
void home(){
delay(10);
Serial.println ("Homing");
limit = digitalRead(limitswitch);
while (limit == 1) {
limit = digitalRead(limitswitch);
stepper.move(-1); // clockwise
delay(5);
}
myEnc.write (0);
stepcount = 0;
updateDisplay();
}
void updateDisplay(){
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" MAGLOOP CONTROL ");
lcd.setCursor(0, 1);
lcd.print("Position ");
lcd.setCursor(16,1);
lcd.print(currpos);
lcd.setCursor(0, 2);
lcd.print("");
lcd.setCursor(16,2);
lcd.print("");
lcd.setCursor(0, 3);
lcd.print("");
lcd.setCursor(14, 3);
lcd.print("");
delay(10);
}
void loop() {
button = 1;
button = digitalRead (button_pin);
if (button == 0){
home();
button = 1;
delay(50);
}
long newPosition = myEnc.read();
Serial.println (newPosition);
if (newPosition < 0) {
newPosition = 0;
}
if (newPosition > 400) {
newPosition = 400;
}
if (newPosition > oldPosition) {
stepcount = (newPosition - oldPosition);
stepper.move (stepcount);
delay(10);
}
if (newPosition < oldPosition) {
stepcount = (oldPosition - newPosition);
stepper.move (- stepcount);
delay(10);
}
oldPosition = newPosition;
currpos = newPosition;
updateDisplay();
}
Now, I'm just a novice programmer, so any help would be appreciated.
Thanks.
