Uan Dung / Mbed OS Final4

Dependencies:   MLX90614

Files at this revision

API Documentation at this revision

Comitter:
Uan
Date:
Tue Jun 30 07:38:14 2020 +0000
Commit message:
Test;

Changed in this revision

.gitignore Show annotated file Show diff for this revision Revisions of this file
CONTRIBUTING.md Show annotated file Show diff for this revision Revisions of this file
MLX90614.lib Show annotated file Show diff for this revision Revisions of this file
README.md Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-os.lib Show annotated file Show diff for this revision Revisions of this file
mbed_app.json Show annotated file Show diff for this revision Revisions of this file
stats_report.h Show annotated file Show diff for this revision Revisions of this file
tests/README.md Show annotated file Show diff for this revision Revisions of this file
tests/blinky.log Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.gitignore	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,4 @@
+.build
+.mbed
+projectfiles
+*.py*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CONTRIBUTING.md	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,5 @@
+# Contributing to Mbed OS
+
+Mbed OS is an open-source, device software platform for the Internet of Things. Contributions are an important part of the platform, and our goal is to make it as simple as possible to become a contributor.
+
+To encourage productive collaboration, as well as robust, consistent and maintainable code, we have a set of guidelines for [contributing to Mbed OS](https://os.mbed.com/docs/mbed-os/latest/contributing/index.html).
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MLX90614.lib	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/Uan/code/MLX90614/#d7cf841daf8a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README.md	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,152 @@
+# Getting started example for Mbed OS
+
+This guide reviews the steps required to get Blinky with the addition of dynamic OS statistics working on an Mbed OS platform. (Note: To see a rendered example you can import into the Arm Online Compiler, please see our [quick start](https://os.mbed.com/docs/mbed-os/latest/quick-start/online-with-the-online-compiler.html#importing-the-code).)
+
+Please install [Mbed CLI](https://github.com/ARMmbed/mbed-cli#installing-mbed-cli).
+
+## Import the example application
+
+From the command-line, import the example:
+
+```
+mbed import mbed-os-example-blinky
+cd mbed-os-example-blinky
+```
+
+### Now compile
+
+Invoke `mbed compile`, and specify the name of your platform and your favorite toolchain (`GCC_ARM`, `ARM`, `IAR`). For example, for the Arm Compiler:
+
+```
+mbed compile -m K64F -t ARM
+```
+
+Your PC may take a few minutes to compile your code. At the end, you see the following result:
+
+```
+[snip]
+
+Image: ./BUILD/K64F/GCC_ARM/mbed-os-example-blinky.bin
+```
+
+### Program your board
+
+1. Connect your Mbed device to the computer over USB.
+1. Copy the binary file to the Mbed device.
+1. Press the reset button to start the program.
+
+The LED on your platform turns on and off. The main thread will additionally take a snapshot of the device's runtime statistics and display it over serial to your PC. The snapshot includes:
+
+* System Information:
+    * Mbed OS Version: Will currently default to 999999
+    * Compiler ID
+        * ARM = 1
+        * GCC_ARM = 2
+        * IAR = 3
+    * [CPUID Register Information](#cpuid-register-information)
+    * [Compiler Version](#compiler-version)
+* CPU Statistics
+    * Percentage of runtime that the device has spent awake versus in sleep
+* Heap Statistics
+    * Current heap size
+    * Max heap size which refers to the largest the heap has grown to
+* Thread Statistics
+    * Provides information on all running threads in the OS including
+        * Thread ID
+        * Thread Name
+        * Thread State
+        * Thread Priority
+        * Thread Stack Size
+        * Thread Stack Space
+
+#### Compiler Version
+
+| Compiler | Version Layout |
+| -------- | -------------- |
+| ARM      | PVVbbbb (P = Major; VV = Minor; bbbb = build number) |
+| GCC      | VVRRPP  (VV = Version; RR = Revision; PP = Patch)    |
+| IAR      | VRRRPPP (V = Version; RRR = Revision; PPP = Patch)   |
+
+#### CPUID Register Information
+
+| Bit Field | Field Description | Values |
+| --------- | ----------------- | ------ |
+|[31:24]    | Implementer       | 0x41 = ARM |
+|[23:20]    | Variant           | Major revision 0x0  =  Revision 0 |
+|[19:16]    | Architecture      | 0xC  = Baseline Architecture |
+|           |                   | 0xF  = Constant (Mainline Architecture) |
+|[15:4]     | Part Number       | 0xC20 =  Cortex-M0 |
+|           |                   | 0xC60 = Cortex-M0+ |
+|           |                   | 0xC23 = Cortex-M3  |
+|           |                   | 0xC24 = Cortex-M4  |
+|           |                   | 0xC27 = Cortex-M7  |
+|           |                   | 0xD20 = Cortex-M23 |
+|           |                   | 0xD21 = Cortex-M33 |
+|[3:0]      | Revision          | Minor revision: 0x1 = Patch 1 |
+
+
+
+You can view individual examples and additional API information of the statistics collection tools at the bottom of the page in the [related links section](#related-links).
+
+
+### Output
+
+To view the serial output you can use any terminal client of your choosing such as [PuTTY](http://www.putty.org/) or [CoolTerm](http://freeware.the-meiers.org/). Unless otherwise specified, printf defaults to a baud rate of 9600 on Mbed OS.
+
+You can find more information on the Mbed OS configuration tools and serial communication in Mbed OS in the related [related links section](#related-links).
+
+The output should contain the following block transmitted at the blinking LED frequency (actual values may vary depending on your target, build profile, and toolchain):
+
+```
+=============================== SYSTEM INFO  ================================
+Mbed OS Version: 999999
+CPU ID: 0x410fc241
+Compiler ID: 2
+Compiler Version: 60300
+RAM0: Start 0x20000000 Size: 0x30000
+RAM1: Start 0x1fff0000 Size: 0x10000
+ROM0: Start 0x0 Size: 0x100000
+================= CPU STATS =================
+Idle: 98% Usage: 2%
+================ HEAP STATS =================
+Current heap: 1096
+Max heap size: 1096
+================ THREAD STATS ===============
+ID: 0x20001eac
+Name: main_thread
+State: 2
+Priority: 24
+Stack Size: 4096
+Stack Space: 3296
+
+ID: 0x20000f5c
+Name: idle_thread
+State: 1
+Priority: 1
+Stack Size: 512
+Stack Space: 352
+
+ID: 0x20000f18
+Name: timer_thread
+State: 3
+Priority: 40
+Stack Size: 768
+Stack Space: 664
+
+```
+
+## Troubleshooting
+
+If you have problems, you can review the [documentation](https://os.mbed.com/docs/latest/tutorials/debugging.html) for suggestions on what could be wrong and how to fix it.
+
+## Related Links
+
+* [Mbed OS Stats API](https://os.mbed.com/docs/latest/apis/mbed-statistics.html)
+* [Mbed OS Configuration](https://os.mbed.com/docs/latest/reference/configuration.html)
+* [Mbed OS Serial Communication](https://os.mbed.com/docs/latest/tutorials/serial-communication.html)
+
+### License and contributions
+
+The software is provided under Apache-2.0 license. Contributions to this project are accepted under the same license. Please see contributing.md for more info.
+
+This project contains code from other projects. The original license text is included in those source files. They must comply with our license guide.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,214 @@
+// Final funcional para recoger todos los datos analogicos de la PCB. Precisa de un conversor externo i2c a
+// analógico para el MLX90614, debido a la baja velocidad del puerto i2c.
+
+#include "mbed.h"
+#include "MLX90614.h"
+
+// Asignación de pines para entradas analógicas, separación en dos ADCs
+AnalogIn TempS1(PA_5);    // ADC1, lecturas de baja y media frecuencia
+AnalogIn TempS2(PA_6);
+AnalogIn TempS3(PA_7);
+AnalogIn TempS4(PB_1);
+AnalogIn TempA(PC_2);
+AnalogIn Par(A1);
+AnalogIn Vel(A2);
+AnalogIn Volt(A0);
+AnalogIn Corr1(A3); // ADC3, lecturas de alta frecuencia
+AnalogIn Corr2(A4);
+AnalogIn Corr3(A5);
+
+AnalogIn TempAux1(PA_4);
+AnalogIn TempAux2(PF_4);
+int MTempAux1;
+int MTempAux2;
+
+
+
+// Comunicaciones con periféricos
+
+SPI spi(PF_9,PF_8,PF_7); // SPI MOSI, MISO, SCLK
+DigitalOut NSST(PF_2);
+DigitalOut NSSW(PE_6);
+DigitalOut NSSV(PC_8);
+DigitalOut NSSC(PE_3);
+
+I2C i2c(D14, D15); // Asignación de pines I2C para el sensor IR de temperatura: I2C_SDA, I2C_SCL 
+MLX90614 mlx90614(&i2c);    // Inicialización del sensor infrarrojo de temperatura
+int select; // 0 = object temp, 1 = ambient temp, no funciona con 0
+
+
+// Declaración de variables para guardar las mediciones
+float buff;     
+int MTempS1;        
+int MTempS2;
+int MTempS3;
+int MTempS4;
+int MTempA;
+int MTempR;
+int MPar;
+int MVel;
+int MVolt;
+int MCorr1;
+int MCorr2;
+int MCorr3;
+
+char C1;
+char C2;
+
+
+EventQueue queue(64 * EVENTS_EVENT_SIZE);   // Lista de eventos para distribuir a threads
+
+Serial pc(USBTX,USBRX);                     // Inicialización del puerto serie al PC
+
+Thread thread1;                             // Inicialización de multi-threading
+Thread thread2;
+Thread thread3;
+
+Ticker ISREnvio;                           // Inicialización de interrupciones
+Ticker ISRTemperaturas;
+Ticker ISRVI;
+
+void Envio();                               // Declaración de subrutinas de interrupciones
+void Temperaturas();
+void VI();
+
+
+// ENCODER
+
+InterruptIn encoder(D8);
+
+Timer tiempo;
+float aux1;
+int aux2;
+int cambio;
+
+void subida();
+
+
+void subida()        // Envío de datos por puerto serie al PC
+{ 
+
+        
+        if (cambio==0) 
+            {
+                cambio=1;
+                tiempo.start();
+            }
+                
+        else 
+            {
+                cambio=0;
+                tiempo.stop();
+                aux1 = tiempo.read();
+                tiempo.reset();
+            }
+        
+}
+
+
+
+
+// FINAL ENCODER
+
+
+
+void Envio()        // Envío de datos por puerto serie al PC
+{ 
+
+        printf("%f %i %i %i %i %i\n", // Cambiar escalado  %i %i %i %i %i
+             aux1*1000000, MTempS4, MVolt, MCorr1, MCorr2, MCorr3); 
+//
+}
+
+void Temperaturas()     // Lectura de temperaturas (NTCs estátor y ambiente + IR rotor)
+{        
+
+            //MTempS1=TempS1*4096; // Escalar con el circuito
+            //MTempS2=TempS2*4096;
+            //MTempS3=TempS3*4096;
+            //MTempS4=TempS4*4096;
+            //MTempA=TempA*4096;
+            // MTempS1 = 292.4*pow(buff,3) - 382.46*pow(buff,2) + 282.26*buff - 13.152; 
+            
+            buff=TempS1; 
+            MTempS1 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;    
+            buff=TempS2; 
+            MTempS2 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+            buff=TempS3; 
+            MTempS3 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+            buff=TempS4; 
+            MTempS4 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+            buff=TempA; 
+            MTempA = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+            
+            buff=TempAux1; 
+            MTempAux1 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+            buff=TempAux2; 
+            MTempAux2 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131; 
+             
+                     
+            //MTempR=mlx90614.read_temp(1)*10;   // Lectura del IR
+           
+}
+
+    
+void VI()     // Lectura de I en 3 fases, V en una fase
+{        
+
+            MCorr1=Corr1*4096;   // Escalar con el circuito
+            MCorr2=Corr2*4096;
+            MCorr3=Corr3*4096;
+ 
+            buff=TempS4; 
+            MTempS4 = 2924*pow(buff,3) - 3825*pow(buff,2) + 2823*buff - 131;  
+       
+            MVolt=Volt*4096; // Escalar con el circuito  
+            
+            if((tiempo.read()>1)||(aux1>1)) aux1=0;
+            if(tiempo.read()>1) 
+                {
+                    tiempo.stop();
+                    tiempo.reset();
+                }
+            
+             
+}    
+
+int main(void)   // Thread 0
+{
+    //MTempR=mlx90614.read_temp(1);
+    pc.baud(2000000);   // Baudrate a 2Mbauds
+    spi.format(16,3);   // 16 bits de información, modo 3 (rising edge, lógica inversa)
+    spi.frequency(1000000);     // 1MHz   
+    printf("Introduzca ganancias:\n");
+    
+    NSSC=1;   
+    NSST=1;
+    NSSW=1;
+    NSSV=1;
+    
+    encoder.rise(&subida);  // attach the address of the flip function to the rising edge
+    //encoder.fall(&bajada);  // attach the address of the flip function to the rising edge
+    
+    
+    // Asignación de interrupciones y periodos de muestreo (en segundos)
+    
+    ISREnvio.attach(queue.event(Envio), 0.0004);             
+    //ISRTemperaturas.attach(queue.event(Temperaturas), 0.0005);
+    ISRVI.attach(queue.event(VI), 0.0004);      
+            
+    thread1.start(callback(&queue, &EventQueue::dispatch_forever));     // Apertura de threads
+    thread2.start(callback(&queue, &EventQueue::dispatch_forever));
+    //thread3.start(callback(&queue, &EventQueue::dispatch_forever)); 
+      
+    while (1)   // Thread 0 en espera indefinida
+    {
+        wait(10);
+    }
+}
+
+// NOTA: Se utiliza multithreading en lugar de interrupciones en thread0 ya que el uso de funciones
+// bloqueantes (ADC, puerto serie) en una interrupción común puede causar problemas.
+// Prueba de que el periodo de muestreo se cumple: Si no se cumpliera el periodo de muestreo más exigente,
+// daría un error deoverflow del EventQueue
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,1 @@
+https://github.com/ARMmbed/mbed-os/#0063e5de32fc575f061244c96ac60c41c07bd2e6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed_app.json	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,11 @@
+{
+    "target_overrides": {
+        "*": {
+            "platform.stack-stats-enabled": true,
+            "platform.heap-stats-enabled": true,
+            "platform.cpu-stats-enabled": true,
+            "platform.thread-stats-enabled": true,
+            "platform.sys-stats-enabled": true
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stats_report.h	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,132 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2018 ARM Limited
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#ifndef STATS_REPORT_H
+#define STATS_REPORT
+
+#include "mbed.h"
+
+/**
+ *  System Reporting library. Provides runtime information on device:
+ *      - CPU sleep, idle, and wake times
+ *      - Heap and stack usage
+ *      - Thread information
+ *      - Static system information
+ */
+class SystemReport {
+    mbed_stats_heap_t   heap_stats;
+    mbed_stats_cpu_t    cpu_stats;
+    mbed_stats_sys_t    sys_stats;
+
+    mbed_stats_thread_t *thread_stats;
+    uint8_t   thread_count;
+    uint8_t   max_thread_count;
+    uint32_t  sample_time_ms;
+
+public:
+    /**
+     *  SystemReport - Sample rate in ms is required to handle the CPU percent awake logic
+     */
+    SystemReport(uint32_t sample_rate) : max_thread_count(8), sample_time_ms(sample_rate)
+    {
+        thread_stats = new mbed_stats_thread_t[max_thread_count];
+
+        // Collect the static system information
+        mbed_stats_sys_get(&sys_stats);
+
+        printf("=============================== SYSTEM INFO  ================================\r\n");
+        printf("Mbed OS Version: %ld \r\n", sys_stats.os_version);
+        printf("CPU ID: 0x%lx \r\n", sys_stats.cpu_id);
+        printf("Compiler ID: %d \r\n", sys_stats.compiler_id);
+        printf("Compiler Version: %ld \r\n", sys_stats.compiler_version);
+
+        for (int i = 0; i < MBED_MAX_MEM_REGIONS; i++) {
+            if (sys_stats.ram_size[i] != 0) {
+                printf("RAM%d: Start 0x%lx Size: 0x%lx \r\n", i, sys_stats.ram_start[i], sys_stats.ram_size[i]);
+            }
+        }
+        for (int i = 0; i < MBED_MAX_MEM_REGIONS; i++) {
+            if (sys_stats.rom_size[i] != 0) {
+                printf("ROM%d: Start 0x%lx Size: 0x%lx \r\n", i, sys_stats.rom_start[i], sys_stats.rom_size[i]);
+            }
+        }
+    }
+
+    ~SystemReport(void)
+    {
+        free(thread_stats);
+    }
+
+    /**
+     *  Report on each Mbed OS Platform stats API
+     */
+    void report_state(void)
+    {
+        report_cpu_stats();
+        report_heap_stats();
+        report_thread_stats();
+
+        // Clear next line to separate subsequent report logs
+        printf("\r\n");
+    }
+
+    /**
+     *  Report CPU idle and awake time in terms of percentage
+     */
+    void report_cpu_stats(void)
+    {
+        static uint64_t prev_idle_time = 0;
+
+        printf("================= CPU STATS =================\r\n");
+
+        // Collect and print cpu stats
+        mbed_stats_cpu_get(&cpu_stats);
+
+        uint64_t diff = (cpu_stats.idle_time - prev_idle_time);
+        uint8_t idle = (diff * 100) / (sample_time_ms * 1000);  // usec;
+        uint8_t usage = 100 - ((diff * 100) / (sample_time_ms * 1000));  // usec;;
+        prev_idle_time = cpu_stats.idle_time;
+
+        printf("Idle: %d%% Usage: %d%% \r\n", idle, usage);
+    }
+
+    /**
+     *  Report current heap stats. Current heap refers to the current amount of
+     *  allocated heap. Max heap refers to the highest amount of heap allocated
+     *  since reset.
+     */
+    void report_heap_stats(void)
+    {
+        printf("================ HEAP STATS =================\r\n");
+
+        // Collect and print heap stats
+        mbed_stats_heap_get(&heap_stats);
+
+        printf("Current heap: %lu\r\n", heap_stats.current_size);
+        printf("Max heap size: %lu\r\n", heap_stats.max_size);
+    }
+
+    /**
+     *  Report active thread stats
+     */
+    void report_thread_stats(void)
+    {
+        printf("================ THREAD STATS ===============\r\n");
+
+        // Collect and print running thread stats
+        int count = mbed_stats_thread_get_each(thread_stats, max_thread_count);
+
+        for (int i = 0; i < count; i++) {
+            printf("ID: 0x%lx \r\n",        thread_stats[i].id);
+            printf("Name: %s \r\n",         thread_stats[i].name);
+            printf("State: %ld \r\n",       thread_stats[i].state);
+            printf("Priority: %ld \r\n",    thread_stats[i].priority);
+            printf("Stack Size: %ld \r\n",  thread_stats[i].stack_size);
+            printf("Stack Space: %ld \r\n", thread_stats[i].stack_space);
+        }
+    }
+};
+
+#endif // STATS_REPORT_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/README.md	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,12 @@
+# Testing examples
+
+Examples are tested using tool [htrun](https://github.com/ARMmbed/mbed-os-tools/tree/master/packages/mbed-host-tests) and templated print log. 
+
+To run the test, use following command after you build the example:
+```
+mbedhtrun -d D: -p COM4 -m K64F -f .\BUILD\K64F\GCC_ARM\blinky.bin --compare-log tests\blinky.log
+```
+
+
+More details about `htrun` are [here](https://github.com/ARMmbed/mbed-os-tools/tree/master/packages/mbed-host-tests#testing-mbed-os-examples).
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/blinky.log	Tue Jun 30 07:38:14 2020 +0000
@@ -0,0 +1,29 @@
+=============================== SYSTEM INFO  ================================
+Mbed OS Version:
+CPU ID: 0x[0-9a-fA-F]+
+Compiler ID: \d+
+Compiler Version:
+================= CPU STATS =================
+Idle: \d+% Usage: \d+%
+================ HEAP STATS =================
+Current heap: \d+
+Max heap size: \d+
+================ THREAD STATS ===============
+ID: 0x[0-9a-fA-F]+
+Name: main
+State: \d+
+Priority: \d+
+Stack Size: \d+
+Stack Space: \d+
+ID: 0x[0-9a-fA-F]+
+Name: rtx_idle
+State: \d+
+Priority: \d+
+Stack Size: \d+
+Stack Space: \d+
+ID: 0x[0-9a-fA-F]+
+Name: rtx_timer
+State: \d+
+Priority: \d+
+Stack Size: \d+
+Stack Space: \d+