Mål: Att accelerera steppermotorn till en given position med hjälp av en rotary encoder. Rotera encodern och tryck in den för att starta steppermotorn.
Fritzing layout
Arduino koden
// Blocking.pde // -*- mode: C++ -*- // // Shows how to use the blocking call runToNewPosition // Which sets a new target position and then waits until the stepper has // achieved it. // // Copyright (C) 2009 Mike McCauley // $Id: Blocking.pde,v 1.1 2011/01/05 01:51:01 mikem Exp mikem $ // edited: maker 18.12.2016 // rotate encoder to a position // press encoder button to accelerate stepper to position #include <AccelStepper.h> #include <Arduino.h> const int PinCLK = 2; // Used for generating interrupts using CLK signal const int PinDT = 7; // Used for reading DT signal const int PinSW = 8; // Used for the push button switch volatile int virtualPosition = 0; AccelStepper stepper(4,3,4,5,6); // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5 void isr () { static unsigned long lastInterruptTime = 0; unsigned long interruptTime = millis(); // If interrupts come faster than 5ms, assume it's a bounce and ignore if (interruptTime - lastInterruptTime > 5) { if (!digitalRead(PinDT)) virtualPosition = (virtualPosition + 1); else virtualPosition = virtualPosition - 1; } lastInterruptTime = interruptTime; Serial.print("position = "); Serial.println(virtualPosition); } // ISR void setup() { stepper.setMaxSpeed(400.0); stepper.setAcceleration(100.0); Serial.begin(9600); pinMode(PinCLK,INPUT); pinMode(PinDT, INPUT); pinMode(PinSW, INPUT); attachInterrupt(0, isr, FALLING); // interrupt 0 is always connected to pin 2 on Arduino UNO Serial.println("Start"); } void loop() { int lastCount = 0; while (true) { if (!(digitalRead(PinSW))) { // check if pushbutton is pressed while (!digitalRead(PinSW)) {} // wait til switch is released delay(20); // debounce stepper.runToNewPosition(virtualPosition); } if (virtualPosition != lastCount) { lastCount = virtualPosition; } } }