gfurtadoalmeida / esp32-driver-mcp320x

ESP32 driver for Microchip MCP3204 and MCP3208 12-bit ADCs.
MIT License
12 stars 2 forks source link

esp32 cpu crashes when reading is done in a loop #3

Closed isfandyarIOTMAV closed 1 year ago

isfandyarIOTMAV commented 1 year ago

Cpu crashes when your example code is put in a while (1) loop with vtask delay

gfurtadoalmeida commented 1 year ago

Are you putting the entire code in the while body or just the acquire, read, and release methods? Could you share your code?

isfandyarIOTMAV commented 1 year ago

Are you putting the entire code in the while body or just the acquire, read, and release methods? Could you share your code?

following code causes crashes and you comment out release and delete it stops but i cannot use your mcp320x_read or read voltage inside a for loop or called in another function

``void app_main() { spi_bus_config_t bus_cfg = {.mosi_io_num = GPIO_NUM_23, .miso_io_num = GPIO_NUM_19, .sclk_io_num = GPIO_NUM_18, .quadwp_io_num = -1, .quadhd_io_num = -1, .data4_io_num = -1, .data5_io_num = -1, .data6_io_num = -1, .data7_io_num = -1, .max_transfer_sz = 3, // 24 bits. .flags = SPICOMMON_BUSFLAG_MASTER, .intr_flags = ESP_INTR_FLAG_LEVEL3};

mcp320x_config_t mcp320x_cfg = {.host = SPI3_HOST, .device_model = MCP3208_MODEL, .clock_speed_hz = 1 1000 1000, // 1 Mhz. .reference_voltage = 3300, // 5V .cs_io_num = GPIO_NUM_5};

// Bus initialization is up to the developer. spi_bus_initialize(mcp320x_cfg.host, &bus_cfg, 0);

// Add the device to the SPI bus. mcp320x_t *mcp320x_handle = mcp320x_install(&mcp320x_cfg);

// Occupy the SPI bus for multiple transactions. mcp320x_acquire(mcp320x_handle, portMAX_DELAY);

uint16_t voltage = 0; while (1) { // Read voltage, sampling 1000 times. mcp320x_read_voltage(mcp320x_handle, MCP320X_CHANNEL_0, MCP320X_READ_MODE_SINGLE, 1000, &voltage);

// Unoccupy the SPI bus.
mcp320x_release(mcp320x_handle);

//     Free resources.
mcp320x_delete(mcp320x_handle);

ESP_LOGI("mcp320x", "Voltage: %d mV", voltage);
vTaskDelay(1000 / portTICK_PERIOD_MS);

} }"

isfandyarIOTMAV commented 1 year ago

plus in you example i had to remove " .isr_cpu_id = INTR_CPU_ID_AUTO," from spi config because in esp 5.1.1 its not there

isfandyarIOTMAV commented 1 year ago

assert failed: xQueueSemaphoreTake IDF\components\freertos\queue.c:1545 (( pxQueue )) error

gfurtadoalmeida commented 1 year ago

You're acquiring the bus before the while loop and then releasing it and freeing the driver on every interation of your loop.

Calling mcp320x_delete will delete the driver, freeing all internal resources, rendering it unusable and causing the assert failed: xQueueSemaphoreTake IDF\components\freertos\queue.c:1545 (( pxQueue )) error when calling mcp320x_release on the next iteration.

Trying to free the bus (mcp320x_release) after it was freed will raise an error too.

Try this:

void app_main() {
    spi_bus_config_t bus_cfg = {.mosi_io_num = GPIO_NUM_23,
    .miso_io_num = GPIO_NUM_19,
    .sclk_io_num = GPIO_NUM_18,
    .quadwp_io_num = -1,
    .quadhd_io_num = -1,
    .data4_io_num = -1,
    .data5_io_num = -1,
    .data6_io_num = -1,
    .data7_io_num = -1,
    .max_transfer_sz = 3, // 24 bits.
    .flags = SPICOMMON_BUSFLAG_MASTER,
    .intr_flags = ESP_INTR_FLAG_LEVEL3};

    mcp320x_config_t mcp320x_cfg = {.host = SPI3_HOST,
    .device_model = MCP3208_MODEL,
    .clock_speed_hz = 1 * 1000 * 1000, // 1 Mhz.
    .reference_voltage = 3300, // 5V
    .cs_io_num = GPIO_NUM_5};

    // Bus initialization is up to the developer.
    spi_bus_initialize(mcp320x_cfg.host, &bus_cfg, 0);

    // Add the device to the SPI bus.
    mcp320x_t *mcp320x_handle = mcp320x_install(&mcp320x_cfg);

    uint16_t voltage = 0;

    while (1) {
        // Occupy the SPI bus for multiple transactions.
        mcp320x_acquire(mcp320x_handle, portMAX_DELAY);

        // Read voltage, sampling 1000 times.
        mcp320x_read_voltage(mcp320x_handle, MCP320X_CHANNEL_0, MCP320X_READ_MODE_SINGLE, 1000, &voltage);

        // Unoccupy the SPI bus.
        mcp320x_release(mcp320x_handle);

        ESP_LOGI("mcp320x", "Voltage: %d mV", voltage);

        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }

    // Free resources.
    mcp320x_delete(mcp320x_handle);
}
isfandyarIOTMAV commented 1 year ago

@gfurtadoalmeida thank you this works but this causes core 0 panic i am running some calculation to measure current from sensors

#include "MCP3208.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "math.h"

double offsetI;
double filteredI;
double sqV, sumV, sqI, sumI, instP, sumP;
double realPower, apparentPower, powerFactor, Vrms, Irms;

double calcIrms_with_mcp3208(int numberOfSamples, mcp320x_t *handle) {
  uint16_t sampleI = 0;
  double sumI = 0;

  for (int n = 0; n < numberOfSamples; n++) {
    mcp320x_acquire(handle, portMAX_DELAY);
    mcp320x_read(handle, MCP320X_READ_MODE_SINGLE, MCP320X_CHANNEL_0, 1000,
                 &sampleI);

    offsetI = (offsetI + (sampleI - offsetI) / 1024);
    filteredI = sampleI - offsetI;

    // Root-mean-square method current
    // 1) square current values
    sqI = filteredI * filteredI;
    // 2) sum
    sumI += sqI;
    mcp320x_release(handle);
    vTaskDelay(500);
  }
  // Unoccupy the SPI bus.

  double I_RATIO = 90.9 * ((3300 / 1000.0) / (4096));
  Irms = I_RATIO * sqrt(sumI / numberOfSamples);

  // Reset accumulators
  sumI = 0;
  mcp320x_delete(handle);
  //--------------------------------------------------------------------------------------

  return Irms;
}

void app_main() {
  spi_bus_config_t bus_cfg = {.mosi_io_num = GPIO_NUM_23,
                              .miso_io_num = GPIO_NUM_19,
                              .sclk_io_num = GPIO_NUM_18,
                              .quadwp_io_num = -1,
                              .quadhd_io_num = -1,
                              .data4_io_num = -1,
                              .data5_io_num = -1,
                              .data6_io_num = -1,
                              .data7_io_num = -1,
                              .max_transfer_sz = 3, // 24 bits.
                              .flags = SPICOMMON_BUSFLAG_MASTER,
                              .intr_flags = ESP_INTR_FLAG_LEVEL3};

  mcp320x_config_t mcp320x_cfg = {.host = SPI3_HOST,
                                  .device_model = MCP3208_MODEL,
                                  .clock_speed_hz = 1 * 1000 * 1000, // 1 Mhz.
                                  .reference_voltage = 3300,         // 5V
                                  .cs_io_num = GPIO_NUM_5};

  // Bus initialization is up to the developer.
  spi_bus_initialize(mcp320x_cfg.host, &bus_cfg, 0);

  // Add the device to the SPI bus.
  mcp320x_t *mcp320x_handle = mcp320x_install(&mcp320x_cfg);

  uint16_t voltage = 0;
  double irms;
  while (1) {
    // Occupy the SPI bus for multiple transactions.
    irms = calcIrms_with_mcp3208(1048, &mcp320x_handle);

    ESP_LOGI("mcp320x", "Current: %f mA", irms);

    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }

  // Free resources.
  // mcp320x_delete(mcp320x_handle);
}
gfurtadoalmeida commented 1 year ago

Can you post the entire error?

You can move mcp320x_acquire(handle, portMAX_DELAY); to before the for loop and move the mcp320x_release(handle); after the for loop.

 mcp320x_acquire(handle, portMAX_DELAY);

 for (int n = 0; n < numberOfSamples; n++) {
    mcp320x_read(handle, MCP320X_READ_MODE_SINGLE, MCP320X_CHANNEL_0, 1000,
                 &sampleI);

    offsetI = (offsetI + (sampleI - offsetI) / 1024);
    filteredI = sampleI - offsetI;

    // Root-mean-square method current
    // 1) square current values
    sqI = filteredI * filteredI;
    // 2) sum
    sumI += sqI;

    vTaskDelay(500);
  }
  // Unoccupy the SPI bus.
  mcp320x_release(handle);
isfandyarIOTMAV commented 1 year ago

doing that causes this Rebooting... ets Jun 8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x12 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:2 load:0x3fff0030,len:6608 load:0x40078000,len:14788 ho 0 tail 12 room 4 load:0x40080400,len:3792 entry 0x40080694 ␛[0;32mI (29) boot: ESP-IDF 4.4.1 2nd stage bootloader␛[0m ␛[0;32mI (29) boot: compile time 17:48:13␛[0m ␛[0;32mI (29) boot: chip revision: 1␛[0m ␛[0;32mI (32) boot_comm: chip revision: 1, min. bootloader chip revision: 0␛[0m ␛[0;32mI (39) boot.esp32: SPI Speed : 40MHz␛[0m ␛[0;32mI (43) boot.esp32: SPI Mode : DIO␛[0m ␛[0;32mI (48) boot.esp32: SPI Flash Size : 4MB␛[0m ␛[0;32mI (52) boot: Enabling RNG early entropy source...␛[0m ␛[0;32mI (58) boot: Partition Table:␛[0m ␛[0;32mI (61) boot: ## Label Usage Type ST Offset Length␛[0m ␛[0;32mI (69) boot: 0 nvs WiFi data 01 02 00009000 00006000␛[0m ␛[0;32mI (76) boot: 1 phy_init RF data 01 01 0000f000 00001000␛[0m ␛[0;32mI (84) boot: 2 factory factory app 00 00 00010000 00100000␛[0m ␛[0;32mI (91) boot: End of partition table␛[0m ␛[0;32mI (95) boot_comm: chip revision: 1, min. application chip revision: 0␛[0m ␛[0;32mI (102) esp_image: segment 0: paddr=00010020 vaddr=3f400020 size=09518h ( 38168) map␛[0m ␛[0;32mI (125) esp_image: segment 1: paddr=00019540 vaddr=3ffb0000 size=024a0h ( 9376) load␛[0m ␛[0;32mI (129) esp_image: segment 2: paddr=0001b9e8 vaddr=40080000 size=04630h ( 17968) load␛[0m ␛[0;32mI (138) esp_image: segment 3: paddr=00020020 vaddr=400d0020 size=17854h ( 96340) map␛[0m ␛[0;32mI (174) esp_image: segment 4: paddr=0003787c vaddr=40084630 size=08630h ( 34352) load␛[0m ␛[0;32mI (188) esp_image: segment 5: paddr=0003feb4 vaddr=50000000 size=00010h ( 16) load␛[0m ␛[0;32mI (195) boot: Loaded app from partition at offset 0x10000␛[0m ␛[0;32mI (195) boot: Disabling RNG early entropy source...␛[0m ␛[0;32mI (208) cpu_start: Pro cpu up.␛[0m ␛[0;32mI (209) cpu_start: Starting app cpu, entry point is 0x40082330␛[0m ␛[0;32mI (195) cpu_start: App cpu up.␛[0m ␛[0;32mI (223) cpu_start: Pro cpu start user code␛[0m ␛[0;32mI (223) cpu_start: cpu freq: 160000000␛[0m ␛[0;32mI (223) cpu_start: Application information:␛[0m ␛[0;32mI (227) cpu_start: Project name: esp32_ads1115␛[0m ␛[0;32mI (233) cpu_start: App version: 1␛[0m ␛[0;32mI (237) cpu_start: Compile time: Oct 27 2023 17:45:47␛[0m ␛[0;32mI (243) cpu_start: ELF file SHA256: 564bce5caa48174c...␛[0m ␛[0;32mI (249) cpu_start: ESP-IDF: 4.4.1␛[0m ␛[0;32mI (254) heap_init: Initializing. RAM available for dynamic allocation:␛[0m ␛[0;32mI (262) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM␛[0m ␛[0;32mI (268) heap_init: At 3FFB2E20 len 0002D1E0 (180 KiB): DRAM␛[0m ␛[0;32mI (274) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM␛[0m ␛[0;32mI (280) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM␛[0m ␛[0;32mI (287) heap_init: At 4008CC60 len 000133A0 (76 KiB): IRAM␛[0m ␛[0;32mI (294) spi_flash: detected chip: generic␛[0m ␛[0;32mI (297) spi_flash: flash io: dio␛[0m ␛[0;32mI (302) cpu_start: Starting scheduler on PRO CPU.␛[0m ␛[0;32mI (0) cpu_start: Starting scheduler on APP CPU.␛[0m Guru Meditation Error: Core 0 panic'ed (LoadProhibited). Exception was unhandled.

Core 0 register dump: PC : 0x400814df PS : 0x00060830 A0 : 0x80081779 A1 : 0x3ffb59f0
A2 : 0xe82dfe76 A3 : 0x00001800 A4 : 0x0000000c A5 : 0x00000000 A6 : 0x3ffb6dfc A7 : 0x00000000 A8 : 0x8008350b A9 : 0x3ffb59d0
A10 : 0x3ffb6e60 A11 : 0x00001800 A12 : 0x3ffaed60 A13 : 0x00000000 A14 : 0x3ffb6ce0 A15 : 0x00000000 SAR : 0x00000017 EXCCAUSE: 0x0000001c
EXCVADDR: 0xe82dfefe LBEG : 0x4000c2e0 LEND : 0x4000c2f6 LCOUNT : 0x00000000

Backtrace:0x400814dc:0x3ffb59f00x40081776:0x3ffb5a10 0x400d0f0b:0x3ffb5a40 0x400d10bf:0x3ffb5a70 0x400d11d8:0x3ffb5ab0 0x400e7690:0x3ffb5b30 0x400889a1:0x3ffb5b50

gfurtadoalmeida commented 1 year ago

Your function calcIrms_with_mcp3208(int numberOfSamples, mcp320x_t *handle) expects a mcp320x_t pointer. The following line might be the problem as you're passing the address of the pointer instead of the pointer.

irms = calcIrms_with_mcp3208(1048, &mcp320x_handle);

Could you change it to the following line?

irms = calcIrms_with_mcp3208(1048, mcp320x_handle);
isfandyarIOTMAV commented 1 year ago

for further debugging this the result of my core dump

===============================================================
==================== ESP32 CORE DUMP START ====================

Crashed task handle: 0x3ffb5c08, name: 'main', GDB name: 'process 1073437704'

================== CURRENT THREAD REGISTERS ===================
exccause       0x1c (LoadProhibitedCause)
excvaddr       0x99125e0
epc1           0x0
epc2           0x0
epc3           0x0
epc4           0x0
epc5           0x0
epc6           0x0
epc7           0x0
eps2           0x0
eps3           0x0
eps4           0x0
eps5           0x0
eps6           0x0
eps7           0x0
pc             0x400816af          0x400816af <get_acquiring_dev+3>
lbeg           0x4000c2e0          1073791712
lend           0x4000c2f6          1073791734
lcount         0x0                 0
sar            0x1c                28
ps             0x60a20             395808
threadptr      <unavailable>
br             <unavailable>
scompare1      <unavailable>
acclo          <unavailable>
acchi          <unavailable>
m0             <unavailable>
m1             <unavailable>
m2             <unavailable>
m3             <unavailable>
expstate       <unavailable>
f64r_lo        <unavailable>
f64r_hi        <unavailable>
f64s           <unavailable>
fcr            <unavailable>
fsr            <unavailable>
a0             0x800816d5          -2146953515
a1             0x3ffb5a00          1073437184
a2             0x9912558           160507224
a3             0x1800              6144
a4             0x3ffae884          1073408132
a5             0x0                 0
a6             0x2                 2
a7             0x0                 0
a8             0x80083c0c          -2146943988
a9             0x3ffb59d0          1073437136
a10            0x3ffb6fd0          1073442768
a11            0x3ffb6fd0          1073442768
a12            0x0                 0
a13            0x60e23             396835
a14            0xb33fffff          -1287651329
a15            0xb33fffff          -1287651329

==================== CURRENT THREAD STACK =====================
#0  get_acquiring_dev (host=0x9912558) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:555
#1  0x400816d5 in spi_bus_device_is_polling (dev=0x3ffb6fd0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:566
#2  0x40081980 in spi_device_acquire_bus (device=0x3ffb6fd0, wait=4294967295) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:977
#3  0x400d125e in mcp320x_acquire (handle=0x3ffb5b28, timeout=4294967295) at src/MCP3208.c:66
#4  0x400d1416 in calcIrms_with_mcp3208 (numberOfSamples=1048, handle=0x3ffb5b28) at src/main.c:146
#5  0x400d1565 in app_main () at src/main.c:206
#6  0x400892e7 in main_task (args=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\app_startup.c:208
#7  0x40088ef0 in vPortTaskWrapper (pxCode=0x40089250 <main_task>, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

======================== THREADS INFO =========================
  Id   Target Id          Frame
* 1    process 1073437704 get_acquiring_dev (host=0x9912558) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:555
  2    process 1073439588 vPortTaskWrapper (pxCode=0x0, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:161
  3    process 1073441472 0x400856b6 in esp_cpu_wait_for_intr () at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\esp_hw_support\\cpu.c:121
  4    process 1073411412 0x4000bff0 in ?? ()
  5    process 1073413640 0x4000bff0 in ?? ()
  6    process 1073413296 0x4000bff0 in ?? ()

==================== THREAD 1 (TCB: 0x3ffb5c08, name: 'main') =====================
#0  get_acquiring_dev (host=0x9912558) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:555
#1  0x400816d5 in spi_bus_device_is_polling (dev=0x3ffb6fd0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:566
#2  0x40081980 in spi_device_acquire_bus (device=0x3ffb6fd0, wait=4294967295) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\driver\\spi\\gpspi\\spi_master.c:977
#3  0x400d125e in mcp320x_acquire (handle=0x3ffb5b28, timeout=4294967295) at src/MCP3208.c:66
#4  0x400d1416 in calcIrms_with_mcp3208 (numberOfSamples=1048, handle=0x3ffb5b28) at src/main.c:146
#5  0x400d1565 in app_main () at src/main.c:206
#6  0x400892e7 in main_task (args=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\app_startup.c:208
#7  0x40088ef0 in vPortTaskWrapper (pxCode=0x40089250 <main_task>, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

==================== THREAD 2 (TCB: 0x3ffb6364, name: 'IDLE') =====================
#0  vPortTaskWrapper (pxCode=0x0, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:161
#1  0x40000000 in ?? ()

==================== THREAD 3 (TCB: 0x3ffb6ac0, name: 'IDLE') =====================
#0  0x400856b6 in esp_cpu_wait_for_intr () at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\esp_hw_support\\cpu.c:121
#1  0x400d507a in esp_vApplicationIdleHook () at C:/Users/ISFAND_PC/.platformio/packages/framework-espidf/components/esp_system/freertos_hooks.c:59
#2  0x400878c5 in prvIdleTask (pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\       asks.c:4327
#3  0x40088ef0 in vPortTaskWrapper (pxCode=0x400878bc <prvIdleTask>, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

==================== THREAD 4 (TCB: 0x3ffaf554, name: 'ipc0') =====================
#0  0x4000bff0 in ?? ()
#1  0x400891d6 in vPortClearInterruptMaskFromISR (prev_level=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\include/freertos/portmacro.h:568
#2  vPortExitCritical (mux=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:532
#3  0x40088965 in xTaskGenericNotifyWait (uxIndexToWait=0, ulBitsToClearOnEntry=<optimized out>, ulBitsToClearOnExit=4294967295, pulNotificationValue=0x3ffaf490, xTicksToWait=4294967295) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\     asks.c:5911
#4  0x40082641 in ipc_task (arg=0x0) at C:/Users/ISFAND_PC/.platformio/packages/framework-espidf/components/esp_system/esp_ipc.c:58
#5  0x40088ef0 in vPortTaskWrapper (pxCode=0x40082614 <ipc_task>, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

==================== THREAD 5 (TCB: 0x3ffafe08, name: 'esp_timer') =====================
#0  0x4000bff0 in ?? ()
#1  0x400891d6 in vPortClearInterruptMaskFromISR (prev_level=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\include/freertos/portmacro.h:568
#2  vPortExitCritical (mux=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:532
#3  0x40088829 in ulTaskGenericNotifyTake (uxIndexToWait=0, xClearCountOnExit=1, xTicksToWait=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\ asks.c:5820
#4  0x400d5a1f in timer_task (arg=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\esp_timer\\src\\esp_timer.c:475
#5  0x40088ef0 in vPortTaskWrapper (pxCode=0x400d5a10 <timer_task>, pvParameters=0x0) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

==================== THREAD 6 (TCB: 0x3ffafcb0, name: 'ipc1') =====================
#0  0x4000bff0 in ?? ()
#1  0x400891d6 in vPortClearInterruptMaskFromISR (prev_level=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\include/freertos/portmacro.h:568
#2  vPortExitCritical (mux=<optimized out>) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:532
#3  0x40088965 in xTaskGenericNotifyWait (uxIndexToWait=0, ulBitsToClearOnEntry=<optimized out>, ulBitsToClearOnExit=4294967295, pulNotificationValue=0x3ffafbf0, xTicksToWait=4294967295) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\     asks.c:5911
#4  0x40082641 in ipc_task (arg=0x1) at C:/Users/ISFAND_PC/.platformio/packages/framework-espidf/components/esp_system/esp_ipc.c:58
#5  0x40088ef0 in vPortTaskWrapper (pxCode=0x40082614 <ipc_task>, pvParameters=0x1) at C:\\Users\\ISFAND_PC\\.platformio\\packages\\framework-espidf\\components\\freertos\\FreeRTOS-Kernel\\portable\\xtensa\\port.c:162

======================= ALL MEMORY REGIONS ========================
Name   Address   Size   Attrs
.rtc.text 0x400c0000 0x0 RW
.rtc.dummy 0x3ff80000 0x0 RW
.rtc.force_fast 0x3ff80000 0x0 RW
.rtc_noinit 0x50000000 0x0 RW
.rtc.force_slow 0x50000000 0x0 RW
.rtc_fast_reserved 0x3ff82000 0x0 RW
.iram0.vectors 0x40080000 0x403 R XA
.iram0.text 0x40080404 0xdb0f R XA
.dram0.data 0x3ffb0000 0x2ee4 RW A
.ext_ram_noinit 0x3f800000 0x0 RW
.ext_ram.bss 0x3f800000 0x0 RW
.flash.appdesc 0x3f400020 0x100 R  A
.flash.rodata 0x3f400120 0xb08c RW A
.flash.rodata_noload 0x3f40b1ac 0x0 RW
.flash.text 0x400d0020 0x1708f R XA
.iram0.data 0x4008df14 0x0 RW
.iram0.bss 0x4008df14 0x0 RW
.dram0.heap_start 0x3ffb3850 0x0 RW
.coredump.tasks.data 0x3ffb5c08 0x154 RW
.coredump.tasks.data 0x3ffb5940 0x2c0 RW
.coredump.tasks.data 0x3ffb6364 0x154 RW
.coredump.tasks.data 0x3ffb6230 0x120 RW
.coredump.tasks.data 0x3ffb6ac0 0x154 RW
.coredump.tasks.data 0x3ffb6910 0x1a0 RW
.coredump.tasks.data 0x3ffaf554 0x154 RW
.coredump.tasks.data 0x3ffaf380 0x1c0 RW
.coredump.tasks.data 0x3ffafe08 0x154 RW
.coredump.tasks.data 0x3ffb4a40 0x1b0 RW
.coredump.tasks.data 0x3ffafcb0 0x154 RW
.coredump.tasks.data 0x3ffafae0 0x1c0 RW

===================== ESP32 CORE DUMP END =====================
===============================================================
Exception in thread Thread-1 (_readerthread):
Exception in thread Thread-2 (_readerthread):
Traceback (most recent call last):
Traceback (most recent call last):
  File "threading.py", line 1038, in _bootstrap_inner
  File "threading.py", line 1038, in _bootstrap_inner
  File "threading.py", line 975, in run
  File "threading.py", line 975, in run
  File "subprocess.py", line 1552, in _readerthread
  File "subprocess.py", line 1552, in _readerthread
OSError: [Errno 22] Invalid argument
OSError: [Errno 22] Invalid argument
Done!``
gfurtadoalmeida commented 1 year ago

Did you try the fix suggested on this comment?

I've changed the example and committed it.

isfandyarIOTMAV commented 1 year ago

yes i have tried your suggestion of passing point instead of address still does not work your example does not in main_app()

there is some issue when libraries is called from other functions i will further test it out

Thank you for your help

gfurtadoalmeida commented 1 year ago

@isfandyarIOTMAV, you're deleting the driver on your calcIrms_with_mcp3208 function and you inverted the parameters on mcp320x_read.

I've adjusted your code, it is working now:

#include "esp32_driver_mcp320x/mcp320x.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "math.h"

double offsetI;
double filteredI;
double sqV, sumV, sqI, sumI, instP, sumP;
double realPower, apparentPower, powerFactor, Vrms, Irms;

double calcIrms_with_mcp3208(int numberOfSamples, mcp320x_t *handle)
{
    uint16_t sampleI = 0;
    double sumI = 0;

    mcp320x_acquire(handle, portMAX_DELAY);

    for (int n = 0; n < numberOfSamples; n++)
    {
        mcp320x_read(handle, MCP320X_CHANNEL_0, MCP320X_READ_MODE_SINGLE, 1000,
                     &sampleI);

        offsetI = (offsetI + (sampleI - offsetI) / 1024);
        filteredI = sampleI - offsetI;

        // Root-mean-square method current
        // 1) square current values
        sqI = filteredI * filteredI;
        // 2) sum
        sumI += sqI;
        vTaskDelay(10);
    }

    // Unoccupy the SPI bus.
    mcp320x_release(handle);

    double I_RATIO = 90.9 * ((3300 / 1000.0) / (4096));
    Irms = I_RATIO * sqrt(sumI / numberOfSamples);

    return Irms;
}

void app_main(void)
{
    spi_bus_config_t bus_cfg = {.mosi_io_num = GPIO_NUM_23,
                                .miso_io_num = GPIO_NUM_19,
                                .sclk_io_num = GPIO_NUM_18,
                                .quadwp_io_num = -1,
                                .quadhd_io_num = -1,
                                .data4_io_num = -1,
                                .data5_io_num = -1,
                                .data6_io_num = -1,
                                .data7_io_num = -1,
                                .max_transfer_sz = 3, // 24 bits.
                                .flags = SPICOMMON_BUSFLAG_MASTER,
                                .intr_flags = ESP_INTR_FLAG_LEVEL3};

    mcp320x_config_t mcp320x_cfg = {.host = SPI3_HOST,
                                    .device_model = MCP3204_MODEL,
                                    .clock_speed_hz = 1 * 1000 * 1000, // 1 Mhz.
                                    .reference_voltage = 3300,         // 5V
                                    .cs_io_num = GPIO_NUM_22};

    // Bus initialization is up to the developer.
    spi_bus_initialize(mcp320x_cfg.host, &bus_cfg, 0);

    // Add the device to the SPI bus.
    mcp320x_t *mcp320x_handle = mcp320x_install(&mcp320x_cfg);

    ESP_LOGI("mcp320x", "Initializaing readings");

    while (1)
    {
        // Occupy the SPI bus for multiple transactions.
        double irms = calcIrms_with_mcp3208(100, mcp320x_handle);

        ESP_LOGI("mcp320x", "Current: %f mA", irms);

        vTaskDelay(pdMS_TO_TICKS(1000));
    }

    // Free resources.
    mcp320x_delete(mcp320x_handle);
}

Log output:

I (0) cpu_start: App cpu up.
I (209) cpu_start: Pro cpu start user code
I (209) cpu_start: cpu freq: 240000000 Hz
I (209) cpu_start: Application information:
I (214) cpu_start: Project name:     esp32_driver_mcp320x
I (220) cpu_start: App version:      ef191ba-dirty
I (226) cpu_start: Compile time:     Oct 28 2023 13:21:19
I (232) cpu_start: ELF file SHA256:  2c4f7aa547601147...
I (238) cpu_start: ESP-IDF:          v5.1-dirty
I (243) cpu_start: Min chip rev:     v1.0
I (248) cpu_start: Max chip rev:     v3.99
I (253) cpu_start: Chip rev:         v1.0
I (257) heap_init: Initializing. RAM available for dynamic allocation:
I (265) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (270) heap_init: At 3FFB2AE0 len 0002D520 (181 KiB): DRAM
I (277) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (283) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (290) heap_init: At 4008D728 len 000128D8 (74 KiB): IRAM
I (297) spi_flash: detected chip: generic
I (300) spi_flash: flash io: dio
I (305) app_start: Starting scheduler on CPU0
I (0[0 a2mIstart: Star_ing : heduter on CPU0

I (314) main_task: Calling app_main()
I (319) mcp320x: Initializaing readings
I (49579) mcp320x: Current: 16.595403 mA
isfandyar01 commented 1 year ago

thanks alot it is working I really appreciate your efforts