2020/02/21

STM32 Analog-to-digital converters(ADCs)

single channel/single conversion
scan channel/single conversion
single channel/continuous conversion
scan channel/continuous conversion

Datasheet
Three 12-bit analog-to-digital converters are embedded and each ADC shares up to 16 external channels, performing conversions in the single-shot or scan mode. In scan mode, automatic conversion is performed on a selected group of analog inputs.

Additional logic functions embedded in the ADC interface allow:
- Simultaneous sample and hold
- Interleaved sample and hold

The ADC can be served by the DMA controller. An analog watchdog feature allows very precise monitoring of the converted voltage of one, some or all selected channels. An interrupt is generated when the converted voltage is outside the programmed thresholds.

To synchronize A/D conversion and timers, the ADCs could be triggered by any of TIM1, TIM2, TIM3, TIM4, TIM5, or TIM8 timer.


RM0090 Chapter 13 Analog-to-digital converter (ADC)

13.1 ADC introduction
The 12-bit ADC is a successive approximation analog-to-digital converter. It has up to 19 multiplexed channels allowing it to measure signals from 16 external sources, two internal sources, and the Vbat channel. The A/D conversion of the channels can be performed in single, continuous, scan or discontinuous mode. The result of the ADC is stored into a left or right-aligned 16-bit data register.

The analog watchdog feature allows the application to detect if the input voltage goes beyond the user-defined, higher or lower thresholds.

13.2 ADC main features
- 12-bit, 10-bit, 8-bit or 6 bit configurable resolution
- Interrupt generation at the end of conversion, end of injected conversion, and in case of analog watchdog or overrun events
- Single and continuous conversion modes
- Scan mode for automatic conversion of channel 0 to channel 'n'
- Data alignment with in-built data coherency
- Channel-wise programmable sampling time
- External trigger option with configurable polarity for both regular and injected conversions
- Discontinuous mode
- Dual/Triple mode (on devices with 2 ADCs or more)
- Configurable DMA data storage in Dual/Triple ADC mode
- Configurable delay between conversions in Dual/Triple interleaved mode
- ADC conversion type (refer to the datasheets)
- ADC supply requirements: 2.4V to 3.6V at full speed and down to 1.8V at slower speed
- ADC input range: Vref- <= Vin <= Vref+
- DMA request generation during regular channel conversion

13.3 ADC functional description
13.3.1 ADC on-off control
The ADC is powered on by setting the ADON bit in the ADC_CR2 register. When the ADON bit is set for the first time, it wakes up the ADC from the Power-down mode.

Conversion starts when either the SWSTART or the JSWSTART bit is set.

You can stop conversion and put the ADC in power down mode by clearing the ADON bit. In this mode the ADC consumes almost no power (only a few uA).

13.3.2 ADC clock
The ADC features two clock schemes:
- Clock for the analog circuitry: ADCCLK, common to all ADCs

- Clock for the digital interface (used for registers read/write access)


13.3.3 Channel selection
There are 16 multiplexed channels. It is possible to organize the conversions in two groups: regular and injected. A group consists of a sequence of conversions that can be done on any channel and in any order.

- A regular group

- An injected group

13.3.4 Single conversion mode



AN4073 Application note
How to improve ADC accuracy when using STM32F2xx and STM32F4xx microcontrollers

The purpose of this application note is to show how to improve the accuracy of A/D conversions for applications using the STM32F2xx and STM32F4xx microcontrollers.

It also explains the firmware methodology, which can be applied to reduce the ADC error and gives some general tips on writing firmware for better ADC accuracy.

Please note that the data provided with this application note is for reference only, measured in a lab under typical conditions (unless specified otherwise) and not tested in production.

1. Overview of parameters impacting the ADC accuracy

The accuracy of an analog to digital conversion has an impact on the overall system quality and efficiency. To improve the accuracy, you need to understand the errors associated with the ADC and the parameters affecting them.
전체적인 시스템 품질과 효율성이 ADC의 정확도에 영향을 미친다. 정확도를 개선하려면 ADC에 연관된 문제점과 거기 관계된 파라미터에 대한 이해가 필요하다.

The ADC, itself, cannot ensure the accuracy of results. It depends on your overall system design. For this reason, you need to do some careful preparation before starting your development.
ADC 자체는 정확도와 상관없고 시스템의 전체적인 디자인에 관련이 있다. 그러므로 개발을 시작하기 전에 세심한 주의를 기울여야한다.

Many parameters impact the ADC accuracy, depending on the application. Some of these factors are: PCB layout, voltage source, I/O switching and analog source impedance.
PCB 아트웍, 전압소스, 입출력 스위칭 신호와 아날로그 임피던스 등 많은 요소가 ADC 정확도에 영향을 미치는 요소이다.

For more details about ADC errors, please refer to AN2834: How to get the best ADC accuracy in STM32F10xxx devices and AN3137: A/D converter on STM8L devices application notes.

2. Firmware techniques for improving the conversion accuracy

2.1 Averaging
Averaging is a simple technique where you sample an analog input several times and take the average of the results. This technique is helpful to eliminate the effect of noise on the analog input or a wrong conversion.
여러번 샘플값을 얻어서 평균내는 간단한 방법이 있다. 노이즈나 잘못 변환된 값을 제거하는데 도움이 된다.

2.1.1 Averaging of N ADC samples
When this method is used, it is better to collect the samples in multiples of 2(N should be a multiple of 2). This makes it more efficient to compute the average because you can do the division by right-shifting the sum of the converted values. This saves CPU time and code memory needed to execute a division algorithm (in Cortex-Mx, this takes 1 CPU cycle)




















This averaging technique is used to measure the voltage on one analog input pin. A total of N conversions is considered and the average is calculated. This is done in a loop in the firmware.
샘플 수집은 2의 지수승으로 하는것이 좋다. 평균값 계산시 오른쪽 비트 시프트 만으로 나눗셈 연산이 되므로 CPU 타임과 코드 메모리를 절약할 수 있다.
이 방법은 하나의 아날로그 전압 측정에 유용하다. N번의 변환과 평균값 계산을 펌웨어에서 루프로 진행한다.

Total conversion time = (number of samples * ADC conversion time) + computation time.
Computation time = time taken to read the results, add them together and calculate the average by dividing the total by the number of samples.

There is a trade-off between the total conversion time and the number of samples used to average, depending on the analog signal variations and the time available for computation.
총 작업시간 = (샘플 수 * 변환시간) + 계산시간
계산시간 = 샘플을 읽고,그 샘플을 모두 더하고 평균내는데 걸리는 시간
총 작업시간과 샘플 수 사이에 균형을 맞춰야한다.

2.1.2 Averaging of N-X ADC samples
This method is based on taking N ADC samples, sorting them from the highest to the lowest value (or the reverse) and deleting the dispersed X samples.
이 방법은 N ADC 샘플 추출 기반으로 최대, 최소값을 정렬한 후 튀는 값들을 제거하는 방식이다.

It is recommended to choose N and X as multiples of 2.
N과 X는 2의 지수값으로 정하는걸 추천한다.

This averaging method is more efficient than the previous one, as it deletes the most dispersed values which could impact the average, and it gives a good trade-off between the execution time and the conversion accuracy.
이 방식이 평균값에 영향을 미치는 튀는 값들을 제거하기 때문에 이전 방식보다 더 효과적이다.

N번 샘플 수집 -> 크기 순으로 정렬 -> X/2개의 상위 샘플 제거, X/2개의 하위 샘플 제거 -> 남은 샘플 평균값 계산


2.2 Additional recommendation
ADC conversion results are the ratio of the input voltage to the reference voltage. If there is noise in the reference voltage, then the results may not be accurate. Both hardware and firmware design are responsible for reducing the noise.

The execution of code generates some non-negligible noise on the internal power supply network of the microcontroller. To filter this noise, the Vdda(or Vref) and VSSA analog supply pins are available on the microcontroller package; You can connect a capacitor filter to these power supply pins to filter a high frequency noise.

Here are some general firmware design tips for reducing system noise in order to achieve a better ADC conversion accuracy:
1. Avoid starting transmission on any communication peripheral just before starting the ADC conversion. The toggling of the I/Os may create some noise in the supply voltage.
2. Avoid toggling high-sink I/Os which cause noise ripple in the power supply.
3. Avoid toggling digital outputs on the same I/O port as the A/D input is being converted. This can introduce switching noise into the analog inputs.
4. It is recommended to configure the STM32F2/F4 ART with data cache + instruction cache enable and to disable the prefetch. This will avoid extra CPU accesses to the Flash memory causing an additional noise which can significantly decrease the ADC accuracy in some applications.

오 N sampling, N-X sampling 소스도 있네


































2020/02/20

Kivy garden Graph widget

The Graph widget is a widget for displaying plots.
It supports drawing multiple plot with different colors on the Graph. It also supports a title, ticks, labeled ticks, grids and a log or linear representation on both the x and y axis, independently.































To display a plot. First create a graph which will function as a "canvas" for the plots. Then create plot objects e.g. MeshLinePlot and add them to the graph.

To create a graph with x-axis between 0-100, y-axis between -1 to 1, x and y labels of and X and Y, respectively, x major and minor ticks every 25, 5 units, respectively, y major ticks every 1 units, full x and y grids and with a red line plot containing a sine wave on this range:

1
2
3
4
5
6
7
8
9
from math import sin
from kivy.garden.graph import Graph, MeshLinePlot
graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
x_ticks_major=25, y_ticks_major=1,
y_grid_label=True, x_grid_label=True, padding=5,
x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
plot = MeshLinePlot(color=[1001])
plot.points = [(x, sin(x / 10.)) for x in range(0101)]
graph.add_plot(plot)
cs

The MeshLinePlot plot is a particular plot which draws a set of points using a mesh object. The points are given as a list of tuples, with each tuple being a (x, y) coordinate in the graph's units.

You can create different types of plots other than MeshLinePlot by inheriting from the Plot class and implementing the required functions. The Graph object provides a "canvas" to which a Plot's instructions are added. The plot object is responsible for updating these instructions to show within the bounding box of the graph the proper plot. The Graph notifies the Plot when it needs to be redrawn due to changes. See MeshLinePlot class for how it is done.

2020/02/14

STM32F439ZIT 기본 Firmware

Board Name : STM32-144-DUI
Board Version : 0.0.1
Code : Greig
MCU : STM32F439ZIT6

전원, MCU 및 주변회로, USB-to-Serial 만 수납하여 펌웨어 테스트 진행함.




































0. 준비사항
0.1 STM32CubeMX 설치 및 업데이트
0.2 STM32CubeProgrammer 설치 및 업데이트
0.3 STM32CubeIDE 설치 및 업데이트


1. STM32CubeMX
STM32CubeMX를 사용해서 프로젝트를 생성한다.

1.1 MCU Selector



















1.2 Project Settings
























1.3 Pinout & Configuration
1.3.1 RCC Configuration
























1.3.2 USART3 Configuration

























1.3.3 Clock Configuration
























1.3.4 Generate Code


2. STM32CubeIDE
2.1 Project Import




































2.2 Test Build













OK 문제없음.



3. Communication with Host PC
3.1 Protocol Format
- Host PC to MCU : "명령어" + i개의 "cmd_arg" + "\r"
    *. 명령어 : 대문자 알파벳
    *. i개의 cmd_arg : 숫자
    *. \r : Carriage Return
- MCU to Host PC : "명령어" + i개의 "cmd_arg" + "\r\n" + j개의 "rtn_arg" + "\r\n>"
    *. 명령어 : 대문자 알파벳
    *. i개의 cmd_arg : 숫자
    *. \r : Carriage Return
    *. \n : Line Feed
    *. j개의 rtn_arg : 숫자 또는 대소문자 알파벳
    *. > : 응답 문장의 종료

예를 들어 LED를 ON 하려면
Host to MCU로 "LED 0 1\r" 이렇게 명령을 보내고
MCU to Host로 "LED 0 1\r\nLED"LED Num-0 ON\r\n" 이렇게 응답을 받게 된다.

간단한 통신 테스트용 앱을 만들어보자.(Python + Kivy)






























COM 포트 연결되면 "VER\r"이란 명령어가 날아가고 보드의 버전 정보를 읽어오도록 해보자.
뿅뿅





























OK 굳.