Engee documentation
Notebook

Code generation for MIC32 (Sawtooth Signal Generator)

This demo presents the development of the Engee model for a two-channel sawtooth signal generator, followed by code generation and execution on the MIK32 NUKE V0.3 debug board.

Introduction

The target device used in this demo is the MIK32 NUKE V0.3 debug board based on the K1948VC018 MIK32 Amur microcontroller. The Engee model developed in this example generates sawtooth signals and transfers them to the microcontroller's digital-to-analogue converters (DACs), while the modulated signal of the second DAC is generated with a fixed phase shift. In addition, the peripherals of the controller are also connected in the model. Compilation and loading of the code into the microcontroller is made from VS Code with PlatformIO extension.

Model description

The model of this example is mik32_dac.engee. To connect and work with the periphery of the microcontroller are used blocks C Function. The counter block Counter Free-Running generates a sawtooth signal according to the specified digit capacity of the resulting number, when the maximum value is reached, the counter is reset to zero and continues operation.

mik32_dac_model_2.png

The phase shift of the signal for the second DAC is organised by the block Variable Integer Delay - it sets the maximum buffer value for the stored previous values of the signal, and the value input to the input d from the constant block determines the fixed phase shift of the signal.

Connecting peripherals

To work with MIC32 peripherals, the model uses the following blocks C Function: systemClockConfig, DAC12 and DAC13. The blocks have the following purpose:

  • systemClockConfig - sets up the clocking subsystem and frequency monitor of the microcontroller;
  • DAC12 - initialises DAC 1 and generates the output value at the P1.12 output;
  • DAC13 - initialises DAC 2 and generates the output value at the P1.13 output.

DACs of the microcontroller are based on two-stage 6-bit resistive matrices, internal DAC reference voltage is 1.2 V. The total digit capacity is 12 bits.

Each of the blocks C Function connects a header file for the corresponding peripheral from the MIK32 HAL library. Blocks DAC12 and DAC13 among other things connect header files mik32_dac12_typedef.h and mik32_dac13_typedef.h to declare the name of the DAC variable structure. The pluggable header files are contained in the directory include/ of the example. Below is an example of connecting header files in block DAC12.

mik32_dac_include.png

A more detailed description of the principles of code operation in C Function blocks is given in the comments to the code.

Modelling results

To simulate the sawtooth signal generator download and run model mik32_dac:

In [ ]:
# @markdown **Программное управление моделированием:**  
# @markdown Требуется ввести только имя модели
имя_модели = "mik32_dac" # @param {type:"string"}
if имя_модели in [m.name for m in engee.get_all_models()]
    модель = engee.open( имя_модели );
else
    модель = engee.load( "$(@__DIR__)/"*имя_модели*".engee" );
end
данные = engee.run(модель);

For convenience and clarity of application, code cell masking is used in the example of service code cells. The next code cell is updated automatically.

In [ ]:
# @markdown **Построение графиков:**  
# @markdown Библиотека Plots.jl, бэкэнд gr()
Формат = :svg # @param [":svg", ":png"] {type:"raw"} 
gr(format = Формат)
Ширина = 900 # @param {type:"integer"}
Высота = 300 # @param {type:"integer"}
Сигнал_1 = "Saw" # @param {type:"string"} 
Подпись_1 = "ЦАП 1" # @param {type:"string"} 
Сигнал_2 = "ShiftSaw" # @param {type:"string"} 
Подпись_2 = "ЦАП 2" # @param {type: "string"} 
Расположение_подписей = :topleft # @param [":none", ":topleft", ":top", ":topright", ":left", ":right", ":bottomleft",":bottom",":bottomright", ":outerright", ":outerleft", ":outertop", ":outerbottom", ":outertopright", ":outertopleft", ":outerbottomright", :outerbottomleft] {type:"raw"}    
Заголовок = "Сигналы ЦАП" # @param {type:"string"} 
Подпись_X = "Время моделирования, с" # @param {type:"string"} 
Подпись_Y = "Амплитуда сигнала" # @param {type:"string"} 
plot(size = (Ширина, Высота), legend = Расположение_подписей, title=Заголовок, xlabel=Подпись_X, ylabel=Подпись_Y)
plot!(данные[Сигнал_1].time, данные[Сигнал_1].value;
      label = Подпись_1, lw = 2)
plot!(данные[Сигнал_2].time, данные[Сигнал_2].value;
      label = Подпись_2, st = :step, lw = 2)
Out[0]:

As can be seen from the obtained graphs, sawtooth signals are modelled with a given amplitude $N=2^{12}=4095$, the signal for the second DAC is transmitted with a delay of 1024 samples.

Code generation

Generate code from the model to then load the algorithm developed in the model into the microcontroller:

In [ ]:
# @markdown **Генерация кода:**  
# @markdown Папка для результатов генерации кода будет создана в папке скрипта:
папка = "code" # @param {type:"string"}

# @markdown Генерация кода для подсистемы:
включить = false # @param {type:"boolean"}
if(включить)
    подсистема = "" # @param {type:"string"}
    engee.generate_code( "$(@__DIR__)/"*имя_модели*".engee", "$(@__DIR__)/"*папка;
                     subsystem_name = подсистема)
else
    engee.generate_code( "$(@__DIR__)/"*имя_модели*".engee", "$(@__DIR__)/"*папка)
end
[ Info: Generated code and artifacts: /user/start/examples/codegen/mik32_dac/code

The files obtained in the specified folder - header mik32_dac.h and source mik32_dac.c - we use further when building the project. The generated file of the main program main.c will not be used in the project, for code execution in the development environment prepared by main.cpp, located in the root folder mik32_dac of the example.

Preparing the project in the development environment

The development environment through which the project is built and loaded into the target device is VS Code with the PlatformIO add-on. The environment configurations and connections are not considered in this example, as they are described in detail at resources) of the controller developer.
From the example directory, let's transfer the generated files, main.cpp, mik32_dac12_typedef.h mik32_dac13_typedef.h and the configuration file platformio.ini to the PlatformIO project.

mik32_dac_platfotmio.png

After that you can proceed to build the project and load the programme.

Code execution on MIK32

Let's connect the debug board MIK32 NUKE V0.3 to the USB-port of the computer, then in PlatformIO we can observe the connected device. To correctly identify the connection of this board requires a USB driver. The driver used in the example is libusbK.

After successful connection, let's proceed to the project building:
"PLATFORMIO -> PROJECT TASKS -> mik32v2 -> General -> Build ".
If there are no build errors, load the compiled code into the microcontroller:
"PLATFORMIO -> PROJECT TASKS -> mik32v2 -> General -> Upload ".

In this example a digital PC oscilloscope PcoScope 2205A is used to capture the DAC signals generated on pins P1.12 and P1.13 of the debug board, the measurement results are displayed in the PicoScope 7 T&M software.

osc1_2.png

As can be seen from the oscillograms, the sawtooth signal plots have the maximum amplitude in voltage (1.2 V), which corresponds to the specified output signal level (4095). The signal of the second DAC has the specified phase shift.

Conclusion

In this example we have considered the development of Engee model for the program of generation of sawtooth signals with 12-bit resolution and fixed phase shift for K1948VK018 MIK32 Amur microcontroller as a part of MIK32 NUKE V0.3 debug board. The developed model is embedded by generated files into the PlatformIO environment project for VS Code with further assembly, loading and execution on the target device.