├── keywords.txt ├── README.md ├── examples └── basic │ └── basic.ino ├── src ├── InstructionSet.cpp ├── InstructionSet.h ├── utility │ ├── ExodeThread.cpp │ ├── ExodeThread.h │ ├── Thread.cpp │ ├── ThreadController.h │ ├── Thread.h │ ├── ThreadController.cpp │ ├── AccelStepper.cpp │ └── AccelStepper.h ├── Exode.h ├── Exode.cpp └── exode_set.h ├── library.properties └── LICENSE.txt /keywords.txt: -------------------------------------------------------------------------------- 1 | _exode KEYWORD1 2 | run KEYWORD2 3 | setup KEYWORD2 4 | load_exode_instructions KEYWORD2 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExodeCore 2 | **version 1.0** 3 | This repository is the arduino core of the [Exode project](https://github.com/sne3ks/Exode). 4 | -------------------------------------------------------------------------------- /examples/basic/basic.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void setup() { 5 | _exode.setup(); 6 | load_exode_instructions(0); 7 | } 8 | 9 | void loop() { 10 | // Enjoy it ! 11 | _exode.run(); 12 | } 13 | -------------------------------------------------------------------------------- /src/InstructionSet.cpp: -------------------------------------------------------------------------------- 1 | #include "InstructionSet.h" 2 | 3 | InstructionSet::InstructionSet(int len){ 4 | // Initialisation of the instruction's set 5 | _len= len; 6 | _SET= (_inst*) malloc(len*sizeof(_inst)); 7 | } 8 | 9 | void InstructionSet::set(char id, _inst foo){ 10 | this->_SET[id]= foo; 11 | } 12 | 13 | void InstructionSet::exec(char id, byte o[]){ 14 | if (this->_SET[id] != NULL)this->_SET[id](o); 15 | } 16 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=ExodeCore 2 | version=0.3.2 3 | author=Lenselle Nicolas 4 | maintainer=Lenselle Nicolas 5 | sentence=Communication between Arduino microcontroller boards and a connected computers. 6 | paragraph=Exode is a Python library for communication between Arduino microcontroller boards and a connected computer. Write Python script and take control on your board. 7 | category=Communication 8 | url=http://sne3ks.github.io/Exode/ 9 | architectures=* 10 | includes=Exode.h,exode_set.h 11 | -------------------------------------------------------------------------------- /src/InstructionSet.h: -------------------------------------------------------------------------------- 1 | /* 2 | InstructionSet.h - 3 | 4 | A set of Instructions 5 | 6 | Created by Lenselle Nicolas, december, 2015 7 | APACHE License 2.0 8 | */ 9 | 10 | #ifndef InstructionSet_h 11 | #define InstructionSet_h 12 | 13 | #if defined(ARDUINO) && ARDUINO >= 100 14 | #include 15 | #else 16 | #include 17 | #endif 18 | 19 | // _inst : a pointer to a function with an 20 | // byte array as argument 21 | typedef void (*_inst)(byte*); 22 | 23 | class InstructionSet{ 24 | 25 | protected: 26 | _inst* _SET; 27 | int _len; 28 | 29 | public: 30 | 31 | InstructionSet(int len); 32 | 33 | void set(char id, _inst foo); 34 | void exec(char id, byte o[]); 35 | }; 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /src/utility/ExodeThread.cpp: -------------------------------------------------------------------------------- 1 | #include "ExodeThread.h" 2 | 3 | 4 | ExodeThread::ExodeThread(byte o[], void (*callback)(byte o[]), unsigned long _interval):Thread(){ 5 | 6 | op = o; 7 | 8 | onRun(callback); 9 | 10 | enabled = true; 11 | _cached_next_run = 0; 12 | last_run = 0; 13 | 14 | ThreadID = (int)this; 15 | #ifdef USE_THREAD_NAMES 16 | ThreadName = "Thread "; 17 | ThreadName = ThreadName + ThreadID; 18 | #endif 19 | 20 | setInterval(_interval); 21 | 22 | }; 23 | 24 | void ExodeThread::onRun(void (*callback)(byte o[])){ 25 | _onRun = callback; 26 | } 27 | 28 | void ExodeThread::run(){ 29 | if(_onRun != NULL) 30 | _onRun(op); 31 | 32 | runned(); 33 | } 34 | 35 | int ExodeThread::getId(){ 36 | return ThreadID; 37 | } 38 | -------------------------------------------------------------------------------- /src/utility/ExodeThread.h: -------------------------------------------------------------------------------- 1 | /* 2 | ExodeThread.h - An runnable object 3 | 4 | ExodeThread inherited from Thread 5 | See here : https://github.com/ivanseidel/ArduinoThread 6 | 7 | ExodeThread is adapted for Exode, callback function 8 | use a byte array to hold the operandes 9 | 10 | Created by Lenselle Nicolas, december, 2015 11 | APACHE License 2.0 12 | */ 13 | 14 | #ifndef ExodeThread_h 15 | #define ExodeThread_h 16 | 17 | #include "Thread.h" 18 | 19 | #if defined(ARDUINO) && ARDUINO >= 100 20 | #include 21 | #else 22 | #include 23 | #endif 24 | 25 | class ExodeThread : public Thread{ 26 | 27 | protected : 28 | void (*_onRun)(byte o[]); 29 | 30 | public : 31 | 32 | ExodeThread(byte o[], void (*callback)(byte o[]) = NULL, unsigned long _interval = 0); 33 | 34 | // Associated operandes 35 | byte *op; 36 | void setOperande(byte o[]); 37 | 38 | int getId(); 39 | 40 | void onRun(void (*callback)(byte o[])); 41 | void run(); 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /src/utility/Thread.cpp: -------------------------------------------------------------------------------- 1 | #include "Thread.h" 2 | 3 | Thread::Thread(void (*callback)(void), unsigned long _interval){ 4 | enabled = true; 5 | onRun(callback); 6 | _cached_next_run = 0; 7 | last_run = 0; 8 | 9 | ThreadID = (int)this; 10 | #ifdef USE_THREAD_NAMES 11 | ThreadName = "Thread "; 12 | ThreadName = ThreadName + ThreadID; 13 | #endif 14 | 15 | setInterval(_interval); 16 | }; 17 | 18 | void Thread::runned(unsigned long time){ 19 | // Saves last_run 20 | last_run = time; 21 | 22 | // Cache next run 23 | _cached_next_run = last_run + interval; 24 | } 25 | 26 | void Thread::setInterval(unsigned long _interval){ 27 | // Save interval 28 | interval = _interval; 29 | 30 | // Cache the next run based on the last_run 31 | _cached_next_run = last_run + interval; 32 | } 33 | 34 | bool Thread::shouldRun(unsigned long time){ 35 | // If the "sign" bit is set the signed difference would be negative 36 | bool time_remaining = (time - _cached_next_run) & 0x80000000; 37 | 38 | // Exceeded the time limit, AND is enabled? Then should run... 39 | return !time_remaining && enabled; 40 | } 41 | 42 | void Thread::onRun(void (*callback)(void)){ 43 | _onRun = callback; 44 | } 45 | 46 | void Thread::run(){ 47 | if(_onRun != NULL) 48 | _onRun(); 49 | 50 | // Update last_run and _cached_next_run 51 | runned(); 52 | } 53 | -------------------------------------------------------------------------------- /src/utility/ThreadController.h: -------------------------------------------------------------------------------- 1 | /* 2 | ThreadController.h - Controlls a list of Threads with different timings 3 | 4 | Basicaly, what it does is to keep track of current Threads and run when 5 | necessary. 6 | 7 | ThreadController is an extended class of Thread, because of that, 8 | it allows you to add a ThreadController inside another ThreadController... 9 | 10 | For instructions, go to https://github.com/ivanseidel/ArduinoThread 11 | 12 | Created by Ivan Seidel Gomes, March, 2013. 13 | Released into the public domain. 14 | */ 15 | 16 | #ifndef ThreadController_h 17 | #define ThreadController_h 18 | 19 | #include "Thread.h" 20 | #include "inttypes.h" 21 | 22 | #define MAX_THREADS 15 23 | 24 | class ThreadController: public Thread{ 25 | protected: 26 | Thread* thread[MAX_THREADS]; 27 | int cached_size; 28 | public: 29 | ThreadController(unsigned long _interval = 0); 30 | 31 | // run() Method is overrided 32 | void run(); 33 | 34 | // Adds a thread in the first available slot (remove first) 35 | // Returns if the Thread could be added or not 36 | bool add(Thread* _thread); 37 | 38 | // remove the thread (given the Thread* or ThreadID) 39 | void remove(int _id); 40 | void remove(Thread* _thread); 41 | 42 | // Removes all threads 43 | void clear(); 44 | 45 | // Return the quantity of Threads 46 | int size(bool cached = true); 47 | 48 | // Return the I Thread on the array 49 | // Returns NULL if none found 50 | Thread* get(int index); 51 | }; 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /src/Exode.h: -------------------------------------------------------------------------------- 1 | /* 2 | Exode.h - 3 | 4 | ExodeArduinoCore is an interface between Arduino Board and 5 | an other devices (computer, Rasberry Pi, phone..). 6 | 7 | From theses devices you send instructions to the 8 | Arduino board, and Exode will interpret your 9 | instructions, and execute them on the board. 10 | 11 | Exode use a specific protocol, see the link below 12 | http://sne3ks.github.io/ExodeDoc/#how-it-works 13 | 14 | Created by Lenselle Nicolas, december, 2015 15 | APACHE License 2.0 16 | 17 | */ 18 | 19 | #ifndef Exode_h 20 | #define Exode_h 21 | 22 | #include "utility/ThreadController.h" 23 | #include "utility/ExodeThread.h" 24 | #include "InstructionSet.h" 25 | 26 | #if defined(ARDUINO) && ARDUINO >= 100 27 | #include 28 | #else 29 | #include 30 | #endif 31 | 32 | class Exode{ 33 | 34 | protected: 35 | 36 | byte len_input; // incomming instruction's length (byte array) 37 | int cursor_input; 38 | byte *_INPUT; // byte array to hold the current instruction 39 | 40 | // Multithread 41 | ThreadController* controller; 42 | Thread* listener; 43 | 44 | InstructionSet* instructionSet[10]; 45 | 46 | public: 47 | 48 | Exode(); 49 | 50 | void setup(); 51 | 52 | void listen(); 53 | void execute(byte *bytecode); 54 | 55 | void addInstructionSet(char id, InstructionSet* set); 56 | 57 | void sendUnsignedInt(byte key, int value); 58 | 59 | void addThread(ExodeThread *th); 60 | void addThread(Thread *th); 61 | 62 | void deleteThread(ExodeThread *th); 63 | void deleteThread(int id); 64 | 65 | 66 | void run(); 67 | }; 68 | 69 | #endif 70 | 71 | extern Exode _exode; 72 | -------------------------------------------------------------------------------- /src/Exode.cpp: -------------------------------------------------------------------------------- 1 | #include "Exode.h" 2 | 3 | Exode _exode= Exode(); 4 | void callback_listen(){ _exode.listen(); } 5 | 6 | Exode::Exode(){ 7 | len_input = 0; 8 | cursor_input = 0; 9 | 10 | // Initialisation of the multithreading 11 | controller = new ThreadController(); 12 | listener = new Thread(); 13 | listener->onRun(callback_listen); 14 | 15 | listener->setInterval(1); 16 | controller->add(listener); 17 | } 18 | 19 | void Exode::setup(){ 20 | Serial.begin(9600); 21 | } 22 | 23 | void Exode::execute(byte *_in){ 24 | //this->instSet->exec(_in[0], _in); 25 | instructionSet[_in[0]]->exec(_in[1], (_in+1)); 26 | } 27 | 28 | 29 | void Exode::listen(){ 30 | /* Read the input and execute the instruction 31 | * the first byte reading define the next instruction's 32 | * number of bytes. 33 | */ 34 | 35 | while ( Serial.available()>0 ){ 36 | byte b= Serial.read(); 37 | if(len_input == 0){ len_input = b; _INPUT = (byte*)malloc(len_input); } 38 | else{ 39 | _INPUT[cursor_input] = b; 40 | cursor_input++; 41 | } 42 | 43 | if(len_input != 0 && len_input == cursor_input){ 44 | cursor_input = 0; 45 | len_input = 0; 46 | execute(_INPUT); free(_INPUT); 47 | } 48 | 49 | } 50 | 51 | } 52 | 53 | 54 | void Exode::sendUnsignedInt(byte key, int value){ 55 | /* Each value send to the device is coded on 5 byte, 56 | We don't need a "stop" byte. 57 | */ 58 | // Id between 0 and 255 (1 byte ) 59 | Serial.write(key); 60 | unsigned long int n = value; 61 | 62 | unsigned char bytes[4]; 63 | bytes[0] = (n >> 24) & 0xFF; 64 | bytes[1] = (n >> 16) & 0xFF; 65 | bytes[2] = (n >> 8) & 0xFF; 66 | bytes[3] = n & 0xFF; 67 | 68 | Serial.write(bytes[3]); 69 | Serial.write(bytes[2]); 70 | Serial.write(bytes[1]); 71 | Serial.write(bytes[0]); 72 | 73 | } 74 | 75 | void Exode::run(){ 76 | controller->run(); 77 | } 78 | 79 | void Exode::addThread(ExodeThread *th){ 80 | controller->add(th); 81 | } 82 | 83 | void Exode::addThread(Thread *th){ 84 | controller->add(th); 85 | } 86 | 87 | void Exode::deleteThread(ExodeThread *th){ 88 | free(th->op); 89 | controller->remove(th); 90 | } 91 | 92 | void Exode::deleteThread(int id){ 93 | controller->remove(id); 94 | } 95 | 96 | void Exode::addInstructionSet(char id, InstructionSet* set){ 97 | instructionSet[id]= set; 98 | } 99 | -------------------------------------------------------------------------------- /src/utility/Thread.h: -------------------------------------------------------------------------------- 1 | /* 2 | Thread.h - An runnable object 3 | 4 | Thread is responsable for holding the "action" for something, 5 | also, it responds if it "should" or "should not" run, based on 6 | the current time; 7 | 8 | For instructions, go to https://github.com/ivanseidel/ArduinoThread 9 | 10 | Created by Ivan Seidel Gomes, March, 2013. 11 | Released into the public domain. 12 | */ 13 | 14 | #ifndef Thread_h 15 | #define Thread_h 16 | 17 | #if defined(ARDUINO) && ARDUINO >= 100 18 | #include 19 | #else 20 | #include 21 | #endif 22 | 23 | #include 24 | 25 | /* 26 | Uncomment this line to enable ThreadName Strings. 27 | 28 | It might be usefull if you are loging thread with Serial, 29 | or displaying a list of threads... 30 | */ 31 | // #define USE_THREAD_NAMES 1 32 | 33 | class Thread{ 34 | protected: 35 | // Desired interval between runs 36 | unsigned long interval; 37 | 38 | // Last runned time in Ms 39 | unsigned long last_run; 40 | 41 | // Scheduled run in Ms (MUST BE CACHED) 42 | unsigned long _cached_next_run; 43 | 44 | /* 45 | IMPORTANT! Run after all calls to run() 46 | Updates last_run and cache next run. 47 | NOTE: This MUST be called if extending 48 | this class and implementing run() method 49 | */ 50 | void runned(unsigned long time); 51 | 52 | // Default is to mark it runned "now" 53 | void runned() { runned(millis()); } 54 | 55 | // Callback for run() if not implemented 56 | void (*_onRun)(void); 57 | 58 | public: 59 | 60 | // If the current Thread is enabled or not 61 | bool enabled; 62 | 63 | // ID of the Thread (initialized from memory adr.) 64 | int ThreadID; 65 | 66 | #ifdef USE_THREAD_NAMES 67 | // Thread Name (used for better UI). 68 | String ThreadName; 69 | #endif 70 | 71 | Thread(void (*callback)(void) = NULL, unsigned long _interval = 0); 72 | 73 | // Set the desired interval for calls, and update _cached_next_run 74 | virtual void setInterval(unsigned long _interval); 75 | 76 | // Return if the Thread should be runned or not 77 | virtual bool shouldRun(unsigned long time); 78 | 79 | // Default is to check whether it should run "now" 80 | bool shouldRun() { return shouldRun(millis()); } 81 | 82 | // Callback set 83 | void onRun(void (*callback)(void)); 84 | 85 | // Runs Thread 86 | virtual void run(); 87 | }; 88 | 89 | #endif 90 | -------------------------------------------------------------------------------- /src/utility/ThreadController.cpp: -------------------------------------------------------------------------------- 1 | #include "Thread.h" 2 | #include "ThreadController.h" 3 | 4 | ThreadController::ThreadController(unsigned long _interval): Thread(){ 5 | cached_size = 0; 6 | 7 | clear(); 8 | setInterval(_interval); 9 | 10 | #ifdef USE_THREAD_NAMES 11 | // Overrides name 12 | ThreadName = "ThreadController "; 13 | ThreadName = ThreadName + ThreadID; 14 | #endif 15 | } 16 | 17 | /* 18 | ThreadController run() (cool stuf) 19 | */ 20 | void ThreadController::run(){ 21 | // Run this thread before 22 | if(_onRun != NULL) 23 | _onRun(); 24 | 25 | unsigned long time = millis(); 26 | int checks = 0; 27 | for(int i = 0; i < MAX_THREADS && checks <= cached_size; i++){ 28 | // Object exists? Is enabled? Timeout exceeded? 29 | if(thread[i]){ 30 | checks++; 31 | if(thread[i]->shouldRun(time)){ 32 | thread[i]->run(); 33 | } 34 | } 35 | } 36 | 37 | // ThreadController extends Thread, so we should flag as runned thread 38 | runned(); 39 | } 40 | 41 | 42 | /* 43 | List controller (boring part) 44 | */ 45 | bool ThreadController::add(Thread* _thread){ 46 | // Check if the Thread already exists on the array 47 | for(int i = 0; i < MAX_THREADS; i++){ 48 | if(thread[i] != NULL && thread[i]->ThreadID == _thread->ThreadID) 49 | return true; 50 | } 51 | 52 | // Find an empty slot 53 | for(int i = 0; i < MAX_THREADS; i++){ 54 | if(!thread[i]){ 55 | // Found a empty slot, now add Thread 56 | thread[i] = _thread; 57 | cached_size++; 58 | return true; 59 | } 60 | } 61 | 62 | // Array is full 63 | return false; 64 | } 65 | 66 | void ThreadController::remove(int id){ 67 | // Find Threads with the id, and removes 68 | bool found = false; 69 | for(int i = 0; i < MAX_THREADS; i++){ 70 | if(thread[i]->ThreadID == id){ 71 | thread[i] = NULL; 72 | cached_size--; 73 | return; 74 | } 75 | } 76 | } 77 | 78 | void ThreadController::remove(Thread* _thread){ 79 | remove(_thread->ThreadID); 80 | } 81 | 82 | void ThreadController::clear(){ 83 | for(int i = 0; i < MAX_THREADS; i++){ 84 | thread[i] = NULL; 85 | } 86 | cached_size = 0; 87 | } 88 | 89 | int ThreadController::size(bool cached){ 90 | if(cached) 91 | return cached_size; 92 | 93 | int size = 0; 94 | for(int i = 0; i < MAX_THREADS; i++){ 95 | if(thread[i]) 96 | size++; 97 | } 98 | cached_size = size; 99 | 100 | return cached_size; 101 | } 102 | 103 | Thread* ThreadController::get(int index){ 104 | int pos = -1; 105 | for(int i = 0; i < MAX_THREADS; i++){ 106 | if(thread[i] != NULL){ 107 | pos++; 108 | 109 | if(pos == index) 110 | return thread[i]; 111 | } 112 | } 113 | 114 | return NULL; 115 | } 116 | -------------------------------------------------------------------------------- /src/exode_set.h: -------------------------------------------------------------------------------- 1 | /* 2 | exode_instructions.h - 3 | 4 | Created by Lenselle Nicolas, december, 2015 5 | APACHE License 2.0 6 | */ 7 | #include "InstructionSet.h" 8 | #include "utility/Thread.h" 9 | 10 | #include "Servo.h" 11 | #define MAX_SERVO 12 12 | Servo* servo[MAX_SERVO]; 13 | 14 | #include "utility/AccelStepper.h" 15 | #define MAX_STEPPER 12 16 | AccelStepper* stepper[MAX_STEPPER]; 17 | 18 | /* 19 | * INSTRUCTION'S ID 20 | */ 21 | 22 | #define PINMODE 0 23 | 24 | #define DIGWRITE 1 25 | #define DIGREAD 2 26 | #define DIGSWITCH 3 27 | 28 | #define ANAWRITE 4 29 | #define ANAREAD 5 30 | 31 | #define ADDSERVO 6 32 | #define RMSERVO 7 33 | #define WRTSERVO 8 34 | 35 | #define PULSE 9 36 | #define PULSEIN 10 37 | 38 | #define EXCTHRD 11 39 | #define INITHRD 12 40 | #define DELTHRD 13 41 | 42 | #define CHKEXD 14 43 | 44 | #define ADDSTEP 15 45 | #define ACCSTEP 16 46 | #define SPDSTEP 17 47 | #define MOVSTEP 18 48 | 49 | /* 50 | * DEFINITIONS 51 | */ 52 | 53 | void _pinMode(byte o[]){ 54 | /* 55 | o[1]: pin 56 | o[2]: mode 57 | o[3]: isAnalogic 58 | */ 59 | 60 | if(o[3]==1) 61 | o[1]= analogInputToDigitalPin(o[1]); 62 | 63 | pinMode(o[1],o[2]); 64 | } 65 | 66 | 67 | 68 | void _digitalWrite(byte o[]){ 69 | /* 70 | o[1]: pin 71 | o[2]: level 72 | */ 73 | 74 | digitalWrite(o[1],o[2]); 75 | } 76 | 77 | 78 | 79 | void _digitalRead(byte o[]){ 80 | /* 81 | o[1]: pin 82 | o[2]: key 83 | */ 84 | 85 | int val = 0; 86 | if (digitalRead(o[1]) == HIGH) val = 1; 87 | _exode.sendUnsignedInt(o[2], val); 88 | } 89 | 90 | 91 | 92 | void _digitalSwitch(byte o[]){ 93 | /* 94 | o[1]: pin 95 | */ 96 | 97 | digitalWrite(o[1], digitalRead(o[1])^1 ); 98 | } 99 | 100 | 101 | 102 | void _analogWrite(byte o[]){ 103 | /* 104 | o[1]: pin 105 | o[2]: value 106 | */ 107 | 108 | analogWrite(o[1], o[2]); 109 | } 110 | 111 | 112 | 113 | void _analogRead(byte o[]){ 114 | /* 115 | o[1]: pin 116 | o[2]: key 117 | */ 118 | _exode.sendUnsignedInt(o[2], analogRead(analogInputToDigitalPin(o[1]))); 119 | } 120 | 121 | 122 | 123 | void _addServo(byte o[]){ 124 | /* 125 | o[1]: pin 126 | o[2]: key 127 | o[3]: us 128 | */ 129 | int us = *((unsigned long*)(o+3)); 130 | 131 | char id= 0; 132 | for(; id < MAX_SERVO; id++){ 133 | if( servo[id] == nullptr ){ 134 | servo[id]= new Servo(); 135 | servo[id]->attach(o[1]); 136 | servo[id]->writeMicroseconds(us); 137 | break; 138 | } 139 | } 140 | 141 | _exode.sendUnsignedInt(o[2], id); 142 | } 143 | 144 | 145 | 146 | 147 | void _removeServo(byte o[]){ 148 | /* 149 | o[1]: id 150 | */ 151 | servo[o[1]]->detach(); 152 | free(servo[o[1]]); 153 | servo[o[1]]= nullptr; 154 | } 155 | 156 | 157 | 158 | void _writeServo(byte o[]){ 159 | /* 160 | o[1]: id 161 | o[2]: us 162 | */ 163 | int us = *((unsigned long*)(o+2)); 164 | servo[o[1]]->writeMicroseconds(us); 165 | } 166 | 167 | 168 | 169 | void _pulse(byte o[]){ 170 | /* 171 | o[1]: pin 172 | o[2]: us 173 | */ 174 | int us= *((unsigned long*)(o+2)); 175 | digitalWrite(o[1], 1); 176 | delay(us); 177 | digitalWrite(o[1], 0); 178 | } 179 | 180 | 181 | 182 | 183 | void _pulseIn(byte o[]){ 184 | /* 185 | o[1]: pin 186 | o[2]: key 187 | */ 188 | _exode.sendUnsignedInt(o[2], pulseIn(o[1], 1)); 189 | } 190 | 191 | 192 | 193 | 194 | void _executeThread(byte o[]){ 195 | /* 196 | o[1]: bytecode len 197 | */ 198 | 199 | int stop_bit = o[1]+1; 200 | 201 | // place cursor on the first instruction 202 | for( int cursor= 2; cursor <= stop_bit;){ 203 | 204 | //cursor+1 the position of the function's id 205 | _exode.execute(o+(cursor+1)); 206 | 207 | //update the cursor position 208 | // curentPos + block lenght + 1 209 | cursor= cursor+o[cursor]+1; 210 | } 211 | 212 | } 213 | 214 | 215 | 216 | 217 | void _initThread(byte o[]){ 218 | /* 219 | o[1]: key 220 | o[2-5]: us (period) 221 | o[6]: len 222 | */ 223 | byte *op = (byte*)malloc(o[6]+1); 224 | int us = *((unsigned long*)(o+2)); 225 | ExodeThread *ex_th = new ExodeThread(op, &_executeThread, us); 226 | _exode.addThread(ex_th); 227 | _exode.sendUnsignedInt(o[1], ex_th->getId()); 228 | 229 | // i don't why, but i've to copy the op here... 230 | for(int i= 0; i <= o[6]; i++) op[1+i] = o[6+i]; 231 | 232 | } 233 | 234 | 235 | 236 | 237 | void _deleteThread(byte o[]){ 238 | /* 239 | o[1]: id 240 | */ 241 | _exode.deleteThread(*((unsigned long*)(o+1))); 242 | } 243 | 244 | 245 | 246 | 247 | void _checkExode(byte o[]){ 248 | _exode.sendUnsignedInt(202, 404); 249 | } 250 | 251 | 252 | 253 | void _addStepper(byte o[]){ 254 | /* 255 | o[1]: key 256 | o[2]: type (cf AccelStepper documentation) 257 | o[3]: pin1 258 | o[4]: pin2 259 | o[5]: pin3 260 | o[6]: pin4 261 | */ 262 | 263 | char id= 0; 264 | for(; id < MAX_STEPPER; id++){ 265 | if( stepper[id] == nullptr ){ 266 | stepper[id]= new AccelStepper(o[2], o[3], o[4], o[5], o[6]); 267 | stepper[id]->setAcceleration(50); 268 | stepper[id]->setMaxSpeed(100); 269 | break; 270 | } 271 | } 272 | 273 | _exode.sendUnsignedInt(o[1], id); 274 | } 275 | 276 | 277 | 278 | void _setStepperAcceleration(byte o[]){ 279 | /* 280 | o[1]: stepper id 281 | o[2]: acceleration (steps.s-2) 282 | */ 283 | float acc = (*((float *)(o+2))); 284 | stepper[o[1]]->setAcceleration(acc); 285 | } 286 | 287 | 288 | void _setStepperSpeed(byte o[]){ 289 | /* 290 | o[1]: stepper id 291 | o[2]: speed * 100 (steps.s-1) 292 | */ 293 | float speed = (*((float *)(o+2))); 294 | stepper[o[1]]->setMaxSpeed(speed); 295 | } 296 | 297 | 298 | 299 | void _moveStepper(byte o[]){ 300 | /* 301 | o[1]: stepper id 302 | o[2]: relative (signed long) 303 | */ 304 | long relative = (*((long*)(o+2))); 305 | stepper[o[1]]->moveTo(relative); 306 | } 307 | 308 | 309 | 310 | 311 | 312 | /* 313 | * CONTROLLER 314 | */ 315 | 316 | void stepper_controller(){ 317 | for(char id=0; id < MAX_STEPPER; id++) 318 | if (stepper[id] != NULL) 319 | stepper[id]->run(); 320 | } 321 | 322 | 323 | 324 | 325 | 326 | /* 327 | * LOADER 328 | */ 329 | 330 | void load_exode_instructions(char id){ 331 | 332 | InstructionSet* exode_inst= new InstructionSet(19); 333 | 334 | exode_inst->set(PINMODE, &_pinMode); 335 | exode_inst->set(DIGWRITE, &_digitalWrite); 336 | exode_inst->set(DIGREAD, &_digitalRead); 337 | exode_inst->set(DIGSWITCH, &_digitalSwitch); 338 | exode_inst->set(ANAWRITE, &_analogWrite); 339 | exode_inst->set(ANAREAD, &_analogRead); 340 | exode_inst->set(ADDSERVO, &_addServo); 341 | exode_inst->set(RMSERVO, &_removeServo); 342 | exode_inst->set(WRTSERVO, &_writeServo); 343 | exode_inst->set(PULSE, &_pulse); 344 | exode_inst->set(PULSEIN, &_pulseIn); 345 | exode_inst->set(EXCTHRD, &_executeThread); 346 | exode_inst->set(INITHRD, &_initThread); 347 | exode_inst->set(DELTHRD, &_deleteThread); 348 | exode_inst->set(CHKEXD, &_checkExode); 349 | exode_inst->set(ADDSTEP, &_addStepper); 350 | exode_inst->set(ACCSTEP, &_setStepperAcceleration); 351 | exode_inst->set(SPDSTEP, &_setStepperSpeed); 352 | exode_inst->set(MOVSTEP, &_moveStepper); 353 | 354 | _exode.addInstructionSet(id, exode_inst); 355 | 356 | Thread* stepper_thread= new Thread(); 357 | stepper_thread->setInterval(1); 358 | stepper_thread->onRun(stepper_controller); 359 | 360 | _exode.addThread(stepper_thread); 361 | 362 | } 363 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {2016} {Lenselle Nicolas} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/utility/AccelStepper.cpp: -------------------------------------------------------------------------------- 1 | // AccelStepper.cpp 2 | // 3 | // Copyright (C) 2009 Mike McCauley 4 | // $Id: AccelStepper.cpp,v 1.14 2012/12/22 21:41:22 mikem Exp mikem $ 5 | 6 | #include "AccelStepper.h" 7 | 8 | #if 0 9 | // Some debugging assistance 10 | void dump(uint8_t* p, int l) 11 | { 12 | int i; 13 | 14 | for (i = 0; i < l; i++) 15 | { 16 | Serial.print(p[i], HEX); 17 | Serial.print(" "); 18 | } 19 | Serial.println(""); 20 | } 21 | #endif 22 | 23 | void AccelStepper::moveTo(long absolute) 24 | { 25 | if (_targetPos != absolute) 26 | { 27 | _targetPos = absolute; 28 | computeNewSpeed(); 29 | // compute new n? 30 | } 31 | } 32 | 33 | void AccelStepper::move(long relative) 34 | { 35 | moveTo(_currentPos + relative); 36 | } 37 | 38 | // Implements steps according to the current step interval 39 | // You must call this at least once per step 40 | // returns true if a step occurred 41 | boolean AccelStepper::runSpeed() 42 | { 43 | // Dont do anything unless we actually have a step interval 44 | if (!_stepInterval) 45 | return false; 46 | 47 | unsigned long time = micros(); 48 | // Gymnastics to detect wrapping of either the nextStepTime and/or the current time 49 | unsigned long nextStepTime = _lastStepTime + _stepInterval; 50 | if ( ((nextStepTime >= _lastStepTime) && ((time >= nextStepTime) || (time < _lastStepTime))) 51 | || ((nextStepTime < _lastStepTime) && ((time >= nextStepTime) && (time < _lastStepTime)))) 52 | 53 | { 54 | if (_direction == DIRECTION_CW) 55 | { 56 | // Clockwise 57 | _currentPos += 1; 58 | } 59 | else 60 | { 61 | // Anticlockwise 62 | _currentPos -= 1; 63 | } 64 | step(_currentPos & 0x7); // Bottom 3 bits (same as mod 8, but works with + and - numbers) 65 | 66 | _lastStepTime = time; 67 | return true; 68 | } 69 | else 70 | { 71 | return false; 72 | } 73 | } 74 | 75 | long AccelStepper::distanceToGo() 76 | { 77 | return _targetPos - _currentPos; 78 | } 79 | 80 | long AccelStepper::targetPosition() 81 | { 82 | return _targetPos; 83 | } 84 | 85 | long AccelStepper::currentPosition() 86 | { 87 | return _currentPos; 88 | } 89 | 90 | // Useful during initialisations or after initial positioning 91 | // Sets speed to 0 92 | void AccelStepper::setCurrentPosition(long position) 93 | { 94 | _targetPos = _currentPos = position; 95 | _n = 0; 96 | _stepInterval = 0; 97 | } 98 | 99 | void AccelStepper::computeNewSpeed() 100 | { 101 | long distanceTo = distanceToGo(); // +ve is clockwise from curent location 102 | 103 | long stepsToStop = (long)((_speed * _speed) / (2.0 * _acceleration)); // Equation 16 104 | 105 | if (distanceTo == 0 && stepsToStop <= 1) 106 | { 107 | // We are at the target and its time to stop 108 | _stepInterval = 0; 109 | _speed = 0.0; 110 | _n = 0; 111 | return; 112 | } 113 | 114 | if (distanceTo > 0) 115 | { 116 | // We are anticlockwise from the target 117 | // Need to go clockwise from here, maybe decelerate now 118 | if (_n > 0) 119 | { 120 | // Currently accelerating, need to decel now? Or maybe going the wrong way? 121 | if ((stepsToStop >= distanceTo) || _direction == DIRECTION_CCW) 122 | _n = -stepsToStop; // Start deceleration 123 | } 124 | else if (_n < 0) 125 | { 126 | // Currently decelerating, need to accel again? 127 | if ((stepsToStop < distanceTo) && _direction == DIRECTION_CW) 128 | _n = -_n; // Start accceleration 129 | } 130 | } 131 | else if (distanceTo < 0) 132 | { 133 | // We are clockwise from the target 134 | // Need to go anticlockwise from here, maybe decelerate 135 | if (_n > 0) 136 | { 137 | // Currently accelerating, need to decel now? Or maybe going the wrong way? 138 | if ((stepsToStop >= -distanceTo) || _direction == DIRECTION_CW) 139 | _n = -stepsToStop; // Start deceleration 140 | } 141 | else if (_n < 0) 142 | { 143 | // Currently decelerating, need to accel again? 144 | if ((stepsToStop < -distanceTo) && _direction == DIRECTION_CCW) 145 | _n = -_n; // Start accceleration 146 | } 147 | } 148 | 149 | // Need to accelerate or decelerate 150 | if (_n == 0) 151 | { 152 | // First step from stopped 153 | _cn = _c0; 154 | _direction = (distanceTo > 0) ? DIRECTION_CW : DIRECTION_CCW; 155 | } 156 | else 157 | { 158 | // Subsequent step. Works for accel (n is +_ve) and decel (n is -ve). 159 | _cn = _cn - ((2.0 * _cn) / ((4.0 * _n) + 1)); // Equation 13 160 | _cn = max(_cn, _cmin); 161 | } 162 | _n++; 163 | _stepInterval = _cn; 164 | _speed = 1000000.0 / _cn; 165 | if (_direction == DIRECTION_CCW) 166 | _speed = -_speed; 167 | 168 | #if 0 169 | Serial.println(_speed); 170 | Serial.println(_acceleration); 171 | Serial.println(_cn); 172 | Serial.println(_c0); 173 | Serial.println(_n); 174 | Serial.println(_stepInterval); 175 | Serial.println(distanceTo); 176 | Serial.println(stepsToStop); 177 | Serial.println("-----"); 178 | #endif 179 | } 180 | 181 | // Run the motor to implement speed and acceleration in order to proceed to the target position 182 | // You must call this at least once per step, preferably in your main loop 183 | // If the motor is in the desired position, the cost is very small 184 | // returns true if we are still running to position 185 | boolean AccelStepper::run() 186 | { 187 | if (runSpeed()) 188 | computeNewSpeed(); 189 | return true; 190 | } 191 | 192 | AccelStepper::AccelStepper(uint8_t interface, uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4) 193 | { 194 | _interface = interface; 195 | _currentPos = 0; 196 | _targetPos = 0; 197 | _speed = 0.0; 198 | _maxSpeed = 1.0; 199 | _acceleration = 1.0; 200 | _sqrt_twoa = 1.0; 201 | _stepInterval = 0; 202 | _minPulseWidth = 1; 203 | _enablePin = 0xff; 204 | _lastStepTime = 0; 205 | _pin[0] = pin1; 206 | _pin[1] = pin2; 207 | _pin[2] = pin3; 208 | _pin[3] = pin4; 209 | 210 | // NEW 211 | _n = 0; 212 | _c0 = 0.0; 213 | _cn = 0.0; 214 | _cmin = 1.0; 215 | _direction = DIRECTION_CCW; 216 | 217 | int i; 218 | for (i = 0; i < 4; i++) 219 | _pinInverted[i] = 0; 220 | enableOutputs(); 221 | } 222 | 223 | AccelStepper::AccelStepper(void (*forward)(), void (*backward)()) 224 | { 225 | _interface = 0; 226 | _currentPos = 0; 227 | _targetPos = 0; 228 | _speed = 0.0; 229 | _maxSpeed = 1.0; 230 | _acceleration = 1.0; 231 | _sqrt_twoa = 1.0; 232 | _stepInterval = 0; 233 | _minPulseWidth = 1; 234 | _enablePin = 0xff; 235 | _lastStepTime = 0; 236 | _pin[0] = 0; 237 | _pin[1] = 0; 238 | _pin[2] = 0; 239 | _pin[3] = 0; 240 | _forward = forward; 241 | _backward = backward; 242 | 243 | // NEW 244 | _n = 0; 245 | _c0 = 0.0; 246 | _cn = 0.0; 247 | _cmin = 1.0; 248 | _direction = DIRECTION_CCW; 249 | 250 | int i; 251 | for (i = 0; i < 4; i++) 252 | _pinInverted[i] = 0; 253 | } 254 | 255 | void AccelStepper::setMaxSpeed(float speed) 256 | { 257 | if (_maxSpeed != speed) 258 | { 259 | _maxSpeed = speed; 260 | _cmin = 1000000.0 / speed; 261 | // Recompute _n from current speed and adjust speed if accelerating or cruising 262 | if (_n > 0) 263 | { 264 | _n = (long)((_speed * _speed) / (2.0 * _acceleration)); // Equation 16 265 | computeNewSpeed(); 266 | } 267 | } 268 | } 269 | 270 | void AccelStepper::setAcceleration(float acceleration) 271 | { 272 | if (acceleration == 0.0) 273 | return; 274 | if (_acceleration != acceleration) 275 | { 276 | // Recompute _n per Equation 17 277 | _n = _n * (_acceleration / acceleration); 278 | // New c0 per Equation 7 279 | _c0 = sqrt(2.0 / acceleration) * 1000000.0; 280 | _acceleration = acceleration; 281 | computeNewSpeed(); 282 | } 283 | } 284 | 285 | void AccelStepper::setSpeed(float speed) 286 | { 287 | if (speed == _speed) 288 | return; 289 | speed = constrain(speed, -_maxSpeed, _maxSpeed); 290 | if (speed == 0.0) 291 | _stepInterval = 0; 292 | else 293 | { 294 | _stepInterval = fabs(1000000.0 / speed); 295 | _direction = (speed > 0.0) ? DIRECTION_CW : DIRECTION_CCW; 296 | } 297 | _speed = speed; 298 | } 299 | 300 | float AccelStepper::speed() 301 | { 302 | return _speed; 303 | } 304 | 305 | // Subclasses can override 306 | void AccelStepper::step(uint8_t step) 307 | { 308 | switch (_interface) 309 | { 310 | case FUNCTION: 311 | step0(step); 312 | break; 313 | 314 | case DRIVER: 315 | step1(step); 316 | break; 317 | 318 | case FULL2WIRE: 319 | step2(step); 320 | break; 321 | 322 | case FULL3WIRE: 323 | step3(step); 324 | break; 325 | 326 | case FULL4WIRE: 327 | step4(step); 328 | break; 329 | 330 | case HALF3WIRE: 331 | step6(step); 332 | break; 333 | 334 | case HALF4WIRE: 335 | step8(step); 336 | break; 337 | } 338 | } 339 | 340 | // You might want to override this to implement eg serial output 341 | // bit 0 of the mask corresponds to _pin[0] 342 | // bit 1 of the mask corresponds to _pin[1] 343 | // .... 344 | void AccelStepper::setOutputPins(uint8_t mask) 345 | { 346 | uint8_t numpins = 2; 347 | if (_interface == FULL4WIRE || _interface == HALF4WIRE) 348 | numpins = 4; 349 | uint8_t i; 350 | for (i = 0; i < numpins; i++) 351 | digitalWrite(_pin[i], (mask & (1 << i)) ? (HIGH ^ _pinInverted[i]) : (LOW ^ _pinInverted[i])); 352 | } 353 | 354 | // 0 pin step function (ie for functional usage) 355 | void AccelStepper::step0(uint8_t step) 356 | { 357 | if (_speed > 0) 358 | _forward(); 359 | else 360 | _backward(); 361 | } 362 | 363 | // 1 pin step function (ie for stepper drivers) 364 | // This is passed the current step number (0 to 7) 365 | // Subclasses can override 366 | void AccelStepper::step1(uint8_t step) 367 | { 368 | // _pin[0] is step, _pin[1] is direction 369 | setOutputPins(_direction ? 0b11 : 0b01); // step HIGH 370 | // Caution 200ns setup time 371 | // Delay the minimum allowed pulse width 372 | delayMicroseconds(_minPulseWidth); 373 | setOutputPins(_direction ? 0b10 : 0b00); // step LOW 374 | 375 | } 376 | 377 | // 2 pin step function 378 | // This is passed the current step number (0 to 7) 379 | // Subclasses can override 380 | void AccelStepper::step2(uint8_t step) 381 | { 382 | switch (step & 0x3) 383 | { 384 | case 0: /* 01 */ 385 | setOutputPins(0b10); 386 | break; 387 | 388 | case 1: /* 11 */ 389 | setOutputPins(0b11); 390 | break; 391 | 392 | case 2: /* 10 */ 393 | setOutputPins(0b01); 394 | break; 395 | 396 | case 3: /* 00 */ 397 | setOutputPins(0b00); 398 | break; 399 | } 400 | } 401 | // 3 pin step function 402 | // This is passed the current step number (0 to 7) 403 | // Subclasses can override 404 | void AccelStepper::step3(uint8_t step) 405 | { 406 | switch (step % 3) 407 | { 408 | case 0: // 100 409 | setOutputPins(0b100); 410 | break; 411 | 412 | case 1: // 001 413 | setOutputPins(0b001); 414 | break; 415 | 416 | case 2: //010 417 | setOutputPins(0b010); 418 | break; 419 | 420 | } 421 | } 422 | 423 | // 4 pin step function for half stepper 424 | // This is passed the current step number (0 to 7) 425 | // Subclasses can override 426 | void AccelStepper::step4(uint8_t step) 427 | { 428 | switch (step & 0x3) 429 | { 430 | case 0: // 1010 431 | setOutputPins(0b0101); 432 | break; 433 | 434 | case 1: // 0110 435 | setOutputPins(0b0110); 436 | break; 437 | 438 | case 2: //0101 439 | setOutputPins(0b1010); 440 | break; 441 | 442 | case 3: //1001 443 | setOutputPins(0b1001); 444 | break; 445 | } 446 | } 447 | 448 | // 3 pin step function 449 | // This is passed the current step number (0 to 7) 450 | // Subclasses can override 451 | void AccelStepper::step6(uint8_t step) 452 | { 453 | switch (step % 6) 454 | { 455 | case 0: // 100 456 | setOutputPins(0b100); 457 | break; 458 | 459 | case 1: // 101 460 | setOutputPins(0b101); 461 | break; 462 | 463 | case 2: // 001 464 | setOutputPins(0b001); 465 | break; 466 | 467 | case 3: // 011 468 | setOutputPins(0b011); 469 | break; 470 | 471 | case 4: // 010 472 | setOutputPins(0b010); 473 | break; 474 | 475 | case 5: //011 476 | setOutputPins(0b110); 477 | break; 478 | 479 | } 480 | } 481 | 482 | // 4 pin step function 483 | // This is passed the current step number (0 to 7) 484 | // Subclasses can override 485 | void AccelStepper::step8(uint8_t step) 486 | { 487 | switch (step & 0x7) 488 | { 489 | case 0: // 1000 490 | setOutputPins(0b0001); 491 | break; 492 | 493 | case 1: // 1010 494 | setOutputPins(0b0101); 495 | break; 496 | 497 | case 2: // 0010 498 | setOutputPins(0b0100); 499 | break; 500 | 501 | case 3: // 0110 502 | setOutputPins(0b0110); 503 | break; 504 | 505 | case 4: // 0100 506 | setOutputPins(0b0010); 507 | break; 508 | 509 | case 5: //0101 510 | setOutputPins(0b1010); 511 | break; 512 | 513 | case 6: // 0001 514 | setOutputPins(0b1000); 515 | break; 516 | 517 | case 7: //1001 518 | setOutputPins(0b1001); 519 | break; 520 | } 521 | } 522 | 523 | // Prevents power consumption on the outputs 524 | void AccelStepper::disableOutputs() 525 | { 526 | if (! _interface) return; 527 | 528 | setOutputPins(0); // Handles inversion automatically 529 | if (_enablePin != 0xff) 530 | digitalWrite(_enablePin, LOW ^ _enableInverted); 531 | } 532 | 533 | void AccelStepper::enableOutputs() 534 | { 535 | if (! _interface) 536 | return; 537 | 538 | pinMode(_pin[0], OUTPUT); 539 | pinMode(_pin[1], OUTPUT); 540 | if (_interface == FULL4WIRE || _interface == HALF4WIRE) 541 | { 542 | pinMode(_pin[2], OUTPUT); 543 | pinMode(_pin[3], OUTPUT); 544 | } 545 | 546 | if (_enablePin != 0xff) 547 | { 548 | digitalWrite(_enablePin, HIGH ^ _enableInverted); 549 | pinMode(_enablePin, OUTPUT); 550 | } 551 | } 552 | 553 | void AccelStepper::setMinPulseWidth(unsigned int minWidth) 554 | { 555 | _minPulseWidth = minWidth; 556 | } 557 | 558 | void AccelStepper::setEnablePin(uint8_t enablePin) 559 | { 560 | _enablePin = enablePin; 561 | 562 | // This happens after construction, so init pin now. 563 | if (_enablePin != 0xff) 564 | { 565 | digitalWrite(_enablePin, HIGH ^ _enableInverted); 566 | pinMode(_enablePin, OUTPUT); 567 | } 568 | } 569 | 570 | void AccelStepper::setPinsInverted(bool direction, bool step, bool enable) 571 | { 572 | _pinInverted[0] = step; 573 | _pinInverted[1] = direction; 574 | _enableInverted = enable; 575 | } 576 | 577 | 578 | // Blocks until the target position is reached and stopped 579 | void AccelStepper::runToPosition() 580 | { 581 | while (_speed != 0 || distanceToGo() != 0) 582 | run(); 583 | } 584 | 585 | boolean AccelStepper::runSpeedToPosition() 586 | { 587 | if (_targetPos == _currentPos) 588 | return false; 589 | if (_targetPos >_currentPos) 590 | _direction = DIRECTION_CW; 591 | else 592 | _direction = DIRECTION_CCW; 593 | return runSpeed(); 594 | } 595 | 596 | // Blocks until the new target position is reached 597 | void AccelStepper::runToNewPosition(long position) 598 | { 599 | moveTo(position); 600 | runToPosition(); 601 | } 602 | 603 | void AccelStepper::stop() 604 | { 605 | if (_speed != 0.0) 606 | { 607 | long stepsToStop = (long)((_speed * _speed) / (2.0 * _acceleration)) + 1; // Equation 16 (+integer rounding) 608 | if (_speed > 0) 609 | move(stepsToStop); 610 | else 611 | move(-stepsToStop); 612 | } 613 | } 614 | -------------------------------------------------------------------------------- /src/utility/AccelStepper.h: -------------------------------------------------------------------------------- 1 | // AccelStepper.h 2 | // 3 | /// \mainpage AccelStepper library for Arduino 4 | /// 5 | /// This is the Arduino AccelStepper library. 6 | /// It provides an object-oriented interface for 2 or 4 pin stepper motors. 7 | /// 8 | /// The standard Arduino IDE includes the Stepper library 9 | /// (http://arduino.cc/en/Reference/Stepper) for stepper motors. It is 10 | /// perfectly adequate for simple, single motor applications. 11 | /// 12 | /// AccelStepper significantly improves on the standard Arduino Stepper library in several ways: 13 | /// \li Supports acceleration and deceleration 14 | /// \li Supports multiple simultaneous steppers, with independent concurrent stepping on each stepper 15 | /// \li API functions never delay() or block 16 | /// \li Supports 2, 3 and 4 wire steppers, plus 3 and 4 wire half steppers. 17 | /// \li Supports alternate stepping functions to enable support of AFMotor (https://github.com/adafruit/Adafruit-Motor-Shield-library) 18 | /// \li Supports stepper drivers such as the Sparkfun EasyDriver (based on 3967 driver chip) 19 | /// \li Very slow speeds are supported 20 | /// \li Extensive API 21 | /// \li Subclass support 22 | /// 23 | /// The latest version of this documentation can be downloaded from 24 | /// http://www.open.com.au/mikem/arduino/AccelStepper 25 | /// 26 | /// Example Arduino programs are included to show the main modes of use. 27 | /// 28 | /// The version of the package that this documentation refers to can be downloaded 29 | /// from http://www.open.com.au/mikem/arduino/AccelStepper/AccelStepper-1.30.zip 30 | /// You can find the latest version at http://www.open.com.au/mikem/arduino/AccelStepper 31 | /// 32 | /// You can also find online help and discussion at http://groups.google.com/group/accelstepper 33 | /// Please use that group for all questions and discussions on this topic. 34 | /// Do not contact the author directly, unless it is to discuss commercial licensing. 35 | /// 36 | /// Tested on Arduino Diecimila and Mega with arduino-0018 & arduino-0021 37 | /// on OpenSuSE 11.1 and avr-libc-1.6.1-1.15, 38 | /// cross-avr-binutils-2.19-9.1, cross-avr-gcc-4.1.3_20080612-26.5. 39 | /// 40 | /// \par Installation 41 | /// Install in the usual way: unzip the distribution zip file to the libraries 42 | /// sub-folder of your sketchbook. 43 | /// 44 | /// This software is Copyright (C) 2010 Mike McCauley. Use is subject to license 45 | /// conditions. The main licensing options available are GPL V2 or Commercial: 46 | /// 47 | /// \par Theory 48 | /// This code uses speed calculations as described in 49 | /// "Generate stepper-motor speed profiles in real time" by David Austin 50 | /// http://fab.cba.mit.edu/classes/MIT/961.09/projects/i0/Stepper_Motor_Speed_Profile.pdf 51 | /// with the exception that AccelStepper uses steps per second rather than radians per second 52 | /// (because we dont know the step angle of the motor) 53 | /// An initial step interval is calculated for the first step, based on the desired acceleration 54 | /// Subsequent shorter step intervals are calculated based 55 | /// on the previous step until max speed is acheived. 56 | /// 57 | /// \par Open Source Licensing GPL V2 58 | /// This is the appropriate option if you want to share the source code of your 59 | /// application with everyone you distribute it to, and you also want to give them 60 | /// the right to share who uses it. If you wish to use this software under Open 61 | /// Source Licensing, you must contribute all your source code to the open source 62 | /// community in accordance with the GPL Version 2 when your application is 63 | /// distributed. See http://www.gnu.org/copyleft/gpl.html 64 | /// 65 | /// \par Commercial Licensing 66 | /// This is the appropriate option if you are creating proprietary applications 67 | /// and you are not prepared to distribute and share the source code of your 68 | /// application. Contact info@open.com.au for details. 69 | /// 70 | /// \par Revision History 71 | /// \version 1.0 Initial release 72 | /// 73 | /// \version 1.1 Added speed() function to get the current speed. 74 | /// \version 1.2 Added runSpeedToPosition() submitted by Gunnar Arndt. 75 | /// \version 1.3 Added support for stepper drivers (ie with Step and Direction inputs) with _pins == 1 76 | /// \version 1.4 Added functional contructor to support AFMotor, contributed by Limor, with example sketches. 77 | /// \version 1.5 Improvements contributed by Peter Mousley: Use of microsecond steps and other speed improvements 78 | /// to increase max stepping speed to about 4kHz. New option for user to set the min allowed pulse width. 79 | /// Added checks for already running at max speed and skip further calcs if so. 80 | /// \version 1.6 Fixed a problem with wrapping of microsecond stepping that could cause stepping to hang. 81 | /// Reported by Sandy Noble. 82 | /// Removed redundant _lastRunTime member. 83 | /// \version 1.7 Fixed a bug where setCurrentPosition() did not always work as expected. 84 | /// Reported by Peter Linhart. 85 | /// \version 1.8 Added support for 4 pin half-steppers, requested by Harvey Moon 86 | /// \version 1.9 setCurrentPosition() now also sets motor speed to 0. 87 | /// \version 1.10 Builds on Arduino 1.0 88 | /// \version 1.11 Improvments from Michael Ellison: 89 | /// Added optional enable line support for stepper drivers 90 | /// Added inversion for step/direction/enable lines for stepper drivers 91 | /// \version 1.12 Announce Google Group 92 | /// \version 1.13 Improvements to speed calculation. Cost of calculation is now less in the worst case, 93 | /// and more or less constant in all cases. This should result in slightly beter high speed performance, and 94 | /// reduce anomalous speed glitches when other steppers are accelerating. 95 | /// However, its hard to see how to replace the sqrt() required at the very first step from 0 speed. 96 | /// \version 1.14 Fixed a problem with compiling under arduino 0021 reported by EmbeddedMan 97 | /// \version 1.15 Fixed a problem with runSpeedToPosition which did not correctly handle 98 | /// running backwards to a smaller target position. Added examples 99 | /// \version 1.16 Fixed some cases in the code where abs() was used instead of fabs(). 100 | /// \version 1.17 Added example ProportionalControl 101 | /// \version 1.18 Fixed a problem: If one calls the funcion runSpeed() when Speed is zero, it makes steps 102 | /// without counting. reported by Friedrich, Klappenbach. 103 | /// \version 1.19 Added MotorInterfaceType and symbolic names for the number of pins to use 104 | /// for the motor interface. Updated examples to suit. 105 | /// Replaced individual pin assignment variables _pin1, _pin2 etc with array _pin[4]. 106 | /// _pins member changed to _interface. 107 | /// Added _pinInverted array to simplify pin inversion operations. 108 | /// Added new function setOutputPins() which sets the motor output pins. 109 | /// It can be overridden in order to provide, say, serial output instead of parallel output 110 | /// Some refactoring and code size reduction. 111 | /// \version 1.20 Improved documentation and examples to show need for correctly 112 | /// specifying AccelStepper::FULL4WIRE and friends. 113 | /// \version 1.21 Fixed a problem where desiredSpeed could compute the wrong step acceleration 114 | /// when _speed was small but non-zero. Reported by Brian Schmalz. 115 | /// Precompute sqrt_twoa to improve performance and max possible stepping speed 116 | /// \version 1.22 Added Bounce.pde example 117 | /// Fixed a problem where calling moveTo(), setMaxSpeed(), setAcceleration() more 118 | /// frequently than the step time, even 119 | /// with the same values, would interfere with speed calcs. Now a new speed is computed 120 | /// only if there was a change in the set value. Reported by Brian Schmalz. 121 | /// \version 1.23 Rewrite of the speed algorithms in line with 122 | /// http://fab.cba.mit.edu/classes/MIT/961.09/projects/i0/Stepper_Motor_Speed_Profile.pdf 123 | /// Now expect smoother and more linear accelerations and decelerations. The desiredSpeed() 124 | /// function was removed. 125 | /// \version 1.24 Fixed a problem introduced in 1.23: with runToPosition, which did never returned 126 | /// \version 1.25 Now ignore attempts to set acceleration to 0.0 127 | /// \version 1.26 Fixed a problem where certina combinations of speed and accelration could cause 128 | /// oscillation about the target position. 129 | /// \version 1.27 Added stop() function to stop as fast as possible with current acceleration parameters. 130 | /// Also added new Quickstop example showing its use. 131 | /// \version 1.28 Fixed another problem where certain combinations of speed and accelration could cause 132 | /// oscillation about the target position. 133 | /// Added support for 3 wire full and half steppers such as Hard Disk Drive spindle. 134 | /// Contributed by Yuri Ivatchkovitch. 135 | /// \version 1.29 Fixed a problem that could cause a DRIVER stepper to continually step 136 | /// with some sketches. Reported by Vadim. 137 | /// \version 1.30 Fixed a problem that could cause stepper to back up a few steps at the end of 138 | /// accelerated travel with certain speeds. Reported and patched by jolo. 139 | /// 140 | /// \author Mike McCauley (mikem@open.com.au) DO NOT CONTACT THE AUTHOR DIRECTLY: USE THE LISTS 141 | // Copyright (C) 2009-2012 Mike McCauley 142 | // $Id: AccelStepper.h,v 1.15 2012/12/22 21:41:22 mikem Exp mikem $ 143 | 144 | #ifndef AccelStepper_h 145 | #define AccelStepper_h 146 | 147 | #include 148 | #if ARDUINO >= 100 149 | #include 150 | #else 151 | #include 152 | #include 153 | #endif 154 | 155 | // These defs cause trouble on some versions of Arduino 156 | #undef round 157 | 158 | ///////////////////////////////////////////////////////////////////// 159 | /// \class AccelStepper AccelStepper.h 160 | /// \brief Support for stepper motors with acceleration etc. 161 | /// 162 | /// This defines a single 2 or 4 pin stepper motor, or stepper moter with fdriver chip, with optional 163 | /// acceleration, deceleration, absolute positioning commands etc. Multiple 164 | /// simultaneous steppers are supported, all moving 165 | /// at different speeds and accelerations. 166 | /// 167 | /// \par Operation 168 | /// This module operates by computing a step time in microseconds. The step 169 | /// time is recomputed after each step and after speed and acceleration 170 | /// parameters are changed by the caller. The time of each step is recorded in 171 | /// microseconds. The run() function steps the motor if a new step is due. 172 | /// The run() function must be called frequently until the motor is in the 173 | /// desired position, after which time run() will do nothing. 174 | /// 175 | /// \par Positioning 176 | /// Positions are specified by a signed long integer. At 177 | /// construction time, the current position of the motor is consider to be 0. Positive 178 | /// positions are clockwise from the initial position; negative positions are 179 | /// anticlockwise. The curent position can be altered for instance after 180 | /// initialization positioning. 181 | /// 182 | /// \par Caveats 183 | /// This is an open loop controller: If the motor stalls or is oversped, 184 | /// AccelStepper will not have a correct 185 | /// idea of where the motor really is (since there is no feedback of the motor's 186 | /// real position. We only know where we _think_ it is, relative to the 187 | /// initial starting point). 188 | /// 189 | /// \par Performance 190 | /// The fastest motor speed that can be reliably supported is about 4000 steps per 191 | /// second at a clock frequency of 16 MHz on Arduino such as Uno etc. 192 | /// Faster processors can support faster stepping speeds. 193 | /// However, any speed less than that 194 | /// down to very slow speeds (much less than one per second) are also supported, 195 | /// provided the run() function is called frequently enough to step the motor 196 | /// whenever required for the speed set. 197 | /// Calling setAcceleration() is expensive, 198 | /// since it requires a square root to be calculated. 199 | class AccelStepper 200 | { 201 | public: 202 | /// \brief Symbolic names for number of pins. 203 | /// Use this in the pins argument the AccelStepper constructor to 204 | /// provide a symbolic name for the number of pins 205 | /// to use. 206 | typedef enum 207 | { 208 | FUNCTION = 0, ///< Use the functional interface, implementing your own driver functions (internal use only) 209 | DRIVER = 1, ///< Stepper Driver, 2 driver pins required 210 | FULL2WIRE = 2, ///< 2 wire stepper, 2 motor pins required 211 | FULL3WIRE = 3, ///< 3 wire stepper, such as HDD spindle, 3 motor pins required 212 | FULL4WIRE = 4, ///< 4 wire full stepper, 4 motor pins required 213 | HALF3WIRE = 6, ///< 3 wire half stepper, such as HDD spindle, 3 motor pins required 214 | HALF4WIRE = 8 ///< 4 wire half stepper, 4 motor pins required 215 | } MotorInterfaceType; 216 | 217 | /// Constructor. You can have multiple simultaneous steppers, all moving 218 | /// at different speeds and accelerations, provided you call their run() 219 | /// functions at frequent enough intervals. Current Position is set to 0, target 220 | /// position is set to 0. MaxSpeed and Acceleration default to 1.0. 221 | /// The motor pins will be initialised to OUTPUT mode during the 222 | /// constructor by a call to enableOutputs(). 223 | /// \param[in] interface Number of pins to interface to. 1, 2, 4 or 8 are 224 | /// supported, but it is preferred to use the \ref MotorInterfaceType symbolic names. 225 | /// AccelStepper::DRIVER (1) means a stepper driver (with Step and Direction pins). 226 | /// If an enable line is also needed, call setEnablePin() after construction. 227 | /// You may also invert the pins using setPinsInverted(). 228 | /// AccelStepper::FULL2WIRE (2) means a 2 wire stepper (2 pins required). 229 | /// AccelStepper::FULL3WIRE (3) means a 3 wire stepper, such as HDD spindle (3 pins required). 230 | /// AccelStepper::FULL4WIRE (4) means a 4 wire stepper (4 pins required). 231 | /// AccelStepper::HALF3WIRE (6) means a 3 wire half stepper, such as HDD spindle (3 pins required) 232 | /// AccelStepper::HALF4WIRE (8) means a 4 wire half stepper (4 pins required) 233 | /// Defaults to AccelStepper::FULL4WIRE (4) pins. 234 | /// \param[in] pin1 Arduino digital pin number for motor pin 1. Defaults 235 | /// to pin 2. For a AccelStepper::DRIVER (pins==1), 236 | /// this is the Step input to the driver. Low to high transition means to step) 237 | /// \param[in] pin2 Arduino digital pin number for motor pin 2. Defaults 238 | /// to pin 3. For a AccelStepper::DRIVER (pins==1), 239 | /// this is the Direction input the driver. High means forward. 240 | /// \param[in] pin3 Arduino digital pin number for motor pin 3. Defaults 241 | /// to pin 4. 242 | /// \param[in] pin4 Arduino digital pin number for motor pin 4. Defaults 243 | /// to pin 5. 244 | AccelStepper(uint8_t interface = AccelStepper::FULL4WIRE, uint8_t pin1 = 2, uint8_t pin2 = 3, uint8_t pin3 = 4, uint8_t pin4 = 5); 245 | 246 | /// Alternate Constructor which will call your own functions for forward and backward steps. 247 | /// You can have multiple simultaneous steppers, all moving 248 | /// at different speeds and accelerations, provided you call their run() 249 | /// functions at frequent enough intervals. Current Position is set to 0, target 250 | /// position is set to 0. MaxSpeed and Acceleration default to 1.0. 251 | /// Any motor initialization should happen before hand, no pins are used or initialized. 252 | /// \param[in] forward void-returning procedure that will make a forward step 253 | /// \param[in] backward void-returning procedure that will make a backward step 254 | AccelStepper(void (*forward)(), void (*backward)()); 255 | 256 | /// Set the target position. The run() function will try to move the motor 257 | /// from the current position to the target position set by the most 258 | /// recent call to this function. Caution: moveTo() also recalculates the speed for the next step. 259 | /// If you are trying to use constant speed movements, you should call setSpeed() after calling moveTo(). 260 | /// \param[in] absolute The desired absolute position. Negative is 261 | /// anticlockwise from the 0 position. 262 | void moveTo(long absolute); 263 | 264 | /// Set the target position relative to the current position 265 | /// \param[in] relative The desired position relative to the current position. Negative is 266 | /// anticlockwise from the current position. 267 | void move(long relative); 268 | 269 | /// Poll the motor and step it if a step is due, implementing 270 | /// accelerations and decelerations to acheive the target position. You must call this as 271 | /// frequently as possible, but at least once per minimum step interval, 272 | /// preferably in your main loop. 273 | /// \return true if the motor is at the target position. 274 | boolean run(); 275 | 276 | /// Poll the motor and step it if a step is due, implmenting a constant 277 | /// speed as set by the most recent call to setSpeed(). You must call this as 278 | /// frequently as possible, but at least once per step interval, 279 | /// \return true if the motor was stepped. 280 | boolean runSpeed(); 281 | 282 | /// Sets the maximum permitted speed. the run() function will accelerate 283 | /// up to the speed set by this function. 284 | /// \param[in] speed The desired maximum speed in steps per second. Must 285 | /// be > 0. Caution: Speeds that exceed the maximum speed supported by the processor may 286 | /// Result in non-linear accelerations and decelerations. 287 | void setMaxSpeed(float speed); 288 | 289 | /// Sets the acceleration and deceleration parameter. 290 | /// \param[in] acceleration The desired acceleration in steps per second 291 | /// per second. Must be > 0.0. This is an expensive call since it requires a square 292 | /// root to be calculated. Dont call more ofthen than needed 293 | void setAcceleration(float acceleration); 294 | 295 | /// Sets the desired constant speed for use with runSpeed(). 296 | /// \param[in] speed The desired constant speed in steps per 297 | /// second. Positive is clockwise. Speeds of more than 1000 steps per 298 | /// second are unreliable. Very slow speeds may be set (eg 0.00027777 for 299 | /// once per hour, approximately. Speed accuracy depends on the Arduino 300 | /// crystal. Jitter depends on how frequently you call the runSpeed() function. 301 | void setSpeed(float speed); 302 | 303 | /// The most recently set speed 304 | /// \return the most recent speed in steps per second 305 | float speed(); 306 | 307 | /// The distance from the current position to the target position. 308 | /// \return the distance from the current position to the target position 309 | /// in steps. Positive is clockwise from the current position. 310 | long distanceToGo(); 311 | 312 | /// The most recently set target position. 313 | /// \return the target position 314 | /// in steps. Positive is clockwise from the 0 position. 315 | long targetPosition(); 316 | 317 | /// The currently motor position. 318 | /// \return the current motor position 319 | /// in steps. Positive is clockwise from the 0 position. 320 | long currentPosition(); 321 | 322 | /// Resets the current position of the motor, so that wherever the motor 323 | /// happens to be right now is considered to be the new 0 position. Useful 324 | /// for setting a zero position on a stepper after an initial hardware 325 | /// positioning move. 326 | /// Has the side effect of setting the current motor speed to 0. 327 | /// \param[in] position The position in steps of wherever the motor 328 | /// happens to be right now. 329 | void setCurrentPosition(long position); 330 | 331 | /// Moves the motor at the currently selected constant speed (forward or reverse) 332 | /// to the target position and blocks until it is at 333 | /// position. Dont use this in event loops, since it blocks. 334 | void runToPosition(); 335 | 336 | /// Runs at the currently selected speed until the target position is reached 337 | /// Does not implement accelerations. 338 | /// \return true if it stepped 339 | boolean runSpeedToPosition(); 340 | 341 | /// Moves the motor to the new target position and blocks until it is at 342 | /// position. Dont use this in event loops, since it blocks. 343 | /// \param[in] position The new target position. 344 | void runToNewPosition(long position); 345 | 346 | /// Sets a new target position that causes the stepper 347 | /// to stop as quickly as possible, using to the current speed and acceleration parameters. 348 | void stop(); 349 | 350 | /// Disable motor pin outputs by setting them all LOW 351 | /// Depending on the design of your electronics this may turn off 352 | /// the power to the motor coils, saving power. 353 | /// This is useful to support Arduino low power modes: disable the outputs 354 | /// during sleep and then reenable with enableOutputs() before stepping 355 | /// again. 356 | void disableOutputs(); 357 | 358 | /// Enable motor pin outputs by setting the motor pins to OUTPUT 359 | /// mode. Called automatically by the constructor. 360 | void enableOutputs(); 361 | 362 | /// Sets the minimum pulse width allowed by the stepper driver. The minimum practical pulse width is 363 | /// approximately 20 microseconds. Times less than 20 microseconds 364 | /// will usually result in 20 microseconds or so. 365 | /// \param[in] minWidth The minimum pulse width in microseconds. 366 | void setMinPulseWidth(unsigned int minWidth); 367 | 368 | /// Sets the enable pin number for stepper drivers. 369 | /// 0xFF indicates unused (default). 370 | /// Otherwise, if a pin is set, the pin will be turned on when 371 | /// enableOutputs() is called and switched off when disableOutputs() 372 | /// is called. 373 | /// \param[in] enablePin Arduino digital pin number for motor enable 374 | /// \sa setPinsInverted 375 | void setEnablePin(uint8_t enablePin = 0xff); 376 | 377 | /// Sets the inversion for stepper driver pins 378 | /// \param[in] direction True for inverted direction pin, false for non-inverted 379 | /// \param[in] step True for inverted step pin, false for non-inverted 380 | /// \param[in] enable True for inverted enable pin, false (default) for non-inverted 381 | void setPinsInverted(bool direction, bool step, bool enable = false); 382 | 383 | protected: 384 | 385 | /// \brief Direction indicator 386 | /// Symbolic names for the direction the motor is turning 387 | typedef enum 388 | { 389 | DIRECTION_CCW = 0, ///< Clockwise 390 | DIRECTION_CW = 1 ///< Counter-Clockwise 391 | } Direction; 392 | 393 | /// Forces the library to compute a new instantaneous speed and set that as 394 | /// the current speed. It is called by 395 | /// the library: 396 | /// \li after each step 397 | /// \li after change to maxSpeed through setMaxSpeed() 398 | /// \li after change to acceleration through setAcceleration() 399 | /// \li after change to target position (relative or absolute) through 400 | /// move() or moveTo() 401 | void computeNewSpeed(); 402 | 403 | /// Low level function to set the motor output pins 404 | /// bit 0 of the mask corresponds to _pin[0] 405 | /// bit 1 of the mask corresponds to _pin[1] 406 | /// You can override this to impment, for example serial chip output insted of using the 407 | /// output pins directly 408 | virtual void setOutputPins(uint8_t mask); 409 | 410 | /// Called to execute a step. Only called when a new step is 411 | /// required. Subclasses may override to implement new stepping 412 | /// interfaces. The default calls step1(), step2(), step4() or step8() depending on the 413 | /// number of pins defined for the stepper. 414 | /// \param[in] step The current step phase number (0 to 7) 415 | virtual void step(uint8_t step); 416 | 417 | /// Called to execute a step using stepper functions (pins = 0) Only called when a new step is 418 | /// required. Calls _forward() or _backward() to perform the step 419 | /// \param[in] step The current step phase number (0 to 7) 420 | virtual void step0(uint8_t step); 421 | 422 | /// Called to execute a step on a stepper driver (ie where pins == 1). Only called when a new step is 423 | /// required. Subclasses may override to implement new stepping 424 | /// interfaces. The default sets or clears the outputs of Step pin1 to step, 425 | /// and sets the output of _pin2 to the desired direction. The Step pin (_pin1) is pulsed for 1 microsecond 426 | /// which is the minimum STEP pulse width for the 3967 driver. 427 | /// \param[in] step The current step phase number (0 to 7) 428 | virtual void step1(uint8_t step); 429 | 430 | /// Called to execute a step on a 2 pin motor. Only called when a new step is 431 | /// required. Subclasses may override to implement new stepping 432 | /// interfaces. The default sets or clears the outputs of pin1 and pin2 433 | /// \param[in] step The current step phase number (0 to 7) 434 | virtual void step2(uint8_t step); 435 | 436 | /// Called to execute a step on a 3 pin motor, such as HDD spindle. Only called when a new step is 437 | /// required. Subclasses may override to implement new stepping 438 | /// interfaces. The default sets or clears the outputs of pin1, pin2, 439 | /// pin3 440 | /// \param[in] step The current step phase number (0 to 7) 441 | virtual void step3(uint8_t step); 442 | 443 | /// Called to execute a step on a 4 pin motor. Only called when a new step is 444 | /// required. Subclasses may override to implement new stepping 445 | /// interfaces. The default sets or clears the outputs of pin1, pin2, 446 | /// pin3, pin4. 447 | /// \param[in] step The current step phase number (0 to 7) 448 | virtual void step4(uint8_t step); 449 | 450 | /// Called to execute a step on a 3 pin motor, such as HDD spindle. Only called when a new step is 451 | /// required. Subclasses may override to implement new stepping 452 | /// interfaces. The default sets or clears the outputs of pin1, pin2, 453 | /// pin3 454 | /// \param[in] step The current step phase number (0 to 7) 455 | virtual void step6(uint8_t step); 456 | 457 | /// Called to execute a step on a 4 pin half-steper motor. Only called when a new step is 458 | /// required. Subclasses may override to implement new stepping 459 | /// interfaces. The default sets or clears the outputs of pin1, pin2, 460 | /// pin3, pin4. 461 | /// \param[in] step The current step phase number (0 to 7) 462 | virtual void step8(uint8_t step); 463 | 464 | private: 465 | /// Number of pins on the stepper motor. Permits 2 or 4. 2 pins is a 466 | /// bipolar, and 4 pins is a unipolar. 467 | uint8_t _interface; // 0, 1, 2, 4, 8, See MotorInterfaceType 468 | 469 | /// Arduino pin number assignments for the 2 or 4 pins required to interface to the 470 | /// stepper motor or driver 471 | uint8_t _pin[4]; 472 | 473 | /// Whether the _pins is inverted or not 474 | uint8_t _pinInverted[4]; 475 | 476 | /// The current absolution position in steps. 477 | long _currentPos; // Steps 478 | 479 | /// The target position in steps. The AccelStepper library will move the 480 | /// motor from the _currentPos to the _targetPos, taking into account the 481 | /// max speed, acceleration and deceleration 482 | long _targetPos; // Steps 483 | 484 | /// The current motos speed in steps per second 485 | /// Positive is clockwise 486 | float _speed; // Steps per second 487 | 488 | /// The maximum permitted speed in steps per second. Must be > 0. 489 | float _maxSpeed; 490 | 491 | /// The acceleration to use to accelerate or decelerate the motor in steps 492 | /// per second per second. Must be > 0 493 | float _acceleration; 494 | float _sqrt_twoa; // Precomputed sqrt(2*_acceleration) 495 | 496 | /// The current interval between steps in microseconds. 497 | /// 0 means the motor is currently stopped with _speed == 0 498 | unsigned long _stepInterval; 499 | 500 | /// The last step time in microseconds 501 | unsigned long _lastStepTime; 502 | 503 | /// The minimum allowed pulse width in microseconds 504 | unsigned int _minPulseWidth; 505 | 506 | /// Is the direction pin inverted? 507 | ///bool _dirInverted; /// Moved to _pinInverted[1] 508 | 509 | /// Is the step pin inverted? 510 | ///bool _stepInverted; /// Moved to _pinInverted[0] 511 | 512 | /// Is the enable pin inverted? 513 | bool _enableInverted; 514 | 515 | /// Enable pin for stepper driver, or 0xFF if unused. 516 | uint8_t _enablePin; 517 | 518 | /// The pointer to a forward-step procedure 519 | void (*_forward)(); 520 | 521 | /// The pointer to a backward-step procedure 522 | void (*_backward)(); 523 | 524 | /// The step counter for speed calculations 525 | long _n; 526 | 527 | /// Initial step size in microseconds 528 | float _c0; 529 | 530 | /// Last step size in microseconds 531 | float _cn; 532 | 533 | /// Min step size in microseconds based on maxSpeed 534 | float _cmin; // at max speed 535 | 536 | /// Current direction motor is spinning in 537 | boolean _direction; // 1 == CW 538 | 539 | }; 540 | 541 | /// @example Random.pde 542 | /// Make a single stepper perform random changes in speed, position and acceleration 543 | 544 | /// @example Overshoot.pde 545 | /// Check overshoot handling 546 | /// which sets a new target position and then waits until the stepper has 547 | /// achieved it. This is used for testing the handling of overshoots 548 | 549 | /// @example MultiStepper.pde 550 | /// Shows how to multiple simultaneous steppers 551 | /// Runs one stepper forwards and backwards, accelerating and decelerating 552 | /// at the limits. Runs other steppers at the same time 553 | 554 | /// @example ConstantSpeed.pde 555 | /// Shows how to run AccelStepper in the simplest, 556 | /// fixed speed mode with no accelerations 557 | 558 | /// @example Blocking.pde 559 | /// Shows how to use the blocking call runToNewPosition 560 | /// Which sets a new target position and then waits until the stepper has 561 | /// achieved it. 562 | 563 | /// @example AFMotor_MultiStepper.pde 564 | /// Control both Stepper motors at the same time with different speeds 565 | /// and accelerations. 566 | 567 | /// @example AFMotor_ConstantSpeed.pde 568 | /// Shows how to run AccelStepper in the simplest, 569 | /// fixed speed mode with no accelerations 570 | 571 | /// @example ProportionalControl.pde 572 | /// Make a single stepper follow the analog value read from a pot or whatever 573 | /// The stepper will move at a constant speed to each newly set posiiton, 574 | /// depending on the value of the pot. 575 | 576 | /// @example Bounce.pde 577 | /// Make a single stepper bounce from one limit to another, observing 578 | /// accelrations at each end of travel 579 | 580 | /// @example Quickstop.pde 581 | /// Check stop handling. 582 | /// Calls stop() while the stepper is travelling at full speed, causing 583 | /// the stepper to stop as quickly as possible, within the constraints of the 584 | /// current acceleration. 585 | 586 | #endif 587 | --------------------------------------------------------------------------------