a stepper motor view as a serial midi device, use an interface such ttymidi to generate a serial to 115200 baudrate midi instrument

Dependencies:   MIDI mbed X-NUCLEO-IHM05A1

main.cpp

Committer:
gidiana
Date:
2019-10-01
Revision:
34:215d5ee0f434
Parent:
33:c1cefad6d338

File content as of revision 34:215d5ee0f434:

#include "mbed.h"
#include "L6208.h"
#include "pitches.h"
#include "MIDI.h"

#define VREFA_PWM_PIN D3
#define VREFB_PWM_PIN D9


l6208_init_t init =
{
  65000,            //Acceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  80,              //Acceleration current torque in % (from 0 to 100)
  65000,            //Deceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  80,              //Deceleration current torque in % (from 0 to 100)
  8000,            //Running speed in step/s or (1/16)th step/s for microstep modes
  80,              //Running current torque in % (from 0 to 100)
  40,              //Holding current torque in % (from 0 to 100)
  STEP_MODE_1_16,  //Step mode via enum motorStepMode_t
  FAST_DECAY,      //Decay mode via enum motorDecayMode_t
  0,               //Dwelling time in ms
  FALSE,           //Automatic HIZ STOP
  100000           //VREFA and VREFB PWM frequency (Hz)
};

unsigned long motorSpeeds[] = {0, 0, 0, 0, 0};
int flag=0;
// Utility
//InterruptIn button(USER_BUTTON);
DigitalOut led(LED1);

// Motor Control
L6208 *motor;

InterruptIn end1(USER_BUTTON, PullUp);
DigitalIn end0(PA_5, PullUp);

    
MIDI MIDI(PA_2, PA_3);
  
void handleNoteOn(byte channel, byte pitch, byte velocity) //MIDI Note ON Command
{
  
  motorSpeeds[channel] = pitchVals[pitch]/4; //set the motor speed to specified pitch
 
}

void handleNoteOff(byte channel, byte pitch, byte velocity) //MIDI Note OFF Command
{
  motorSpeeds[channel] = 0; //set motor speed to zero
  flag=!flag;
}
  /* Main ----------------------------------------------------------------------*/
  
  int main()
  {
    led=1;
    
    MIDI.begin(MIDI_CHANNEL_OMNI); //listen to all MIDI channels
    MIDI.setHandleNoteOn(handleNoteOn); //execute function when note on message is recieved
    MIDI.setHandleNoteOff(handleNoteOff); //execute function when note off message is recieved
    
    // Motor Initialization
    motor = new L6208(D2, D8, D7, D4, D5, D6, VREFA_PWM_PIN, VREFB_PWM_PIN);
    motor->set_step_mode(StepperMotor::STEP_MODE_1_16);
    if (motor->init(&init) != COMPONENT_OK)
    {
      printf("ERROR: vvMotor Init\n\r");
      exit(EXIT_FAILURE);
    }

    
    printf("DONE: Motor Init\n\r"); 
    printf("Running!\n\r");
     
    while(true)
    {
      MIDI.read();
      if(motorSpeeds[0]==0)
        motor->hard_stop();
      else
      {
        
        motor->set_max_speed(motorSpeeds[0]);
        if (flag==1)
        motor->run(StepperMotor::BWD);
        else
        motor->run(StepperMotor::FWD);
        
       
      
      }
  }
}