Dank voor de opmerking Rob, het is erg leuk om te doen!
Er zullen nog wel wat puntjes op de i gezet worden. Een verbeteringspunt is nog het delay tussen het schakelen van de sperleds en start/einde beweging.
Iets wat ik nog wat belangrijker vind is " de kortste weg vinden" Nu draait ie vanuit 0 altijd linksom naar de grootste hoek, even ingesteld op 270 graden terwijl hij ook 90 rechtsom had gekund.
Ik weet even niet of jij dit erin had zitten en het hier verknoeid is?
De code kan nog wel wat opgeschoond worden. Bijvoorbeeld "TrackLed" past niet meer.
De sketch dan, hoop dat ik je goed begrepen heb:
/* Turntable control
* =================
* For a partial turntable. 4 tracks at angles of 15, 20 and 15 degrees
*
* Beschrijving (NL)
* Besturing voor een modelspoor segmentdraaischijf met 4 sporen.
* De draaischijf wordt aangedreven met een stappenmotor.
* Bediening met een '0-positie' sensor en 4 drukknoppen op een spanningsdeler
* Terugmelding over 4 LEDs: een LED voor elk spoor.
*
* versie 2.0, 20 okt 2018
*/
/***** Import needed libraries ******/
#include <AccelStepper.h>
#define FULLSTEP 4
#define HALFSTEP 8
/***** Declare Pin Numbers *******/
// motor pins
#define motorPin1 2 // Blue - 28BYJ48 pin 1
#define motorPin2 3 // Pink - 28BYJ48 pin 2
#define motorPin3 4 // Yellow - 28BYJ48 pin 3
#define motorPin4 5 // Orange - 28BYJ48 pin 4
// sensor pins (analog)
#define startPin 8 // pin to detect turntable start position
#define buttonsPin A1 // analog pin to read buttons by Voltage divider
// led indicators pins
# define trackLed1 9 // led for track 1
# define trackLed2 10 // led for track 2
# define trackLed3 11 // led for track 3
# define trackLed4 12 // led for track 4
// spersein leds
# define sperledRed 6 // rode led spersein
# define sperledWit 7 // witte led spersein
#define ledpin 13 // LED on Arduino
/******* Definitions for turntable control ******/
// ---- Turntable ----
// Physical definitions
#define slack 9 // steps of slack in stepper motor axel from middle
#define initMove -30 // steps to move at initialisation before sensor read
#define numberOfTracks 10 // number of tracks on turntable
// arrays below must correspond with number of tracks:
// positions for 10 turntable tracks (motor steps from 0) -> 1 omwenteling = ~ 26500 stappen.
int track[numberOfTracks]{-100, -2000, -3100, -4200, -5300, -6400, -7500, -13000, -15000, -17000};
int buttonBoundary[numberOfTracks]{1000, 900, 800, 700, 650, 550, 480, 380, 280, 180};
// Operational definitions
#define startTrack 0 // initial track to move to (after detecting 0-position sensor)
#define maxTurnSpeed 400.0 // maximum speed of stepper motor normal operation -> van 55 naar 400 =~ 60sec / omwenteling
#define startTurnSpeed 120.0 // start speed of stepper motor -> van 20 naar 120 verhoogd
#define turnAccelleration 46.0 // acceleration of stepper motor
// ---- Led display ----
unsigned long prevms = 0; // blinking led milisecs last on/off
unsigned long curms = millis(); // blinking led milisecs now
const long blnkint = 250; // blink interval in milliisec.
/******* Global variables ******/
// ---- Turntable variables ----
int currentTrack = 0; // position after initialisation
int newTrack = 0; // 1st position to move to after initialisation
int button = -1; // button pressed (0, 1 2 or 3, -1 is no button)
// ---- Led display variables ----
int blnk = HIGH;
/****** Objects *******/
// ---- Stepper motor object ----
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
// array of pins used to send out the binary-encoded track number
int ledPins[]{trackLed1, trackLed2, trackLed3, trackLed4};
/****** Functions ******/
#define ArrayCount(x) (sizeof(x) / sizeof(x[0]))
// ---- initialiation: 0-position detection ----
// Turntable initialisation after starting/resetting Arduino.
// It first moves the stepper motor counterclockwise (defined by initMove),
// and then moves the turntable clockwise slowly untill 0-positions is sensed
// on "startPin".
// Motor position "0"is set to the sensor position.
// Function returns "true" if sensor has been detected.
//
// Maximum steps is to find sensor: last track position + initial move steps.
// When 0 position is not sensed, function returns "false".
bool initTurntable() {
bool succesfull = true; // return parameter
int x = 0; // step counter
digitalWrite(ledpin, LOW); // show initialisation ongoing on Arduino board
// calculate total maximum number of steps (maxSteps) to find sensor:
// the number of steps to position of last track, including slack and initial move
int maxSteps = abs(track[numberOfTracks - 1]) + abs(initMove) + 2 * slack; // sensor must be found in less steps
// move turntable into start / reset position
stepper1.setMaxSpeed(10); // verhoogd van 1 naar 10
stepper1.setAcceleration(500.0);
stepper1.setSpeed(10); // verhoogd van 1 naar 10
// start with a move counterclockwise in case just beyond sensor...
x = initMove;
// now keep turning the table slowly until start point sensed
do {
stepper1.runToNewPosition(x);
x++; //was x++; nu sneller naar 0 positie
} while ((digitalRead(startPin) == LOW) && (x < maxSteps)); //run until sensor active, or max steps done (error)
if (x < maxSteps) { // start position sensed. Intialise stepper position
stepper1.setCurrentPosition(0); // sensor position = 0
digitalWrite(ledpin, HIGH); // end of initialisation
} else { // initialisation error
succesfull = false;
}
stepper1.disableOutputs(); // Turn off stepper motor power
return succesfull;
}
// ---- read button sensor ----
// function to get button from analog pin
// returns button 0-3 pressed.
// returns -1 if no button pressed
int getButtonPressed() {
int r = analogRead(buttonsPin);
int b = -1;
if (r < buttonBoundary[0]) { // a button was pressed
delay(200); // wait for analog pin to stabalize
r = analogRead(buttonsPin);
// check which boundary value has been read on analog buttonPin
if (r < buttonBoundary[0]) {
b = numberOfTracks - 1; // check lat button to first
while (r > buttonBoundary[b]) {
b--;
}
}
}
return b;
}
// ---- turntable movement calculation ----
// function to calculate new position for turntable to move to
// input: new track number
// output: new stepper position with corrections mechanical inaccuracies
int calcNewPosition(int trk) {
int pos = 0; // new stepper motor position
int curTurnDirection = 0; // current direction in Turntable = calculate for slack in movement
// keep values last move before calculating new move
currentTrack = newTrack;
newTrack = trk;
// Init new move
// check direction for additional slack movement.
// calculate new stepper position
if (newTrack > currentTrack) {
curTurnDirection = -1; // counterclockwise
} else {
curTurnDirection = 1; // clockwise
}
// calculate position to move to
pos = track[newTrack]; // bare track position
pos = pos + (curTurnDirection * 2 * slack); // correction for slack
return pos;
}
// ---- LED indiator function ----
// led on / of / blink function
// trackNumber: track number
// func: 0 = off, 1 = blink, 2 = on
void setLed(int trackNumber, int func) {
if (func == 0) {
writeLedPins(trackNumber, LOW);
}
if (func == 2) {
writeLedPins(trackNumber, HIGH);
}
if (func == 1) {
curms = millis();
if (curms - prevms >= blnkint) {
prevms = curms;
if (blnk == HIGH) {
blnk = LOW;
} else {
blnk = HIGH;
}
writeLedPins(trackNumber, blnk);
}
}
}
// Set led pins depending on the binary input in the `ledPins` array, at position `led`.
void writeLedPins(int trackNumber, int value) {
//Serial.println();
//Serial.print("Track: ");
//Serial.println(trackNumber);
// Loop over all led pins.
for (int i = 0; i < ArrayCount(ledPins); ++i) {
// If the bit for the current led pin is set, set the pin.
digitalWrite(ledPins[i], trackNumber & (int) round(pow(2, i)) ? value : LOW);
//Serial.print(trackNumber & (int) round(pow(2, i)) ? value : LOW);
}
//Serial.println();
}
void setSperSign(bool isWhite) {
digitalWrite(sperledRed, isWhite ? LOW : HIGH);
digitalWrite(sperledWit, isWhite ? HIGH : LOW);
}
/****** SETUP: RUNS ONCE ******/
void setup() {
bool init = false; // turntable intialisation status
//Serial.begin(9600);
int x = 0;
// set the digital led pins as output and initialise values
while (x < ArrayCount(ledPins)) {
pinMode(ledPins[x], OUTPUT);
analogWrite(ledPins[x], 255);
digitalWrite(ledPins[x], LOW); // show initializing: all track leds off
x++;
}
// show: initializing: Loop through all leds
for (int i = 0; i < numberOfTracks; ++i) {
writeLedPins(i, HIGH);
delay(250);
}
writeLedPins(0, LOW);
pinMode(ledpin, OUTPUT);
digitalWrite(startPin, LOW); // initialise startpin low. Default HIGH, aangepast ivm IR tunnel
digitalWrite(buttonsPin, HIGH); // initialise button read
// turntable initialisation: search for 0-position sensor
init = initTurntable(); // initialise turntable.
while (not init) { // Find 0-position (sensor), false = 0-pos. not found
digitalWrite(ledpin, HIGH); // Blink led indefenitely
delay(100);
digitalWrite(ledpin, LOW);
delay(100);
}
// no error: setup turntable and led indicators for normal operation
x = 0;
while (x < ArrayCount(ledPins)) { // switch off track leds
digitalWrite(ledPins[x], LOW);
x++;
}
// Setings for speed and accelaration during normal operation
stepper1.setMaxSpeed(maxTurnSpeed);
stepper1.setAcceleration(turnAccelleration);
stepper1.setSpeed(startTurnSpeed);
// move to initial track
stepper1.moveTo(calcNewPosition(startTrack)); // move to new position in normal operation
stepper1.runSpeed();
}//--(end setup )---
/****** LOOP: RUNS CONSTANTLY ******/
void loop() {
stepper1.run(); // operate the stepper motor
// turntable stop
if (stepper1.distanceToGo() == 0) { // turntable at desired position
stepper1.disableOutputs(); // turn stepper motor off (all pins low)
setLed(newTrack, 2); //turn on led for track positioned to
button = getButtonPressed(); // check if a button was pressed
delay(250);
setSperSign(true);
if (button > -1 && button != newTrack) { // button pressed for another track than positioned on
setSperSign(false);
delay(100); // Wacht een seconde na het spersignaal
setLed(newTrack, 0); //turn off led for this track, we're moving away from it.
stepper1.moveTo(calcNewPosition(button)); // calculate new stepper position and move to it.
}
}// turntable moving
else { // turntable turning (moving to desired position)
setLed(newTrack, 1); // blink the LED for the track where turntable is moving to
}
}//--(end main loop )---
//*********( THE END )***********