1 /* 2 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha (at) intel.com> 3 * Copyright (c) 2014 Intel Corporation. 4 * 5 * Permission is hereby granted, free of charge, to any person obtaining 6 * a copy of this software and associated documentation files (the 7 * "Software"), to deal in the Software without restriction, including 8 * without limitation the rights to use, copy, modify, merge, publish, 9 * distribute, sublicense, and/or sell copies of the Software, and to 10 * permit persons to whom the Software is furnished to do so, subject to 11 * the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be 14 * included in all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 */ 24 25 #include <iostream> 26 #include <string> 27 #include <stdexcept> 28 #include <unistd.h> 29 #include <stdlib.h> 30 31 #include "stepmotor.h" 32 33 using namespace upm; 34 35 StepMotor::StepMotor (int dirPin, int stePin) 36 : m_pwmStepContext(stePin), m_dirPinCtx(dirPin) { 37 mraa::Result error = mraa::SUCCESS; 38 m_name = "StepMotor"; 39 40 m_stePin = stePin; 41 m_dirPin = dirPin; 42 43 error = m_dirPinCtx.dir (mraa::DIR_OUT); 44 if (error != mraa::SUCCESS) { 45 mraa::printError (error); 46 } 47 } 48 49 void 50 StepMotor::setSpeed (int speed) { 51 if (speed > MAX_PERIOD) { 52 m_speed = MAX_PERIOD; 53 } 54 55 if (speed < MIN_PERIOD) { 56 m_speed = MIN_PERIOD; 57 } 58 59 m_speed = speed; 60 } 61 62 mraa::Result 63 StepMotor::stepForward (int ticks) { 64 dirForward (); 65 return move (ticks); 66 } 67 68 mraa::Result 69 StepMotor::stepBackwards (int ticks) { 70 dirBackwards (); 71 return move (ticks); 72 } 73 74 mraa::Result 75 StepMotor::move (int ticks) { 76 mraa::Result error = mraa::SUCCESS; 77 78 m_pwmStepContext.enable (1); 79 for (int tick = 0; tick < ticks; tick++) { 80 m_pwmStepContext.period_us (m_speed); 81 m_pwmStepContext.pulsewidth_us (PULSEWIDTH); 82 } 83 m_pwmStepContext.enable (0); 84 85 return error; 86 } 87 88 mraa::Result 89 StepMotor::dirForward () { 90 mraa::Result error = mraa::SUCCESS; 91 92 error = m_dirPinCtx.write (HIGH); 93 if (error != mraa::SUCCESS) { 94 mraa::printError (error); 95 } 96 97 return error; 98 } 99 100 mraa::Result 101 StepMotor::dirBackwards () { 102 mraa::Result error = mraa::SUCCESS; 103 104 error = m_dirPinCtx.write (LOW); 105 if (error != mraa::SUCCESS) { 106 mraa::printError (error); 107 } 108 109 return error; 110 } 111