1 /* 2 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha (at) intel.com> 3 * Copyright (c) 2014 Intel Corporation. 4 * 5 * Permission is hereby granted, free of charge, to any person obtaining 6 * a copy of this software and associated documentation files (the 7 * "Software"), to deal in the Software without restriction, including 8 * without limitation the rights to use, copy, modify, merge, publish, 9 * distribute, sublicense, and/or sell copies of the Software, and to 10 * permit persons to whom the Software is furnished to do so, subject to 11 * the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be 14 * included in all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 */ 24 25 #include <iostream> 26 #include <unistd.h> 27 #include <stdlib.h> 28 #include <string> 29 #include <stdexcept> 30 31 #include "ecs1030.h" 32 33 using namespace upm; 34 35 ECS1030::ECS1030 (uint8_t pinNumber) { 36 m_dataPinCtx = mraa_aio_init(pinNumber); 37 if (m_dataPinCtx == NULL) { 38 throw std::invalid_argument(std::string(__FUNCTION__) + 39 ": mraa_aio_init() failed"); 40 } 41 42 m_calibration = 111.1; 43 } 44 45 ECS1030::~ECS1030 () { 46 mraa_result_t error = MRAA_SUCCESS; 47 48 error = mraa_aio_close (m_dataPinCtx); 49 if (error != MRAA_SUCCESS) { 50 } 51 } 52 53 double 54 ECS1030::getCurrency_A () { 55 int sensorValue = 0; 56 float rLoad = 0; 57 float volt = 0; 58 float rms = 0; 59 60 for (int i = 0; i < NUMBER_OF_SAMPLES; i++) { 61 sensorValue = mraa_aio_read (m_dataPinCtx); 62 volt = (VOLT_M * sensorValue) - 2.5; 63 volt = volt * volt; 64 rms = rms + volt; 65 usleep (DELAY_MS); 66 } 67 68 rms = rms / (float)NUMBER_OF_SAMPLES; 69 rms = sqrt(rms); 70 return rms / R_LOAD; 71 } 72 73 double 74 ECS1030::getCurrency_B () { 75 double sumCurrency = 0; 76 77 for (int i = 0; i < NUMBER_OF_SAMPLES; i++) { 78 m_lastSample = m_sample; 79 m_sample = mraa_aio_read (m_dataPinCtx); 80 m_lastFilter = m_filteredSample; 81 m_filteredSample = 0.996 * (m_lastFilter + m_sample - m_lastSample); 82 sumCurrency += (m_filteredSample * m_filteredSample); 83 } 84 85 double ratio = m_calibration * ((SUPPLYVOLTAGE / 1000.0) / (ADC_RESOLUTION)); 86 return ( ratio * sqrt(sumCurrency / NUMBER_OF_SAMPLES) ); 87 } 88 89 double 90 ECS1030::getPower_A () { 91 return 220.0 * getCurrency_A (); 92 } 93 94 double 95 ECS1030::getPower_B () { 96 return 220.0 * getCurrency_B (); 97 } 98