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.

MSP430I2041: How to read EMDC GUI outputs through Serial Communication

Part Number: MSP430I2041

Lets explain the work done from my side in this project

1. I am using an MSP430i2041 EVM board. I did EMDC GUI for a single phase ac meter ( Current sensor: Shunt resistor). Completed calibration part and getting proper output in the GUI. For your reference I will attach the image below

My supplied voltage is 230 and a 60W bulb is used. so I am getting all the outputs properly.

2. In order to add our own functions, I export this code to CCS Studio and try to send all the parameters to Modem through serial communication (My objective).

3. To Monitor the output through serial I alter the code a little bit and check through serial monitor. The value continuously changes. I am not getting constant value. I am also attached to my code here. First one is emLibGUIApp.c second one is emDCCommandHandlerss.c

/* --COPYRIGHT--,TI
*MSP Source and Object Code Software License Agreement
*
*
**IMPORTANT - PLEASE CAREFULLY READ THE FOLLOWING LICENSE AGREEMENT, WHICH IS LEGALLY BINDING.  AFTER YOU READ IT, YOU WILL BE ASKED WHETHER YOU ACCEPT AND AGREE TO ITS TERMS.  DO NOT CLICK  "I ACCEPT" UNLESS: (1) YOU WILL USE THE LICENSED MATERIALS FOR YOUR OWN BENEFIT AND PERSONALLY ACCEPT, AGREE TO AND INTEND TO BE BOUND BY THESE TERMS; OR (2) YOU ARE AUTHORIZED TO, AND INTEND TO BE BOUND BY, THESE TERMS ON BEHALF OF YOUR COMPANY.
*
*
**Important - Read carefully: This Source and Object Code Software License Agreement ("Agreement") is a legal agreement between you and Texas Instruments Incorporated ("TI").  In this Agreement "you" means you personally if you will exercise the rights granted for your own benefit, but it means your company (or you on behalf of your company) if you will exercise the rights granted for your company's benefit.  The "Licensed Materials" subject to this Agreement include the software programs and any associated electronic documentation (in each case, in whole or in part) that accompany this Agreement, are set forth in the applicable software manifest and you access "on-line", as well as any updates or upgrades to such software programs or documentation, if any, provided to you at TI's sole discretion.  The Licensed Materials are specifically designed and licensed for use solely and exclusively with MSP microcontroller devices manufactured by or for TI ("TI Devices").  By installing, copying or otherwise using the Licensed Materials you agree to abide by the provisions set forth herein.  This Agreement is displayed for you to read prior to using the Licensed Materials.  If you choose not to accept or agree with these provisions, do not download or install the Licensed Materials.
*
**Note Regarding Possible Access to Other Licensed Materials:  The Licensed Materials may be bundled with software and associated electronic documentation, if any, licensed under terms other than the terms of this Agreement (in whole or in part, "Other Licensed Materials"), including, for example Open Source Software and/or TI-owned or third party Proprietary Software licensed under such other terms.  "Open Source Software" means any software licensed under terms requiring that (A) other software ("Proprietary Software") incorporated, combined or distributed with such software or developed using such software: (i) be disclosed or distributed in source code form; or (ii) otherwise be licensed on terms inconsistent with the terms of this Agreement, including but not limited to permitting use of the Proprietary Software on or with devices other than TI Devices, or (B) require the owner of Proprietary Software to license any of its patents to users of the Open Source Software and/or Proprietary Software incorporated, combined or distributed with such Open Source Software or developed using such Open Source Software.
*
**If by accepting this Agreement, you gain access to Other Licensed Materials, they will be listed in the applicable software manifest.  Your use of the Other Licensed Materials is subject to the applicable other licensing terms acknowledgements and disclaimers as specified in the applicable software manifest and/or identified or included with the Other Licensed Materials in the software bundle.  For clarification, this Agreement does not limit your rights under, or grant you rights that supersede, the terms of any applicable Other Licensed Materials license agreement.  If any of the Other Licensed Materials is Open Source Software that has been provided to you in object code only under terms that obligate TI to provide to you or show you where you can access the source code versions of such Open Source Software, TI will provide to you, or show you where you can access, such source code if you contact TI at Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager, Embedded Processing.  In the event you choose not to accept or agree with the terms in any applicable Other Licensed Materials license agreement, you must terminate this Agreement.
*
**1.    License Grant and Use Restrictions.
*
**a.    Licensed Materials License Grant.  Subject to the terms of this Agreement, TI hereby grants to you a limited, non-transferable, non-exclusive, non-assignable, non-sublicensable, fully paid-up and royalty-free license to:
*
*            i.    Limited Source Code License:  make copies, prepare derivative works, display internally and use internally the Licensed Materials provided to you in source code for the sole purpose of developing object and executable versions of such Licensed Materials, or any derivative thereof, that execute solely and exclusively on TI Devices, for end use in Licensee Products, and maintaining and supporting such Licensed Materials, or any derivative thereof, and Licensee Products.  For purposes of this Agreement, "Licensee Product" means a product that consists of both hardware, including one or more TI Devices, and software components, including only executable versions of the Licensed Materials that execute solely and exclusively on such TI Devices.
*
*            ii.    Object Code Evaluation, Testing and Use License:  make copies, display internally, distribute internally and use internally the Licensed Materials in object code for the sole purposes of evaluating and testing the Licensed Materials and designing and developing Licensee Products, and maintaining and supporting the Licensee Products;
*
*            iii.    Demonstration License:  demonstrate to third parties the Licensed Materials executing solely and exclusively on TI Devices as they are used in Licensee Products, provided that such Licensed Materials are demonstrated in object or executable versions only and
*
*        iv.    Production and Distribution License:  make, use, import, export and otherwise distribute the Licensed Materials as part of a Licensee Product, provided that such Licensee Products include only embedded executable copies of such Licensed Materials that execute solely and exclusively on TI Devices.
*
*    b.    Contractors.  The licenses granted to you hereunder shall include your on-site and off-site contractors (either an individual or entity), while such contractors are performing work for or providing services to you, provided that such contractors have executed work-for-hire agreements with you containing applicable terms and conditions consistent with the terms and conditions set forth in this Agreement and provided further that you shall be liable to TI for any breach by your contractors of this Agreement to the same extent as you would be if you had breached the Agreement yourself.
*
*    c.    No Other License.  Nothing in this Agreement shall be construed as a license to any intellectual property rights of TI other than those rights embodied in the Licensed Materials provided to you by TI.  EXCEPT AS PROVIDED HEREIN, NO OTHER LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY OTHER TI INTELLECTUAL PROPERTY RIGHTS IS GRANTED HEREIN.
*
*    d.    Covenant not to Sue.  During the term of this Agreement, you agree not to assert a claim against TI or its licensees that the Licensed Materials infringe your intellectual property rights.
*
*    e.    Restrictions.  You shall maintain the source code versions of the Licensed Materials under password control protection and shall not disclose such source code versions of the Licensed Materials, to any person other than your employees and contractors whose job performance requires access.  You shall not use the Licensed Materials with a processing device other than a TI Device, and you agree that any such unauthorized use of the Licensed Materials is a material breach of this Agreement.  You shall not use the Licensed Materials for the purpose of analyzing or proving infringement of any of your patents by either TI or TI's customers.  Except as expressly provided in this Agreement, you shall not copy, publish, disclose, display, provide, transfer or make available the Licensed Materials to any third party and you shall not sublicense, transfer, or assign the Licensed Materials or your rights under this Agreement to any third party.  You shall not mortgage, pledge or encumber the Licensed Materials in any way.  You may use the Licensed Materials with Open Source Software or with software developed using Open Source Software tools provided you do not incorporate, combine or distribute the Licensed Materials in a manner that subjects the Licensed Materials to any license obligations or any other intellectual property related terms of any license governing such Open Source Software.
*
*    f.    Termination.  This Agreement is effective on the date the Licensed Materials are delivered to you together with this Agreement and will remain in full force and effect until terminated.  You may terminate this Agreement at any time by written notice to TI.  Without prejudice to any other rights, if you fail to comply with the terms of this Agreement or you are acquired, TI may terminate your right to use the Licensed Materials upon written notice to you.  Upon termination of this Agreement, you will destroy any and all copies of the Licensed Materials in your possession, custody or control and provide to TI a written statement signed by your authorized representative certifying such destruction. Except for Sections 1(a), 1(b) and 1(d), all provisions of this Agreement shall survive termination of this Agreement.
*
**2.    Licensed Materials Ownership.  The Licensed Materials are licensed, not sold to you, and can only be used in accordance with the terms of this Agreement.  Subject to the licenses granted to you pursuant to this Agreement, TI and its licensors own and shall continue to own all right, title and interest in and to the Licensed Materials, including all copies thereof.  You agree that all fixes, modifications and improvements to the Licensed Materials conceived of or made by TI that are based, either in whole or in part, on your feedback, suggestions or recommendations are the exclusive property of TI and all right, title and interest in and to such fixes, modifications or improvements to the Licensed Materials will vest solely in TI.  Moreover, you acknowledge and agree that when your independently developed software or hardware components are combined, in whole or in part, with the Licensed Materials, your right to use the combined work that includes the Licensed Materials remains subject to the terms and conditions of this Agreement.
*
**3.    Intellectual Property Rights.
*
*    a.    The Licensed Materials contain copyrighted material, trade secrets and other proprietary information of TI and its licensors and are protected by copyright laws, international copyright treaties, and trade secret laws, as well as other intellectual property laws.  To protect TI's and its licensors' rights in the Licensed Materials, you agree, except as specifically permitted by statute by a provision that cannot be waived by contract, not to "unlock", decompile, reverse engineer, disassemble or otherwise translate to a human-perceivable form any portions of the Licensed Materials provided to you in object code format only, nor permit any person or entity to do so.  You shall not remove, alter, cover, or obscure any confidentiality, trade secret, trade mark, patent, copyright or other proprietary notice or other identifying marks or designs from any component of the Licensed Materials and you shall reproduce and include in all copies of the Licensed Materials the copyright notice(s) and proprietary legend(s) of TI and its licensors as they appear in the Licensed Materials.  TI reserves all rights not specifically granted under this Agreement.
*
*    b.    Certain Licensed Materials may be based on industry recognized standards or software programs published by industry recognized standards bodies and certain third parties may claim to own patents, copyrights, and other intellectual property rights that cover implementation of those standards.  You acknowledge and agree that this Agreement does not convey a license to any such third party patents, copyrights, and other intellectual property rights and that you are solely responsible for any patent, copyright, or other intellectual property right claim that relates to your use or distribution of the Licensed Materials or your use or distribution of your products that include or incorporate the Licensed Materials.  Moreover, you acknowledge that you are responsible for any fees or royalties that may be payable to any third party based on such third party's interests in the Licensed Materials or any intellectual property rights that cover implementation of any industry recognized standard, any software program published by any industry recognized standards bodies or any other proprietary technology.
*
**4.    Confidential Information.  You acknowledge and agree that the Licensed Materials contain trade secrets and other confidential information of TI and its licensors.  You agree to use the Licensed Materials solely within the scope of the licenses set forth herein, to maintain the Licensed Materials in strict confidence, to use at least the same procedures and degree of care that you use to prevent disclosure of your own confidential information of like importance but in no instance less than reasonable care, and to prevent disclosure of the Licensed Materials to any third party, except as may be necessary and required in connection with your rights and obligations hereunder; provided, however, that you may not provide the Licensed Materials to any business organization or group within your company or to customers or contractors that design or manufacture semiconductors unless TI gives written consent.  You agree to obtain executed confidentiality agreements with your employees and contractors having access to the Licensed Materials and to diligently take steps to enforce such agreements in this respect.  TI may disclose your contact information to TI's licensors.
*
**5.    Warranties and Limitations.  THE LICENSED MATERIALS ARE PROVIDED "AS IS".  FURTHERMORE, YOU ACKNOWLEDGE AND AGREE THAT THE LICENSED MATERIALS HAVE NOT BEEN TESTED OR CERTIFIED BY ANY GOVERNMENT AGENCY OR INDUSTRY REGULATORY ORGANIZATION OR ANY OTHER THIRD PARTY ORGANIZATION.  YOU AGREE THAT PRIOR TO USING, INCORPORATING OR DISTRIBUTING THE LICENSED MATERIALS IN OR WITH ANY COMMERCIAL PRODUCT THAT YOU WILL THOROUGHLY TEST THE PRODUCT AND THE FUNCTIONALITY OF THE LICENSED MATERIALS IN OR WITH THAT PRODUCT AND BE SOLELY RESPONSIBLE FOR ANY PROBLEMS OR FAILURES.
*
**TI AND ITS LICENSORS MAKE NO WARRANTY OR REPRESENTATION, EITHER EXPRESS, IMPLIED OR STATUTORY, REGARDING THE LICENSED MATERIALS, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT OF ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER INTELLECTUAL PROPERTY RIGHTS.  YOU AGREE TO USE YOUR INDEPENDENT JUDGMENT IN DEVELOPING YOUR PRODUCTS.  NOTHING CONTAINED IN THIS AGREEMENT WILL BE CONSTRUED AS A WARRANTY OR REPRESENTATION BY TI TO MAINTAIN PRODUCTION OF ANY TI SEMICONDUCTOR DEVICE OR OTHER HARDWARE OR SOFTWARE WITH WHICH THE LICENSED MATERIALS MAY BE USED.
*
**IN NO EVENT SHALL TI OR ITS LICENSORS, BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, IN CONNECTION WITH OR ARISING OUT OF THIS AGREEMENT OR THE USE OF THE LICENSED MATERIALS REGARDLESS OF WHETHER TI HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  EXCLUDED DAMAGES INCLUDE, BUT ARE NOT LIMITED TO, COST OF REMOVAL OR REINSTALLATION, OUTSIDE COMPUTER TIME, LABOR COSTS, LOSS OF DATA, LOSS OF GOODWILL, LOSS OF PROFITS, LOSS OF SAVINGS, OR LOSS OF USE OR INTERRUPTION OF BUSINESS.  IN NO EVENT WILL TI'S OR ITS LICENSORS' AGGREGATE LIABILITY UNDER THIS AGREEMENT OR ARISING OUT OF YOUR USE OF THE LICENSED MATERIALS EXCEED FIVE HUNDRED U.S. DOLLARS (US$500).
*
*    Because some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages or limitation on how long an implied warranty lasts, the above limitations or exclusions may not apply to you.
*
**6.    Indemnification Disclaimer.  YOU ACKNOWLEDGE AND AGREE THAT TI SHALL NOT BE LIABLE FOR AND SHALL NOT DEFEND OR INDEMNIFY YOU AGAINST ANY THIRD PARTY INFRINGEMENT CLAIM THAT RELATES TO OR IS BASED ON YOUR MANUFACTURE, USE, OR DISTRIBUTION OF THE LICENSED MATERIALS OR YOUR MANUFACTURE, USE, OFFER FOR SALE, SALE, IMPORTATION OR DISTRIBUTION OF YOUR PRODUCTS THAT INCLUDE OR INCORPORATE THE LICENSED MATERIALS.
*
**7.    No Technical Support.  TI and its licensors are under no obligation to install, maintain or support the Licensed Materials.
*
**8.    Notices.  All notices to TI hereunder shall be delivered to Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager - Embedded Processing, with a copy to Texas Instruments Incorporated, 13588 N. Central Expressway, Mail Station 3999, Dallas, Texas 75243, Attention: Law Department - Embedded Processing.  All notices shall be deemed served when received by TI.
*
**9.    Export Control.  The Licensed Materials are subject to export control under the U.S. Commerce Department's Export Administration Regulations ("EAR").  Unless prior authorization is obtained from the U.S. Commerce Department, neither you nor your subsidiaries shall export, re-export, or release, directly or indirectly (including, without limitation, by permitting the Licensed Materials to be downloaded), any technology, software, or software source code, received from TI, or export, directly or indirectly, any direct product of such technology, software, or software source code, to any person, destination or country to which the export, re-export, or release of the technology, software, or software source code, or direct product is prohibited by the EAR.  You represent and warrant that you (i) are not located in, or under the control of, a national or resident of Cuba, Iran, North Korea, Sudan and Syria or any other country subject to a U.S. goods embargo; (ii) are not on the U.S. Treasury Department's List of Specially Designated Nationals or the U.S. Commerce Department's Denied Persons List or Entity List; and (iii) will not use the Licensed Materials or transfer the Licensed Materials for use in any military, nuclear, chemical or biological weapons, or missile technology end-uses.  Any software export classification made by TI shall not be construed as a representation or warranty regarding the proper export classification for such software or whether an export license or other documentation is required for the exportation of such software.
*
**10.    Governing Law and Severability; Waiver.  This Agreement will be governed by and interpreted in accordance with the laws of the State of Texas, without reference to conflict of laws principles.  If for any reason a court of competent jurisdiction finds any provision of the Agreement to be unenforceable, that provision will be enforced to the maximum extent possible to effectuate the intent of the parties, and the remainder of the Agreement shall continue in full force and effect.  This Agreement shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, or by the Uniform Computer Information Transactions Act (UCITA).  The parties agree that non-exclusive jurisdiction for any dispute arising out of or relating to this Agreement lies within the courts located in the State of Texas.  Notwithstanding the foregoing, any judgment may be enforced in any United States or foreign court, and either party may seek injunctive relief in any United States or foreign court.  Failure by TI to enforce any provision of this Agreement shall not be deemed a waiver of future enforcement of that or any other provision in this Agreement or any other agreement that may be in place between the parties.
*
**11.    PRC Provisions.  If you are located in the People's Republic of China ("PRC") or if the Licensed Materials will be sent to the PRC, the following provisions shall apply:
*
*    a.    Registration Requirements.  You shall be solely responsible for performing all acts and obtaining all approvals that may be required in connection with this Agreement by the government of the PRC, including but not limited to registering pursuant to, and otherwise complying with, the PRC Measures on the Administration of Software Products, Management Regulations on Technology Import-Export, and Technology Import and Export Contract Registration Management Rules.  Upon receipt of such approvals from the government authorities, you shall forward evidence of all such approvals to TI for its records.  In the event that you fail to obtain any such approval or registration, you shall be solely responsible for any and all losses, damages or costs resulting therefrom, and shall indemnify TI for all such losses, damages or costs.
*
**b.    Governing Language.  This Agreement is written and executed in the English language and shall be authoritative and controlling, whether or not translated into a language other than English to comply with law or for reference purposes.  If a translation of this Agreement is required for any purpose, including but not limited to registration of the Agreement pursuant to any governmental laws, regulations or rules, you shall be solely responsible for creating such translation.
*
**12.    Contingencies.    TI shall not be in breach of this Agreement and shall not be liable for any non-performance or delay in performance if such non-performance or delay is due to a force majeure event or other circumstances beyond TI's reasonable control.
*
**13.        Entire Agreement.  This is the entire agreement between you and TI and this Agreement supersedes any prior agreement between the parties related to the subject matter of this Agreement.  Notwithstanding the foregoing, any signed and effective software license agreement relating to the subject matter hereof and stating expressly that such agreement shall control regardless of any subsequent click-wrap, shrink-wrap or web-wrap, shall supersede the terms of this Agreement.  No amendment or modification of this Agreement will be effective unless in writing and signed by a duly authorized representative of TI.  You hereby warrant and represent that you have obtained all authorizations and other applicable consents required empowering you to enter into this Agreement.
*
*
*
* --/COPYRIGHT--*/

//#############################################################################
//
//! \file   EMLibGUIApp.c
//!
//! \brief  Handles main loop and interaction between EM Library and GUI
//!
//!  Group:          MSP Embedded Software Development
//!  Target Device:  MSP430i2041
//!
//!  (C) Copyright 2017, Texas Instruments, Inc.
//#############################################################################
#include "EMLibGUIApp.h"
#include "hmiDC/hmi.h"
uint8_t gemResultStatus;

void uart_init()
{
    WDTCTL = WDTPW | WDTHOLD;           // Stop watchdog timer

    P1SEL0 |=   BIT2 | BIT3;            // P1.2/3 eUSCI_A Function
    P1SEL1 &= ~(BIT2 | BIT3);

    UCA0CTL1 |= UCSWRST;                // Hold eUSCI in reset
    UCA0CTL1 |= UCSSEL_2;               // SMCLK
    UCA0BR0   = 142;                    // 115200 baud
    UCA0BR1   = 0;
    UCA0MCTLW = 0x2200;                 // 16.384MHz/115200 = 142.22 (See UG)
    UCA0CTL1 &= ~UCSWRST;               // Release from reset
}

void uart_transmit_byte(uint8_t recieve_byte)
{
        __delay_cycles(1000);
        UCA0TXBUF =recieve_byte;
        __delay_cycles(1000);
        __delay_cycles(10000);
}


void uart_transmit(char *ptr,int len)
{
            int count;
            for(count=0;count<len;count++)
            {
            __delay_cycles(1000);
            UCA0TXBUF =*(ptr+count);
            __delay_cycles(1000);
            }
    //    UCA0TXBUF ='\n';
        __delay_cycles(10000);
}


void EMLibGUIApp_Init(void)
{
    EM_message_code code;

    // Initialize the Energy Measurement Library
    code = EM_configureEnergyMeasurement(&gEmSWConfig, (EM_SW_Lib_Result_Handle *) &gEmSWResult);

    if(code != EM_message_code_no_error)
    {
        // Error occurred
        while(1);
    }


    // Initialize run time calibration values
    EM_initalizeCalibrationValues((uint8_t*)g_emPhaseCalibration,
                                  (uint8_t*)g_savedEmPhaseCalibration);

    // Initialize DC Filter
    EM_initDCFilters(&gEmSWConfig, (EM_SW_Lib_Result_Handle *) &gEmSWResult);

    // HAL_ADC_init
    HAL_ADC_init(&halAdcConfig);

    // Delay ~200us for 1.2V ref to settle
    __delay_cycles(3200);

    // Start the conversion
    HAL_ADC_startConversion(&halAdcConfig);

    /* turn on global interrupts */
    __enable_interrupt();
}

void EMLibGUIApp_Engine(void)
{
	
    /* Start Energy Measurement -- Main loop  */
    uart_init();

    while(1)
    {

		// EM Lib Foreground process

    //    uart_transmit("Start Function\n",15);

		EM_foregroundProc(&gemResultStatus);

		HMI_stateMachine(gemResultStatus);

	//	uart_transmit("Stop Function\n",14);
    }
}

/* --COPYRIGHT--,TI
 *MSP Source and Object Code Software License Agreement
 *
 *
 **IMPORTANT - PLEASE CAREFULLY READ THE FOLLOWING LICENSE AGREEMENT, WHICH IS LEGALLY BINDING.  AFTER YOU READ IT, YOU WILL BE ASKED WHETHER YOU ACCEPT AND AGREE TO ITS TERMS.  DO NOT CLICK  "I ACCEPT" UNLESS: (1) YOU WILL USE THE LICENSED MATERIALS FOR YOUR OWN BENEFIT AND PERSONALLY ACCEPT, AGREE TO AND INTEND TO BE BOUND BY THESE TERMS; OR (2) YOU ARE AUTHORIZED TO, AND INTEND TO BE BOUND BY, THESE TERMS ON BEHALF OF YOUR COMPANY.
 *
 *
 **Important - Read carefully: This Source and Object Code Software License Agreement ("Agreement") is a legal agreement between you and Texas Instruments Incorporated ("TI").  In this Agreement "you" means you personally if you will exercise the rights granted for your own benefit, but it means your company (or you on behalf of your company) if you will exercise the rights granted for your company's benefit.  The "Licensed Materials" subject to this Agreement include the software programs and any associated electronic documentation (in each case, in whole or in part) that accompany this Agreement, are set forth in the applicable software manifest and you access "on-line", as well as any updates or upgrades to such software programs or documentation, if any, provided to you at TI's sole discretion.  The Licensed Materials are specifically designed and licensed for use solely and exclusively with MSP microcontroller devices manufactured by or for TI ("TI Devices").  By installing, copying or otherwise using the Licensed Materials you agree to abide by the provisions set forth herein.  This Agreement is displayed for you to read prior to using the Licensed Materials.  If you choose not to accept or agree with these provisions, do not download or install the Licensed Materials.
 *
 **Note Regarding Possible Access to Other Licensed Materials:  The Licensed Materials may be bundled with software and associated electronic documentation, if any, licensed under terms other than the terms of this Agreement (in whole or in part, "Other Licensed Materials"), including, for example Open Source Software and/or TI-owned or third party Proprietary Software licensed under such other terms.  "Open Source Software" means any software licensed under terms requiring that (A) other software ("Proprietary Software") incorporated, combined or distributed with such software or developed using such software: (i) be disclosed or distributed in source code form; or (ii) otherwise be licensed on terms inconsistent with the terms of this Agreement, including but not limited to permitting use of the Proprietary Software on or with devices other than TI Devices, or (B) require the owner of Proprietary Software to license any of its patents to users of the Open Source Software and/or Proprietary Software incorporated, combined or distributed with such Open Source Software or developed using such Open Source Software.
 *
 **If by accepting this Agreement, you gain access to Other Licensed Materials, they will be listed in the applicable software manifest.  Your use of the Other Licensed Materials is subject to the applicable other licensing terms acknowledgements and disclaimers as specified in the applicable software manifest and/or identified or included with the Other Licensed Materials in the software bundle.  For clarification, this Agreement does not limit your rights under, or grant you rights that supersede, the terms of any applicable Other Licensed Materials license agreement.  If any of the Other Licensed Materials is Open Source Software that has been provided to you in object code only under terms that obligate TI to provide to you or show you where you can access the source code versions of such Open Source Software, TI will provide to you, or show you where you can access, such source code if you contact TI at Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager, Embedded Processing.  In the event you choose not to accept or agree with the terms in any applicable Other Licensed Materials license agreement, you must terminate this Agreement.
 *
 **1.    License Grant and Use Restrictions.
 *
 **a.    Licensed Materials License Grant.  Subject to the terms of this Agreement, TI hereby grants to you a limited, non-transferable, non-exclusive, non-assignable, non-sublicensable, fully paid-up and royalty-free license to:
 *
 *            i.    Limited Source Code License:  make copies, prepare derivative works, display internally and use internally the Licensed Materials provided to you in source code for the sole purpose of developing object and executable versions of such Licensed Materials, or any derivative thereof, that execute solely and exclusively on TI Devices, for end use in Licensee Products, and maintaining and supporting such Licensed Materials, or any derivative thereof, and Licensee Products.  For purposes of this Agreement, "Licensee Product" means a product that consists of both hardware, including one or more TI Devices, and software components, including only executable versions of the Licensed Materials that execute solely and exclusively on such TI Devices.
 *
 *            ii.    Object Code Evaluation, Testing and Use License:  make copies, display internally, distribute internally and use internally the Licensed Materials in object code for the sole purposes of evaluating and testing the Licensed Materials and designing and developing Licensee Products, and maintaining and supporting the Licensee Products;
 *
 *            iii.    Demonstration License:  demonstrate to third parties the Licensed Materials executing solely and exclusively on TI Devices as they are used in Licensee Products, provided that such Licensed Materials are demonstrated in object or executable versions only and
 *
 *        iv.    Production and Distribution License:  make, use, import, export and otherwise distribute the Licensed Materials as part of a Licensee Product, provided that such Licensee Products include only embedded executable copies of such Licensed Materials that execute solely and exclusively on TI Devices.
 *
 *    b.    Contractors.  The licenses granted to you hereunder shall include your on-site and off-site contractors (either an individual or entity), while such contractors are performing work for or providing services to you, provided that such contractors have executed work-for-hire agreements with you containing applicable terms and conditions consistent with the terms and conditions set forth in this Agreement and provided further that you shall be liable to TI for any breach by your contractors of this Agreement to the same extent as you would be if you had breached the Agreement yourself.
 *
 *    c.    No Other License.  Nothing in this Agreement shall be construed as a license to any intellectual property rights of TI other than those rights embodied in the Licensed Materials provided to you by TI.  EXCEPT AS PROVIDED HEREIN, NO OTHER LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY OTHER TI INTELLECTUAL PROPERTY RIGHTS IS GRANTED HEREIN.
 *
 *    d.    Covenant not to Sue.  During the term of this Agreement, you agree not to assert a claim against TI or its licensees that the Licensed Materials infringe your intellectual property rights.
 *
 *    e.    Restrictions.  You shall maintain the source code versions of the Licensed Materials under password control protection and shall not disclose such source code versions of the Licensed Materials, to any person other than your employees and contractors whose job performance requires access.  You shall not use the Licensed Materials with a processing device other than a TI Device, and you agree that any such unauthorized use of the Licensed Materials is a material breach of this Agreement.  You shall not use the Licensed Materials for the purpose of analyzing or proving infringement of any of your patents by either TI or TI's customers.  Except as expressly provided in this Agreement, you shall not copy, publish, disclose, display, provide, transfer or make available the Licensed Materials to any third party and you shall not sublicense, transfer, or assign the Licensed Materials or your rights under this Agreement to any third party.  You shall not mortgage, pledge or encumber the Licensed Materials in any way.  You may use the Licensed Materials with Open Source Software or with software developed using Open Source Software tools provided you do not incorporate, combine or distribute the Licensed Materials in a manner that subjects the Licensed Materials to any license obligations or any other intellectual property related terms of any license governing such Open Source Software.
 *
 *    f.    Termination.  This Agreement is effective on the date the Licensed Materials are delivered to you together with this Agreement and will remain in full force and effect until terminated.  You may terminate this Agreement at any time by written notice to TI.  Without prejudice to any other rights, if you fail to comply with the terms of this Agreement or you are acquired, TI may terminate your right to use the Licensed Materials upon written notice to you.  Upon termination of this Agreement, you will destroy any and all copies of the Licensed Materials in your possession, custody or control and provide to TI a written statement signed by your authorized representative certifying such destruction. Except for Sections 1(a), 1(b) and 1(d), all provisions of this Agreement shall survive termination of this Agreement.
 *
 **2.    Licensed Materials Ownership.  The Licensed Materials are licensed, not sold to you, and can only be used in accordance with the terms of this Agreement.  Subject to the licenses granted to you pursuant to this Agreement, TI and its licensors own and shall continue to own all right, title and interest in and to the Licensed Materials, including all copies thereof.  You agree that all fixes, modifications and improvements to the Licensed Materials conceived of or made by TI that are based, either in whole or in part, on your feedback, suggestions or recommendations are the exclusive property of TI and all right, title and interest in and to such fixes, modifications or improvements to the Licensed Materials will vest solely in TI.  Moreover, you acknowledge and agree that when your independently developed software or hardware components are combined, in whole or in part, with the Licensed Materials, your right to use the combined work that includes the Licensed Materials remains subject to the terms and conditions of this Agreement.
 *
 **3.    Intellectual Property Rights.
 *
 *    a.    The Licensed Materials contain copyrighted material, trade secrets and other proprietary information of TI and its licensors and are protected by copyright laws, international copyright treaties, and trade secret laws, as well as other intellectual property laws.  To protect TI's and its licensors' rights in the Licensed Materials, you agree, except as specifically permitted by statute by a provision that cannot be waived by contract, not to "unlock", decompile, reverse engineer, disassemble or otherwise translate to a human-perceivable form any portions of the Licensed Materials provided to you in object code format only, nor permit any person or entity to do so.  You shall not remove, alter, cover, or obscure any confidentiality, trade secret, trade mark, patent, copyright or other proprietary notice or other identifying marks or designs from any component of the Licensed Materials and you shall reproduce and include in all copies of the Licensed Materials the copyright notice(s) and proprietary legend(s) of TI and its licensors as they appear in the Licensed Materials.  TI reserves all rights not specifically granted under this Agreement.
 *
 *    b.    Certain Licensed Materials may be based on industry recognized standards or software programs published by industry recognized standards bodies and certain third parties may claim to own patents, copyrights, and other intellectual property rights that cover implementation of those standards.  You acknowledge and agree that this Agreement does not convey a license to any such third party patents, copyrights, and other intellectual property rights and that you are solely responsible for any patent, copyright, or other intellectual property right claim that relates to your use or distribution of the Licensed Materials or your use or distribution of your products that include or incorporate the Licensed Materials.  Moreover, you acknowledge that you are responsible for any fees or royalties that may be payable to any third party based on such third party's interests in the Licensed Materials or any intellectual property rights that cover implementation of any industry recognized standard, any software program published by any industry recognized standards bodies or any other proprietary technology.
 *
 **4.    Confidential Information.  You acknowledge and agree that the Licensed Materials contain trade secrets and other confidential information of TI and its licensors.  You agree to use the Licensed Materials solely within the scope of the licenses set forth herein, to maintain the Licensed Materials in strict confidence, to use at least the same procedures and degree of care that you use to prevent disclosure of your own confidential information of like importance but in no instance less than reasonable care, and to prevent disclosure of the Licensed Materials to any third party, except as may be necessary and required in connection with your rights and obligations hereunder; provided, however, that you may not provide the Licensed Materials to any business organization or group within your company or to customers or contractors that design or manufacture semiconductors unless TI gives written consent.  You agree to obtain executed confidentiality agreements with your employees and contractors having access to the Licensed Materials and to diligently take steps to enforce such agreements in this respect.  TI may disclose your contact information to TI's licensors.
 *
 **5.    Warranties and Limitations.  THE LICENSED MATERIALS ARE PROVIDED "AS IS".  FURTHERMORE, YOU ACKNOWLEDGE AND AGREE THAT THE LICENSED MATERIALS HAVE NOT BEEN TESTED OR CERTIFIED BY ANY GOVERNMENT AGENCY OR INDUSTRY REGULATORY ORGANIZATION OR ANY OTHER THIRD PARTY ORGANIZATION.  YOU AGREE THAT PRIOR TO USING, INCORPORATING OR DISTRIBUTING THE LICENSED MATERIALS IN OR WITH ANY COMMERCIAL PRODUCT THAT YOU WILL THOROUGHLY TEST THE PRODUCT AND THE FUNCTIONALITY OF THE LICENSED MATERIALS IN OR WITH THAT PRODUCT AND BE SOLELY RESPONSIBLE FOR ANY PROBLEMS OR FAILURES.
 *
 **TI AND ITS LICENSORS MAKE NO WARRANTY OR REPRESENTATION, EITHER EXPRESS, IMPLIED OR STATUTORY, REGARDING THE LICENSED MATERIALS, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT OF ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADE SECRETS OR OTHER INTELLECTUAL PROPERTY RIGHTS.  YOU AGREE TO USE YOUR INDEPENDENT JUDGMENT IN DEVELOPING YOUR PRODUCTS.  NOTHING CONTAINED IN THIS AGREEMENT WILL BE CONSTRUED AS A WARRANTY OR REPRESENTATION BY TI TO MAINTAIN PRODUCTION OF ANY TI SEMICONDUCTOR DEVICE OR OTHER HARDWARE OR SOFTWARE WITH WHICH THE LICENSED MATERIALS MAY BE USED.
 *
 **IN NO EVENT SHALL TI OR ITS LICENSORS, BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, PUNITIVE OR CONSEQUENTIAL DAMAGES, HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, IN CONNECTION WITH OR ARISING OUT OF THIS AGREEMENT OR THE USE OF THE LICENSED MATERIALS REGARDLESS OF WHETHER TI HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  EXCLUDED DAMAGES INCLUDE, BUT ARE NOT LIMITED TO, COST OF REMOVAL OR REINSTALLATION, OUTSIDE COMPUTER TIME, LABOR COSTS, LOSS OF DATA, LOSS OF GOODWILL, LOSS OF PROFITS, LOSS OF SAVINGS, OR LOSS OF USE OR INTERRUPTION OF BUSINESS.  IN NO EVENT WILL TI'S OR ITS LICENSORS' AGGREGATE LIABILITY UNDER THIS AGREEMENT OR ARISING OUT OF YOUR USE OF THE LICENSED MATERIALS EXCEED FIVE HUNDRED U.S. DOLLARS (US$500).
 *
 *    Because some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages or limitation on how long an implied warranty lasts, the above limitations or exclusions may not apply to you.
 *
 **6.    Indemnification Disclaimer.  YOU ACKNOWLEDGE AND AGREE THAT TI SHALL NOT BE LIABLE FOR AND SHALL NOT DEFEND OR INDEMNIFY YOU AGAINST ANY THIRD PARTY INFRINGEMENT CLAIM THAT RELATES TO OR IS BASED ON YOUR MANUFACTURE, USE, OR DISTRIBUTION OF THE LICENSED MATERIALS OR YOUR MANUFACTURE, USE, OFFER FOR SALE, SALE, IMPORTATION OR DISTRIBUTION OF YOUR PRODUCTS THAT INCLUDE OR INCORPORATE THE LICENSED MATERIALS.
 *
 **7.    No Technical Support.  TI and its licensors are under no obligation to install, maintain or support the Licensed Materials.
 *
 **8.    Notices.  All notices to TI hereunder shall be delivered to Texas Instruments Incorporated, 12500 TI Boulevard, Mail Station 8638, Dallas, Texas 75243, Attention: Contracts Manager - Embedded Processing, with a copy to Texas Instruments Incorporated, 13588 N. Central Expressway, Mail Station 3999, Dallas, Texas 75243, Attention: Law Department - Embedded Processing.  All notices shall be deemed served when received by TI.
 *
 **9.    Export Control.  The Licensed Materials are subject to export control under the U.S. Commerce Department's Export Administration Regulations ("EAR").  Unless prior authorization is obtained from the U.S. Commerce Department, neither you nor your subsidiaries shall export, re-export, or release, directly or indirectly (including, without limitation, by permitting the Licensed Materials to be downloaded), any technology, software, or software source code, received from TI, or export, directly or indirectly, any direct product of such technology, software, or software source code, to any person, destination or country to which the export, re-export, or release of the technology, software, or software source code, or direct product is prohibited by the EAR.  You represent and warrant that you (i) are not located in, or under the control of, a national or resident of Cuba, Iran, North Korea, Sudan and Syria or any other country subject to a U.S. goods embargo; (ii) are not on the U.S. Treasury Department's List of Specially Designated Nationals or the U.S. Commerce Department's Denied Persons List or Entity List; and (iii) will not use the Licensed Materials or transfer the Licensed Materials for use in any military, nuclear, chemical or biological weapons, or missile technology end-uses.  Any software export classification made by TI shall not be construed as a representation or warranty regarding the proper export classification for such software or whether an export license or other documentation is required for the exportation of such software.
 *
 **10.    Governing Law and Severability; Waiver.  This Agreement will be governed by and interpreted in accordance with the laws of the State of Texas, without reference to conflict of laws principles.  If for any reason a court of competent jurisdiction finds any provision of the Agreement to be unenforceable, that provision will be enforced to the maximum extent possible to effectuate the intent of the parties, and the remainder of the Agreement shall continue in full force and effect.  This Agreement shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, or by the Uniform Computer Information Transactions Act (UCITA).  The parties agree that non-exclusive jurisdiction for any dispute arising out of or relating to this Agreement lies within the courts located in the State of Texas.  Notwithstanding the foregoing, any judgment may be enforced in any United States or foreign court, and either party may seek injunctive relief in any United States or foreign court.  Failure by TI to enforce any provision of this Agreement shall not be deemed a waiver of future enforcement of that or any other provision in this Agreement or any other agreement that may be in place between the parties.
 *
 **11.    PRC Provisions.  If you are located in the People's Republic of China ("PRC") or if the Licensed Materials will be sent to the PRC, the following provisions shall apply:
 *
 *    a.    Registration Requirements.  You shall be solely responsible for performing all acts and obtaining all approvals that may be required in connection with this Agreement by the government of the PRC, including but not limited to registering pursuant to, and otherwise complying with, the PRC Measures on the Administration of Software Products, Management Regulations on Technology Import-Export, and Technology Import and Export Contract Registration Management Rules.  Upon receipt of such approvals from the government authorities, you shall forward evidence of all such approvals to TI for its records.  In the event that you fail to obtain any such approval or registration, you shall be solely responsible for any and all losses, damages or costs resulting therefrom, and shall indemnify TI for all such losses, damages or costs.
 *
 **b.    Governing Language.  This Agreement is written and executed in the English language and shall be authoritative and controlling, whether or not translated into a language other than English to comply with law or for reference purposes.  If a translation of this Agreement is required for any purpose, including but not limited to registration of the Agreement pursuant to any governmental laws, regulations or rules, you shall be solely responsible for creating such translation.
 *
 **12.    Contingencies.    TI shall not be in breach of this Agreement and shall not be liable for any non-performance or delay in performance if such non-performance or delay is due to a force majeure event or other circumstances beyond TI's reasonable control.
 *
 **13.        Entire Agreement.  This is the entire agreement between you and TI and this Agreement supersedes any prior agreement between the parties related to the subject matter of this Agreement.  Notwithstanding the foregoing, any signed and effective software license agreement relating to the subject matter hereof and stating expressly that such agreement shall control regardless of any subsequent click-wrap, shrink-wrap or web-wrap, shall supersede the terms of this Agreement.  No amendment or modification of this Agreement will be effective unless in writing and signed by a duly authorized representative of TI.  You hereby warrant and represent that you have obtained all authorizations and other applicable consents required empowering you to enter into this Agreement.
 *
 *
 *
 * --/COPYRIGHT--*/
//#############################################################################
//
//! \file   emDCCommandHandlers.c
//!
//! \brief  Implements serial communication protocol between with Energy
//!  Measurement Device
//!
//!  Group:          MSP Embedded Software Development
//!  Target Device:  MSP430i2041
//!
//!  (C) Copyright 2017, Texas Instruments, Inc.
//#############################################################################


#include <msp430.h>
#include <emDCCommandHandlers.h>
#include "driverlib.h"
#include "emSwLib.h"
#include "hal.h"
#include <stdio.h>

#if (COMM_SERIAL_INTERFACE==COMM_UART)
extern volatile uint16_t g_ui16UARTTransmitBytesLeft;
#else
extern volatile uint8_t g_I2CSlaveStatus;
#endif

extern void uart_transmit_byte(uint8_t recieve_byte);
extern void uart_transmit(char *ptr,int len);

COMAND_HANDLER gCommandHandler;

static void Handler_config_mode(Packet_t *packet);
static void Handler_app_version(Packet_t *packet);
static void Handler_req_calib_values(Packet_t *packet);
static void Handler_adc_buffer_size(Packet_t *packet);
static void Handler_calib_values(Packet_t *packet);
static void Handler_calib_phase(Packet_t *packet);
static void Handler_calib_save(Packet_t *packet);

COMAND_HANDLER * CommandHandler_getUserParamsPtr(void)
{
    return &gCommandHandler;
}

void CommandHandler_registerCmdListeners()
{
    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_CONFIG_MODE,
                        &Handler_config_mode);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_APP_VERSION,
                        &Handler_app_version);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_REQ_CALIB_VALUES,
                        &Handler_req_calib_values);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_ADC_BUFFER_SIZE,
                        &Handler_adc_buffer_size);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_CALIB_VALUES,
                        &Handler_calib_values);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_CALIB_PHASE,
                        &Handler_calib_phase);

    Comm_addCmdListener(COMMAND_HANDLER_EM_GUI_ID_BYTE,
                        COMMAND_HANDLER_CALIB_SAVE,
                        &Handler_calib_save);
}


void CommandHandler_transmitPacket(Packet_t *packet)
{
    Comm_writePacket(packet);

#if (COMM_SERIAL_INTERFACE==COMM_UART)
    while(g_ui16UARTTransmitBytesLeft!=0);
#else
    while(g_I2CSlaveStatus != 0x01);
#endif

}

void Handler_config_mode(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        gCommandHandler.appMode = packet->payload[i++];
        // Clear calib phase ID
        gCommandHandler.calibPhaseID = 0x00;
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] = gCommandHandler.appMode;

        Comm_writePacket(packet);
    }
}

void Handler_app_version(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        gCommandHandler.deviceId = (COMMAND_HANDLER_DEVICE_TYPE) packet->payload[i++];
        gCommandHandler.fwId = (COMMAND_HANDLER_FIRMWARE_ID) packet->payload[i++];

    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] = (uint8_t)gCommandHandler.deviceId;
        packet->payload[i++] = (uint8_t)gCommandHandler.fwId;

        Comm_writePacket(packet);
    }
}

void Handler_req_calib_values(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        gCommandHandler.calibReqUpdate = packet->payload[i++];
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] =(uint8_t)gCommandHandler.calibReqUpdate;

        Comm_writePacket(packet);
    }
}

void Handler_adc_buffer_size(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        // Do nothing
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] = (uint8_t) HAL_ADC_V_ARRAY_LENGTH;
        packet->payload[i++] = (uint8_t) HAL_ADC_I_ARRAY_LENGTH;

        Comm_writePacket(packet);
    }
}

void Handler_calib_values(Packet_t *packet)
{
    uint8_t *calib = (uint8_t *) gEmSWConfig.meterConfig->phaseConfigPtr[gCommandHandler.calibPhaseIdx].phaseCalibPtr;

    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        //Voltage Scale Factor
        calib[0] = packet->payload[4];
        calib[1] = packet->payload[5];
        calib[2] = packet->payload[6];
        calib[3] = packet->payload[7];

        // Current Scale Factor
        calib[4] = packet->payload[8];
        calib[5] = packet->payload[9];
        calib[6] = packet->payload[10];
        calib[7] = packet->payload[11];

        // Active Power Scale Factor
        calib[8] = packet->payload[12];
        calib[9] = packet->payload[13];
        calib[10] = packet->payload[14];
        calib[11] = packet->payload[15];

        // Reactive Power Scale Factor
        calib[12] = packet->payload[12];
        calib[13] = packet->payload[13];
        calib[14] = packet->payload[14];
        calib[15] = packet->payload[15];

        // Phase Correction
        calib[16] = packet->payload[16];
        calib[17] = packet->payload[17];

        gCommandHandler.calibSetPreloadFlag = true;
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        //Voltage Scale Factor
        packet->payload[4] = calib[0];
        packet->payload[5] = calib[1];
        packet->payload[6] = calib[2];
        packet->payload[7] = calib[3];

        // Current Scale Factor
        packet->payload[8] = calib[4];
        packet->payload[9] = calib[5];
        packet->payload[10] = calib[6];
        packet->payload[11] = calib[7];

        // Active Power Scale Factor
        packet->payload[12] = calib[8];
        packet->payload[13] = calib[9];
        packet->payload[14] = calib[10];
        packet->payload[15] = calib[11];

        // Phase Correction
        packet->payload[16] = calib[16];
        packet->payload[17] = calib[17];

        Comm_writePacket(packet);
    }
}

void Handler_calib_phase(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        gCommandHandler.calibPhaseID = packet->payload[i];
        gCommandHandler.calibPhaseIdxFlag = true;
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] =(uint8_t)gCommandHandler.calibPhaseID;

        Comm_writePacket(packet);
    }
}

void Handler_calib_save(Packet_t *packet)
{
    uint8_t i = 3;
    //
    // check if WRITE command
    //
    if (packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] ==
            COMMAND_HANDLER_WRITE_CMD)
    {
        gCommandHandler.calibReqSaveFlag = 0x01;
    }else
    {
        packet->payload[COMMAND_HANDLER_R_W_BYTE_POS] =COMMAND_HANDLER_WRITE_CMD;

        // Echo values in case command was received in read command
        packet->payload[i++] =(uint8_t)gCommandHandler.calibPhaseID;

        Comm_writePacket(packet);
    }
}

/**********CommandHandler_setApplicationVersion**********/
/* this function initializes the global variable "gComandHandler" of type "COMAND_HANDLER"
 * ... "COMAND_HANDLER" is the struct that is used to hold all the data received from the GUI
 * this global variable is used to store all the desired values/data retrieved from a GUI 'Request Update'
 *
 * specifically the following routine will initialize the deviceID, and fwId variables within
 * the "COMMAND_HANDLER" struct for "gComandHandler"
 */
void CommandHandler_setApplicationVersion(
        COMMAND_HANDLER_DEVICE_TYPE deviceID,
        COMMAND_HANDLER_FIRMWARE_ID fwId)
{
    gCommandHandler.deviceId = deviceID;
    gCommandHandler.fwId = fwId;

}

void CommandHandler_transmitVRMS(Packet_t *packet,
                                 uint8_t phaseID,
                                 uint8_t *vrms)
{
    uint32_t v_data1;
    uint32_t v_data2;
    uint32_t v_data3;
    uint32_t volt_data;

    packet->length = 8;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_VRMS_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = vrms[0];
    packet->payload[5] = vrms[1];
    packet->payload[6] = vrms[2];
    packet->payload[7] = vrms[3];

   v_data1=vrms[3]<<24;
   v_data2=vrms[2]<<16;
   v_data3=vrms[1]<<8;
   volt_data=vrms[3]|vrms[2]|vrms[1]|vrms[0];

   float voltage = volt_data * (5.0 / 16777216.0);


    //Serial Transmit

       char vrms1[4];
       char setting[4];
       sprintf(setting,"%x%x%X",packet->payload[0],packet->payload[1],packet->payload[2],packet->payload[3]);
       __delay_cycles(1000);
       uart_transmit_byte('\n');
       uart_transmit("Config Bits:",12);
       uart_transmit_byte('\n');
       uart_transmit_byte(setting[0]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(setting[1]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(setting[2]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(setting[3]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);


       //sprintf(vrms1,"%f",voltage);
       sprintf(vrms1,"%d%d%d%d",packet->payload[4],packet->payload[5],packet->payload[6],packet->payload[7]);
       __delay_cycles(1000);
       uart_transmit_byte('\n');
       uart_transmit("Voltage:",8);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(vrms1[3]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(vrms1[2]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(vrms1[1]);
       uart_transmit_byte('\n');
       __delay_cycles(1000);
       uart_transmit_byte(vrms1[0]);
       __delay_cycles(1000);

    //Comm_writePacket(packet);
}

void CommandHandler_transmitIRMS(Packet_t *packet,
                                 uint8_t phaseID,
                                 uint8_t *irms)
{
    packet->length = 8;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_IRMS_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = irms[0];
    packet->payload[5] = irms[1];
    packet->payload[6] = irms[2];
    packet->payload[7] = irms[3];

    //Serial Transmit

       char irms1[4];
       sprintf(irms1,"%d%d%d%d",irms[0],irms[1],irms[2],irms[3]);
       __delay_cycles(1000);
       uart_transmit_byte('\n');
       uart_transmit("Current:",8);
       __delay_cycles(1000);
       uart_transmit_byte(irms1[0]);
       __delay_cycles(1000);
       uart_transmit_byte(irms1[1]);
       __delay_cycles(1000);
       uart_transmit_byte(irms1[2]);
       __delay_cycles(1000);
       uart_transmit_byte(irms1[3]);
       __delay_cycles(1000);

   // Comm_writePacket(packet);
}

void CommandHandler_transmitVPeak(Packet_t *packet,
                                 uint8_t phaseID,
                                 uint8_t *vPeak)
{
    packet->length = 8;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_VPEAK_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = vPeak[0];
    packet->payload[5] = vPeak[1];
    packet->payload[6] = vPeak[2];
    packet->payload[7] = vPeak[3];

  //  Comm_writePacket(packet);
}

void CommandHandler_transmitIPeak(Packet_t *packet,
                                 uint8_t phaseID,
                                 uint8_t *iPeak)
{
    packet->length = 8;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_IPEAK_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = iPeak[0];
    packet->payload[5] = iPeak[1];
    packet->payload[6] = iPeak[2];
    packet->payload[7] = iPeak[3];

  //  Comm_writePacket(packet);
}

void CommandHandler_transmitPowerFactor(Packet_t *packet,
                                        uint8_t phaseID,
                                        uint8_t *pFactor)
{
    packet->length = 8;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_POWER_FACTOR_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = pFactor[0];
    packet->payload[5] = pFactor[1];
    packet->payload[6] = pFactor[2];
    packet->payload[7] = pFactor[3];

    //Serial

    char pFactor1[4];
    sprintf(pFactor1,"%d%d%d%d",pFactor[0],pFactor[1],pFactor[2],pFactor[3]);
    __delay_cycles(1000);
    uart_transmit_byte('\n');
    uart_transmit("Power Factor:",13);
    __delay_cycles(1000);
    uart_transmit_byte(pFactor1[0]);
    __delay_cycles(1000);
    uart_transmit_byte(pFactor1[1]);
    __delay_cycles(1000);
    uart_transmit_byte(pFactor1[2]);
    __delay_cycles(1000);
    uart_transmit_byte(pFactor1[3]);
    __delay_cycles(1000);

  //  Comm_writePacket(packet);
}

void CommandHandler_transmitFrequency(Packet_t *packet,
                                      uint8_t phaseID,
                                      uint8_t *frequency)
{
    packet->length = 6;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_FREQUENCY_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = frequency[0];
    packet->payload[5] = frequency[1];

   // Comm_writePacket(packet);
}

void CommandHandler_transmitActivePower(Packet_t *packet,
                                        uint8_t phaseID,
                                        uint8_t *actPower)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_ACTIVE_POWER_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = actPower[0];
    packet->payload[5] = actPower[1];
    packet->payload[6] = actPower[2];
    packet->payload[7] = actPower[3];
    packet->payload[8] = actPower[4];
    packet->payload[9] = actPower[5];
    packet->payload[10] = actPower[6];
	packet->payload[11] = actPower[7];
	
    //Serial

    char actPower1[8];
    sprintf(actPower1,"%d%d%d%d",actPower[0],actPower[1],actPower[2],actPower[3]);
    __delay_cycles(1000);
    uart_transmit_byte('\n');
    uart_transmit("Active Power:",13);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[0]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[1]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[2]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[3]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[4]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[5]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[6]);
    __delay_cycles(1000);
    uart_transmit_byte(actPower1[7]);
    __delay_cycles(1000);
  //  Comm_writePacket(packet);
}

void CommandHandler_transmitReactivePower(Packet_t *packet,
                                         uint8_t phaseID,
                                         uint8_t *reactPower)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_REACTIVE_POWER_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = reactPower[0];
    packet->payload[5] = reactPower[1];
    packet->payload[6] = reactPower[2];
    packet->payload[7] = reactPower[3];
    packet->payload[8] = reactPower[4];
    packet->payload[9] = reactPower[5];
    packet->payload[10] = reactPower[6];
	packet->payload[11] = reactPower[7];
	
  //  Comm_writePacket(packet);
}

void CommandHandler_transmitApparentPower(Packet_t *packet,
                                          uint8_t phaseID,
                                          uint8_t *appPower)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_APPARENT_POWER_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = appPower[0];
    packet->payload[5] = appPower[1];
    packet->payload[6] = appPower[2];
    packet->payload[7] = appPower[3];
    packet->payload[8] = appPower[4];
    packet->payload[9] = appPower[5];
    packet->payload[10] = appPower[6];
	packet->payload[11] = appPower[7];
	
 //   Comm_writePacket(packet);
}

void CommandHandler_transmitActiveEnergy(Packet_t *packet,
                                         uint8_t phaseID,
                                         uint8_t *actEnergy)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_ACTIVE_ENERGY_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = actEnergy[0];
    packet->payload[5] = actEnergy[1];
    packet->payload[6] = actEnergy[2];
    packet->payload[7] = actEnergy[3];
    packet->payload[8] = actEnergy[4];
    packet->payload[9] = actEnergy[5];
    packet->payload[10] = actEnergy[6];
	packet->payload[11] = actEnergy[7];
	
    //Serial

    char actEnergy1[8];
    sprintf(actEnergy1,"%d%d%d%d",actEnergy[0],actEnergy[1],actEnergy[2],actEnergy[3]);
    __delay_cycles(1000);
    uart_transmit_byte('\n');
    uart_transmit("Active Energy:",13);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[0]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[1]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[2]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[3]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[4]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[5]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[6]);
    __delay_cycles(1000);
    uart_transmit_byte(actEnergy1[7]);
    __delay_cycles(1000);

  //  Comm_writePacket(packet);
}

void CommandHandler_transmitReactiveEnergy(Packet_t *packet,
                                          uint8_t phaseID,
                                          uint8_t *reactEnergy)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_REACTIVE_ENERGY_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = reactEnergy[0];
    packet->payload[5] = reactEnergy[1];
    packet->payload[6] = reactEnergy[2];
    packet->payload[7] = reactEnergy[3];
    packet->payload[8] = reactEnergy[4];
    packet->payload[9] = reactEnergy[5];
    packet->payload[10] = reactEnergy[6];
	packet->payload[11] = reactEnergy[7];
	
 //   Comm_writePacket(packet);
}

void CommandHandler_transmitApparentEnergy(Packet_t *packet,
                                           uint8_t phaseID,
                                           uint8_t *appEnergy)
{
    packet->length = 12;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_APPARENT_ENERGY_ID;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;
    packet->payload[4] = appEnergy[0];
    packet->payload[5] = appEnergy[1];
    packet->payload[6] = appEnergy[2];
    packet->payload[7] = appEnergy[3];
    packet->payload[8] = appEnergy[4];
    packet->payload[9] = appEnergy[5];
    packet->payload[10] = appEnergy[6];
	packet->payload[11] = appEnergy[7];
	
  //  Comm_writePacket(packet);
}

void CommandHandler_transmitCalibration(Packet_t *packet,
                                           uint8_t phaseID,
                                           uint8_t *calib)
{
    packet->length = 18;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_CALIB_VALUES;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = phaseID;

    //Voltage Scale Factor
    packet->payload[4] = calib[0];
    packet->payload[5] = calib[1];
    packet->payload[6] = calib[2];
    packet->payload[7] = calib[3];

    // Current Scale Factor
    packet->payload[8] = calib[4];
    packet->payload[9] = calib[5];
    packet->payload[10] = calib[6];
    packet->payload[11] = calib[7];

    // Active Power Scale Factor
    packet->payload[12] = calib[8];
    packet->payload[13] = calib[9];
    packet->payload[14] = calib[10];
    packet->payload[15] = calib[11];

    // Phase Correction
    packet->payload[16] = calib[16];
    packet->payload[17] = calib[17];

  //  Comm_writePacket(packet);
}

void CommandHandler_transmitReqCalibrationValues(Packet_t *packet)
{
    packet->length = 4;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_REQ_CALIB_VALUES;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    // Target has transmitted all the phase calibration values to EMDC
    packet->payload[3] = COMMAND_HANDLER_CALIB_REQ_COMPLETED;

 //   Comm_writePacket(packet);
}

void CommandHandler_transmitCalibrationSave(Packet_t *packet)
{
    packet->length = 5;
    packet->payload[0] = COMMAND_HANDLER_EM_GUI_ID_BYTE;
    packet->payload[1] = COMMAND_HANDLER_CALIB_SAVE;
    packet->payload[2] = COMMAND_HANDLER_WRITE_CMD;
    packet->payload[3] = gCommandHandler.calibPhaseID;
    // Target has finished writing calibration values to flash
    packet->payload[4] = 0x01;

 //   Comm_writePacket(packet);
}

If there is any better idea, please suggest to me how to transfer the raw data through serial communication to another controller.

and also I want to know how the (Vrms/Irms/etc) 4 bytes of data are displayed in the GUI in floating number. what happened behind the GUI since all the conversions took place in the EMDC software side I guess. 

  • Hi Murugan,

    Can you explain a little more on the values constantly differing? Are you saying they differ per run or your values differ from the values in the EDMC GUI?

    I'm also concerned with all the delays you have. There are delays in your uart transmit and delays before you call the function, I think these compounded delays could be adding to some issues you are seeing. 

    Regards,

    Luke

  • Hi Luke,

    Thanks for all your support...

    Finally I almost completed this project through serial communication by writing and reading hex values. To add additional code, I wrote my own state machine and now it's working fine. In future if I need any help on this project, I will create a new thread.

    Thanks & Regards

    Murugan

**Attention** This is a public forum