//Fixed the issue with the stepper mottor moving a the start of the simulation
#include <Servo.h>
// Define stepper motor and servo pins
#define STEP_PIN 9
#define DIR_PIN 8
//#define INPUT_SERVO_PIN 6
//#define OUTPUT_SERVO_PIN 5
#define BUTTON_PIN 2
#define HOME_SWITCH 4
#define OPTICAL_SWITCH 7
Servo inputServo;
Servo outputServo;
bool shuffleStarted = false;
int stepperSpeed = 1000; // Stepper motor speed (delay in microseconds)
void setup() {
// Set up the stepper motor control pins
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
// Set up the button pin
pinMode(BUTTON_PIN, INPUT_PULLUP); // Use internal pull-up resistor
// Set up the Optical Switch
pinMode(HOME_SWITCH, INPUT_PULLUP);
// Attach servos
//inputServo.attach(INPUT_SERVO_PIN);
//outputServo.attach(OUTPUT_SERVO_PIN);
// Initialize servos to default positions
//inputServo.write(0);
//outputServo.write(0);
// Serial for debugging
Serial.begin(9600);
//homeStepper();
}
void loop() {
// Check if the button is pressed
if (digitalRead(2) == HIGH) {
shuffleStarted = true; // Start shuffling
}
// If shuffle has started, perform shuffling and dispensing
if (shuffleStarted) {
shuffleCards();
dispenseCard();
shuffleStarted = false; // Reset after shuffling
}
delay(100); // Small delay to debounce the button
}
void shuffleCards() {
for (int i = 0; i < 10; i++) { // Shuffle 10 times
int randomPosition = random(0, 200); // Random position on wheel
//rotateInputMotor();
//delay(1000); // Wait a bit
rotateStepper(randomPosition);
delay(900);
}
}
// rotateInputMotor(){
//inputServo.write(200);
// delay(500);
//
void rotateStepper(int steps) {
digitalWrite(DIR_PIN, HIGH); // Set direction
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(stepperSpeed); // Adjust delay for speed Original: 500
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(stepperSpeed); // Adjust delay for speed
}
}
void dispenseCard() {
//outputServo.write(90); // Open output gate
//delay(1000); // Wait for card to fall
for (int i = 0; i < 10; i++) {
rotateStepper(20); // Rotate stepper in increments of 20 steps
delay(1000); // Wait a bit to ensure smooth movement
}
//outputServo.write(0); // Close output gate
}
void homeStepper() {
digitalWrite(DIR_PIN, LOW); // Set direction towards home
while (digitalRead(HOME_SWITCH) == HIGH) { // Rotate until the switch is triggered
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(stepperSpeed); // Adjust delay for speed
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(stepperSpeed);
}
}