motore cofano

Dependencies:   mbed X-NUCLEO-IHM05A1

Exercise_IHM05A1.cpp

Committer:
Vito1704
Date:
2018-11-19
Revision:
11:196c4677e0ca
Parent:
10:2622d1ab5984

File content as of revision 11:196c4677e0ca:

/**
 ******************************************************************************
 * @file    main.cpp
 * @author  IPC Rennes
 * @version V1.0.0
 * @date    April 13th, 2016
 * @brief   mbed simple application for the STMicroelectronics X-NUCLEO-IHM05A1
 *          Motor Control Expansion Board: control of 1 motor.
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *   1. Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *   3. Neither the name of STMicroelectronics nor the names of its contributors
 *      may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ******************************************************************************
 */

/* Includes ------------------------------------------------------------------*/

/* mbed specific header files. */
#include "mbed.h"

/* Component specific header files. */
#include "L6208.h"
#include "SampledSound.h"
#include "Clacson.h"
 DigitalIn myButton(USER_BUTTON);
 DigitalIn Input (PC_0);
AnalogIn InWave(PA_0);
Serial pc(USBTX, USBRX);
//DigitalOut myRele(PC_3);
DigitalOut LedAD (PC_2) ;//bianche telecamere
DigitalOut LedAS (PC_3) ;//bianche telecamere
DigitalOut LedPD (PC_10) ;//rosse
DigitalOut LedPS (PC_12) ;//rosse
AnalogOut OutWave(PA_4); // pin di output per la forma d'onda analogica
DigitalOut myD2(PA_10);//pin di output proveniente dal raspberry
DigitalOut led2(LED2); // LED su scheda
/* Definitions ---------------------------------------------------------------*/
#ifdef TARGET_NUCLEO_F334R8
#define VREFA_PWM_PIN D11
#define VREFB_PWM_PIN D9
#elif TARGET_NUCLEO_F302R8
#define VREFA_PWM_PIN D11
#define VREFB_PWM_PIN D15 /* HW mandatory patch: bridge manually D9 with D15 */
#else
#define VREFA_PWM_PIN D3
#define VREFB_PWM_PIN D9
#endif
#define NUMSAMPLE 300
// ticker per la generazione dell'onda con DAC
Ticker SampleOutTicker;

void my_error_handler(uint16_t error)
{
  /* Printing to the console. */
  pc.printf("Error %d detected\r\n\n", error);
  
  /* Infinite loop */
  while (true) {
  }    
}



// ticker per l'acquisizione dell'onda con ADC
Ticker SamplingTicker;

// carattere in arrivo dal PC ed equivalente numerico
volatile char cReadChar;
volatile int nReadChar;

// flag che diventa true quando si vuole fermare l'acquisizione
volatile bool bStop;

// valore letto dall'ADC e corrispondente in tensione
volatile unsigned short usReadADCLux;
volatile float fReadVoltage;

// valore di temperatura letto dall'ADC
volatile float fLux;                                                                                                                                                                                                       

// prototipo di funzione che genera i campioni della sinusoide da utilizzare per la generazione tramite DAC
void CalculateSinewave(void);
// funzione di generazione suono della frequenza e ampiezza selezionate
void SoundGenerate(double fFrequency);
                
// carattere in arrivo dal PC

volatile char CReadMusic;                

uint32_t nProva;

// indice nell'array dei campioni da porre in output da DAC per Marimba
volatile uint32_t nSampleSoundIndex;

// Periodo di generazione campioni in output DeltaT = T/NumSample
double fDeltaT;
// amplificazione per il dato da spedire sull'ADC
volatile double fAmp;
//volatile double fAmpNew;
// flag per bloccare la generazione del segnale
volatile int bGenerate = false;

// frequenza segnale da generare
volatile double fFreq;
//flag che diventa true se bisogna fermare la generazione di suoni

// periodo della sinusoide da generare
double fPeriod;
// tipo di suono da generare: 0=Sine, 1= Square
char cSoundWave;

// nota corrispondente al tasto premuto
volatile char cKeyToPlay= '\0';


//**********************************************************************
// generazione suoni con i sample da file di campioni in SoundSample.h 
//**********************************************************************
void SampleOut() 
{
   
    // genera campioni fino al raggiungimento del numero di campioni nel file Sound.h
    if((nSampleSoundIndex < nSampleNum) && (bGenerate == true))
    {
        // mette in output un campione della forma d'onda moltiplicato per l'amplificazione fAmp
        OutWave.write_u16(naInputSoundWave[nSampleSoundIndex]*fAmp);
        // incrementa l'indice del campione in output, nSampleNum è il numero dei campioni nle file Sound.h
        nSampleSoundIndex++;
    }
    else
    {
        // se è stato generato il numero di campioni del file oppure bGenerate = false, ferma la generazione di suoni
        bGenerate = false;
    }    
}

// prototipo di funzione che genera i campioni della sinusoide da utilizzare per la generazione tramite DAC
void CalculateSinewave(void);
// funzione di generazione suono della frequenza e ampiezza selezionate
void SoundGenerate(double fFrequency);

/* Variables -----------------------------------------------------------------*/

/* Initialization parameters of the motor connected to the expansion board. */
l6208_init_t init =
{
 
  1500,            //Acceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  20,              //Acceleration current torque in % (from 0 to 100)
  1500,            //Deceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  30,              //Deceleration current torque in % (from 0 to 100)
  1500,            //Running speed in step/s or (1/16)th step/s for microstep modes
  50,              //Running current torque in % (from 0 to 100)
  20,              //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)
};

/* Motor Control Component. */
L6208 *motor;

/* Functions -----------------------------------------------------------------*/

/**
 * @brief  This is an example of user handler for the flag interrupt.
 * @param  None
 * @retval None
 * @note   If needed, implement it, and then attach and enable it:
 *           + motor->attach_flag_irq(&my_flag_irq_handler);
 *           + motor->enable_flag_irq();
 *         To disable it:
 *           + motor->DisbleFlagIRQ();
 */
void my_flag_irq_handler(void)
{
  pc.printf("    WARNING: \"FLAG\" interrupt triggered:\r\n");
  motor->disable();
  pc.printf("    Motor disabled.\r\n\n");
}

/**
 * @brief  This is an example of error handler.
 * @param[in] error Number of the error
 * @retval None
 * @note   If needed, implement it, and then attach it:
 *           + motor->attach_error_handler(&my_error_handler);
 */

/* Main ----------------------------------------------------------------------*/

int main()
{
       //inizializza variabili 
    bGenerate= false;
   bStop= true;
    cReadChar= 0;
    //nSampleOutIndex= 0;
    //nSampleOutCount= 0;
    nSampleSoundIndex= 0;
    
     //imposta il funzionamento del pulsante come "PullDown": Aperto = '0'. L'altra modalità di funzionamento è PullUp
    myButton.mode(PullUp);
    
    // configura velocità della comunicazione seriale su USB-VirtualCom e invia messaggio di benvenuto
    pc.baud(921600); //921600 bps
    
    // test dei LED
    led2=1; // Blu
    wait_ms(500);
    led2=0;
        
   pc.printf("\r\nHallo Amaldi Students - Exercise 12 \r\n");
    pc.printf("\n\r*** Sampled Sound Generator ***\n\r");
                
    // fissa l'amplificazione da 0 a 1
    fAmp = 1.0;  
      
    // attende la pressione di tasti sulla marimba
    while(true)
    {   
        if(myButton == 0)
        {
            while(myButton != 1){}; // attendi che il tasto sia rilasciato
            fFreq=nSamplePerSec/nUnderSampleFactor;// campioni per secondo da generare = nSamplePerSec/nUnderSampleFactor
            pc.printf("--- Sound Generation ---\n\r");
            pc.printf("--- Clacson ---\n\r");
            if (myD2 == 1)
            {
             bGenerate = true; // flag true quando è attiva la generazione di suoni
             nSampleSoundIndex =0; //inizializza indice dell'array
             fDeltaT = (1.0/fFreq);  // fFreq dipende dal periodo di campionamento e dal fattore di sottocampionamento
             SampleOutTicker.attach(&SampleOut,fDeltaT); // avvia generazione
            }
            else
            {
             bGenerate = false; // arresta la generazione di suoni
            }
        }
    } // while   
    // periodo di campionamento
    int nDeltaT;
    
        
    // configura velocità della comunicazione seriale su USB-VirtualCom e invia messaggio di benvenuto
    pc.baud(921600); //921600 bps
    // messaggio di benvenuto
    pc.printf("\r\nHey Bro! Say Goodbye to your Sister !\r\n");
    pc.printf("Enter Acquisition Time, DeltaT[sec]= [1 - 9]: \r\n");
   // pc.printf("\r\n*** Bluetooth Temp Acquisition ***\r\n");
    
    // inizializza variabili
    bStop=true;
    //myRele = 0x00; // spegni il relè
    
    
     
    LedAD =0x00 ;
    LedAS =0x00 ;
    LedPD =0x00 ;
    LedPS =0x00 ;
    wait(1);
    LedAD =0x01 ;
    LedAS =0x01 ;
    LedPD =0x01 ;
    LedPS =0x01 ;
    wait(1);
    LedAD =0x00 ;
    LedAS =0x00 ;
    LedPD =0x00 ;
    LedPS =0x00 ;
    wait(1);
    LedAD =0x01;
    wait_ms(500);
    LedAS =0x01 ;
    wait_ms(500);
    LedPD =0x01 ;
    wait_ms(500);
    LedPS =0x01 ;
    wait(1);   
  // configura velocità della comunicazione seriale su USB-VirtualCom e invia messaggio di benvenuto
  pc.baud(921600); //921600 bps
  //pc.baud(9600); //256000 bps
  pc.printf("*** Test Motor ***\n\r");
  
  /* Printing to the console. */
  pc.printf("STARTING MAIN PROGRAM\r\n");
  pc.printf("    Reminder:\r\n");
  pc.printf("    The position unit is in agreement to the step mode.\r\n");
  pc.printf("    The speed, acceleration or deceleration unit depend on the step mode:\r\n");
  pc.printf("    - For normal mode and half step mode, the unit is steps/s or /s^2.\r\n");
  pc.printf("    - For microstep modes, the unit is (1/16)steps/s or /s^2.\r\n");
    
//----- Initialization 
  /* Initializing Motor Control Component. */
  motor = new L6208(D2, D8, D7, D4, D5, D6, VREFA_PWM_PIN, VREFB_PWM_PIN);
  if (motor->init(&init) != COMPONENT_OK) {
    exit(EXIT_FAILURE);
  }

  /* Attaching and enabling an interrupt handler. */
  motor->attach_flag_irq(&my_flag_irq_handler);
  motor->enable_flag_irq();
    
  /* Attaching an error handler */
  motor->attach_error_handler(&my_error_handler);

  /* Printing to the console. */
  pc.printf("Motor Control Application Example for 1 Motor\r\n");

//----- run the motor BACKWARD
  pc.printf("--> Running the motor backward.\r\n");
  motor->run(StepperMotor::BWD);
  
  while (motor->get_status()!=STEADY) {
    /* Print reached speed to the console in step/s or microsteps/s */
    pc.printf("    Reached Speed: %d microstep/s.\r\n", motor->get_speed());
    wait_ms(50);    
  }
  pc.printf("    Reached Speed: %d microstep/s.\r\n", motor->get_speed());
     
  /* Wait for 1 second */  
  wait_ms(1000);
  

  
//----- Soft stop required while running
  pc.printf("--> Soft stop requested.\r\n");
  motor->soft_stop(); 
  
  
//----- Change step mode to full step mode
  motor->set_step_mode(StepperMotor::STEP_MODE_FULL);
  pc.printf("    Motor step mode: %d (0:FS, 1:1/2, 2:1/4, 3:1/8, 4:1/16).\r\n", motor->get_step_mode());
  
  /* Get current position of device and print to the console */
  pc.printf("    Position: %d.\r\n", motor->get_position());
  
  /* Set speed, acceleration and deceleration to scale with normal mode */
  motor->set_max_speed(init.maxSpeedSps>>4);
  motor->set_acceleration(motor->get_acceleration()>>4);
  motor->set_deceleration(motor->get_deceleration()>>4);
  /* Print parameters to the console */  
  pc.printf("    Motor Max Speed: %d step/s.\r\n", motor->get_max_speed());
  pc.printf("    Motor Min Speed: %d step/s.\r\n", motor->get_min_speed());
  pc.printf("    Motor Acceleration: %d step/s.\r\n", motor->get_acceleration());
  pc.printf("    Motor Deceleration: %d step/s.\r\n", motor->get_deceleration());
  
//----- move of 200 steps in the FW direction
  pc.printf("--> Moving forward 200 steps.\r\n");
  motor->move(StepperMotor::FWD, 200);
int i,a=0;
  
  while (true) {
  
  if ( Input == 0 ) 
  {
     a=a+1;
   }
   if(a>1)
   {
    a=0;
     
   }
         
     if(a==0)
     {
        /* Request device to go position -3200 */
        motor->go_to(150);
        /* Waiting while the motor is active. */
       motor->wait_while_active();
    }
    else 
    {
        /* Request device to go position -3200 */
     motor->go_to(-150);
     /* Waiting while the motor is active. */
     motor->wait_while_active();
  
    }
    

}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/