This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Implement SCI on 28027F

Other Parts Discussed in Thread: CONTROLSUITE, MOTORWARE

Hello to everyone,


I'm trying implement the 'sci_echoback' example of C2000_LaunchPad from controlSUITE on Lab5b of Motorware. I already test and modify the code for what I need and I get what I want. The problem now is to do the migration from controlSUITE to Motorware. Could someone point me what I should change on the code that I have on controlSUITE to could be applied on Motorware?

  • Hello,

    Please refer to this thread http://e2e.ti.com/support/microcontrollers/c2000/f/902/p/334989/1168654.aspx#1168654

    I think it may help you.

    Best regards,

    Maria

  • Hello Maria,


    I already follow that thread, but maybe something missed to me. I don't have a big knowledge on this area, but I'll try again implement that steps.

    I started by follow and modify the example of 'sci_echoback' (C:\ti\controlSUITE\development_kits\C2000_LaunchPad\f2802x_examples\sci_echoback) and with the right modifications I get what I want (send 2 bytes as a query and receive 3 bytes as response). The problem is that I can't simply "copy & paste" the code for motorware to use on Lab5b...

  • Hi Bruno,

    We currently don't have a one to one mapping of controlSUITE examples to Motorware. However, replacing the bit fields with the Motorware drivers should be easy. 

    Please take a look at C:\TI\controlSUITE\device_support\f2802x\v220\f2802x_examples_drivers\scia_loopback on how to initialize the drivers.

    Thanks

    Noah

  • Hello Bruno,

    Bruno Ramos1 said:
    I started by follow and modify the example of 'sci_echoback' (C:\ti\controlSUITE\development_kits\C2000_LaunchPad\f2802x_examples\sci_echoback)

    I suggest you to use the example in device_support folder (C:\ti\controlSUITE\device_support\f2802x\v220\f2802x_examples_drivers\sci_echoback), because the example in development_kits is not updated well.

    Bruno Ramos1 said:
    The problem is that I can't simply "copy & paste" the code for motorware to use on Lab5b...

    Yes, you can not, but you can follow your setting from ControlSuite to be put in motorware.

    In the thread that I mentioned, you can see:

    void HAL_setupSCI(HAL_Handle handle) {
        HAL_Obj *obj = (HAL_Obj *) handle;
        // Initialize all SCI registers based on your requirement. This is only example.

        // SCI stop bit, parity, loopback, char bits, idle/address mode (SCICCR = 0x07)
        SCI_setNumStopBits(obj->sciaHandle, SCI_NumStopBits_One);    // SCICCR bit 7
        SCI_setParity(obj->sciaHandle, SCI_Parity_Odd);                          // SCICCR bit 6
        SCI_disableParity(obj->sciaHandle);                                               // SCICCR bit 5
        SCI_disableLoopBack(obj->sciaHandle);                                        // SCICCR bit 4
        SCI_setMode(obj->sciaHandle, SCI_Mode_IdleLine);                     // SCICCR bit 3
        SCI_setCharLength(obj->sciaHandle, SCI_CharLength_8_Bits);   // SCICCR bit 0-2

        // TX enable, RX enable, RX ERR INT enable, SLEEP, TXWAKE (SCICTL1 = 0x03)
        SCI_disableRxErrorInt(obj->sciaHandle);                        // SCICTL1 bit 6
        SCI_disable(obj->sciaHandle);                                        // SCICTL1 bit 5
        SCI_disableTxWake(obj->sciaHandle);                           // SCICTL1 bit 3
        SCI_disableSleep(obj->sciaHandle);                              // SCICTL1 bit 2
        SCI_enableTx(obj->sciaHandle);                                    // SCICTL1 bit 1
        SCI_enableRx(obj->sciaHandle);                                    // SCICTL1 bit 0

        // TXINT enable, RXINT enable, TXEMPTY, TXRDY (SCICTL2 = 0x03)
       SCI_enableRxInt(obj->sciaHandle);                            // SCICTL2 bit 1
       SCI_disableTxInt(obj->sciaHandle);                            // SCICTL2 bit 0

        // SCIH-SCIL BAUD - SCI_BAUD = (LSPCLK/(SCI_BRR*8)) - 1
        SCI_setBaudRate(obj->sciaHandle, SCI_BaudRate_19_2_kBaud);

        // Reset SCI
        SCI_enable(obj->sciaHandle);

        PIE_enableSciInt(obj->pieHandle, SCI_RXA);                 // enable SCI interrupt
        CPU_enableInt(obj->cpuHandle, CPU_IntNumber_9);    // enable CPU interrupt
    }

    This is similar with void scia_echoback_init() and void scia_fifo_init(). So modify the content of this function with the setting that you use in void scia_echoback_init() and void scia_fifo_init().

    And in proj_lab05b.c, put your echoback code.

    Best regards,

    Maria

  • Hello Maria,


    Thanks a lot for your reply and help. I'll try that and see if I can achieve what I want. I don't doubt about what you said, I just doubt of my knowledge and capacity....


    Best Regards,
    BrunoRamos

  • Maria,


    Could you please enligthen me about your code related with the thread that you refer above? I think that something is missing at my side, but I can't figured out what it is.... at this line:

    'PIE_enableSciInt(obj->pieHandle, SCI_RXA);                 // enable SCI interrupt'

    and:

    5. in pie.c, add PIE_enableSciInt()

    void PIE_enableSciInt(PIE_Handle pieHandle,const SCI_Type_e sciType)
    {
      PIE_Obj *pie = (PIE_Obj *)pieHandle;
      uint16_t index = 8;         // index is counted from 0, so INT9 has index 8
      uint16_t setValue = (1 << sciType);


      // set the value
      pie->PIEIER_PIEIFR[index].IER |= setValue;

      return;
    } // end of PIE_enableSciInt() function

    I don't have any relation with SCI_Type_e and SCI_RXA on my code. Could you please give me a tip about this? This isn't related because the devices are differents (I'm using a 02x and you a 06x)?


    Thanks in advance.

    BR,
    Bruno Ramos

  • Hello Bruno,

    If your SCI doesn't use interrupt, you don't need PIE_enableSciInt()  function. Like you can see in the comment, this function is used to enable SCI interrupt.

    Btw, I also use F28027F chip.

    Best regards,

    Maria

  • Hello Maria,


    I need the interrupts on my SCI. My goal is: send 2 bytes as a query to a device (in this case a encoder) and receive 3 bytes as response, and I need to use the interrupt after finish to send the 2 bytes.

    I modified the code on the 'Example_F2802xSci_Echoback' and 'Example_F2802xSci_FFDLB_int' and I get what I want. Now I want to implement this on Lab5b and probably something is missing to me. Maybe this require more experience on the programming field, what I don't have unfortunately. I hope that you (or anyone) could guide me (I don't wanna that do my job for me, ofc, just need a little help). Thank you for all.


    Best Regards,
    Bruno Ramos

  • Hello Bruno,

    Which exactly the part that confused?

    Maybe I can help you, eventhough maybe the response cannot be fast.

    However, I don't use SCI FIFO in my code so I hope you have no difficulties to make your own SCI APIs for this.

    Also I only use RX interrupt.

    If you need interrupt, then you need to enable the PIE bit related to SCI interrupt. When I modified the motorware, there was no PIE API for enabling SCI interrupt, so I made my own.

    Best regards,

    Maria

  • Hello Maria,


    Thanks a lot for your disponibility. Here is my code based on the example on ControlSUITE (C:\ti\controlSUITE\device_support\f2802x\v220\f2802x_examples_drivers\sci_echoback):

    0172.Example_2802xSci_Echoback.c
    //#############################################################################
    //
    //  File:   f2802x_examples/sci_echoback/Example_F2802xSci_Echoback.c
    //
    //  Title:  F2802x Device SCI Echoback.
    //
    //  Group:          C2000
    //  Target Device:  TMS320F2802x
    //
    //! \addtogroup example_list
    //!  <h1>SCI Echoback</h1>
    //!
    //!   This test recieves and echo-backs data through the SCI-A port.
    //!
    //!   -# Configure hyperterminal:
    //!      Use the included hyperterminal configuration file SCI_96.ht.
    //!      To load this configuration in hyperterminal: file->open
    //!      and then select the SCI_96.ht file.
    //!   -# Check the COM port.
    //!      The configuration file is currently setup for COM1.
    //!      If this is not correct, disconnect Call->Disconnect
    //!      Open the File-Properties dialog and select the correct COM port.
    //!   -# Connect hyperterminal Call->Call
    //!      and then start the 2802x SCI echoback program execution.
    //!   -# The program will print out a greeting and then ask you to
    //!      enter a character which it will echo back to hyperterminal.
    //!
    //!   Watch Variables:
    //!   - LoopCount for the number of characters sent
    //!   - ErrorCount
    //
    //  (C) Copyright 2012, Texas Instruments, Inc.
    //#############################################################################
    // $TI Release: PACKAGE NAME $
    // $Release Date: PACKAGE RELEASE DATE $
    //#############################################################################
    
    #include "DSP28x_Project.h"     // Device Headerfile and Examples Include File
    #include <stdio.h>
    #include <file.h>
    
    #include "f2802x_common/include/adc.h"
    #include "f2802x_common/include/clk.h"
    #include "f2802x_common/include/flash.h"
    #include "f2802x_common/include/gpio.h"
    #include "f2802x_common/include/pie.h"
    #include "f2802x_common/include/pll.h"
    #include "f2802x_common/include/sci.h"
    #include "f2802x_common/include/wdog.h"
    
    //#include "DSP28x_usDelay"
    
    //#include "usDelay.h"
    
    // Prototype statements for functions found within this file.
    
    __interrupt void sciaRxFifoIsr(void);
    void scia_echoback_init(void);
    void scia_fifo_init(void);
    void scia_xmit(int a);
    void scia_msg(char *msg);
    
    // Global counts used in this example
    uint16_t LoopCount;
    uint16_t ErrorCount;
    
    uint32_t delay = 0;
    uint16_t inc = 0;
    uint8_t encoderTipoLeitura = 0;
    uint16_t msgRXInc[3];
    uint16_t msgRXDec[3];
    extern uint16_t estupido;
    uint32_t tent = 0;
    uint32_t delay_var = 0;
    
    
    ADC_Handle myAdc;
    CLK_Handle myClk;
    FLASH_Handle myFlash;
    GPIO_Handle myGpio;
    PIE_Handle myPie;
    SCI_Handle mySci;
    
    void main(void)
    {    
    /*   uint16_t ReceivedChar;
        char *msg;
    */
        CPU_Handle myCpu;
        PLL_Handle myPll;
        WDOG_Handle myWDog;
        
        // Initialize all the handles needed for this application    
        myAdc = ADC_init((void *)ADC_BASE_ADDR, sizeof(ADC_Obj));
        myClk = CLK_init((void *)CLK_BASE_ADDR, sizeof(CLK_Obj));
        myCpu = CPU_init((void *)NULL, sizeof(CPU_Obj));
        myFlash = FLASH_init((void *)FLASH_BASE_ADDR, sizeof(FLASH_Obj));
        myGpio = GPIO_init((void *)GPIO_BASE_ADDR, sizeof(GPIO_Obj));
        myPie = PIE_init((void *)PIE_BASE_ADDR, sizeof(PIE_Obj));
        myPll = PLL_init((void *)PLL_BASE_ADDR, sizeof(PLL_Obj));
        mySci = SCI_init((void *)SCIA_BASE_ADDR, sizeof(SCI_Obj));
        myWDog = WDOG_init((void *)WDOG_BASE_ADDR, sizeof(WDOG_Obj));
    
        // Perform basic system initialization    
        WDOG_disable(myWDog);
        CLK_enableAdcClock(myClk);
        (*Device_cal)();
        
        //Select the internal oscillator 1 as the clock source
        CLK_setOscSrc(myClk, CLK_OscSrc_Internal);
        
        // Setup the PLL for x10 /2 which will yield 50Mhz = 10Mhz * 10 / 2
        PLL_setup(myPll, PLL_Multiplier_12, PLL_DivideSelect_ClkIn_by_2);
        
        // Disable the PIE and all interrupts
        PIE_disable(myPie);
        PIE_disableAllInts(myPie);
        CPU_disableGlobalInts(myCpu);
        CPU_clearIntFlags(myCpu);
    
        // If running from flash copy RAM only functions to RAM   
    #ifdef _FLASH
        memcpy(&RamfuncsRunStart, &RamfuncsLoadStart, (size_t)&RamfuncsLoadSize);
    #endif   
        
        // Initalize GPIO
        GPIO_setPullUp(myGpio, GPIO_Number_28, GPIO_PullUp_Enable);
        GPIO_setPullUp(myGpio, GPIO_Number_29, GPIO_PullUp_Disable);
    	//GPIO_setDirection(myGpio,GPIO_Number_29,GPIO_Direction_Output);
    	GPIO_setQualification(myGpio, GPIO_Number_28, GPIO_Qual_ASync);
    	GPIO_setMode(myGpio, GPIO_Number_28, GPIO_28_Mode_SCIRXDA);
    	GPIO_setMode(myGpio, GPIO_Number_29, GPIO_29_Mode_SCITXDA);
    	GPIO_setMode(myGpio, GPIO_Number_18, GPIO_18_Mode_GeneralPurpose);
    	GPIO_setDirection(myGpio,GPIO_Number_18,GPIO_Direction_Output);
    	GPIO_setPullUp(myGpio, GPIO_Number_18, GPIO_PullUp_Enable);
    
        // Setup a debug vector table and enable the PIE
        PIE_setDebugIntVectorTable(myPie);
        PIE_enable(myPie);
        /*
        LoopCount = 0;
        ErrorCount = 0;
    */
    
        // Interrupts that are used in this example are re-mapped to
        // ISR functions found within this file.
            EALLOW;    // This is needed to write to EALLOW protected registers
        //   PieVectTable.SCIRXINTA = &sciaRxFifoIsr;
            ((PIE_Obj *)myPie)->SCIRXINTA = &sciaRxFifoIsr;
        //   PieVectTable.SCITXINTA = &sciaTxFifoIsr;
        //    ((PIE_Obj *)myPie)->SCITXINTA = &sciaTxFifoIsr;
            EDIS;   // This is needed to disable write to EALLOW protected registers
    
            // Register interrupt handlers in the PIE vector table
    	PIE_registerPieIntHandler(myPie, PIE_GroupNumber_9, PIE_SubGroupNumber_1, (intVec_t)&sciaRxFifoIsr);
    //    PIE_registerPieIntHandler(myPie, PIE_GroupNumber_9, PIE_SubGroupNumber_2, (intVec_t)&sciaTxFifoIsr);
    
    
        scia_echoback_init();  // Initalize SCI for echoback
        scia_fifo_init();      // Initialize the SCI FIFO
    /*
        msg = "\r\n\n\nHello World!\0";
        scia_msg(msg);
    
        msg = "\r\nYou will enter a character, and the DSP will echo it back! \n\0";
        scia_msg(msg);
    */
       // delay_var = 2130;
    
        // Enable interrupts required for this example
       PIE_enableInt(myPie, PIE_GroupNumber_9, PIE_InterruptSource_SCIARX);
        //   PIE_enableInt(myPie, PIE_GroupNumber_9, PIE_InterruptSource_SCIATX);
    
       CPU_enableInt(myCpu, CPU_IntNumber_9);
       CPU_enableGlobalInts(myCpu);
    
    
        for(;;)
        {
     /*       msg = "\r\nEnter a character: \0";
            scia_msg(msg);
    
            // Wait for inc character
            while(SCI_getRxFifoStatus(mySci) < SCI_FifoStatus_1_Word){
            }
    
            // Get character
            ReceivedChar = SCI_getData(mySci);
    
            // Echo character back
            msg = "  You sent: \0";
            scia_msg(msg);
            scia_xmit(ReceivedChar);
    
            LoopCount++;
        }
    */
    
        	GPIO_setHigh(myGpio, GPIO_Number_18);
    	/* delay = 10000;
    		 while(delay != 0)
    		 {
    			 delay--;
    
    		 }
    	GPIO_setLow(myGpio, GPIO_Number_18);
    	delay = 10000;
    			 while(delay != 0)
    			 {
    				 delay--;
    
    			 }
    
    	*/
    	 //__delay_cycles(1);
    //	 delay = 6000;
    
    	 DELAY_US(2000);
    
    /*		 while(delay != 0)
    		 {
    			 delay--;
    		 }*/
    
    	scia_xmit(0xA2);
    
    	if(encoderTipoLeitura == 0)
    	{
    		scia_xmit(0xB0);
    	}
    	else
    	{
    		scia_xmit(0xB3);
    	}
    
    	//scia_xmit(0x00);
    
    	while(SCI_getTxFifoStatus(mySci) != SCI_FifoStatus_Empty);
    
    	while(SCI_isTxReady(mySci) == 0);
    
    	while(SCI_isTxEmpty(mySci) == 0);
    
    
    	 //__delay_cycles(2);
    //	delay = 20;
    	//delay = delay_var;
    /*	 while(delay != 0)
    	 {
    		 delay--;
    	 }
    */
    	inc = 0;
    
    	GPIO_setLow(myGpio, GPIO_Number_18);
    
    /*//
    	if (msgRXInc[1] == 0xFA && msgRXInc[2] == 0xFA)
    	{
    		/// erro stop motor...
    	}
    	else if (msgRXInc[1] == 0xFB && msgRXInc[2] == 0xFB)
    	{
    		/// erro stop motor...
    	}
    	else
    	{
    		//system ok ... see what is the position of the encoder
    	}
    */
    
    	/*SCI_resetRxFifo(mySci);
    
    	while(inc < 5)
    	{
    		tent = 120000;
    
    		while((SCI_getRxFifoStatus(mySci) == SCI_FifoStatus_Empty) && tent > 0)
    		{
    			tent --;
    		}
    
    		if(encoderTipoLeitura == 0)
    				{
    					msgRXDec[inc] = SCI_getData(mySci);
    				}
    				else
    				{
    					msgRXInc[inc] = SCI_getData(mySci);
    				}
    		inc++;
    	}*/
    
    	 //__delay_cycles(2);
    
    	DELAY_US(5000);
    /*	 delay = 400000;
    	 while(delay != 0)
    	 {
    		 delay--;
    	 }
    */
    	if(encoderTipoLeitura == 0)
    	{
    		encoderTipoLeitura = 1;
    	}
    	else
    	{
    		encoderTipoLeitura = 0;
    
    		DELAY_US(50000);
    		 //__delay_cycles(1000);
    
    /*		delay = 1000000;
    
    		while(delay != 0)
    		{
    			 delay--;
    		 }
    */	}
        }//for(;;)
    }
    
    __interrupt void sciaRxFifoIsr(void)
    {
    	if(inc < 3)
    	{
    	if(encoderTipoLeitura == 0)
    					{
    						msgRXDec[inc] = SCI_getData(mySci);
    					}
    					else
    					{
    						msgRXInc[inc] = SCI_getData(mySci);
    					}
    			inc++;
    	}
    /*	if(inc < 10)
    	{
    		while(SCI_getRxFifoStatus(mySci) != SCI_FifoLevel_Empty)
    		{
    			if(encoderTipoLeitura == 0)
    			{
    				msgRXDec[inc++] = SCI_read(mySci);
    			}
    			else
    			{
    				msgRXInc[inc++] = SCI_getData(mySci);
    			}
    		}
    	}
    */
    /*	msgRXDec[inc++] = SCI_getData(mySci);
    	if (inc == 9)
    		inc = 0;
    */
        // Clear Overflow flag
        SCI_clearRxFifoOvf(mySci);
    
        // Clear Interrupt flag
        SCI_clearRxFifoInt(mySci);
    
        // Issue PIE ack
        PIE_clearInt(myPie, PIE_GroupNumber_9);
    
        return;
    }
    
    
    // Test 1,SCIA  DLB, 8-bit word, baud rate 0x000F, default, 1 STOP bit, no parity
    void scia_echoback_init()
    {
    
        CLK_enableSciaClock(myClk);
    
        // 1 stop bit,  No loopback
        // No parity,8 char bits,
        // async mode, idle-line protocol
        SCI_setMode(mySci,SCI_Mode_IdleLine);
     //   SCI_disableParity(mySci);
        SCI_enableParity(mySci);
        SCI_setParity(mySci,SCI_Parity_Even);
        SCI_setNumStopBits(mySci, SCI_NumStopBits_One);
        SCI_setCharLength(mySci, SCI_CharLength_8_Bits);
        
        SCI_enableTx(mySci);
        SCI_enableRx(mySci);
     //   SCI_enableTxInt(mySci);
        SCI_enableRxInt(mySci);
    
        /*
    	// set fifo interrupt level
    	((SCI_Obj *)mySci)->SCIFFTX &= (~SCI_SCIFFRX_IL_BITS);
    	((SCI_Obj *)mySci)->SCIFFRX |= SCI_FifoLevel_1_Word;
    
    	SCI_clearRxFifoInt(mySci);
    
    	SCI_setPriority(mySci, SCI_Priority_FreeRun);
    
        // Enable interrupts required for this example
    	((PIE_Obj *)myPie)->PIEIER_PIEIFR[9].IER |= (1 << 0);
    
        SCI_clearRxFifoOvf(mySci);
    
        CPU_enableInt(myCpu, CPU_IntNumber_9);
        CPU_enableGlobalInts(myCpu);
    */
    
        // SCI BRR = LSPCLK/(SCI BAUDx8) - 1
    #if (CPU_FRQ_60MHZ)
        SCI_setBaudRate(mySci, (SCI_BaudRate_e)194);
        // ou SCI_setBaudRate(mySci, SCI_BaudRate_9_6_kBaud);
    #elif (CPU_FRQ_50MHZ)
        SCI_setBaudRate(mySci, (SCI_BaudRate_e)162);
    #elif (CPU_FRQ_40MHZ)
        SCI_setBaudRate(mySci, (SCI_BaudRate_e)129);
    #endif
    
        SCI_enable(mySci);
        
        return;
    }
    
    // Transmit a character from the SCI
    void scia_xmit(int a)
    {
    //    while (SciaRegs.SCIFFTX.bit.TXFFST != 0) {}
        while(SCI_getTxFifoStatus(mySci) != SCI_FifoStatus_Empty){
        }
    //    SciaRegs.SCITXBUF=a;
        SCI_putDataBlocking(mySci, a);
    
    }
    
    void scia_msg(char * msg)
    {
        int i;
        i = 0;
        while(msg[i] != '\0')
        {
            scia_xmit(msg[i]);
            i++;
        }
    }
    
    // Initalize the SCI FIFO
    void scia_fifo_init()
    {
        
      //  SCI_enableFifoEnh(mySci);
        SCI_resetTxFifo(mySci);
        SCI_clearTxFifoInt(mySci);
        SCI_resetChannels(mySci);
        SCI_setTxFifoIntLevel(mySci, SCI_FifoLevel_Empty);
    
        SCI_resetRxFifo(mySci);
        SCI_clearRxFifoInt(mySci);
    //    SCI_setRxFifoIntLevel(mySci, SCI_FifoLevel_4_Words);
        SCI_setRxFifoIntLevel(mySci, SCI_FifoLevel_1_Word);
        SCI_disableLoopBack(mySci);
    
        return;
    }
    
    //===========================================================================
    // No more.
    //===========================================================================
    
    

    This works really well, without any problem. Now I tried to implement this on Motorware, but something it's wrong and when I run the code, the program suck on this function 'void SCI_putDataBlocking(SCI_Handle sciHandle, uint16_t data)' on sci.c. And even enable the flag 'gMotorVars.Flag_Run_Identify = true' the motor doesn't run cause the program it's sucked on that part.


    Any explanation for that?

  • Hello Bruno,

    Which version of Motorware that you use?

    Can you check in sci.h of your motorware (\motorware\motorware_1_01_00_xx\sw\drivers\sci\src\32b\f28x\f2802x) whether these lines haven been fixed or not?

    //! \brief Enumeration to define the serial communications interface (SCI) parity
    //!
    typedef enum
    {
    //  SCI_Parity_Odd=(0 << 5),        //!< Denotes odd parity
    //  SCI_Parity_Even=(1 << 5)        //!< Denotes even parity
      SCI_Parity_Odd=(0 << 6),        //!< Denotes odd parity
      SCI_Parity_Even=(1 << 6)        //!< Denotes even parity
    } SCI_Parity_e;

    I used version 12, I don't know in version 13 whether they have been fixed or not.

    Or try to disable the parity, and check whether your code in motorware is running or not.

    Best regards,

    Maria

  • Hello Maria,

    I have the last version of Motorware (motorware_1_01_00_13). I check that lines and it is fixed on this version.

    //! \brief Enumeration to define the serial communications interface (SCI) parity
    //!
    typedef enum
    {
      SCI_Parity_Odd=(0 << 6),        //!< Denotes odd parity
      SCI_Parity_Even=(1 << 6)        //!< Denotes even parity
    } SCI_Parity_e;

    I disabled the parity like you said and nothing changed, still stucking... at this moment it's stuck on this line:

      status = (sci->SCICTL2 & SCI_SCICTL2_TXRDY_BITS) >> 7;

    //! \brief     Determines if the serial communications interface (SCI) is ready to transmit
    //! \param[in] sciHandle  The serial communications interface (SCI) object handle
    //! \return    The transmit status
    static inline bool SCI_txReady(SCI_Handle sciHandle)
    {
      SCI_Obj *sci = (SCI_Obj *)sciHandle;
      bool status;
    
      status = (sci->SCICTL2 & SCI_SCICTL2_TXRDY_BITS) >> 7;
    
      return((bool)status);
    } // end of SCI_txReady() function

    And when I debug the code and press Resume, the Expressions Window load this strange values:

    I need to Pause, press Restart, and just after that, I have the right values on the respective expressions. This never did happen before. What could be?

    Thank you very much for your help Maria!

    Best Regards,
    Bruno Ramos

  • Could you see the image? I'll attach again, cause on my side i can't see...

  • Hello Bruno,

    Did you solve your problem?

    If you delete all of your SCI code in Motorware Lab5b, do you still get these strange values when debugging?

    Also about your SCI code in Motorware Lab5b, I suggest you to check first your SCI code without running the FOC code.

    It means in forever loop, put your SCI code before enabling the system.

    Put the SCI lines before this line:

    // Waiting for enable system flag to be set
        while(!(gMotorVars.Flag_enableSys));


    Best regards,

    Maria

  • Hello Maria,


    At now that strange values never more show up again. Maybe CCS was needing a restart, idk...

    And I can't solve the other problem, that is run SCI and Lab5b together. The program stuck at this function 'SCI_putDataBlocking'.

    void SCI_putDataBlocking(SCI_Handle sciHandle, uint16_t data)
    {
      SCI_Obj *sci = (SCI_Obj *)sciHandle;
    
      while(SCI_txReady(sciHandle) != true)
        {
        }
    
      // write the data
      sci->SCITXBUF = data;
    
      return;
    } // end of SCI_putDataBlocking() function

    I already don't know what I can do more. I really appreciate your effort Maria, thank you very much. I hope that the TI experts could give any help too.

    BR,

    Bruno Ramos

  • Hello Bruno,

    Can you tell us what you already did in hal.c for setting up the SCI in motorware?

    Maybe we can check it for you whether there is something missing or not.

  • Hello Maria,


    I can attach my hal.c and lab5b.c file for you could check easier what is missing.

    3441.hal.c
    /* --COPYRIGHT--,BSD
     * Copyright (c) 2012, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  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.
     *
     * *  Neither the name of Texas Instruments Incorporated 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 OWNER 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.
     * --/COPYRIGHT--*/
    //! \file   solutions/instaspin_foc/boards/hvkit_rev1p1/f28x/f2802xF/src/hal.c
    //! \brief Contains the various functions related to the HAL object (everything outside the CTRL system) 
    //!
    //! (C) Copyright 2011, Texas Instruments, Inc.
    
    
    // **************************************************************************
    // the includes
    
    // drivers
    
    // modules
    
    // platforms
    #include "hal.h"
    #include "user.h"
    #include "hal_obj.h"
    
    //Added
    #include "sw/drivers/sci/src/32b/f28x/f2802x/sci.c"
    #include "sw/drivers/pie/src/32b/f28x/f2802x/pie.h"
    
    #ifdef FLASH
    #pragma CODE_SECTION(HAL_setupFlash,"ramfuncs");
    #endif
    
    // **************************************************************************
    // the defines
    
    
    // **************************************************************************
    // the globals
    
    HAL_Obj hal;
    
    
    // **************************************************************************
    // the functions
    
    //Added
    
    void HAL_setupSCI(HAL_Handle handle) {
        HAL_Obj *obj = (HAL_Obj *) handle;
    
        CLK_enableSciaClock(obj->clkHandle);
    
        // SCI stop bit, parity, loopback, char bits, idle/address mode (SCICCR = 0x07)
        SCI_setNumStopBits(obj->sciaHandle, SCI_NumStopBits_One);    // SCICCR bit 7
        SCI_enableParity(obj->sciaHandle);                                               // SCICCR bit 5
        SCI_setParity(obj->sciaHandle, SCI_Parity_Even);                          // SCICCR bit 6
        SCI_disableLoopBack(obj->sciaHandle);                                        // SCICCR bit 4
        SCI_setMode(obj->sciaHandle, SCI_Mode_IdleLine);                     // SCICCR bit 3
        SCI_setCharLength(obj->sciaHandle, SCI_CharLength_8_Bits);   // SCICCR bit 0-2
    
        // TX enable, RX enable, RX ERR INT enable, SLEEP, TXWAKE (SCICTL1 = 0x03)
        SCI_disableRxErrorInt(obj->sciaHandle);                        // SCICTL1 bit 6
        SCI_disable(obj->sciaHandle);                                        // SCICTL1 bit 5
        SCI_disableTxWake(obj->sciaHandle);                           // SCICTL1 bit 3
        SCI_disableSleep(obj->sciaHandle);                              // SCICTL1 bit 2
        SCI_enableTx(obj->sciaHandle);                                    // SCICTL1 bit 1
        SCI_enableRx(obj->sciaHandle);                                    // SCICTL1 bit 0
    
    	// TXINT enable, RXINT enable, TXEMPTY, TXRDY (SCICTL2 = 0x03)
    	SCI_enableRxInt(obj->sciaHandle);                            // SCICTL2 bit 1
    	SCI_disableTxInt(obj->sciaHandle);                            // SCICTL2 bit 0
    
    	// SCIH-SCIL BAUD - SCI_BAUD = (LSPCLK/(SCI_BRR*8)) - 1
    	SCI_setBaudRate(obj->sciaHandle, SCI_BaudRate_9_6_kBaud);
    
    	// Reset SCI
    	SCI_enable(obj->sciaHandle);
    
    	//  PIE_enableSciInt(obj->pieHandle, SCI_RXA);                 // enable SCI interrupt
    	PIE_enableInt(obj->pieHandle, PIE_GroupNumber_9, PIE_InterruptSource_SCIARX);
    
    	CPU_enableGlobalInts(obj->cpuHandle);
    	CPU_enableInt(obj->cpuHandle, CPU_IntNumber_9);    // enable CPU interrupt
    
    	SCI_resetTxFifo(obj->sciaHandle);
    	SCI_clearTxFifoInt(obj->sciaHandle);
    	SCI_resetChannels(obj->sciaHandle);
    	SCI_setTxFifoIntLevel(obj->sciaHandle, SCI_FifoLevel_Empty);
    
    	SCI_resetRxFifo(obj->sciaHandle);
    	SCI_clearRxFifoInt(obj->sciaHandle);
    	//    SCI_setRxFifoIntLevel(mySci, SCI_FifoLevel_4_Words);
    	SCI_setRxFifoIntLevel(obj->sciaHandle, SCI_FifoLevel_1_Word);
    	SCI_disableLoopBack(obj->sciaHandle);
    
    }
    //SCI
    
    
    void HAL_cal(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable the ADC clock
      CLK_enableAdcClock(obj->clkHandle);
    
    
      // Run the Device_cal() function
      // This function copies the ADC and oscillator calibration values from TI reserved
      // OTP into the appropriate trim registers
      // This boot ROM automatically calls this function to calibrate the interal 
      // oscillators and ADC with device specific calibration data.
      // If the boot ROM is bypassed by Code Composer Studio during the development process,
      // then the calibration must be initialized by the application
      ENABLE_PROTECTED_REGISTER_WRITE_MODE;
      (*Device_cal)();
      DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
      // run offsets calibration in user's memory
      HAL_AdcOffsetSelfCal(handle);
    
      // run oscillator compensation
      HAL_OscTempComp(handle);
    
      // disable the ADC clock
      CLK_disableAdcClock(obj->clkHandle);
    
      return;
    } // end of HAL_cal() function
    
    
    void HAL_OscTempComp(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t Temperature;
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
      // set the ADC voltage reference source to internal
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
      // Set main clock scaling factor (max45MHz clock for the ADC module)
      ADC_setDivideSelect(obj->adcHandle,ADC_DivideSelect_ClkIn_by_2);
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
      // enable non-overlap mode
      ADC_enableNoOverlapMode(obj->adcHandle);
    
      // connect channel A5 internally to the temperature sensor
      ADC_setTempSensorSrc(obj->adcHandle, ADC_TempSensorSrc_Int);
    
      // set SOC0 channel select to ADCINA5
      ADC_setSocChanNumber(obj->adcHandle, ADC_SocNumber_0, ADC_SocChanNumber_A5);
    
      // set SOC0 acquisition period to 26 ADCCLK
      ADC_setSocSampleDelay(obj->adcHandle, ADC_SocNumber_0, ADC_SocSampleDelay_64_cycles);
    
      // connect ADCINT1 to EOC0
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_1, ADC_IntSrc_EOC0);
    
      // clear ADCINT1 flag
      ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
      // enable ADCINT1
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_1);
    
      // force start of conversion on SOC0
      ADC_setSocFrc(obj->adcHandle, ADC_SocFrc_0);
    
      // wait for end of conversion
      while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_1) == 0){}
    
      // clear ADCINT1 flag
      ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
      Temperature = ADC_readResult(obj->adcHandle, ADC_ResultNumber_0);
    
      HAL_osc1Comp(handle, Temperature);
    
      HAL_osc2Comp(handle, Temperature);
    
      return;
    } // end of HAL_OscTempComp() function
    
    
    void HAL_osc1Comp(HAL_Handle handle, const int16_t sensorSample)
    {
    	int16_t compOscFineTrim;
    	HAL_Obj *obj = (HAL_Obj *)handle;
    
    	ENABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        compOscFineTrim = ((sensorSample - getRefTempOffset())*(int32_t)getOsc1FineTrimSlope()
                          + OSC_POSTRIM_OFF + FP_ROUND )/FP_SCALE + getOsc1FineTrimOffset() - OSC_POSTRIM;
    
        if(compOscFineTrim > 31)
          {
            compOscFineTrim = 31;
          }
    	else if(compOscFineTrim < -31)
          {
            compOscFineTrim = -31;
          }
    
        OSC_setTrim(obj->oscHandle, OSC_Number_1, HAL_getOscTrimValue(getOsc1CoarseTrim(), compOscFineTrim));
    
        DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        return;
    } // end of HAL_osc1Comp() function
    
    
    void HAL_osc2Comp(HAL_Handle handle, const int16_t sensorSample)
    {
    	int16_t compOscFineTrim;
    	HAL_Obj *obj = (HAL_Obj *)handle;
    
    	ENABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        compOscFineTrim = ((sensorSample - getRefTempOffset())*(int32_t)getOsc2FineTrimSlope()
                          + OSC_POSTRIM_OFF + FP_ROUND )/FP_SCALE + getOsc2FineTrimOffset() - OSC_POSTRIM;
    
        if(compOscFineTrim > 31)
          {
            compOscFineTrim = 31;
          }
    	else if(compOscFineTrim < -31)
          {
            compOscFineTrim = -31;
          }
    
        OSC_setTrim(obj->oscHandle, OSC_Number_2, HAL_getOscTrimValue(getOsc2CoarseTrim(), compOscFineTrim));
    
        DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        return;
    } // end of HAL_osc2Comp() function
    
    
    uint16_t HAL_getOscTrimValue(int16_t coarse, int16_t fine)
    {
      uint16_t regValue = 0;
    
      if(fine < 0)
        {
          regValue = ((-fine) | 0x20) << 9;
        }
      else
        {
          regValue = fine << 9;
        }
    
      if(coarse < 0)
        {
          regValue |= ((-coarse) | 0x80);
        }
      else
        {
          regValue |= coarse;
        }
    
      return regValue;
    } // end of HAL_getOscTrimValue() function
    
    
    void HAL_AdcOffsetSelfCal(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t AdcConvMean;
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
      // set the ADC voltage reference source to internal
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
      //Select VREFLO internal connection on B5
      ADC_enableVoltRefLoConv(obj->adcHandle);
    
      //Select channel B5 for all SOC
      HAL_AdcCalChanSelect(handle, ADC_SocChanNumber_B5);
    
      //Apply artificial offset (+80) to account for a negative offset that may reside in the ADC core
      ADC_setOffTrim(obj->adcHandle, 80);
    
      //Capture ADC conversion on VREFLO
      AdcConvMean = HAL_AdcCalConversion(handle);
    
      //Set offtrim register with new value (i.e remove artical offset (+80) and create a two's compliment of the offset error)
      ADC_setOffTrim(obj->adcHandle, 80 - AdcConvMean);
    
      //Select external ADCIN5 input pin on B5
      ADC_disableVoltRefLoConv(obj->adcHandle);
    
      return;
    } // end of HAL_AdcOffsetSelfCal() function
    
    
    void HAL_AdcCalChanSelect(HAL_Handle handle, const ADC_SocChanNumber_e chanNumber)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_0,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_1,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_2,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_3,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_4,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_5,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_6,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_7,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_8,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_9,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_10,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_11,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_12,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_13,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_14,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_15,chanNumber);
    
      return;
    } // end of HAL_AdcCalChanSelect() function
    
    
    uint16_t HAL_AdcCalConversion(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t index, SampleSize, Mean;
      uint32_t Sum;
      ADC_SocSampleDelay_e ACQPS_Value;
    
      index       = 0;     //initialize index to 0
      SampleSize  = 256;   //set sample size to 256 (**NOTE: Sample size must be multiples of 2^x where is an integer >= 4)
      Sum         = 0;     //set sum to 0
      Mean        = 999;   //initialize mean to known value
    
      //Set the ADC sample window to the desired value (Sample window = ACQPS + 1)
      ACQPS_Value = ADC_SocSampleDelay_7_cycles;
    
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_0,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_1,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_2,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_3,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_4,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_5,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_6,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_7,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_8,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_9,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_10,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_11,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_12,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_13,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_14,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_15,ACQPS_Value);
    
      // Enabled ADCINT1 and ADCINT2
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_1);
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_2);
    
      // Disable continuous sampling for ADCINT1 and ADCINT2
      ADC_setIntMode(obj->adcHandle, ADC_IntNumber_1, ADC_IntMode_EOC);
      ADC_setIntMode(obj->adcHandle, ADC_IntNumber_2, ADC_IntMode_EOC);
    
      //ADCINTs trigger at end of conversion
      ADC_setIntPulseGenMode(obj->adcHandle, ADC_IntPulseGenMode_Prior);
    
      // Setup ADCINT1 and ADCINT2 trigger source
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_1, ADC_IntSrc_EOC6);
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_2, ADC_IntSrc_EOC14);
    
      // Setup each SOC's ADCINT trigger source
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_0, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_1, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_2, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_3, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_4, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_5, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_6, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_7, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_8, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_9, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_10, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_11, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_12, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_13, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_14, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_15, ADC_Int1TriggersSOC);
    
      // Delay before converting ADC channels
      usDelay(ADC_DELAY_usec);
    
      ADC_setSocFrcWord(obj->adcHandle, 0x00FF);
    
      while( index < SampleSize )
        {
          //Wait for ADCINT1 to trigger, then add ADCRESULT0-7 registers to sum
          while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_1) == 0){}
    
          //Must clear ADCINT1 flag since INT1CONT = 0
          ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_0);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_1);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_2);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_3);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_4);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_5);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_6);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_7);
    
          //Wait for ADCINT2 to trigger, then add ADCRESULT8-15 registers to sum
          while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_2) == 0){}
    
          //Must clear ADCINT2 flag since INT2CONT = 0
          ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_2);
    
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_8);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_9);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_10);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_11);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_12);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_13);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_14);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_15);
    
          index+=16;
    
      } // end data collection
    
      //Disable ADCINT1 and ADCINT2 to STOP the ping-pong sampling
      ADC_disableInt(obj->adcHandle, ADC_IntNumber_1);
      ADC_disableInt(obj->adcHandle, ADC_IntNumber_2);
    
      //Calculate average ADC sample value
      Mean = Sum / SampleSize;
    
      // Clear start of conversion trigger
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_0, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_1, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_2, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_3, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_4, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_5, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_6, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_7, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_8, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_9, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_10, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_11, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_12, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_13, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_14, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_15, ADC_NoIntTriggersSOC);
    
      //return the average
      return(Mean);
    } // end of HAL_AdcCalConversion() function
    
    
    void HAL_disableWdog(HAL_Handle halHandle)
    {
      HAL_Obj *hal = (HAL_Obj *)halHandle;
    
    
      WDOG_disable(hal->wdogHandle);
    
    
      return;
    } // end of HAL_disableWdog() function
    
    
    void HAL_disableGlobalInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_disableGlobalInts(obj->cpuHandle);
    
      return;
    } // end of HAL_disableGlobalInts() function
    
    
    void HAL_enableAdcInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable the PIE interrupts associated with the ADC interrupts
      PIE_enableAdcInt(obj->pieHandle,ADC_IntNumber_1);
    
    
      // enable the ADC interrupts
      ADC_enableInt(obj->adcHandle,ADC_IntNumber_1);
    
    
      // enable the cpu interrupt for ADC interrupts
      CPU_enableInt(obj->cpuHandle,CPU_IntNumber_10);
    
      return;
    } // end of HAL_enableAdcInts() function
    
    
    void HAL_enableDebugInt(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_enableDebugInt(obj->cpuHandle);
    
      return;
    } // end of HAL_enableDebugInt() function
    
    
    void HAL_enableGlobalInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_enableGlobalInts(obj->cpuHandle);
    
      return;
    } // end of HAL_enableGlobalInts() function
    
    
    void HAL_enablePwmInt(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      PIE_enablePwmInt(obj->pieHandle,PWM_Number_1);
    
    
      // enable the interrupt
      PWM_enableInt(obj->pwmHandle[PWM_Number_1]);
    
    
      // enable the cpu interrupt for EPWM1_INT
      CPU_enableInt(obj->cpuHandle,CPU_IntNumber_3);
    
      return;
    } // end of HAL_enablePwmInt() function
    
    
    void HAL_setupFaults(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint_least8_t cnt;
    
    
      // Configure Trip Mechanism for the Motor control software
      // -Cycle by cycle trip on CPU halt
      // -One shot fault trip zone
      // These trips need to be repeated for EPWM1 ,2 & 3
      for(cnt=0;cnt<3;cnt++)
        {
          PWM_enableTripZoneSrc(obj->pwmHandle[cnt],PWM_TripZoneSrc_CycleByCycle_TZ6_NOT);
    
          PWM_enableTripZoneSrc(obj->pwmHandle[cnt],PWM_TripZoneSrc_OneShot_TZ1_NOT);
    
          // What do we want the OST/CBC events to do?
          // TZA events can force EPWMxA
          // TZB events can force EPWMxB
    
          PWM_setTripZoneState_TZA(obj->pwmHandle[cnt],PWM_TripZoneState_EPWM_Low);
          PWM_setTripZoneState_TZB(obj->pwmHandle[cnt],PWM_TripZoneState_EPWM_Low);
        }
    
      return;
    } // end of HAL_setupFaults() function
    
    
    HAL_Handle HAL_init(void *pMemory,const size_t numBytes)
    {
      uint_least8_t cnt;
      HAL_Handle handle;
      HAL_Obj *obj;
    
    
      if(numBytes < sizeof(HAL_Obj))
        return((HAL_Handle)NULL);
    
    
      // assign the handle
      handle = (HAL_Handle)pMemory;
    
    
      // assign the object
      obj = (HAL_Obj *)handle;
    
    
      //Added...
      // Init SCI A registers
      obj->sciaHandle = SCI_init((void *) SCIA_BASE_ADDR, sizeof(SCI_Obj));
      //SCI
    
    
      // initialize the watchdog driver
      obj->wdogHandle = WDOG_init((void *)WDOG_BASE_ADDR,sizeof(WDOG_Obj));
    
    
      // disable watchdog
      HAL_disableWdog(handle);
    
    
      // initialize the ADC
      obj->adcHandle = ADC_init((void *)ADC_BASE_ADDR,sizeof(ADC_Obj));
    
    
      // initialize the clock handle
      obj->clkHandle = CLK_init((void *)CLK_BASE_ADDR,sizeof(CLK_Obj));
    
    
      // initialize the CPU handle
      obj->cpuHandle = CPU_init(&cpu,sizeof(cpu));
    
    
      // initialize the FLASH handle
      obj->flashHandle = FLASH_init((void *)FLASH_BASE_ADDR,sizeof(FLASH_Obj));
    
    
      // initialize the GPIO handle
      obj->gpioHandle = GPIO_init((void *)GPIO_BASE_ADDR,sizeof(GPIO_Obj));
    
    
      // initialize the current offset estimator handles
      for(cnt=0;cnt<USER_NUM_CURRENT_SENSORS;cnt++)
        {
          obj->offsetHandle_I[cnt] = OFFSET_init(&obj->offset_I[cnt],sizeof(obj->offset_I[cnt]));
        }
    
    
      // initialize the voltage offset estimator handles
      for(cnt=0;cnt<USER_NUM_VOLTAGE_SENSORS;cnt++)
        {
          obj->offsetHandle_V[cnt] = OFFSET_init(&obj->offset_V[cnt],sizeof(obj->offset_V[cnt]));
        }
    
    
      // initialize the oscillator handle
      obj->oscHandle = OSC_init((void *)OSC_BASE_ADDR,sizeof(OSC_Obj));
    
    
      // initialize the PIE handle
      obj->pieHandle = PIE_init((void *)PIE_BASE_ADDR,sizeof(PIE_Obj));
    
    
      // initialize the PLL handle
      obj->pllHandle = PLL_init((void *)PLL_BASE_ADDR,sizeof(PLL_Obj));
    
    
      // initialize PWM handle
      obj->pwmHandle[0] = PWM_init((void *)PWM_ePWM1_BASE_ADDR,sizeof(PWM_Obj));
      obj->pwmHandle[1] = PWM_init((void *)PWM_ePWM2_BASE_ADDR,sizeof(PWM_Obj));
      obj->pwmHandle[2] = PWM_init((void *)PWM_ePWM3_BASE_ADDR,sizeof(PWM_Obj));
    
    
      // initialize power handle
      obj->pwrHandle = PWR_init((void *)PWR_BASE_ADDR,sizeof(PWR_Obj));
    
    
      // initialize timer drivers
      obj->timerHandle[0] = TIMER_init((void *)TIMER0_BASE_ADDR,sizeof(TIMER_Obj));
      obj->timerHandle[1] = TIMER_init((void *)TIMER1_BASE_ADDR,sizeof(TIMER_Obj));
      obj->timerHandle[2] = TIMER_init((void *)TIMER2_BASE_ADDR,sizeof(TIMER_Obj));
    
    
      return(handle);
    } // end of HAL_init() function
    
    
    void HAL_setParams(HAL_Handle handle,const USER_Params *pUserParams)
    {
      uint_least8_t cnt;
      HAL_Obj *obj = (HAL_Obj *)handle;
      _iq beta_lp_pu = _IQ(pUserParams->offsetPole_rps/(float_t)pUserParams->ctrlFreq_Hz);
    
    
      HAL_setNumCurrentSensors(handle,pUserParams->numCurrentSensors);
      HAL_setNumVoltageSensors(handle,pUserParams->numVoltageSensors);
    
    
      for(cnt=0;cnt<HAL_getNumCurrentSensors(handle);cnt++)
        {
          HAL_setOffsetBeta_lp_pu(handle,HAL_SensorType_Current,cnt,beta_lp_pu);
          HAL_setOffsetInitCond(handle,HAL_SensorType_Current,cnt,_IQ(0.0));
          HAL_setOffsetValue(handle,HAL_SensorType_Current,cnt,_IQ(0.0));
        }
    
    
      for(cnt=0;cnt<HAL_getNumVoltageSensors(handle);cnt++)
        {
          HAL_setOffsetBeta_lp_pu(handle,HAL_SensorType_Voltage,cnt,beta_lp_pu);
          HAL_setOffsetInitCond(handle,HAL_SensorType_Voltage,cnt,_IQ(0.0));
          HAL_setOffsetValue(handle,HAL_SensorType_Voltage,cnt,_IQ(0.0));
        }
    
    
      // disable global interrupts
      CPU_disableGlobalInts(obj->cpuHandle);
    
    
      // disable cpu interrupts
      CPU_disableInts(obj->cpuHandle);
    
    
      // clear cpu interrupt flags
      CPU_clearIntFlags(obj->cpuHandle);
    
    
    
      //Added....
      HAL_setupSCI(handle);
      //SCI
    
    
      // setup the clocks
      HAL_setupClks(handle);
    
    
      // Setup the PLL
      HAL_setupPll(handle,PLL_ClkFreq_60_MHz);
    
    
      // setup the PIE
      HAL_setupPie(handle);
    
    
      // run the device calibration
      HAL_cal(handle);
    
    
      // setup the peripheral clocks
      HAL_setupPeripheralClks(handle);
    
    
      // setup the GPIOs
      HAL_setupGpios(handle);
    
    
      // setup the flash
      HAL_setupFlash(handle);
    
    
      // setup the ADCs
      HAL_setupAdcs(handle);
    
    
      // setup the PWMs
      HAL_setupPwms(handle,
                    pUserParams->systemFreq_MHz,
                    pUserParams->pwmPeriod_usec,
                    USER_NUM_PWM_TICKS_PER_ISR_TICK);
    
    
      // setup the timers
      HAL_setupTimers(handle,
                      pUserParams->systemFreq_MHz);
    
    
      // set the default current bias
     {
       uint_least8_t cnt;
       _iq bias = _IQ12mpy(ADC_dataBias,_IQ(pUserParams->current_sf));
       
       for(cnt=0;cnt<HAL_getNumCurrentSensors(handle);cnt++)
         {
           HAL_setBias(handle,HAL_SensorType_Current,cnt,bias);
         }
     }
    
    
      //  set the current scale factor
     {
       _iq current_sf = _IQ(pUserParams->current_sf);
    
      HAL_setCurrentScaleFactor(handle,current_sf);
     }
    
    
      // set the default voltage bias
     {
       uint_least8_t cnt;
       _iq bias = _IQ(0.0);
       
       for(cnt=0;cnt<HAL_getNumVoltageSensors(handle);cnt++)
         {
           HAL_setBias(handle,HAL_SensorType_Voltage,cnt,bias);
         }
     }
    
    
      //  set the voltage scale factor
     {
       _iq voltage_sf = _IQ(pUserParams->voltage_sf);
    
      HAL_setVoltageScaleFactor(handle,voltage_sf);
     }
    
     return;
    } // end of HAL_setParams() function
    
    
    void HAL_setupAdcs(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
    
      // set the ADC voltage reference source to internal 
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
    
      // set the ADC interrupt pulse generation to prior
      ADC_setIntPulseGenMode(obj->adcHandle,ADC_IntPulseGenMode_Prior);
    
    
      // set the temperature sensor source to external
      ADC_setTempSensorSrc(obj->adcHandle,ADC_TempSensorSrc_Ext);
    
    
      // configure the interrupt sources
      ADC_disableInt(obj->adcHandle,ADC_IntNumber_1);
      ADC_setIntMode(obj->adcHandle,ADC_IntNumber_1,ADC_IntMode_ClearFlag);
      ADC_setIntSrc(obj->adcHandle,ADC_IntNumber_1,ADC_IntSrc_EOC7);
    
    
      //configure the SOCs for hvkit_rev1p1
      // sample the first sample twice due to errata sprz342f
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_0,ADC_SocChanNumber_B4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_0,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_0,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_1,ADC_SocChanNumber_B4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_1,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_1,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_2,ADC_SocChanNumber_A4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_2,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_2,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_3,ADC_SocChanNumber_A2);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_3,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_3,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_4,ADC_SocChanNumber_B1);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_4,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_4,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_5,ADC_SocChanNumber_B3);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_5,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_5,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_6,ADC_SocChanNumber_B7);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_6,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_6,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_7,ADC_SocChanNumber_A0);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_7,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_7,ADC_SocSampleDelay_7_cycles);
    
      //Potenc 1
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_8,ADC_SocChanNumber_B6);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_8,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_8,ADC_SocSampleDelay_7_cycles);
    
    
      //Potenc 2
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_9,ADC_SocChanNumber_A1);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_9,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_9,ADC_SocSampleDelay_7_cycles);
    
    
      return;
    } // end of HAL_setupAdcs() function
    
    
    void HAL_setupClks(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable internal oscillator 1
      CLK_enableOsc1(obj->clkHandle);
    
      // set the oscillator source
      CLK_setOscSrc(obj->clkHandle,CLK_OscSrc_Internal);
    
      // disable the external clock in
      CLK_disableClkIn(obj->clkHandle);
    
      // disable the crystal oscillator
      CLK_disableCrystalOsc(obj->clkHandle);
    
      // disable oscillator 2
      CLK_disableOsc2(obj->clkHandle);
    
      // set the low speed clock prescaler
      CLK_setLowSpdPreScaler(obj->clkHandle,CLK_LowSpdPreScaler_SysClkOut_by_4);
    
      // set the clock out prescaler
      CLK_setClkOutPreScaler(obj->clkHandle,CLK_ClkOutPreScaler_SysClkOut_by_1);
    
      return;
    } // end of HAL_setupClks() function
    
    
    void HAL_setupFlash(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      FLASH_enablePipelineMode(obj->flashHandle);
    
      FLASH_setNumPagedReadWaitStates(obj->flashHandle,FLASH_NumPagedWaitStates_2);
    
      FLASH_setNumRandomReadWaitStates(obj->flashHandle,FLASH_NumRandomWaitStates_2);
    
      FLASH_setOtpWaitStates(obj->flashHandle,FLASH_NumOtpWaitStates_3);
    
      FLASH_setStandbyWaitCount(obj->flashHandle,FLASH_STANDBY_WAIT_COUNT_DEFAULT);
    
      FLASH_setActiveWaitCount(obj->flashHandle,FLASH_ACTIVE_WAIT_COUNT_DEFAULT);
    
      return;
    } // HAL_setupFlash() function
    
    
    void HAL_setupGpios(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // PWM1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_0,GPIO_0_Mode_EPWM1A);
    
      // PWM2
      GPIO_setMode(obj->gpioHandle,GPIO_Number_1,GPIO_1_Mode_EPWM1B);
    
      // PWM3
      GPIO_setMode(obj->gpioHandle,GPIO_Number_2,GPIO_2_Mode_EPWM2A);
    
      // PWM4
      GPIO_setMode(obj->gpioHandle,GPIO_Number_3,GPIO_3_Mode_EPWM2B);
    
      // PWM5
      GPIO_setMode(obj->gpioHandle,GPIO_Number_4,GPIO_4_Mode_EPWM3A);
    
      // PWM6
      GPIO_setMode(obj->gpioHandle,GPIO_Number_5,GPIO_5_Mode_EPWM3B);
    
      // PWM1-PFC
      GPIO_setMode(obj->gpioHandle,GPIO_Number_6,GPIO_6_Mode_GeneralPurpose);
    
      // PWM2-PFC
      GPIO_setMode(obj->gpioHandle,GPIO_Number_7,GPIO_7_Mode_GeneralPurpose);
    
      // TZ-1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_12,GPIO_12_Mode_TZ1_NOT);
    
      // SPI-SIMO or HALL-2
      GPIO_setMode(obj->gpioHandle,GPIO_Number_16,GPIO_16_Mode_GeneralPurpose);
    
      // SPI-SOMI or HALL-3
      GPIO_setMode(obj->gpioHandle,GPIO_Number_17,GPIO_17_Mode_GeneralPurpose);
    
      // SPI-CLK or SPI-SIMO
      GPIO_setMode(obj->gpioHandle,GPIO_Number_18,GPIO_18_Mode_GeneralPurpose);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_18,GPIO_Direction_Output);
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_18, GPIO_PullUp_Enable);
    
      // SPI-STE or CAP-1/HALL-1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_19,GPIO_19_Mode_GeneralPurpose); //DipSwitch 1
    
      // RX-SLAVE
    //  GPIO_setMode(obj->gpioHandle,GPIO_Number_28,GPIO_28_Mode_GeneralPurpose);
    
      // TX-SLAVE
    //  GPIO_setMode(obj->gpioHandle,GPIO_Number_29,GPIO_29_Mode_GeneralPurpose); //SW1
    
      // I2C-SDA
      GPIO_setMode(obj->gpioHandle,GPIO_Number_32,GPIO_32_Mode_GeneralPurpose);
    
      // I2C-SCL
      GPIO_setMode(obj->gpioHandle,GPIO_Number_33,GPIO_33_Mode_GeneralPurpose);
    
      // ControlCARD LED4
      GPIO_setMode(obj->gpioHandle,GPIO_Number_7,GPIO_7_Mode_GeneralPurpose);
      GPIO_setLow(obj->gpioHandle,GPIO_Number_7);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_7,GPIO_Direction_Output);
    
      // ControlCARD LED3
    /*  GPIO_setMode(obj->gpioHandle,GPIO_Number_28,GPIO_28_Mode_GeneralPurpose);
      GPIO_setLow(obj->gpioHandle,GPIO_Number_28);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_28,GPIO_Direction_Output);
    */
      // JTAG
      GPIO_setMode(obj->gpioHandle,GPIO_Number_35,GPIO_35_Mode_JTAG_TDI);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_36,GPIO_36_Mode_JTAG_TMS);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_37,GPIO_37_Mode_JTAG_TDO);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_38,GPIO_38_Mode_JTAG_TCK);
    
    
      // Setup your GPIOs for SCI
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_28, GPIO_PullUp_Enable);
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_29, GPIO_PullUp_Disable);
    
      GPIO_setQualification(obj->gpioHandle, GPIO_Number_28, GPIO_Qual_ASync);
    
      GPIO_setMode(obj->gpioHandle, GPIO_Number_28, GPIO_28_Mode_SCIRXDA);
      GPIO_setMode(obj->gpioHandle, GPIO_Number_29, GPIO_29_Mode_SCITXDA);
    
      return;
    }  // end of HAL_setupGpios() function
    
    
    void HAL_setupPie(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      PIE_disable(obj->pieHandle);
    
      PIE_disableAllInts(obj->pieHandle);
    
      PIE_clearAllInts(obj->pieHandle);
    
      PIE_clearAllFlags(obj->pieHandle);
    
      PIE_setDefaultIntVectorTable(obj->pieHandle);
    
      PIE_enable(obj->pieHandle);
    
      return;
    } // end of HAL_setupPie() function
    
    
    void HAL_setupPeripheralClks(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CLK_enableAdcClock(obj->clkHandle);
    
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_1);
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_2);
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_3);
    
      CLK_enableEcap1Clock(obj->clkHandle);
    
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_1);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_2);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_3);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_4);
    
      CLK_disableHrPwmClock(obj->clkHandle);
    
      CLK_disableI2cClock(obj->clkHandle);
    
      CLK_enableSciaClock(obj->clkHandle);
    
      CLK_disableSpiaClock(obj->clkHandle);
      
      CLK_enableTbClockSync(obj->clkHandle);
    
      return;
    } // end of HAL_setupPeripheralClks() function
    
    
    void HAL_setupPll(HAL_Handle handle,const PLL_ClkFreq_e clkFreq)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // make sure PLL is not running in limp mode
      if(PLL_getClkStatus(obj->pllHandle) != PLL_ClkStatus_Normal)
        {
          // reset the clock detect
          PLL_resetClkDetect(obj->pllHandle);
    
          // ???????
          asm("        ESTOP0");
        }
    
    
      // Divide Select must be ClkIn/4 before the clock rate can be changed
      if(PLL_getDivideSelect(obj->pllHandle) != PLL_DivideSelect_ClkIn_by_4)
        {
          PLL_setDivideSelect(obj->pllHandle,PLL_DivideSelect_ClkIn_by_4);
        }
    
    
      if(PLL_getClkFreq(obj->pllHandle) != clkFreq)
        {
          // disable the clock detect
          PLL_disableClkDetect(obj->pllHandle);
    
          // set the clock rate
          PLL_setClkFreq(obj->pllHandle,clkFreq);
        }
    
    
      // wait until locked
      while(PLL_getLockStatus(obj->pllHandle) != PLL_LockStatus_Done) {}
    
    
      // enable the clock detect
      PLL_enableClkDetect(obj->pllHandle);
    
    
      // set divide select to ClkIn/2 to get desired clock rate
      // NOTE: clock must be locked before setting this register
      PLL_setDivideSelect(obj->pllHandle,PLL_DivideSelect_ClkIn_by_2);
    
      return;
    } // end of HAL_setupPll() function
    
    
    void HAL_setupPwms(HAL_Handle handle,
                       const uint_least16_t systemFreq_MHz,
                       const float_t pwmPeriod_usec,
                       const uint_least16_t numPwmTicksPerIsrTick)
    {
      HAL_Obj   *obj = (HAL_Obj *)handle;
      uint16_t   halfPeriod_cycles = (uint16_t)((float_t)systemFreq_MHz*pwmPeriod_usec) >> 1;
      uint_least8_t    cnt;
    
    
      // turns off the outputs of the EPWM peripherals which will put the power switches
      // into a high impedance state.
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_1]);
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_2]);
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_3]);
    
      for(cnt=0;cnt<3;cnt++)
        {
          // setup the Time-Base Control Register (TBCTL)
          PWM_setCounterMode(obj->pwmHandle[cnt],PWM_CounterMode_UpDown);
          PWM_disableCounterLoad(obj->pwmHandle[cnt]);
          PWM_setPeriodLoad(obj->pwmHandle[cnt],PWM_PeriodLoad_Immediate);
          PWM_setSyncMode(obj->pwmHandle[cnt],PWM_SyncMode_EPWMxSYNC);
          PWM_setHighSpeedClkDiv(obj->pwmHandle[cnt],PWM_HspClkDiv_by_1);
          PWM_setClkDiv(obj->pwmHandle[cnt],PWM_ClkDiv_by_1);
          PWM_setPhaseDir(obj->pwmHandle[cnt],PWM_PhaseDir_CountUp);
          PWM_setRunMode(obj->pwmHandle[cnt],PWM_RunMode_FreeRun);
    
          // setup the Timer-Based Phase Register (TBPHS)
          PWM_setPhase(obj->pwmHandle[cnt],0);
    
          // setup the Time-Base Counter Register (TBCTR)
          PWM_setCount(obj->pwmHandle[cnt],0);
    
          // setup the Time-Base Period Register (TBPRD)
          // set to zero initially
          PWM_setPeriod(obj->pwmHandle[cnt],0);
    
          // setup the Counter-Compare Control Register (CMPCTL)
          PWM_setLoadMode_CmpA(obj->pwmHandle[cnt],PWM_LoadMode_Zero);
          PWM_setLoadMode_CmpB(obj->pwmHandle[cnt],PWM_LoadMode_Zero);
          PWM_setShadowMode_CmpA(obj->pwmHandle[cnt],PWM_ShadowMode_Shadow);
          PWM_setShadowMode_CmpB(obj->pwmHandle[cnt],PWM_ShadowMode_Immediate);
    
          // setup the Action-Qualifier Output A Register (AQCTLA) 
          PWM_setActionQual_CntUp_CmpA_PwmA(obj->pwmHandle[cnt],PWM_ActionQual_Set);
          PWM_setActionQual_CntDown_CmpA_PwmA(obj->pwmHandle[cnt],PWM_ActionQual_Clear);
    
          // setup the Dead-Band Generator Control Register (DBCTL)
          PWM_setDeadBandOutputMode(obj->pwmHandle[cnt],PWM_DeadBandOutputMode_EPWMxA_Rising_EPWMxB_Falling);
          PWM_setDeadBandPolarity(obj->pwmHandle[cnt],PWM_DeadBandPolarity_EPWMxB_Inverted);
    
          // setup the Dead-Band Rising Edge Delay Register (DBRED)
          PWM_setDeadBandRisingEdgeDelay(obj->pwmHandle[cnt],HAL_PWM_DBRED_CNT);
    
          // setup the Dead-Band Falling Edge Delay Register (DBFED)
          PWM_setDeadBandFallingEdgeDelay(obj->pwmHandle[cnt],HAL_PWM_DBFED_CNT);
          // setup the PWM-Chopper Control Register (PCCTL)
          PWM_disableChopping(obj->pwmHandle[cnt]);
    
          // setup the Trip Zone Select Register (TZSEL)
          PWM_disableTripZones(obj->pwmHandle[cnt]);
        }
    
    
      // setup the Event Trigger Selection Register (ETSEL)
      PWM_disableInt(obj->pwmHandle[PWM_Number_1]);
      PWM_setSocAPulseSrc(obj->pwmHandle[PWM_Number_1],PWM_SocPulseSrc_CounterEqualZero);
      PWM_enableSocAPulse(obj->pwmHandle[PWM_Number_1]);
      
    
      // setup the Event Trigger Prescale Register (ETPS)
      if(numPwmTicksPerIsrTick == 3)
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_ThirdEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_ThirdEvent);
        }
      else if(numPwmTicksPerIsrTick == 2)
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_SecondEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_SecondEvent);
        }
      else
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_FirstEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_FirstEvent);
        }
    
    
      // setup the Event Trigger Clear Register (ETCLR)
      PWM_clearIntFlag(obj->pwmHandle[PWM_Number_1]);
      PWM_clearSocAFlag(obj->pwmHandle[PWM_Number_1]);
    
      // first step to synchronize the pwms
      CLK_disableTbClockSync(obj->clkHandle);
    
      // since the PWM is configured as an up/down counter, the period register is set to one-half 
      // of the desired PWM period
      PWM_setPeriod(obj->pwmHandle[PWM_Number_1],halfPeriod_cycles);
      PWM_setPeriod(obj->pwmHandle[PWM_Number_2],halfPeriod_cycles);
      PWM_setPeriod(obj->pwmHandle[PWM_Number_3],halfPeriod_cycles);
    
      // last step to synchronize the pwms
      CLK_enableTbClockSync(obj->clkHandle);
    
      return;
    }  // end of HAL_setupPwms() function
    
    
    void HAL_setupTimers(HAL_Handle handle,const uint_least16_t systemFreq_MHz)
    {
      HAL_Obj  *obj = (HAL_Obj *)handle;
      uint32_t  timerPeriod_cnts = ((uint32_t)systemFreq_MHz * 1000000) - 1;
    
      // use timer 0 for frequency diagnostics
      TIMER_setDecimationFactor(obj->timerHandle[0],0);
      TIMER_setEmulationMode(obj->timerHandle[0],TIMER_EmulationMode_RunFree);
      TIMER_setPeriod(obj->timerHandle[0],timerPeriod_cnts);
      TIMER_setPreScaler(obj->timerHandle[0],0);
    
      // use timer 1 for CPU usage diagnostics
      TIMER_setDecimationFactor(obj->timerHandle[1],0);
      TIMER_setEmulationMode(obj->timerHandle[1],TIMER_EmulationMode_RunFree);
      TIMER_setPeriod(obj->timerHandle[1],timerPeriod_cnts);
      TIMER_setPreScaler(obj->timerHandle[1],0);
    
      return;
    }  // end of HAL_setupTimers() function
    
    
    // end of file
    

    8507.proj_lab05b.c
    /* --COPYRIGHT--,BSD
     * Copyright (c) 2012, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  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.
     *
     * *  Neither the name of Texas Instruments Incorporated 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 OWNER 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.
     * --/COPYRIGHT--*/
    //! \file   solutions/instaspin_foc/src/proj_lab05b.c
    //! \brief Adjusting the speed current controller
    //!
    //! (C) Copyright 2011, Texas Instruments, Inc.
    
    //! \defgroup PROJ_LAB05b PROJ_LAB05b
    //@{
    
    //! \defgroup PROJ_LAB05b_OVERVIEW Project Overview
    //!
    //! Adjusting the supplied speed controller
    //!
    
    // **************************************************************************
    // the includes
    
    // system includes
    #include <math.h>
    #include "main.h"
    
    #ifdef FLASH
    #pragma CODE_SECTION(mainISR,"ramfuncs");
    #endif
    
    // Include header files used in the main function
    
    
    // **************************************************************************
    // the defines
    
    #define LED_BLINK_FREQ_Hz   5
    
    // **************************************************************************
    // the globals
    
    uint_least16_t gCounter_updateGlobals = 0;
    
    bool Flag_Latch_softwareUpdate = true;
    
    CTRL_Handle ctrlHandle;
    
    HAL_Handle halHandle;
    
    USER_Params gUserParams;
    
    HAL_PwmData_t gPwmData = {_IQ(0.0), _IQ(0.0), _IQ(0.0)};
    
    HAL_AdcData_t gAdcData;
    
    _iq gMaxCurrentSlope = _IQ(0.0);
    
    // Novas vari�veis
    
    bool flagTeste = 0;
    
    bool gSW1;	//push button
    
    bool Flag_button = 0;
    
    double_t x = 0;		// "encoder digital" - contagem de voltas
    double_t y = 0;		// deslocamento
    double_t t = 600;	// n� de voltas
    double_t w = 250;	// abrandamento
    double_t q = 0;
    
    _iq defVel = _IQ(1.4);
    uint32_t tempo = 0;
    uint16_t count_press_run = 0;
    uint16_t count_press_stop = 0;
    uint32_t count_flag_button = 0;
    uint16_t debounce_bt = 0;
    
    
    // ---------------------	SCI		-----------------------------------
    // Prototype statements for functions found within this file.
    
    void scia_xmit(int a);
    
    // Global counts used in this example
    
    uint16_t inc = 0;
    uint16_t encoderTipoLeitura = 0;
    uint16_t msgRXInc[3] = {0, 0, 0};
    uint16_t msgRXDec[3] = {0, 0, 0};
    uint16_t cospelampada;
    
    
    ADC_Handle adcHandle;
    CLK_Handle clkHandle;
    GPIO_Handle gpioHandle;
    SCI_Handle sciaHandle;
    PIE_Handle pieHandle;
    CPU_Handle cpuHandle;
    PLL_Handle pllHandle;
    
    //		    --------------------	x	------------------
    
    #ifdef FAST_ROM_V1p6
    CTRL_Obj *controller_obj;
    #else
    CTRL_Obj ctrl;				//v1p7 format
    #endif
    
    uint16_t gLEDcnt = 0;
    
    volatile MOTOR_Vars_t gMotorVars = MOTOR_Vars_INIT;
    
    #ifdef FLASH
    // Used for running BackGround in flash, and ISR in RAM
    extern uint16_t *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;
    #endif
    
    
    #ifdef DRV8301_SPI
    // Watch window interface to the 8301 SPI
    DRV_SPI_8301_Vars_t gDrvSpi8301Vars;
    #endif
    
    _iq gFlux_pu_to_Wb_sf;
    
    _iq gFlux_pu_to_VpHz_sf;
    
    _iq gTorque_Ls_Id_Iq_pu_to_Nm_sf;
    
    _iq gTorque_Flux_Iq_pu_to_Nm_sf;
    
    // **************************************************************************
    // the functions
    
    void main(void)
    
    {
    
    // --------------------------------SCI------------------------------------------------
    
    	  HAL_setupSCI(halHandle);
    
        // Interrupts that are used in this example are re-mapped to
        // ISR functions found within this file.
            EALLOW;    // This is needed to write to EALLOW protected registers
        //   PieVectTable.SCIRXINTA = &sciaRxFifoIsr;
            ((PIE_Obj *)pieHandle)->SCIRXINTA = &sciaRxFifoIsr;
        //   PieVectTable.SCITXINTA = &sciaTxFifoIsr;
        //    ((PIE_Obj *)myPie)->SCITXINTA = &sciaTxFifoIsr;
            EDIS;   // This is needed to disable write to EALLOW protected registers
    
    	// Register interrupt handlers in the PIE vector table
    	PIE_registerPieIntHandler(pieHandle, PIE_GroupNumber_9, PIE_SubGroupNumber_1, (intVec_t)&sciaRxFifoIsr);
    
    // ---------------------------------x--------------------------------------------------
    
      uint_least8_t estNumber = 0;
    
    #ifdef FAST_ROM_V1p6
      uint_least8_t ctrlNumber = 0;
    #endif
    
      // Only used if running from FLASH
      // Note that the variable FLASH is defined by the project
      #ifdef FLASH
      // Copy time critical code and Flash setup code to RAM
      // The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
      // symbols are created by the linker. Refer to the linker files.
      memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart);
      #endif
    
      // initialize the hardware abstraction layer
      halHandle = HAL_init(&hal,sizeof(hal));
    
    
      // check for errors in user parameters
      USER_checkForErrors(&gUserParams);
    
    
      // store user parameter error in global variable
      gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams);
    
    
      // do not allow code execution if there is a user parameter error
      if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError)
        {
          for(;;)
            {
              gMotorVars.Flag_enableSys = false;
            }
        }
    
    
      // initialize the user parameters
      USER_setParams(&gUserParams);
    
    
      // set the hardware abstraction layer parameters
      HAL_setParams(halHandle,&gUserParams);
    
    
      // initialize the controller
    #ifdef FAST_ROM_V1p6
      ctrlHandle = CTRL_initCtrl(ctrlNumber, estNumber);  		//v1p6 format (06xF and 06xM devices)
      controller_obj = (CTRL_Obj *)ctrlHandle;
    #else
      ctrlHandle = CTRL_initCtrl(estNumber,&ctrl,sizeof(ctrl));	//v1p7 format default
    #endif
    
    
      {
        CTRL_Version version;
    
        // get the version number
        CTRL_getVersion(ctrlHandle,&version);
    
        gMotorVars.CtrlVersion = version;
      }
    
    
      // set the default controller parameters
      CTRL_setParams(ctrlHandle,&gUserParams);
    
    
      // setup faults
      HAL_setupFaults(halHandle);
    
    
      // initialize the interrupt vector table
      HAL_initIntVectorTable(halHandle);
    
    
      // enable the ADC interrupts
      HAL_enableAdcInts(halHandle);
    
    
      // enable global interrupts
      HAL_enableGlobalInts(halHandle);
    
    
      // enable debug interrupts
      HAL_enableDebugInt(halHandle);
    
    
      // disable the PWM
      HAL_disablePwm(halHandle);
    
    
    #ifdef DRV8301_SPI
      // turn on the DRV8301 if present
      HAL_enableDrv(halHandle);
      // initialize the DRV8301 interface
      HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars);
    #endif
    
    
      // enable DC bus compensation
      CTRL_setFlag_enableDcBusComp(ctrlHandle, true);
    
    
      // compute scaling factors for flux and torque calculations
      gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf();
      gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf();
      gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf();
      gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf();
    
    
      for(;;)
       {
    
    	  HAL_setupSCI(halHandle);
    //      -----------------   Encoder  -----------------------
    
    		GPIO_setHigh(gpioHandle, GPIO_Number_18);
    
    		usDelay(2000);
    
    		scia_xmit(0xA2);
    
    		if(encoderTipoLeitura == 0)
    		{
    			scia_xmit(0xB0);
    		}
    		else
    		{
    			scia_xmit(0xB3);
    		}
    
    		//scia_xmit(0x00);
    
    		while(SCI_getTxFifoStatus(sciaHandle) != SCI_FifoStatus_Empty);
    
    		while(SCI_txReady(sciaHandle) == 0);
    
    		while(SCI_isTxEmpty(sciaHandle) == 0);
    
    	//	inc = 0;
    
    		usDelay (1000);
    
    		GPIO_setLow(gpioHandle, GPIO_Number_18);
    
    		usDelay(50000);
    
    		if(encoderTipoLeitura == 0)
    		{
    			encoderTipoLeitura = 1;
    		}
    		else
    		{
    			encoderTipoLeitura = 0;
    
    			usDelay(50000);
    		}
    
    //     --------------------------------x--------------------------
    
         // Waiting for enable system flag to be set
         while(!(gMotorVars.Flag_enableSys))
         {
        	gSW1 = HAL_readGpio(halHandle, HAL_GPIO_SW1);	//Iniciar o sistema atrav�s do bSW1
         	if(gSW1 == 0 && Flag_button == 0)
         	{
         		tempo = 10000;
         		Flag_button = 1;
         		gMotorVars.Flag_enableSys = 1;		//Inicia o sistema
         		gMotorVars.Flag_Run_Identify = 1;	//Arranca com o programa
         	}
          }
    
         // loop while the enable system flag is true
         while(gMotorVars.Flag_enableSys)
         {
        	 //Usar o bot�o 1 (SW1) para parar e reiniciar o programa
        	 if(tempo == 0)
         	 {
        		 tempo = 100;
    
        		 gSW1 = HAL_readGpio(halHandle, HAL_GPIO_SW1);
    
         		if(Flag_button == 1)
         		{
         			if(gSW1 == 0)
         			{
         				debounce_bt++;
    
         				if(debounce_bt >= 10)
         				{
         					if(gMotorVars.Flag_Run_Identify == 0)
     						{
     							gMotorVars.Flag_Run_Identify = 1;
     							count_press_run ++;
     						}
     						else
     						{
     							gMotorVars.Flag_Run_Identify = 0;
     							count_press_stop ++;
     						}
    
         					Flag_button = 2;
         				}
         			}
         			else
         			{
         				debounce_bt = 0;
         			}
         		}
         		else if(Flag_button == 2)
         		{
         			if(gSW1 == 1)
         			{
         				count_flag_button ++;
    
         				Flag_button = 1;
         			}
         		}
         	}
    
    
    
            CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle;
    
            // increment counters
            gCounter_updateGlobals++;
    
            // enable/disable the use of motor parameters being loaded from user.h
            CTRL_setFlag_enableUserMotorParams(ctrlHandle,gMotorVars.Flag_enableUserParams);
    
            // enable/disable Rs recalibration during motor startup
            EST_setFlag_enableRsRecalc(obj->estHandle,gMotorVars.Flag_enableRsRecalc);
    
            // enable/disable automatic calculation of bias values
            CTRL_setFlag_enableOffset(ctrlHandle,gMotorVars.Flag_enableOffsetcalc);
    
    
            if(CTRL_isError(ctrlHandle))
              {
                // set the enable controller flag to false
                CTRL_setFlag_enableCtrl(ctrlHandle,false);
    
                // set the enable system flag to false
                gMotorVars.Flag_enableSys = false;
    
                // disable the PWM
                HAL_disablePwm(halHandle);
              }
            else
              {
                // update the controller state
                bool flag_ctrlStateChanged = CTRL_updateState(ctrlHandle);
    
                // enable or disable the control
                CTRL_setFlag_enableCtrl(ctrlHandle, gMotorVars.Flag_Run_Identify);
    
                if(flag_ctrlStateChanged)
                  {
                    CTRL_State_e ctrlState = CTRL_getState(ctrlHandle);
    
                    if(ctrlState == CTRL_State_OffLine)
                      {
                        // enable the PWM
                        HAL_enablePwm(halHandle);
                      }
                    else if(ctrlState == CTRL_State_OnLine)
                      {
                        if(gMotorVars.Flag_enableOffsetcalc == true)
                        {
                          // update the ADC bias values
                          HAL_updateAdcBias(halHandle);
                        }
                        else
                        {
                          // set the current bias
                          HAL_setBias(halHandle,HAL_SensorType_Current,0,_IQ(I_A_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Current,1,_IQ(I_B_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Current,2,_IQ(I_C_offset));
    
                          // set the voltage bias
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,0,_IQ(V_A_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,1,_IQ(V_B_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,2,_IQ(V_C_offset));
                        }
    
                        // Return the bias value for currents
                        gMotorVars.I_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Current,0);
                        gMotorVars.I_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Current,1);
                        gMotorVars.I_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Current,2);
    
                        // Return the bias value for voltages
                        gMotorVars.V_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Voltage,0);
                        gMotorVars.V_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Voltage,1);
                        gMotorVars.V_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Voltage,2);
    
                        // enable the PWM
                        HAL_enablePwm(halHandle);
                      }
                    else if(ctrlState == CTRL_State_Idle)
                      {
                        // disable the PWM
                        HAL_disablePwm(halHandle);
                        gMotorVars.Flag_Run_Identify = false;
                      }
    
                    if((CTRL_getFlag_enableUserMotorParams(ctrlHandle) == true) &&
                      (ctrlState > CTRL_State_Idle) &&
                      (gMotorVars.CtrlVersion.minor == 6))
                      {
                        // call this function to fix 1p6
                        USER_softwareUpdate1p6(ctrlHandle);
                      }
    
                  }
              }
    
    
            if(EST_isMotorIdentified(obj->estHandle))
              {
                // set the current ramp
                EST_setMaxCurrentSlope_pu(obj->estHandle,gMaxCurrentSlope);
                gMotorVars.Flag_MotorIdentified = true;
    
                // set the speed reference
                CTRL_setSpd_ref_krpm(ctrlHandle,gMotorVars.SpeedRef_krpm);
    
                // usando o Pot 1 para regular a velocidade
                gMotorVars.SpeedRef_krpm = _IQmpy( gAdcData.potentiometer, CTRL_getMaximumSpeed_pu(ctrlHandle) );
    
                // set the speed acceleration
                CTRL_setMaxAccel_pu(ctrlHandle,_IQmpy(MAX_ACCEL_KRPMPS_SF,gMotorVars.MaxAccel_krpmps));
                if(Flag_Latch_softwareUpdate)
                {
                  Flag_Latch_softwareUpdate = false;
    
                  USER_calcPIgains(ctrlHandle);
    
                  // initialize the watch window kp and ki current values with pre-calculated values
                  gMotorVars.Kp_Idq = CTRL_getKp(ctrlHandle,CTRL_Type_PID_Id);
                  gMotorVars.Ki_Idq = CTRL_getKi(ctrlHandle,CTRL_Type_PID_Id);
    
                  // initialize the watch window kp and ki values with pre-calculated values
                  gMotorVars.Kp_spd = CTRL_getKp(ctrlHandle,CTRL_Type_PID_spd);
                  gMotorVars.Ki_spd = CTRL_getKi(ctrlHandle,CTRL_Type_PID_spd);
                }
    
              }
            else
              {
                Flag_Latch_softwareUpdate = true;
    
                // the estimator sets the maximum current slope during identification
                gMaxCurrentSlope = EST_getMaxCurrentSlope_pu(obj->estHandle);
              }
    
    
            // when appropriate, update the global variables
            if(gCounter_updateGlobals >= NUM_MAIN_TICKS_FOR_GLOBAL_VARIABLE_UPDATE)
              {
                // reset the counter
                gCounter_updateGlobals = 0;
    
                updateGlobalVariables_motor(ctrlHandle);
              }
    
    
            // update Kp and Ki gains
            updateKpKiGains(ctrlHandle);
    
            // enable/disable the forced angle
            EST_setFlag_enableForceAngle(obj->estHandle,gMotorVars.Flag_enableForceAngle);
    
            // enable or disable power warp
            CTRL_setFlag_enablePowerWarp(ctrlHandle,gMotorVars.Flag_enablePowerWarp);
    
    #ifdef DRV8301_SPI
            HAL_writeDrvData(halHandle,&gDrvSpi8301Vars);
    
            HAL_readDrvData(halHandle,&gDrvSpi8301Vars);
    #endif
    
          } // end of while(gFlag_enableSys) loop
    
    
        // disable the PWM
        HAL_disablePwm(halHandle);
    
        // set the default controller parameters (Reset the control to re-identify the motor)
        CTRL_setParams(ctrlHandle,&gUserParams);
        gMotorVars.Flag_Run_Identify = false;
    
      } // end of for(;;) loop
    
    } // end of main() function
    
    
    interrupt void mainISR(void)
    {
    	gMotorVars.Flag_enableOffsetcalc = 0;	// desabilitar o calculo dos offsets
    
    	//Debounce botao
    
    	if(tempo > 0)
    	  {
    
    		  tempo--;
    	  }
    
    
    	/*
    	// "Encoder digital"
    
    	gMotorVars.Flag_enableOffsetcalc = 0;	// desabilitar o calculo dos offsets
    //	gMotorVars.SpeedRef_krpm = _IQ(1.5);
      // toggle status LED
    //	if(gLEDcnt++ > 100 && gMotorVars.Flag_Run_Identify == 1 && _IQ(gMotorVars.Speed_krpm) >= 1400)
    	if (gMotorVars.Flag_Run_Identify == 1)
    	{
    		if(++gLEDcnt >= 100) 	 //&& gMotorVars.Speed_krpm >= 23488094)
    			{
    				HAL_toggleLed(halHandle,(GPIO_Number_e)HAL_Gpio_LED3);
    				gLEDcnt = 0;
    
    				//y = (float_t) (( (z) * (float_t) (1000) ) / (float_t) (600) ));
    
    				y = (double_t)((gMotorVars.Speed_krpm /(double_t) 16777.216)/(double_t) 6000);	// faz a conta das rpms...
    
    				//(long) ((0.0) * 16777216.0L)
    
    				x += y;// incrementa variavel (contagem global -> x )...
    */
    /*				if(q == 0)
    				{
    					if(x >= t)
    					{
    						gMotorVars.SpeedRef_krpm = _IQ(0.0);
    						q = 1;
    					}
    				}
    				else if (q == 1)
    				{
    					if(gMotorVars.Speed_krpm <= _IQ(0.0))
    					{
    						//x = 0;
    						q = 2;
    						delaycnt = 0;
    					}
    				}
    				else if (q == 2)
    				{
    					if(delaycnt > 100)
    					{
    						gMotorVars.SpeedRef_krpm = _IQ(-0.8);
    						q=3;
    					}
    					delaycnt ++;
    				}
    
    
    				if (x <= z  && q == 3)
    				{
    					gMotorVars.SpeedRef_krpm = _IQ(-0.2);
    
    					if (x < 0)
    					{
    						gMotorVars.Flag_Run_Identify = 0;
    						x = 0;
    						y = 0;
    						q = 0;
    					}
    				}
    */
    /*				if (flagTeste == 0)
    				{
    					gMotorVars.SpeedRef_krpm = defVel;
    				}
    */
    /*
    				if(x > t-w && flagTeste == 0)
    				{
    					gMotorVars.SpeedRef_krpm = _IQ(0.2);
    					flagTeste = 1;
    				}
    
    				if (x > t)
    				{
    					//gMotorVars.SpeedRef_krpm = _IQ(0.0);
    					x = 0;
    					y = 0;
    					gMotorVars.Flag_Run_Identify = 0; // desliga a flag do motr
    					flagTeste = 0;
    					//q = 0;
    				}
    			}
    		}
    */
    
    
      // acknowledge the ADC interrupt
      HAL_acqAdcInt(halHandle,ADC_IntNumber_1);
    
    
      // convert the ADC data
      HAL_readAdcData(halHandle,&gAdcData);
    
    
      // run the controller
      CTRL_run(ctrlHandle,halHandle,&gAdcData,&gPwmData);
    
    
      // write the PWM compare values
      HAL_writePwmData(halHandle,&gPwmData);
    
    
      // setup the controller
      CTRL_setup(ctrlHandle);
    
    
      return;
    } // end of mainISR() function
    
    
    // -----------------------------SCI------------------------------
    
    interrupt void sciaRxFifoIsr(void)
    {
    	if(inc < 3)
    		{
    
    		if(encoderTipoLeitura == 0)
    			{
    				msgRXDec[inc] = SCI_read(sciaHandle);
    
    			}
    
    			else
    			{
    				msgRXInc[inc] = SCI_read(sciaHandle);
    
    			}
    
    			inc++;
    
    		}
    
    	// Clear Overflow flag
    	SCI_clearRxFifoOvf(sciaHandle);
    
    	// Clear Interrupt flag
    	SCI_clearRxFifoInt(sciaHandle);
    
    	// Issue PIE ack
    	PIE_clearInt(pieHandle, PIE_GroupNumber_9);
    
    	return;
    }
    
    
    // Transmit a character from the SCI
    void scia_xmit(int a)
    {
    //    while (SciaRegs.SCIFFTX.bit.TXFFST != 0) {}
        while(SCI_getTxFifoStatus(sciaHandle) != SCI_FifoStatus_Empty);
    
    //    SciaRegs.SCITXBUF=a;
        SCI_putDataBlocking(sciaHandle, a);
    
    //    SCI_write(sciaHandle, a);
    
    }
    
    // ----------------------------- x ------------------------------
    
    void updateGlobalVariables_motor(CTRL_Handle handle)
    {
      CTRL_Obj *obj = (CTRL_Obj *)handle;
    
      // get the speed estimate
      gMotorVars.Speed_krpm = EST_getSpeed_krpm(obj->estHandle);
    
      // get the real time speed reference coming out of the speed trajectory generator
      gMotorVars.SpeedTraj_krpm = _IQmpy(CTRL_getSpd_int_ref_pu(handle),EST_get_pu_to_krpm_sf(obj->estHandle));
    
      // get the torque estimate
      gMotorVars.Torque_Nm = USER_computeTorque_Nm(handle, gTorque_Flux_Iq_pu_to_Nm_sf, gTorque_Ls_Id_Iq_pu_to_Nm_sf);
    
      // get the magnetizing current
      gMotorVars.MagnCurr_A = EST_getIdRated(obj->estHandle);
    
      // get the rotor resistance
      gMotorVars.Rr_Ohm = EST_getRr_Ohm(obj->estHandle);
    
      // get the stator resistance
      gMotorVars.Rs_Ohm = EST_getRs_Ohm(obj->estHandle);
    
      // get the stator inductance in the direct coordinate direction
      gMotorVars.Lsd_H = EST_getLs_d_H(obj->estHandle);
    
      // get the stator inductance in the quadrature coordinate direction
      gMotorVars.Lsq_H = EST_getLs_q_H(obj->estHandle);
    
      // get the flux in V/Hz in floating point
      gMotorVars.Flux_VpHz = EST_getFlux_VpHz(obj->estHandle);
    
      // get the flux in Wb in fixed point
      gMotorVars.Flux_Wb = USER_computeFlux(handle, gFlux_pu_to_Wb_sf);
    
      // get the controller state
      gMotorVars.CtrlState = CTRL_getState(handle);
    
      // get the estimator state
      gMotorVars.EstState = EST_getState(obj->estHandle);
    
      // Get the DC buss voltage
      gMotorVars.VdcBus_kV = _IQmpy(gAdcData.dcBus,_IQ(USER_IQ_FULL_SCALE_VOLTAGE_V/1000.0));
    
      return;
    } // end of updateGlobalVariables_motor() function
    
    
    void updateKpKiGains(CTRL_Handle handle)
    {
      if((gMotorVars.CtrlState == CTRL_State_OnLine) && (gMotorVars.Flag_MotorIdentified == true) && (Flag_Latch_softwareUpdate == false))
        {
          // set the kp and ki speed values from the watch window
          CTRL_setKp(handle,CTRL_Type_PID_spd,gMotorVars.Kp_spd);
          CTRL_setKi(handle,CTRL_Type_PID_spd,gMotorVars.Ki_spd);
    
          // set the kp and ki current values for Id and Iq from the watch window
          CTRL_setKp(handle,CTRL_Type_PID_Id,gMotorVars.Kp_Idq);
          CTRL_setKi(handle,CTRL_Type_PID_Id,gMotorVars.Ki_Idq);
          CTRL_setKp(handle,CTRL_Type_PID_Iq,gMotorVars.Kp_Idq);
          CTRL_setKi(handle,CTRL_Type_PID_Iq,gMotorVars.Ki_Idq);
    	}
    
      return;
    } // end of updateKpKiGains() function
    
    //@} //defgroup
    // end of file
    
    
    
    

    Do you know if exists any tutorial about config the API on motorware or another important tutorial? Thanks a lot.


    BR,
    Bruno Ramos

  • Hello Bruno,

    Bruno Ramos1 said:
    Do you know if exists any tutorial about config the API on motorware or another important tutorial?

    Please refer to this thread: http://e2e.ti.com/support/microcontrollers/c2000/f/902/t/347563.aspx

    This document has not contained SCI yet, but maybe by following other example, you can get the sense how to modify hal.c.

    I will check your files and will give you feedback when I am ready.

    Best regards,

    Maria

  • Hello Bruno,

    I have checked your files and modified them (please see comment with 'maria' inside the files)

    4162.3441.hal.c
    /* --COPYRIGHT--,BSD
     * Copyright (c) 2012, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  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.
     *
     * *  Neither the name of Texas Instruments Incorporated 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 OWNER 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.
     * --/COPYRIGHT--*/
    //! \file   solutions/instaspin_foc/boards/hvkit_rev1p1/f28x/f2802xF/src/hal.c
    //! \brief Contains the various functions related to the HAL object (everything outside the CTRL system) 
    //!
    //! (C) Copyright 2011, Texas Instruments, Inc.
    
    
    // **************************************************************************
    // the includes
    
    // drivers
    
    // modules
    
    // platforms
    #include "hal.h"
    #include "user.h"
    #include "hal_obj.h"
    
    //Added
    #include "sw/drivers/sci/src/32b/f28x/f2802x/sci.c"
    #include "sw/drivers/pie/src/32b/f28x/f2802x/pie.h"
    
    #ifdef FLASH
    #pragma CODE_SECTION(HAL_setupFlash,"ramfuncs");
    #endif
    
    // **************************************************************************
    // the defines
    
    
    // **************************************************************************
    // the globals
    
    HAL_Obj hal;
    
    
    // **************************************************************************
    // the functions
    
    //Added
    
    void HAL_setupSCI(HAL_Handle handle) {
        HAL_Obj *obj = (HAL_Obj *) handle;
    
        //CLK_enableSciaClock(obj->clkHandle); // no need to call again, already set in HAL_setupPeripheralClks() -maria-
    
        // SCI stop bit, parity, loopback, char bits, idle/address mode (SCICCR = 0x07)
        SCI_setNumStopBits(obj->sciaHandle, SCI_NumStopBits_One);    // SCICCR bit 7
        SCI_enableParity(obj->sciaHandle);                                               // SCICCR bit 5
        SCI_setParity(obj->sciaHandle, SCI_Parity_Even);                          // SCICCR bit 6
        SCI_disableLoopBack(obj->sciaHandle);                                        // SCICCR bit 4
        SCI_setMode(obj->sciaHandle, SCI_Mode_IdleLine);                     // SCICCR bit 3
        SCI_setCharLength(obj->sciaHandle, SCI_CharLength_8_Bits);   // SCICCR bit 0-2
    
        // TX enable, RX enable, RX ERR INT enable, SLEEP, TXWAKE (SCICTL1 = 0x03)
        SCI_disableRxErrorInt(obj->sciaHandle);                        // SCICTL1 bit 6
        SCI_disable(obj->sciaHandle);                                        // SCICTL1 bit 5
        SCI_disableTxWake(obj->sciaHandle);                           // SCICTL1 bit 3
        SCI_disableSleep(obj->sciaHandle);                              // SCICTL1 bit 2
        SCI_enableTx(obj->sciaHandle);                                    // SCICTL1 bit 1
        SCI_enableRx(obj->sciaHandle);                                    // SCICTL1 bit 0
    
    	// TXINT enable, RXINT enable, TXEMPTY, TXRDY (SCICTL2 = 0x03)
    	SCI_enableRxInt(obj->sciaHandle);                            // SCICTL2 bit 1
    	SCI_disableTxInt(obj->sciaHandle);                            // SCICTL2 bit 0
    
    	// SCIH-SCIL BAUD - SCI_BAUD = (LSPCLK/(SCI_BRR*8)) - 1
    	SCI_setBaudRate(obj->sciaHandle, SCI_BaudRate_9_6_kBaud);
    
    	// Reset SCI
    	SCI_enable(obj->sciaHandle);
    
    	//  PIE_enableSciInt(obj->pieHandle, SCI_RXA);                 // enable SCI interrupt
    	PIE_enableInt(obj->pieHandle, PIE_GroupNumber_9, PIE_InterruptSource_SCIARX);
    
    	//CPU_enableGlobalInts(obj->cpuHandle); // no need to call again -maria-
    	CPU_enableInt(obj->cpuHandle, CPU_IntNumber_9);    // enable CPU interrupt
    
    	SCI_resetTxFifo(obj->sciaHandle);
    	SCI_clearTxFifoInt(obj->sciaHandle);
    	SCI_resetChannels(obj->sciaHandle);
    	SCI_setTxFifoIntLevel(obj->sciaHandle, SCI_FifoLevel_Empty);
    
    	SCI_resetRxFifo(obj->sciaHandle);
    	SCI_clearRxFifoInt(obj->sciaHandle);
    	//    SCI_setRxFifoIntLevel(mySci, SCI_FifoLevel_4_Words);
    	SCI_setRxFifoIntLevel(obj->sciaHandle, SCI_FifoLevel_1_Word);
    	//SCI_disableLoopBack(obj->sciaHandle);
    
    }
    
    //Added by Maya
    void HAL_sciaWrite(HAL_Handle handle, const uint16_t data) {
    	HAL_Obj *obj = (HAL_Obj *) handle;
    
    	SCI_write(obj->sciaHandle, data);
    }
    //SCI
    
    
    void HAL_cal(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable the ADC clock
      CLK_enableAdcClock(obj->clkHandle);
    
    
      // Run the Device_cal() function
      // This function copies the ADC and oscillator calibration values from TI reserved
      // OTP into the appropriate trim registers
      // This boot ROM automatically calls this function to calibrate the interal 
      // oscillators and ADC with device specific calibration data.
      // If the boot ROM is bypassed by Code Composer Studio during the development process,
      // then the calibration must be initialized by the application
      ENABLE_PROTECTED_REGISTER_WRITE_MODE;
      (*Device_cal)();
      DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
      // run offsets calibration in user's memory
      HAL_AdcOffsetSelfCal(handle);
    
      // run oscillator compensation
      HAL_OscTempComp(handle);
    
      // disable the ADC clock
      CLK_disableAdcClock(obj->clkHandle);
    
      return;
    } // end of HAL_cal() function
    
    
    void HAL_OscTempComp(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t Temperature;
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
      // set the ADC voltage reference source to internal
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
      // Set main clock scaling factor (max45MHz clock for the ADC module)
      ADC_setDivideSelect(obj->adcHandle,ADC_DivideSelect_ClkIn_by_2);
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
      // enable non-overlap mode
      ADC_enableNoOverlapMode(obj->adcHandle);
    
      // connect channel A5 internally to the temperature sensor
      ADC_setTempSensorSrc(obj->adcHandle, ADC_TempSensorSrc_Int);
    
      // set SOC0 channel select to ADCINA5
      ADC_setSocChanNumber(obj->adcHandle, ADC_SocNumber_0, ADC_SocChanNumber_A5);
    
      // set SOC0 acquisition period to 26 ADCCLK
      ADC_setSocSampleDelay(obj->adcHandle, ADC_SocNumber_0, ADC_SocSampleDelay_64_cycles);
    
      // connect ADCINT1 to EOC0
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_1, ADC_IntSrc_EOC0);
    
      // clear ADCINT1 flag
      ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
      // enable ADCINT1
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_1);
    
      // force start of conversion on SOC0
      ADC_setSocFrc(obj->adcHandle, ADC_SocFrc_0);
    
      // wait for end of conversion
      while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_1) == 0){}
    
      // clear ADCINT1 flag
      ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
      Temperature = ADC_readResult(obj->adcHandle, ADC_ResultNumber_0);
    
      HAL_osc1Comp(handle, Temperature);
    
      HAL_osc2Comp(handle, Temperature);
    
      return;
    } // end of HAL_OscTempComp() function
    
    
    void HAL_osc1Comp(HAL_Handle handle, const int16_t sensorSample)
    {
    	int16_t compOscFineTrim;
    	HAL_Obj *obj = (HAL_Obj *)handle;
    
    	ENABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        compOscFineTrim = ((sensorSample - getRefTempOffset())*(int32_t)getOsc1FineTrimSlope()
                          + OSC_POSTRIM_OFF + FP_ROUND )/FP_SCALE + getOsc1FineTrimOffset() - OSC_POSTRIM;
    
        if(compOscFineTrim > 31)
          {
            compOscFineTrim = 31;
          }
    	else if(compOscFineTrim < -31)
          {
            compOscFineTrim = -31;
          }
    
        OSC_setTrim(obj->oscHandle, OSC_Number_1, HAL_getOscTrimValue(getOsc1CoarseTrim(), compOscFineTrim));
    
        DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        return;
    } // end of HAL_osc1Comp() function
    
    
    void HAL_osc2Comp(HAL_Handle handle, const int16_t sensorSample)
    {
    	int16_t compOscFineTrim;
    	HAL_Obj *obj = (HAL_Obj *)handle;
    
    	ENABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        compOscFineTrim = ((sensorSample - getRefTempOffset())*(int32_t)getOsc2FineTrimSlope()
                          + OSC_POSTRIM_OFF + FP_ROUND )/FP_SCALE + getOsc2FineTrimOffset() - OSC_POSTRIM;
    
        if(compOscFineTrim > 31)
          {
            compOscFineTrim = 31;
          }
    	else if(compOscFineTrim < -31)
          {
            compOscFineTrim = -31;
          }
    
        OSC_setTrim(obj->oscHandle, OSC_Number_2, HAL_getOscTrimValue(getOsc2CoarseTrim(), compOscFineTrim));
    
        DISABLE_PROTECTED_REGISTER_WRITE_MODE;
    
        return;
    } // end of HAL_osc2Comp() function
    
    
    uint16_t HAL_getOscTrimValue(int16_t coarse, int16_t fine)
    {
      uint16_t regValue = 0;
    
      if(fine < 0)
        {
          regValue = ((-fine) | 0x20) << 9;
        }
      else
        {
          regValue = fine << 9;
        }
    
      if(coarse < 0)
        {
          regValue |= ((-coarse) | 0x80);
        }
      else
        {
          regValue |= coarse;
        }
    
      return regValue;
    } // end of HAL_getOscTrimValue() function
    
    
    void HAL_AdcOffsetSelfCal(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t AdcConvMean;
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
      // set the ADC voltage reference source to internal
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
      //Select VREFLO internal connection on B5
      ADC_enableVoltRefLoConv(obj->adcHandle);
    
      //Select channel B5 for all SOC
      HAL_AdcCalChanSelect(handle, ADC_SocChanNumber_B5);
    
      //Apply artificial offset (+80) to account for a negative offset that may reside in the ADC core
      ADC_setOffTrim(obj->adcHandle, 80);
    
      //Capture ADC conversion on VREFLO
      AdcConvMean = HAL_AdcCalConversion(handle);
    
      //Set offtrim register with new value (i.e remove artical offset (+80) and create a two's compliment of the offset error)
      ADC_setOffTrim(obj->adcHandle, 80 - AdcConvMean);
    
      //Select external ADCIN5 input pin on B5
      ADC_disableVoltRefLoConv(obj->adcHandle);
    
      return;
    } // end of HAL_AdcOffsetSelfCal() function
    
    
    void HAL_AdcCalChanSelect(HAL_Handle handle, const ADC_SocChanNumber_e chanNumber)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_0,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_1,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_2,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_3,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_4,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_5,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_6,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_7,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_8,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_9,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_10,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_11,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_12,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_13,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_14,chanNumber);
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_15,chanNumber);
    
      return;
    } // end of HAL_AdcCalChanSelect() function
    
    
    uint16_t HAL_AdcCalConversion(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint16_t index, SampleSize, Mean;
      uint32_t Sum;
      ADC_SocSampleDelay_e ACQPS_Value;
    
      index       = 0;     //initialize index to 0
      SampleSize  = 256;   //set sample size to 256 (**NOTE: Sample size must be multiples of 2^x where is an integer >= 4)
      Sum         = 0;     //set sum to 0
      Mean        = 999;   //initialize mean to known value
    
      //Set the ADC sample window to the desired value (Sample window = ACQPS + 1)
      ACQPS_Value = ADC_SocSampleDelay_7_cycles;
    
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_0,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_1,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_2,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_3,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_4,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_5,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_6,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_7,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_8,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_9,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_10,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_11,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_12,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_13,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_14,ACQPS_Value);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_15,ACQPS_Value);
    
      // Enabled ADCINT1 and ADCINT2
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_1);
      ADC_enableInt(obj->adcHandle, ADC_IntNumber_2);
    
      // Disable continuous sampling for ADCINT1 and ADCINT2
      ADC_setIntMode(obj->adcHandle, ADC_IntNumber_1, ADC_IntMode_EOC);
      ADC_setIntMode(obj->adcHandle, ADC_IntNumber_2, ADC_IntMode_EOC);
    
      //ADCINTs trigger at end of conversion
      ADC_setIntPulseGenMode(obj->adcHandle, ADC_IntPulseGenMode_Prior);
    
      // Setup ADCINT1 and ADCINT2 trigger source
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_1, ADC_IntSrc_EOC6);
      ADC_setIntSrc(obj->adcHandle, ADC_IntNumber_2, ADC_IntSrc_EOC14);
    
      // Setup each SOC's ADCINT trigger source
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_0, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_1, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_2, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_3, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_4, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_5, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_6, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_7, ADC_Int2TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_8, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_9, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_10, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_11, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_12, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_13, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_14, ADC_Int1TriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_15, ADC_Int1TriggersSOC);
    
      // Delay before converting ADC channels
      usDelay(ADC_DELAY_usec);
    
      ADC_setSocFrcWord(obj->adcHandle, 0x00FF);
    
      while( index < SampleSize )
        {
          //Wait for ADCINT1 to trigger, then add ADCRESULT0-7 registers to sum
          while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_1) == 0){}
    
          //Must clear ADCINT1 flag since INT1CONT = 0
          ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_1);
    
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_0);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_1);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_2);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_3);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_4);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_5);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_6);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_7);
    
          //Wait for ADCINT2 to trigger, then add ADCRESULT8-15 registers to sum
          while (ADC_getIntFlag(obj->adcHandle, ADC_IntNumber_2) == 0){}
    
          //Must clear ADCINT2 flag since INT2CONT = 0
          ADC_clearIntFlag(obj->adcHandle, ADC_IntNumber_2);
    
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_8);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_9);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_10);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_11);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_12);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_13);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_14);
          Sum += ADC_readResult(obj->adcHandle, ADC_ResultNumber_15);
    
          index+=16;
    
      } // end data collection
    
      //Disable ADCINT1 and ADCINT2 to STOP the ping-pong sampling
      ADC_disableInt(obj->adcHandle, ADC_IntNumber_1);
      ADC_disableInt(obj->adcHandle, ADC_IntNumber_2);
    
      //Calculate average ADC sample value
      Mean = Sum / SampleSize;
    
      // Clear start of conversion trigger
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_0, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_1, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_2, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_3, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_4, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_5, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_6, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_7, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_8, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_9, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_10, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_11, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_12, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_13, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_14, ADC_NoIntTriggersSOC);
      ADC_setupSocTrigSrc(obj->adcHandle, ADC_SocNumber_15, ADC_NoIntTriggersSOC);
    
      //return the average
      return(Mean);
    } // end of HAL_AdcCalConversion() function
    
    
    void HAL_disableWdog(HAL_Handle halHandle)
    {
      HAL_Obj *hal = (HAL_Obj *)halHandle;
    
    
      WDOG_disable(hal->wdogHandle);
    
    
      return;
    } // end of HAL_disableWdog() function
    
    
    void HAL_disableGlobalInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_disableGlobalInts(obj->cpuHandle);
    
      return;
    } // end of HAL_disableGlobalInts() function
    
    
    void HAL_enableAdcInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable the PIE interrupts associated with the ADC interrupts
      PIE_enableAdcInt(obj->pieHandle,ADC_IntNumber_1);
    
    
      // enable the ADC interrupts
      ADC_enableInt(obj->adcHandle,ADC_IntNumber_1);
    
    
      // enable the cpu interrupt for ADC interrupts
      CPU_enableInt(obj->cpuHandle,CPU_IntNumber_10);
    
      return;
    } // end of HAL_enableAdcInts() function
    
    
    void HAL_enableDebugInt(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_enableDebugInt(obj->cpuHandle);
    
      return;
    } // end of HAL_enableDebugInt() function
    
    
    void HAL_enableGlobalInts(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CPU_enableGlobalInts(obj->cpuHandle);
    
      return;
    } // end of HAL_enableGlobalInts() function
    
    
    void HAL_enablePwmInt(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      PIE_enablePwmInt(obj->pieHandle,PWM_Number_1);
    
    
      // enable the interrupt
      PWM_enableInt(obj->pwmHandle[PWM_Number_1]);
    
    
      // enable the cpu interrupt for EPWM1_INT
      CPU_enableInt(obj->cpuHandle,CPU_IntNumber_3);
    
      return;
    } // end of HAL_enablePwmInt() function
    
    
    void HAL_setupFaults(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
      uint_least8_t cnt;
    
    
      // Configure Trip Mechanism for the Motor control software
      // -Cycle by cycle trip on CPU halt
      // -One shot fault trip zone
      // These trips need to be repeated for EPWM1 ,2 & 3
      for(cnt=0;cnt<3;cnt++)
        {
          PWM_enableTripZoneSrc(obj->pwmHandle[cnt],PWM_TripZoneSrc_CycleByCycle_TZ6_NOT);
    
          PWM_enableTripZoneSrc(obj->pwmHandle[cnt],PWM_TripZoneSrc_OneShot_TZ1_NOT);
    
          // What do we want the OST/CBC events to do?
          // TZA events can force EPWMxA
          // TZB events can force EPWMxB
    
          PWM_setTripZoneState_TZA(obj->pwmHandle[cnt],PWM_TripZoneState_EPWM_Low);
          PWM_setTripZoneState_TZB(obj->pwmHandle[cnt],PWM_TripZoneState_EPWM_Low);
        }
    
      return;
    } // end of HAL_setupFaults() function
    
    
    HAL_Handle HAL_init(void *pMemory,const size_t numBytes)
    {
      uint_least8_t cnt;
      HAL_Handle handle;
      HAL_Obj *obj;
    
    
      if(numBytes < sizeof(HAL_Obj))
        return((HAL_Handle)NULL);
    
    
      // assign the handle
      handle = (HAL_Handle)pMemory;
    
    
      // assign the object
      obj = (HAL_Obj *)handle;
    
    
      //Added...
      // Init SCI A registers
      obj->sciaHandle = SCI_init((void *) SCIA_BASE_ADDR, sizeof(SCI_Obj));
      //SCI
    
    
      // initialize the watchdog driver
      obj->wdogHandle = WDOG_init((void *)WDOG_BASE_ADDR,sizeof(WDOG_Obj));
    
    
      // disable watchdog
      HAL_disableWdog(handle);
    
    
      // initialize the ADC
      obj->adcHandle = ADC_init((void *)ADC_BASE_ADDR,sizeof(ADC_Obj));
    
    
      // initialize the clock handle
      obj->clkHandle = CLK_init((void *)CLK_BASE_ADDR,sizeof(CLK_Obj));
    
    
      // initialize the CPU handle
      obj->cpuHandle = CPU_init(&cpu,sizeof(cpu));
    
    
      // initialize the FLASH handle
      obj->flashHandle = FLASH_init((void *)FLASH_BASE_ADDR,sizeof(FLASH_Obj));
    
    
      // initialize the GPIO handle
      obj->gpioHandle = GPIO_init((void *)GPIO_BASE_ADDR,sizeof(GPIO_Obj));
    
    
      // initialize the current offset estimator handles
      for(cnt=0;cnt<USER_NUM_CURRENT_SENSORS;cnt++)
        {
          obj->offsetHandle_I[cnt] = OFFSET_init(&obj->offset_I[cnt],sizeof(obj->offset_I[cnt]));
        }
    
    
      // initialize the voltage offset estimator handles
      for(cnt=0;cnt<USER_NUM_VOLTAGE_SENSORS;cnt++)
        {
          obj->offsetHandle_V[cnt] = OFFSET_init(&obj->offset_V[cnt],sizeof(obj->offset_V[cnt]));
        }
    
    
      // initialize the oscillator handle
      obj->oscHandle = OSC_init((void *)OSC_BASE_ADDR,sizeof(OSC_Obj));
    
    
      // initialize the PIE handle
      obj->pieHandle = PIE_init((void *)PIE_BASE_ADDR,sizeof(PIE_Obj));
    
    
      // initialize the PLL handle
      obj->pllHandle = PLL_init((void *)PLL_BASE_ADDR,sizeof(PLL_Obj));
    
    
      // initialize PWM handle
      obj->pwmHandle[0] = PWM_init((void *)PWM_ePWM1_BASE_ADDR,sizeof(PWM_Obj));
      obj->pwmHandle[1] = PWM_init((void *)PWM_ePWM2_BASE_ADDR,sizeof(PWM_Obj));
      obj->pwmHandle[2] = PWM_init((void *)PWM_ePWM3_BASE_ADDR,sizeof(PWM_Obj));
    
    
      // initialize power handle
      obj->pwrHandle = PWR_init((void *)PWR_BASE_ADDR,sizeof(PWR_Obj));
    
    
      // initialize timer drivers
      obj->timerHandle[0] = TIMER_init((void *)TIMER0_BASE_ADDR,sizeof(TIMER_Obj));
      obj->timerHandle[1] = TIMER_init((void *)TIMER1_BASE_ADDR,sizeof(TIMER_Obj));
      obj->timerHandle[2] = TIMER_init((void *)TIMER2_BASE_ADDR,sizeof(TIMER_Obj));
    
    
      return(handle);
    } // end of HAL_init() function
    
    
    void HAL_setParams(HAL_Handle handle,const USER_Params *pUserParams)
    {
      uint_least8_t cnt;
      HAL_Obj *obj = (HAL_Obj *)handle;
      _iq beta_lp_pu = _IQ(pUserParams->offsetPole_rps/(float_t)pUserParams->ctrlFreq_Hz);
    
    
      HAL_setNumCurrentSensors(handle,pUserParams->numCurrentSensors);
      HAL_setNumVoltageSensors(handle,pUserParams->numVoltageSensors);
    
    
      for(cnt=0;cnt<HAL_getNumCurrentSensors(handle);cnt++)
        {
          HAL_setOffsetBeta_lp_pu(handle,HAL_SensorType_Current,cnt,beta_lp_pu);
          HAL_setOffsetInitCond(handle,HAL_SensorType_Current,cnt,_IQ(0.0));
          HAL_setOffsetValue(handle,HAL_SensorType_Current,cnt,_IQ(0.0));
        }
    
    
      for(cnt=0;cnt<HAL_getNumVoltageSensors(handle);cnt++)
        {
          HAL_setOffsetBeta_lp_pu(handle,HAL_SensorType_Voltage,cnt,beta_lp_pu);
          HAL_setOffsetInitCond(handle,HAL_SensorType_Voltage,cnt,_IQ(0.0));
          HAL_setOffsetValue(handle,HAL_SensorType_Voltage,cnt,_IQ(0.0));
        }
    
    
      // disable global interrupts
      CPU_disableGlobalInts(obj->cpuHandle);
    
    
      // disable cpu interrupts
      CPU_disableInts(obj->cpuHandle);
    
    
      // clear cpu interrupt flags
      CPU_clearIntFlags(obj->cpuHandle);
    
    
    
      //Added....
      //HAL_setupSCI(handle); //move it down -maria-
      //SCI
    
    
      // setup the clocks
      HAL_setupClks(handle);
    
    
      // Setup the PLL
      HAL_setupPll(handle,PLL_ClkFreq_60_MHz);
    
    
      // setup the PIE
      HAL_setupPie(handle);
    
    
      // run the device calibration
      HAL_cal(handle);
    
    
      // setup the peripheral clocks
      HAL_setupPeripheralClks(handle);
    
    
      // setup the GPIOs
      HAL_setupGpios(handle);
    
    
      // setup the flash
      HAL_setupFlash(handle);
    
    
      // setup the ADCs
      HAL_setupAdcs(handle);
    
    
      // setup the PWMs
      HAL_setupPwms(handle,
                    pUserParams->systemFreq_MHz,
                    pUserParams->pwmPeriod_usec,
                    USER_NUM_PWM_TICKS_PER_ISR_TICK);
    
    
      // setup the timers
      HAL_setupTimers(handle,
                      pUserParams->systemFreq_MHz);
    
      //Added....
        HAL_setupSCI(handle);
        //SCI
    
    
      // set the default current bias
     {
       uint_least8_t cnt;
       _iq bias = _IQ12mpy(ADC_dataBias,_IQ(pUserParams->current_sf));
       
       for(cnt=0;cnt<HAL_getNumCurrentSensors(handle);cnt++)
         {
           HAL_setBias(handle,HAL_SensorType_Current,cnt,bias);
         }
     }
    
    
      //  set the current scale factor
     {
       _iq current_sf = _IQ(pUserParams->current_sf);
    
      HAL_setCurrentScaleFactor(handle,current_sf);
     }
    
    
      // set the default voltage bias
     {
       uint_least8_t cnt;
       _iq bias = _IQ(0.0);
       
       for(cnt=0;cnt<HAL_getNumVoltageSensors(handle);cnt++)
         {
           HAL_setBias(handle,HAL_SensorType_Voltage,cnt,bias);
         }
     }
    
    
      //  set the voltage scale factor
     {
       _iq voltage_sf = _IQ(pUserParams->voltage_sf);
    
      HAL_setVoltageScaleFactor(handle,voltage_sf);
     }
    
     return;
    } // end of HAL_setParams() function
    
    
    void HAL_setupAdcs(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // disable the ADCs
      ADC_disable(obj->adcHandle);
    
    
      // power up the bandgap circuit
      ADC_enableBandGap(obj->adcHandle);
    
    
      // set the ADC voltage reference source to internal 
      ADC_setVoltRefSrc(obj->adcHandle,ADC_VoltageRefSrc_Int);
    
    
      // enable the ADC reference buffers
      ADC_enableRefBuffers(obj->adcHandle);
    
    
      // power up the ADCs
      ADC_powerUp(obj->adcHandle);
    
    
      // enable the ADCs
      ADC_enable(obj->adcHandle);
    
    
      // set the ADC interrupt pulse generation to prior
      ADC_setIntPulseGenMode(obj->adcHandle,ADC_IntPulseGenMode_Prior);
    
    
      // set the temperature sensor source to external
      ADC_setTempSensorSrc(obj->adcHandle,ADC_TempSensorSrc_Ext);
    
    
      // configure the interrupt sources
      ADC_disableInt(obj->adcHandle,ADC_IntNumber_1);
      ADC_setIntMode(obj->adcHandle,ADC_IntNumber_1,ADC_IntMode_ClearFlag);
      ADC_setIntSrc(obj->adcHandle,ADC_IntNumber_1,ADC_IntSrc_EOC7);
    
    
      //configure the SOCs for hvkit_rev1p1
      // sample the first sample twice due to errata sprz342f
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_0,ADC_SocChanNumber_B4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_0,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_0,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_1,ADC_SocChanNumber_B4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_1,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_1,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_2,ADC_SocChanNumber_A4);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_2,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_2,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_3,ADC_SocChanNumber_A2);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_3,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_3,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_4,ADC_SocChanNumber_B1);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_4,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_4,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_5,ADC_SocChanNumber_B3);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_5,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_5,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_6,ADC_SocChanNumber_B7);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_6,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_6,ADC_SocSampleDelay_7_cycles);
    
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_7,ADC_SocChanNumber_A0);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_7,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_7,ADC_SocSampleDelay_7_cycles);
    
      //Potenc 1
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_8,ADC_SocChanNumber_B6);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_8,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_8,ADC_SocSampleDelay_7_cycles);
    
    
      //Potenc 2
      ADC_setSocChanNumber(obj->adcHandle,ADC_SocNumber_9,ADC_SocChanNumber_A1);
      ADC_setSocTrigSrc(obj->adcHandle,ADC_SocNumber_9,ADC_SocTrigSrc_EPWM1_ADCSOCA);
      ADC_setSocSampleDelay(obj->adcHandle,ADC_SocNumber_9,ADC_SocSampleDelay_7_cycles);
    
    
      return;
    } // end of HAL_setupAdcs() function
    
    
    void HAL_setupClks(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // enable internal oscillator 1
      CLK_enableOsc1(obj->clkHandle);
    
      // set the oscillator source
      CLK_setOscSrc(obj->clkHandle,CLK_OscSrc_Internal);
    
      // disable the external clock in
      CLK_disableClkIn(obj->clkHandle);
    
      // disable the crystal oscillator
      CLK_disableCrystalOsc(obj->clkHandle);
    
      // disable oscillator 2
      CLK_disableOsc2(obj->clkHandle);
    
      // set the low speed clock prescaler
      CLK_setLowSpdPreScaler(obj->clkHandle,CLK_LowSpdPreScaler_SysClkOut_by_4);
    
      // set the clock out prescaler
      CLK_setClkOutPreScaler(obj->clkHandle,CLK_ClkOutPreScaler_SysClkOut_by_1);
    
      return;
    } // end of HAL_setupClks() function
    
    
    void HAL_setupFlash(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      FLASH_enablePipelineMode(obj->flashHandle);
    
      FLASH_setNumPagedReadWaitStates(obj->flashHandle,FLASH_NumPagedWaitStates_2);
    
      FLASH_setNumRandomReadWaitStates(obj->flashHandle,FLASH_NumRandomWaitStates_2);
    
      FLASH_setOtpWaitStates(obj->flashHandle,FLASH_NumOtpWaitStates_3);
    
      FLASH_setStandbyWaitCount(obj->flashHandle,FLASH_STANDBY_WAIT_COUNT_DEFAULT);
    
      FLASH_setActiveWaitCount(obj->flashHandle,FLASH_ACTIVE_WAIT_COUNT_DEFAULT);
    
      return;
    } // HAL_setupFlash() function
    
    
    void HAL_setupGpios(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // PWM1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_0,GPIO_0_Mode_EPWM1A);
    
      // PWM2
      GPIO_setMode(obj->gpioHandle,GPIO_Number_1,GPIO_1_Mode_EPWM1B);
    
      // PWM3
      GPIO_setMode(obj->gpioHandle,GPIO_Number_2,GPIO_2_Mode_EPWM2A);
    
      // PWM4
      GPIO_setMode(obj->gpioHandle,GPIO_Number_3,GPIO_3_Mode_EPWM2B);
    
      // PWM5
      GPIO_setMode(obj->gpioHandle,GPIO_Number_4,GPIO_4_Mode_EPWM3A);
    
      // PWM6
      GPIO_setMode(obj->gpioHandle,GPIO_Number_5,GPIO_5_Mode_EPWM3B);
    
      // PWM1-PFC
      GPIO_setMode(obj->gpioHandle,GPIO_Number_6,GPIO_6_Mode_GeneralPurpose);
    
      // PWM2-PFC
      GPIO_setMode(obj->gpioHandle,GPIO_Number_7,GPIO_7_Mode_GeneralPurpose);
    
      // TZ-1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_12,GPIO_12_Mode_TZ1_NOT);
    
      // SPI-SIMO or HALL-2
      GPIO_setMode(obj->gpioHandle,GPIO_Number_16,GPIO_16_Mode_GeneralPurpose);
    
      // SPI-SOMI or HALL-3
      GPIO_setMode(obj->gpioHandle,GPIO_Number_17,GPIO_17_Mode_GeneralPurpose);
    
      // SPI-CLK or SPI-SIMO
      GPIO_setMode(obj->gpioHandle,GPIO_Number_18,GPIO_18_Mode_GeneralPurpose);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_18,GPIO_Direction_Output);
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_18, GPIO_PullUp_Enable);
    
      // SPI-STE or CAP-1/HALL-1
      GPIO_setMode(obj->gpioHandle,GPIO_Number_19,GPIO_19_Mode_GeneralPurpose); //DipSwitch 1
    
      // RX-SLAVE
    //  GPIO_setMode(obj->gpioHandle,GPIO_Number_28,GPIO_28_Mode_GeneralPurpose);
    
      // TX-SLAVE
    //  GPIO_setMode(obj->gpioHandle,GPIO_Number_29,GPIO_29_Mode_GeneralPurpose); //SW1
    
      // I2C-SDA
      GPIO_setMode(obj->gpioHandle,GPIO_Number_32,GPIO_32_Mode_GeneralPurpose);
    
      // I2C-SCL
      GPIO_setMode(obj->gpioHandle,GPIO_Number_33,GPIO_33_Mode_GeneralPurpose);
    
      // ControlCARD LED4
      GPIO_setMode(obj->gpioHandle,GPIO_Number_7,GPIO_7_Mode_GeneralPurpose);
      GPIO_setLow(obj->gpioHandle,GPIO_Number_7);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_7,GPIO_Direction_Output);
    
      // ControlCARD LED3
    /*  GPIO_setMode(obj->gpioHandle,GPIO_Number_28,GPIO_28_Mode_GeneralPurpose);
      GPIO_setLow(obj->gpioHandle,GPIO_Number_28);
      GPIO_setDirection(obj->gpioHandle,GPIO_Number_28,GPIO_Direction_Output);
    */
      // JTAG
      GPIO_setMode(obj->gpioHandle,GPIO_Number_35,GPIO_35_Mode_JTAG_TDI);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_36,GPIO_36_Mode_JTAG_TMS);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_37,GPIO_37_Mode_JTAG_TDO);
      GPIO_setMode(obj->gpioHandle,GPIO_Number_38,GPIO_38_Mode_JTAG_TCK);
    
    
      // Setup your GPIOs for SCI
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_28, GPIO_PullUp_Enable);
      //GPIO_setPullUp(obj->gpioHandle, GPIO_Number_29, GPIO_PullUp_Disable);
      GPIO_setPullUp(obj->gpioHandle, GPIO_Number_29, GPIO_PullUp_Enable); //changed to pull-up enable -maria-
    
      GPIO_setQualification(obj->gpioHandle, GPIO_Number_28, GPIO_Qual_ASync);
    
      GPIO_setMode(obj->gpioHandle, GPIO_Number_28, GPIO_28_Mode_SCIRXDA);
      GPIO_setMode(obj->gpioHandle, GPIO_Number_29, GPIO_29_Mode_SCITXDA);
    
      return;
    }  // end of HAL_setupGpios() function
    
    
    void HAL_setupPie(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      PIE_disable(obj->pieHandle);
    
      PIE_disableAllInts(obj->pieHandle);
    
      PIE_clearAllInts(obj->pieHandle);
    
      PIE_clearAllFlags(obj->pieHandle);
    
      PIE_setDefaultIntVectorTable(obj->pieHandle);
    
      PIE_enable(obj->pieHandle);
    
      return;
    } // end of HAL_setupPie() function
    
    
    void HAL_setupPeripheralClks(HAL_Handle handle)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      CLK_enableAdcClock(obj->clkHandle);
    
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_1);
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_2);
      CLK_enableCompClock(obj->clkHandle,CLK_CompNumber_3);
    
      CLK_enableEcap1Clock(obj->clkHandle);
    
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_1);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_2);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_3);
      CLK_enablePwmClock(obj->clkHandle,PWM_Number_4);
    
      CLK_disableHrPwmClock(obj->clkHandle);
    
      CLK_disableI2cClock(obj->clkHandle);
    
      CLK_enableSciaClock(obj->clkHandle);
    
      CLK_disableSpiaClock(obj->clkHandle);
      
      CLK_enableTbClockSync(obj->clkHandle);
    
      return;
    } // end of HAL_setupPeripheralClks() function
    
    
    void HAL_setupPll(HAL_Handle handle,const PLL_ClkFreq_e clkFreq)
    {
      HAL_Obj *obj = (HAL_Obj *)handle;
    
    
      // make sure PLL is not running in limp mode
      if(PLL_getClkStatus(obj->pllHandle) != PLL_ClkStatus_Normal)
        {
          // reset the clock detect
          PLL_resetClkDetect(obj->pllHandle);
    
          // ???????
          asm("        ESTOP0");
        }
    
    
      // Divide Select must be ClkIn/4 before the clock rate can be changed
      if(PLL_getDivideSelect(obj->pllHandle) != PLL_DivideSelect_ClkIn_by_4)
        {
          PLL_setDivideSelect(obj->pllHandle,PLL_DivideSelect_ClkIn_by_4);
        }
    
    
      if(PLL_getClkFreq(obj->pllHandle) != clkFreq)
        {
          // disable the clock detect
          PLL_disableClkDetect(obj->pllHandle);
    
          // set the clock rate
          PLL_setClkFreq(obj->pllHandle,clkFreq);
        }
    
    
      // wait until locked
      while(PLL_getLockStatus(obj->pllHandle) != PLL_LockStatus_Done) {}
    
    
      // enable the clock detect
      PLL_enableClkDetect(obj->pllHandle);
    
    
      // set divide select to ClkIn/2 to get desired clock rate
      // NOTE: clock must be locked before setting this register
      PLL_setDivideSelect(obj->pllHandle,PLL_DivideSelect_ClkIn_by_2);
    
      return;
    } // end of HAL_setupPll() function
    
    
    void HAL_setupPwms(HAL_Handle handle,
                       const uint_least16_t systemFreq_MHz,
                       const float_t pwmPeriod_usec,
                       const uint_least16_t numPwmTicksPerIsrTick)
    {
      HAL_Obj   *obj = (HAL_Obj *)handle;
      uint16_t   halfPeriod_cycles = (uint16_t)((float_t)systemFreq_MHz*pwmPeriod_usec) >> 1;
      uint_least8_t    cnt;
    
    
      // turns off the outputs of the EPWM peripherals which will put the power switches
      // into a high impedance state.
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_1]);
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_2]);
      PWM_setOneShotTrip(obj->pwmHandle[PWM_Number_3]);
    
      for(cnt=0;cnt<3;cnt++)
        {
          // setup the Time-Base Control Register (TBCTL)
          PWM_setCounterMode(obj->pwmHandle[cnt],PWM_CounterMode_UpDown);
          PWM_disableCounterLoad(obj->pwmHandle[cnt]);
          PWM_setPeriodLoad(obj->pwmHandle[cnt],PWM_PeriodLoad_Immediate);
          PWM_setSyncMode(obj->pwmHandle[cnt],PWM_SyncMode_EPWMxSYNC);
          PWM_setHighSpeedClkDiv(obj->pwmHandle[cnt],PWM_HspClkDiv_by_1);
          PWM_setClkDiv(obj->pwmHandle[cnt],PWM_ClkDiv_by_1);
          PWM_setPhaseDir(obj->pwmHandle[cnt],PWM_PhaseDir_CountUp);
          PWM_setRunMode(obj->pwmHandle[cnt],PWM_RunMode_FreeRun);
    
          // setup the Timer-Based Phase Register (TBPHS)
          PWM_setPhase(obj->pwmHandle[cnt],0);
    
          // setup the Time-Base Counter Register (TBCTR)
          PWM_setCount(obj->pwmHandle[cnt],0);
    
          // setup the Time-Base Period Register (TBPRD)
          // set to zero initially
          PWM_setPeriod(obj->pwmHandle[cnt],0);
    
          // setup the Counter-Compare Control Register (CMPCTL)
          PWM_setLoadMode_CmpA(obj->pwmHandle[cnt],PWM_LoadMode_Zero);
          PWM_setLoadMode_CmpB(obj->pwmHandle[cnt],PWM_LoadMode_Zero);
          PWM_setShadowMode_CmpA(obj->pwmHandle[cnt],PWM_ShadowMode_Shadow);
          PWM_setShadowMode_CmpB(obj->pwmHandle[cnt],PWM_ShadowMode_Immediate);
    
          // setup the Action-Qualifier Output A Register (AQCTLA) 
          PWM_setActionQual_CntUp_CmpA_PwmA(obj->pwmHandle[cnt],PWM_ActionQual_Set);
          PWM_setActionQual_CntDown_CmpA_PwmA(obj->pwmHandle[cnt],PWM_ActionQual_Clear);
    
          // setup the Dead-Band Generator Control Register (DBCTL)
          PWM_setDeadBandOutputMode(obj->pwmHandle[cnt],PWM_DeadBandOutputMode_EPWMxA_Rising_EPWMxB_Falling);
          PWM_setDeadBandPolarity(obj->pwmHandle[cnt],PWM_DeadBandPolarity_EPWMxB_Inverted);
    
          // setup the Dead-Band Rising Edge Delay Register (DBRED)
          PWM_setDeadBandRisingEdgeDelay(obj->pwmHandle[cnt],HAL_PWM_DBRED_CNT);
    
          // setup the Dead-Band Falling Edge Delay Register (DBFED)
          PWM_setDeadBandFallingEdgeDelay(obj->pwmHandle[cnt],HAL_PWM_DBFED_CNT);
          // setup the PWM-Chopper Control Register (PCCTL)
          PWM_disableChopping(obj->pwmHandle[cnt]);
    
          // setup the Trip Zone Select Register (TZSEL)
          PWM_disableTripZones(obj->pwmHandle[cnt]);
        }
    
    
      // setup the Event Trigger Selection Register (ETSEL)
      PWM_disableInt(obj->pwmHandle[PWM_Number_1]);
      PWM_setSocAPulseSrc(obj->pwmHandle[PWM_Number_1],PWM_SocPulseSrc_CounterEqualZero);
      PWM_enableSocAPulse(obj->pwmHandle[PWM_Number_1]);
      
    
      // setup the Event Trigger Prescale Register (ETPS)
      if(numPwmTicksPerIsrTick == 3)
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_ThirdEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_ThirdEvent);
        }
      else if(numPwmTicksPerIsrTick == 2)
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_SecondEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_SecondEvent);
        }
      else
        {
          PWM_setIntPeriod(obj->pwmHandle[PWM_Number_1],PWM_IntPeriod_FirstEvent);
          PWM_setSocAPeriod(obj->pwmHandle[PWM_Number_1],PWM_SocPeriod_FirstEvent);
        }
    
    
      // setup the Event Trigger Clear Register (ETCLR)
      PWM_clearIntFlag(obj->pwmHandle[PWM_Number_1]);
      PWM_clearSocAFlag(obj->pwmHandle[PWM_Number_1]);
    
      // first step to synchronize the pwms
      CLK_disableTbClockSync(obj->clkHandle);
    
      // since the PWM is configured as an up/down counter, the period register is set to one-half 
      // of the desired PWM period
      PWM_setPeriod(obj->pwmHandle[PWM_Number_1],halfPeriod_cycles);
      PWM_setPeriod(obj->pwmHandle[PWM_Number_2],halfPeriod_cycles);
      PWM_setPeriod(obj->pwmHandle[PWM_Number_3],halfPeriod_cycles);
    
      // last step to synchronize the pwms
      CLK_enableTbClockSync(obj->clkHandle);
    
      return;
    }  // end of HAL_setupPwms() function
    
    
    void HAL_setupTimers(HAL_Handle handle,const uint_least16_t systemFreq_MHz)
    {
      HAL_Obj  *obj = (HAL_Obj *)handle;
      uint32_t  timerPeriod_cnts = ((uint32_t)systemFreq_MHz * 1000000) - 1;
    
      // use timer 0 for frequency diagnostics
      TIMER_setDecimationFactor(obj->timerHandle[0],0);
      TIMER_setEmulationMode(obj->timerHandle[0],TIMER_EmulationMode_RunFree);
      TIMER_setPeriod(obj->timerHandle[0],timerPeriod_cnts);
      TIMER_setPreScaler(obj->timerHandle[0],0);
    
      // use timer 1 for CPU usage diagnostics
      TIMER_setDecimationFactor(obj->timerHandle[1],0);
      TIMER_setEmulationMode(obj->timerHandle[1],TIMER_EmulationMode_RunFree);
      TIMER_setPeriod(obj->timerHandle[1],timerPeriod_cnts);
      TIMER_setPreScaler(obj->timerHandle[1],0);
    
      return;
    }  // end of HAL_setupTimers() function
    
    
    // end of file
    
    6471.8507.proj_lab05b.c
    /* --COPYRIGHT--,BSD
     * Copyright (c) 2012, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  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.
     *
     * *  Neither the name of Texas Instruments Incorporated 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 OWNER 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.
     * --/COPYRIGHT--*/
    //! \file   solutions/instaspin_foc/src/proj_lab05b.c
    //! \brief Adjusting the speed current controller
    //!
    //! (C) Copyright 2011, Texas Instruments, Inc.
    
    //! \defgroup PROJ_LAB05b PROJ_LAB05b
    //@{
    
    //! \defgroup PROJ_LAB05b_OVERVIEW Project Overview
    //!
    //! Adjusting the supplied speed controller
    //!
    
    // **************************************************************************
    // the includes
    
    // system includes
    #include <math.h>
    #include "main.h"
    
    #ifdef FLASH
    #pragma CODE_SECTION(mainISR,"ramfuncs");
    #endif
    
    // Include header files used in the main function
    
    
    // **************************************************************************
    // the defines
    
    #define LED_BLINK_FREQ_Hz   5
    
    // **************************************************************************
    // the globals
    
    uint_least16_t gCounter_updateGlobals = 0;
    
    bool Flag_Latch_softwareUpdate = true;
    
    CTRL_Handle ctrlHandle;
    
    HAL_Handle halHandle;
    
    USER_Params gUserParams;
    
    HAL_PwmData_t gPwmData = {_IQ(0.0), _IQ(0.0), _IQ(0.0)};
    
    HAL_AdcData_t gAdcData;
    
    _iq gMaxCurrentSlope = _IQ(0.0);
    
    // Novas vari�veis
    
    bool flagTeste = 0;
    
    bool gSW1;	//push button
    
    bool Flag_button = 0;
    
    double_t x = 0;		// "encoder digital" - contagem de voltas
    double_t y = 0;		// deslocamento
    double_t t = 600;	// n� de voltas
    double_t w = 250;	// abrandamento
    double_t q = 0;
    
    _iq defVel = _IQ(1.4);
    uint32_t tempo = 0;
    uint16_t count_press_run = 0;
    uint16_t count_press_stop = 0;
    uint32_t count_flag_button = 0;
    uint16_t debounce_bt = 0;
    
    
    // ---------------------	SCI		-----------------------------------
    // Prototype statements for functions found within this file.
    
    void scia_xmit(int a);
    
    // Global counts used in this example
    
    uint16_t inc = 0;
    uint16_t encoderTipoLeitura = 0;
    uint16_t msgRXInc[3] = {0, 0, 0};
    uint16_t msgRXDec[3] = {0, 0, 0};
    uint16_t cospelampada;
    
    
    ADC_Handle adcHandle;
    CLK_Handle clkHandle;
    GPIO_Handle gpioHandle;
    SCI_Handle sciaHandle;
    PIE_Handle pieHandle;
    CPU_Handle cpuHandle;
    PLL_Handle pllHandle;
    
    //		    --------------------	x	------------------
    
    #ifdef FAST_ROM_V1p6
    CTRL_Obj *controller_obj;
    #else
    CTRL_Obj ctrl;				//v1p7 format
    #endif
    
    uint16_t gLEDcnt = 0;
    
    volatile MOTOR_Vars_t gMotorVars = MOTOR_Vars_INIT;
    
    #ifdef FLASH
    // Used for running BackGround in flash, and ISR in RAM
    extern uint16_t *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;
    #endif
    
    
    #ifdef DRV8301_SPI
    // Watch window interface to the 8301 SPI
    DRV_SPI_8301_Vars_t gDrvSpi8301Vars;
    #endif
    
    _iq gFlux_pu_to_Wb_sf;
    
    _iq gFlux_pu_to_VpHz_sf;
    
    _iq gTorque_Ls_Id_Iq_pu_to_Nm_sf;
    
    _iq gTorque_Flux_Iq_pu_to_Nm_sf;
    
    // **************************************************************************
    // the functions
    
    void main(void)
    
    {
    /* NO NEED -maria-
    // --------------------------------SCI------------------------------------------------
    
    	  HAL_setupSCI(halHandle);
    
        // Interrupts that are used in this example are re-mapped to
        // ISR functions found within this file.
            EALLOW;    // This is needed to write to EALLOW protected registers
        //   PieVectTable.SCIRXINTA = &sciaRxFifoIsr;
            ((PIE_Obj *)pieHandle)->SCIRXINTA = &sciaRxFifoIsr;
        //   PieVectTable.SCITXINTA = &sciaTxFifoIsr;
        //    ((PIE_Obj *)myPie)->SCITXINTA = &sciaTxFifoIsr;
            EDIS;   // This is needed to disable write to EALLOW protected registers
    
    	// Register interrupt handlers in the PIE vector table
    	PIE_registerPieIntHandler(pieHandle, PIE_GroupNumber_9, PIE_SubGroupNumber_1, (intVec_t)&sciaRxFifoIsr);
    
    // ---------------------------------x--------------------------------------------------
    */
      uint_least8_t estNumber = 0;
    
    #ifdef FAST_ROM_V1p6
      uint_least8_t ctrlNumber = 0;
    #endif
    
      // Only used if running from FLASH
      // Note that the variable FLASH is defined by the project
      #ifdef FLASH
      // Copy time critical code and Flash setup code to RAM
      // The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
      // symbols are created by the linker. Refer to the linker files.
      memCopy((uint16_t *)&RamfuncsLoadStart,(uint16_t *)&RamfuncsLoadEnd,(uint16_t *)&RamfuncsRunStart);
      #endif
    
      // initialize the hardware abstraction layer
      halHandle = HAL_init(&hal,sizeof(hal));
    
    
      // check for errors in user parameters
      USER_checkForErrors(&gUserParams);
    
    
      // store user parameter error in global variable
      gMotorVars.UserErrorCode = USER_getErrorCode(&gUserParams);
    
    
      // do not allow code execution if there is a user parameter error
      if(gMotorVars.UserErrorCode != USER_ErrorCode_NoError)
        {
          for(;;)
            {
              gMotorVars.Flag_enableSys = false;
            }
        }
    
    
      // initialize the user parameters
      USER_setParams(&gUserParams);
    
    
      // set the hardware abstraction layer parameters
      HAL_setParams(halHandle,&gUserParams);
    
    
      // initialize the controller
    #ifdef FAST_ROM_V1p6
      ctrlHandle = CTRL_initCtrl(ctrlNumber, estNumber);  		//v1p6 format (06xF and 06xM devices)
      controller_obj = (CTRL_Obj *)ctrlHandle;
    #else
      ctrlHandle = CTRL_initCtrl(estNumber,&ctrl,sizeof(ctrl));	//v1p7 format default
    #endif
    
    
      {
        CTRL_Version version;
    
        // get the version number
        CTRL_getVersion(ctrlHandle,&version);
    
        gMotorVars.CtrlVersion = version;
      }
    
    
      // set the default controller parameters
      CTRL_setParams(ctrlHandle,&gUserParams);
    
    
      // setup faults
      HAL_setupFaults(halHandle);
    
    
      // initialize the interrupt vector table
      HAL_initIntVectorTable(halHandle);
    
    
      // enable the ADC interrupts
      HAL_enableAdcInts(halHandle);
    
    
      // enable global interrupts
      HAL_enableGlobalInts(halHandle);
    
    
      // enable debug interrupts
      HAL_enableDebugInt(halHandle);
    
    
      // disable the PWM
      HAL_disablePwm(halHandle);
    
    
    #ifdef DRV8301_SPI
      // turn on the DRV8301 if present
      HAL_enableDrv(halHandle);
      // initialize the DRV8301 interface
      HAL_setupDrvSpi(halHandle,&gDrvSpi8301Vars);
    #endif
    
    
      // enable DC bus compensation
      CTRL_setFlag_enableDcBusComp(ctrlHandle, true);
    
    
      // compute scaling factors for flux and torque calculations
      gFlux_pu_to_Wb_sf = USER_computeFlux_pu_to_Wb_sf();
      gFlux_pu_to_VpHz_sf = USER_computeFlux_pu_to_VpHz_sf();
      gTorque_Ls_Id_Iq_pu_to_Nm_sf = USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf();
      gTorque_Flux_Iq_pu_to_Nm_sf = USER_computeTorque_Flux_Iq_pu_to_Nm_sf();
    
    
      for(;;)
       {
    
    	//  HAL_setupSCI(halHandle); // disabled by maria
    //      -----------------   Encoder  -----------------------
    
    		GPIO_setHigh(gpioHandle, GPIO_Number_18);
    
    		usDelay(2000);
    
    		scia_xmit(0xA2);
    
    		if(encoderTipoLeitura == 0)
    		{
    			scia_xmit(0xB0);
    		}
    		else
    		{
    			scia_xmit(0xB3);
    		}
    
    		//scia_xmit(0x00);
    
    		while(SCI_getTxFifoStatus(sciaHandle) != SCI_FifoStatus_Empty);
    
    		while(SCI_txReady(sciaHandle) == 0);
    
    		while(SCI_isTxEmpty(sciaHandle) == 0);
    
    	//	inc = 0;
    
    		usDelay (1000);
    
    		GPIO_setLow(gpioHandle, GPIO_Number_18);
    
    		usDelay(50000);
    
    		if(encoderTipoLeitura == 0)
    		{
    			encoderTipoLeitura = 1;
    		}
    		else
    		{
    			encoderTipoLeitura = 0;
    
    			usDelay(50000);
    		}
    
    //     --------------------------------x--------------------------
    
         // Waiting for enable system flag to be set
         while(!(gMotorVars.Flag_enableSys))
         {
        	gSW1 = HAL_readGpio(halHandle, HAL_GPIO_SW1);	//Iniciar o sistema atrav�s do bSW1
         	if(gSW1 == 0 && Flag_button == 0)
         	{
         		tempo = 10000;
         		Flag_button = 1;
         		gMotorVars.Flag_enableSys = 1;		//Inicia o sistema
         		gMotorVars.Flag_Run_Identify = 1;	//Arranca com o programa
         	}
          }
    
         // loop while the enable system flag is true
         while(gMotorVars.Flag_enableSys)
         {
        	 //Usar o bot�o 1 (SW1) para parar e reiniciar o programa
        	 if(tempo == 0)
         	 {
        		 tempo = 100;
    
        		 gSW1 = HAL_readGpio(halHandle, HAL_GPIO_SW1);
    
         		if(Flag_button == 1)
         		{
         			if(gSW1 == 0)
         			{
         				debounce_bt++;
    
         				if(debounce_bt >= 10)
         				{
         					if(gMotorVars.Flag_Run_Identify == 0)
     						{
     							gMotorVars.Flag_Run_Identify = 1;
     							count_press_run ++;
     						}
     						else
     						{
     							gMotorVars.Flag_Run_Identify = 0;
     							count_press_stop ++;
     						}
    
         					Flag_button = 2;
         				}
         			}
         			else
         			{
         				debounce_bt = 0;
         			}
         		}
         		else if(Flag_button == 2)
         		{
         			if(gSW1 == 1)
         			{
         				count_flag_button ++;
    
         				Flag_button = 1;
         			}
         		}
         	}
    
    
    
            CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle;
    
            // increment counters
            gCounter_updateGlobals++;
    
            // enable/disable the use of motor parameters being loaded from user.h
            CTRL_setFlag_enableUserMotorParams(ctrlHandle,gMotorVars.Flag_enableUserParams);
    
            // enable/disable Rs recalibration during motor startup
            EST_setFlag_enableRsRecalc(obj->estHandle,gMotorVars.Flag_enableRsRecalc);
    
            // enable/disable automatic calculation of bias values
            CTRL_setFlag_enableOffset(ctrlHandle,gMotorVars.Flag_enableOffsetcalc);
    
    
            if(CTRL_isError(ctrlHandle))
              {
                // set the enable controller flag to false
                CTRL_setFlag_enableCtrl(ctrlHandle,false);
    
                // set the enable system flag to false
                gMotorVars.Flag_enableSys = false;
    
                // disable the PWM
                HAL_disablePwm(halHandle);
              }
            else
              {
                // update the controller state
                bool flag_ctrlStateChanged = CTRL_updateState(ctrlHandle);
    
                // enable or disable the control
                CTRL_setFlag_enableCtrl(ctrlHandle, gMotorVars.Flag_Run_Identify);
    
                if(flag_ctrlStateChanged)
                  {
                    CTRL_State_e ctrlState = CTRL_getState(ctrlHandle);
    
                    if(ctrlState == CTRL_State_OffLine)
                      {
                        // enable the PWM
                        HAL_enablePwm(halHandle);
                      }
                    else if(ctrlState == CTRL_State_OnLine)
                      {
                        if(gMotorVars.Flag_enableOffsetcalc == true)
                        {
                          // update the ADC bias values
                          HAL_updateAdcBias(halHandle);
                        }
                        else
                        {
                          // set the current bias
                          HAL_setBias(halHandle,HAL_SensorType_Current,0,_IQ(I_A_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Current,1,_IQ(I_B_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Current,2,_IQ(I_C_offset));
    
                          // set the voltage bias
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,0,_IQ(V_A_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,1,_IQ(V_B_offset));
                          HAL_setBias(halHandle,HAL_SensorType_Voltage,2,_IQ(V_C_offset));
                        }
    
                        // Return the bias value for currents
                        gMotorVars.I_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Current,0);
                        gMotorVars.I_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Current,1);
                        gMotorVars.I_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Current,2);
    
                        // Return the bias value for voltages
                        gMotorVars.V_bias.value[0] = HAL_getBias(halHandle,HAL_SensorType_Voltage,0);
                        gMotorVars.V_bias.value[1] = HAL_getBias(halHandle,HAL_SensorType_Voltage,1);
                        gMotorVars.V_bias.value[2] = HAL_getBias(halHandle,HAL_SensorType_Voltage,2);
    
                        // enable the PWM
                        HAL_enablePwm(halHandle);
                      }
                    else if(ctrlState == CTRL_State_Idle)
                      {
                        // disable the PWM
                        HAL_disablePwm(halHandle);
                        gMotorVars.Flag_Run_Identify = false;
                      }
    
                    if((CTRL_getFlag_enableUserMotorParams(ctrlHandle) == true) &&
                      (ctrlState > CTRL_State_Idle) &&
                      (gMotorVars.CtrlVersion.minor == 6))
                      {
                        // call this function to fix 1p6
                        USER_softwareUpdate1p6(ctrlHandle);
                      }
    
                  }
              }
    
    
            if(EST_isMotorIdentified(obj->estHandle))
              {
                // set the current ramp
                EST_setMaxCurrentSlope_pu(obj->estHandle,gMaxCurrentSlope);
                gMotorVars.Flag_MotorIdentified = true;
    
                // set the speed reference
                CTRL_setSpd_ref_krpm(ctrlHandle,gMotorVars.SpeedRef_krpm);
    
                // usando o Pot 1 para regular a velocidade
                gMotorVars.SpeedRef_krpm = _IQmpy( gAdcData.potentiometer, CTRL_getMaximumSpeed_pu(ctrlHandle) );
    
                // set the speed acceleration
                CTRL_setMaxAccel_pu(ctrlHandle,_IQmpy(MAX_ACCEL_KRPMPS_SF,gMotorVars.MaxAccel_krpmps));
                if(Flag_Latch_softwareUpdate)
                {
                  Flag_Latch_softwareUpdate = false;
    
                  USER_calcPIgains(ctrlHandle);
    
                  // initialize the watch window kp and ki current values with pre-calculated values
                  gMotorVars.Kp_Idq = CTRL_getKp(ctrlHandle,CTRL_Type_PID_Id);
                  gMotorVars.Ki_Idq = CTRL_getKi(ctrlHandle,CTRL_Type_PID_Id);
    
                  // initialize the watch window kp and ki values with pre-calculated values
                  gMotorVars.Kp_spd = CTRL_getKp(ctrlHandle,CTRL_Type_PID_spd);
                  gMotorVars.Ki_spd = CTRL_getKi(ctrlHandle,CTRL_Type_PID_spd);
                }
    
              }
            else
              {
                Flag_Latch_softwareUpdate = true;
    
                // the estimator sets the maximum current slope during identification
                gMaxCurrentSlope = EST_getMaxCurrentSlope_pu(obj->estHandle);
              }
    
    
            // when appropriate, update the global variables
            if(gCounter_updateGlobals >= NUM_MAIN_TICKS_FOR_GLOBAL_VARIABLE_UPDATE)
              {
                // reset the counter
                gCounter_updateGlobals = 0;
    
                updateGlobalVariables_motor(ctrlHandle);
              }
    
    
            // update Kp and Ki gains
            updateKpKiGains(ctrlHandle);
    
            // enable/disable the forced angle
            EST_setFlag_enableForceAngle(obj->estHandle,gMotorVars.Flag_enableForceAngle);
    
            // enable or disable power warp
            CTRL_setFlag_enablePowerWarp(ctrlHandle,gMotorVars.Flag_enablePowerWarp);
    
    #ifdef DRV8301_SPI
            HAL_writeDrvData(halHandle,&gDrvSpi8301Vars);
    
            HAL_readDrvData(halHandle,&gDrvSpi8301Vars);
    #endif
    
          } // end of while(gFlag_enableSys) loop
    
    
        // disable the PWM
        HAL_disablePwm(halHandle);
    
        // set the default controller parameters (Reset the control to re-identify the motor)
        CTRL_setParams(ctrlHandle,&gUserParams);
        gMotorVars.Flag_Run_Identify = false;
    
      } // end of for(;;) loop
    
    } // end of main() function
    
    
    interrupt void mainISR(void)
    {
    	gMotorVars.Flag_enableOffsetcalc = 0;	// desabilitar o calculo dos offsets
    
    	//Debounce botao
    
    	if(tempo > 0)
    	  {
    
    		  tempo--;
    	  }
    
    
    	/*
    	// "Encoder digital"
    
    	gMotorVars.Flag_enableOffsetcalc = 0;	// desabilitar o calculo dos offsets
    //	gMotorVars.SpeedRef_krpm = _IQ(1.5);
      // toggle status LED
    //	if(gLEDcnt++ > 100 && gMotorVars.Flag_Run_Identify == 1 && _IQ(gMotorVars.Speed_krpm) >= 1400)
    	if (gMotorVars.Flag_Run_Identify == 1)
    	{
    		if(++gLEDcnt >= 100) 	 //&& gMotorVars.Speed_krpm >= 23488094)
    			{
    				HAL_toggleLed(halHandle,(GPIO_Number_e)HAL_Gpio_LED3);
    				gLEDcnt = 0;
    
    				//y = (float_t) (( (z) * (float_t) (1000) ) / (float_t) (600) ));
    
    				y = (double_t)((gMotorVars.Speed_krpm /(double_t) 16777.216)/(double_t) 6000);	// faz a conta das rpms...
    
    				//(long) ((0.0) * 16777216.0L)
    
    				x += y;// incrementa variavel (contagem global -> x )...
    */
    /*				if(q == 0)
    				{
    					if(x >= t)
    					{
    						gMotorVars.SpeedRef_krpm = _IQ(0.0);
    						q = 1;
    					}
    				}
    				else if (q == 1)
    				{
    					if(gMotorVars.Speed_krpm <= _IQ(0.0))
    					{
    						//x = 0;
    						q = 2;
    						delaycnt = 0;
    					}
    				}
    				else if (q == 2)
    				{
    					if(delaycnt > 100)
    					{
    						gMotorVars.SpeedRef_krpm = _IQ(-0.8);
    						q=3;
    					}
    					delaycnt ++;
    				}
    
    
    				if (x <= z  && q == 3)
    				{
    					gMotorVars.SpeedRef_krpm = _IQ(-0.2);
    
    					if (x < 0)
    					{
    						gMotorVars.Flag_Run_Identify = 0;
    						x = 0;
    						y = 0;
    						q = 0;
    					}
    				}
    */
    /*				if (flagTeste == 0)
    				{
    					gMotorVars.SpeedRef_krpm = defVel;
    				}
    */
    /*
    				if(x > t-w && flagTeste == 0)
    				{
    					gMotorVars.SpeedRef_krpm = _IQ(0.2);
    					flagTeste = 1;
    				}
    
    				if (x > t)
    				{
    					//gMotorVars.SpeedRef_krpm = _IQ(0.0);
    					x = 0;
    					y = 0;
    					gMotorVars.Flag_Run_Identify = 0; // desliga a flag do motr
    					flagTeste = 0;
    					//q = 0;
    				}
    			}
    		}
    */
    
    
      // acknowledge the ADC interrupt
      HAL_acqAdcInt(halHandle,ADC_IntNumber_1);
    
    
      // convert the ADC data
      HAL_readAdcData(halHandle,&gAdcData);
    
    
      // run the controller
      CTRL_run(ctrlHandle,halHandle,&gAdcData,&gPwmData);
    
    
      // write the PWM compare values
      HAL_writePwmData(halHandle,&gPwmData);
    
    
      // setup the controller
      CTRL_setup(ctrlHandle);
    
    
      return;
    } // end of mainISR() function
    
    
    // -----------------------------SCI------------------------------
    
    interrupt void sciaRxFifoIsr(void)
    {
    	if(inc < 3)
    		{
    
    		if(encoderTipoLeitura == 0)
    			{
    				msgRXDec[inc] = SCI_read(sciaHandle);
    
    			}
    
    			else
    			{
    				msgRXInc[inc] = SCI_read(sciaHandle);
    
    			}
    
    			inc++;
    
    		}
    
    	// Clear Overflow flag
    	SCI_clearRxFifoOvf(sciaHandle);
    
    	// Clear Interrupt flag
    	SCI_clearRxFifoInt(sciaHandle);
    
    	// Issue PIE ack
    	PIE_clearInt(pieHandle, PIE_GroupNumber_9);
    
    	return;
    }
    
    
    // Transmit a character from the SCI
    void scia_xmit(int a)
    {
    //    while (SciaRegs.SCIFFTX.bit.TXFFST != 0) {}
        while(SCI_getTxFifoStatus(sciaHandle) != SCI_FifoStatus_Empty);
    
    //    SciaRegs.SCITXBUF=a;
        //SCI_putDataBlocking(sciaHandle, a);
        HAL_sciaWrite(sciaHandle, a); //try to use this -maria-
    //    SCI_write(sciaHandle, a);
    
    }
    
    // ----------------------------- x ------------------------------
    
    void updateGlobalVariables_motor(CTRL_Handle handle)
    {
      CTRL_Obj *obj = (CTRL_Obj *)handle;
    
      // get the speed estimate
      gMotorVars.Speed_krpm = EST_getSpeed_krpm(obj->estHandle);
    
      // get the real time speed reference coming out of the speed trajectory generator
      gMotorVars.SpeedTraj_krpm = _IQmpy(CTRL_getSpd_int_ref_pu(handle),EST_get_pu_to_krpm_sf(obj->estHandle));
    
      // get the torque estimate
      gMotorVars.Torque_Nm = USER_computeTorque_Nm(handle, gTorque_Flux_Iq_pu_to_Nm_sf, gTorque_Ls_Id_Iq_pu_to_Nm_sf);
    
      // get the magnetizing current
      gMotorVars.MagnCurr_A = EST_getIdRated(obj->estHandle);
    
      // get the rotor resistance
      gMotorVars.Rr_Ohm = EST_getRr_Ohm(obj->estHandle);
    
      // get the stator resistance
      gMotorVars.Rs_Ohm = EST_getRs_Ohm(obj->estHandle);
    
      // get the stator inductance in the direct coordinate direction
      gMotorVars.Lsd_H = EST_getLs_d_H(obj->estHandle);
    
      // get the stator inductance in the quadrature coordinate direction
      gMotorVars.Lsq_H = EST_getLs_q_H(obj->estHandle);
    
      // get the flux in V/Hz in floating point
      gMotorVars.Flux_VpHz = EST_getFlux_VpHz(obj->estHandle);
    
      // get the flux in Wb in fixed point
      gMotorVars.Flux_Wb = USER_computeFlux(handle, gFlux_pu_to_Wb_sf);
    
      // get the controller state
      gMotorVars.CtrlState = CTRL_getState(handle);
    
      // get the estimator state
      gMotorVars.EstState = EST_getState(obj->estHandle);
    
      // Get the DC buss voltage
      gMotorVars.VdcBus_kV = _IQmpy(gAdcData.dcBus,_IQ(USER_IQ_FULL_SCALE_VOLTAGE_V/1000.0));
    
      return;
    } // end of updateGlobalVariables_motor() function
    
    
    void updateKpKiGains(CTRL_Handle handle)
    {
      if((gMotorVars.CtrlState == CTRL_State_OnLine) && (gMotorVars.Flag_MotorIdentified == true) && (Flag_Latch_softwareUpdate == false))
        {
          // set the kp and ki speed values from the watch window
          CTRL_setKp(handle,CTRL_Type_PID_spd,gMotorVars.Kp_spd);
          CTRL_setKi(handle,CTRL_Type_PID_spd,gMotorVars.Ki_spd);
    
          // set the kp and ki current values for Id and Iq from the watch window
          CTRL_setKp(handle,CTRL_Type_PID_Id,gMotorVars.Kp_Idq);
          CTRL_setKi(handle,CTRL_Type_PID_Id,gMotorVars.Ki_Idq);
          CTRL_setKp(handle,CTRL_Type_PID_Iq,gMotorVars.Kp_Idq);
          CTRL_setKi(handle,CTRL_Type_PID_Iq,gMotorVars.Ki_Idq);
    	}
    
      return;
    } // end of updateKpKiGains() function
    
    //@} //defgroup
    // end of file
    
    
    
    

    Also, please put these lines in hal.h

    extern interrupt void sciaRxFifoIsr(void);
    extern void HAL_sciaWrite(HAL_Handle handle, const uint16_t data);

    And modified this function in hal.h

    static inline void HAL_initIntVectorTable(HAL_Handle handle)
     {
      HAL_Obj *obj = (HAL_Obj *)handle;
      PIE_Obj *pie = (PIE_Obj *)obj->pieHandle;


      ENABLE_PROTECTED_REGISTER_WRITE_MODE;

      pie->ADCINT1 = &mainISR;

      pie->SCIRXINTA = &sciaRxFifoIsr; //Added

      DISABLE_PROTECTED_REGISTER_WRITE_MODE;

      return;
     } // end of HAL_initIntVectorTable() function

    then in main.h, please put this line:

    interrupt void sciaRxFifoIsr(void);

    Hope no error when you build them.

    Tell me what you get.

    Best regards,

    Maria

  • Hello Maria,


    1st of all I want to appreciate your work and your effort to try fix this issue.


    I implemented and did the changes that you point on the last post, I debug and didn't return any error. Now the program stuck on this: 'while(SCI_txReady(sciaHandle) == 0);'  -- >  ' status = (sci->SCICTL2 & SCI_SCICTL2_TXRDY_BITS) >> 7;' in sci.h.

    I already try to comment this line and after that the program stuck on 'while(SCI_isTxEmpty(sciaHandle) == 0);' , a function that I add on sci.h.

    static inline bool SCI_isTxEmpty(SCI_Handle sciHandle)
    {
        SCI_Obj *sci = (SCI_Obj *)sciHandle;
        bool status;
    
        status = (sci->SCICTL2 & SCI_SCICTL2_TXEMPTY_BITS) >> 6;
    
        return((bool)status);
    } // end of SCI_isTxEmpty() function
    

    Do you have any ideia, why the program stuck on this functions?

    BR,
    Bruno Ramos

  • Btw, I needed to change this: 

    HAL_sciaWrite(sciaHandle, a); //try to use this -maria-

    by this

    HAL_sciaWrite(halHandle, a);

    otherwise the compiler return me an error... I don't know if this is correct, but was the only way that I find to debug the code.

  • I think it is ok. Is it run now?

  • The last post, was the 1st thing that I did to try debug the code. The post before the last one is what is happening now, that is: the program is stucking on that functions. Even if I comment that functions, the program it's not more stucked, but the motor have a strange behavior.


    I can run the example from controlsuite without any problem, on motorware I can't. I don't know what is missing...

  • Hello Maria,


    I removed the "Verify Answer" with the hope that someone TI experts could help on this thread, but nothing changed... I'll tag all your posts with "Verify Answer" to be thankfull for your help and time. Thanks for all.


    BR,
    Bruno Ramos

  • Hello Bruno,

    I don't know what the situation in your code building (any warning that you skipped?) but I have tried to generate your code and modified them and tested them in my LP. I think the problem in your code is that you don't know how to link hal handle to the peripheral handles (sci and pie in this case).

    Here is my result:

    The transmit worked well, you can see SCITXBUF register changing (yellow sign).

    Also the receiving (the variables in the expression window were changed when I typed a key in my keyboard).

    Here is the zip file that contains the files that needed to be changed in proj_lab5b.

    8358.sci_mw13_f28027f.zip

    Good Luck!

    Best regards,

    Maria

  • Hello Maria,


    Thanks a lot for your time and dedication on this issue. I already solve this. The problem was that the interrupt stop to occur, maybe because some error detect. After read the reference guide of SCI (sprugh1c), and take a special attention on the SCIRXST register, I need to reset the register to force the interrupt to happen again. I don't know if this is caused by the noise or anything worse, but this was the only way that I find to solve this problem.

    Thanks for the time that you spend on this Maria, I hope that everyone have someone like you to help them to solve their issues. ;)

    Thanks a lot again. Best Regards,
    Bruno Ramos

  • Bruno Ramos1 said:
    I already solve this.

    That's great! I am glad!

    Bruno Ramos1 said:
    I hope that everyone have someone like you to help them to solve their issues. ;)

    I hope so too :) I am also still learning about TI C2000 and this forum is the best place for me to throw questions and to find answers about TI C2000.

    Good luck!

    Best regards,

    Maria