当前位置:网站首页>Sensor: MQ-5 gas module measures the gas value (code attached at the bottom)
Sensor: MQ-5 gas module measures the gas value (code attached at the bottom)
2022-06-13 02:02:00 【Cheems_ Pak Choi】
One 、 brief introduction
This article introduces the use of MQ-5 The fuel gas module measures the fuel gas value ,CPU Or choose SCM ,MQ-5 The main technologies used are ADC, Gas is an analog signal for single chip computer , It needs to be converted into a digital signal , Then the gas simulation value is converted into the corresponding gas value through the relevant calculation formula , It is convenient for people to view . For example, the family uses the gas module to measure the gas value , If the gas value exceeds a certain range , An alarm device can be set outside , Ensure the safety of the family .
Two 、ADC Introduce
1、STM32F1 ADC The basic summary
(1)ADC(analog to digital converter) Analog to digital converter , It can convert analog signals into digital signals . According to its transformation principle, it is mainly divided into successive approximation type 、 Double integral type 、 There are three types of voltage frequency conversion .STM32F1 Of ADC It is a successive approximation analog-to-digital converter .
(2)STM32F103 Series usually have 3 individual ADC, these ADC Can be used independently , You can also use double ( Increase the sampling rate ).STM32F1 Of ADC yes 12 Bit by bit analog to digital converter . It has as much as 18 Multiple channels , Measurable from 16 External sources 、2 Internal source signals . These channels are A/D The conversion can be single 、 continuity 、 Scanning or intermittent mode execution .ADC The results can be left justified or right justified in 16 Bit data register .ADC It has the characteristics of simulated watchdog , Allows the application to detect whether the input voltage exceeds the upper or lower user-defined threshold .
2、STM32F1 ADC Structure diagram
STM32F1 ADC With so many functions , By ADC Determined by the internal structure . To better understand STM32F1 Of ADC, You need to understand its internal structure . As shown in the figure below :( You can also check 《STM32F10x Chinese Reference Manual 》-11 A / D converter (ADC) Chapter -ADC Functional specifications ), The following will be introduced according to the labels in the following figure :
.(1) label 1: Voltage input pin
ADC The input voltage range is : VREF- ≤ VIN ≤ VREF+. from VREF-、 VREF+ 、 VDDA 、 VSSA These four external pins determine . Usually we put VSSA and VREF- Grounding , hold VREF+ and VDDA Pick up 3.3V, therefore ADC The input voltage range of is :0~3.3V. Development board we use ADC The input voltage range is 0-3.3V.
(2) label 2: Input channel
STM32 Of ADC Of input channels up to 18 individual , The external 16 The first channel is in the block diagram ADCx_IN0、ADCx_IN1…ADCx_IN5(x=1/2/3, Express ADC Count ), Through this 16 An external channel can collect analog signals . this 16 Two channels correspond to different IO mouth , Which one IO The port can be queried from the data manual , You can also view it from the following figure , Similarly, we also marked it in the schematic diagram of the development board chip . among ADC1 also 2 An internal channel :ADC1 The passage of 16 Connected to the temperature sensor inside the chip , passageway 17 Connected to the internal reference voltage VREFINT.ADC2 and ADC3 The passage of 16、 17 All connected to
The internal VSS.
(3) label 3: Channel conversion sequence
External 16 The channels can be divided into 2 Group channel : Regular channel group and injection channel group , The maximum number of regular channel groups is 16 road , The injection channel group has a maximum of 4 road .
Regular channel group : Understand from the name , Regular channel is a regular channel , Similar to a normally executed program , Usually we use this channel .
Injection channel group : Understand from the name , Injection is insertion , It's a restless channel , It's like interrupting . When the program runs normally , An interrupt can interrupt the execution of a program . Similarly, if in the process of regular channel conversion , There is an injection channel inserted , Then you have to convert the injection channel first , After the injection channel conversion is completed, return to the conversion process of regular channels .
Each group contains a transformation sequence , The sequence can be completed in any channel in any order .
for example , The sequence can be converted in the following order : ADC_IN3、ADC_IN8、 ADC_IN2、 ADC_IN2、 ADC_IN0、 ADC_IN2、 ADC_IN2、 ADC_IN15.
(4) label 4: Trigger source
Select the input channel , Set the conversion order , Then you can start the conversion . To turn on ADC transformation , It can be set directly ADC Control register ADC_CR2 Of ADON Position as 1, Even if it can ADC. Of course ADC It also supports external event triggered transformation , There are many trigger sources , Which trigger source to choose , from ADC Control register 2:ADC_CR2 Of EXTSEL[2:0] and JEXTSEL[2:0] Bit to control .EXTSEL[2:0] Used to select the trigger source of the rule channel ,JEXTSEL[2:0] Trigger source for selecting injection channel . After selecting the touch source , Whether the trigger source should be activated , By ADC Control register ADC_CR2 Of EXTTRIG and JEXTTRIG
These two to activate .
If the external trigger event is enabled , We can also set ADC Control register 2:ADC_CR2 Of EXTEN[1:0] and JEXTEN[1:0] To control the trigger polarity , There can be 4 States , Namely : Disable trigger detection 、 Rising edge detection 、 Falling edge detection and both rising and falling edges are detected .
(5) label 5:ADC The clock
ADC Input clock ADC_CLK from APB2 After frequency division , The maximum is 14MHz, The frequency division factor is determined by RCC Clock configuration register RCC_CFGR Bit 15:14 ADCPRE[1:0] Set up , It can be 2/4/6/8 frequency division , Notice that there is no 1 frequency division . We know APB2 The bus clock is 72M, and ADC The maximum operating frequency is 14M, Therefore, the frequency division factor is generally set as 6, such ADC The input clock of is 12M.
ADC To complete the sampling of input voltage, several ADC_CLK cycle , The number of sampling cycles can be determined by ADC Sampling time register ADC_SMPR1 and ADC_SMPR2 Medium SMP[2:0] Bit settings , ADC_SMPR2 It's the channel that controls 0~9, ADC_SMPR1 It's the channel that controls 10~17. Each channel can be sampled at different times . The minimum sampling period is 1.5 individual , That is, if we want to achieve the fastest sampling , Then the sampling period should be set to 1.5 A cycle , The cycle here is 1/ADC_CLK.
ADC The total conversion time is the same as ADC The input clock of is related to the sampling time , The formula is as follows :
Tconv = Sampling time + 12.5 A cycle
among Tconv by ADC Total conversion time , When ADC_CLK=14Mhz When , And set up 1.5 Sampling time of cycles , be Tcovn=1.5+12.5=14 A cycle =1us.
(6) label 6: Data register
ADC The converted data is different according to the conversion group , The data of the rule group is placed in ADC_DR Send
In the container , The data of the injection group is placed in JDRx Inside .
because STM32F1 Of ADC yes 12 Bit conversion accuracy , The data register is 16 position , therefore ADC
When storing data, there is a distinction between left alignment and right alignment . If it's left aligned ,AD Conversion completed
Stored as data in ADC_DR The register of [4:15] In place ; If it is right aligned , It's stored in
ADC_DR The register of [0:11] In place . Which storage method to choose , Need to pass ADC_CR2
Of 11 position ALIGN Set up .
(7) label 7: interrupt
When the following events occur and the corresponding interrupt flag bit is enabled ,ADC Can produce interruptions .
1. End of conversion ( Rule conversion ) And injection conversion ends
2. Simulated watchdog Events
3.DMA request
We know STM32F1 ADC The conversion mode can be divided into single conversion and continuous conversion .
》》 In single conversion mode ,ADC Perform a conversion . Can pass ADC_CR2 The register of SWSTART position ( Only for regular channels ) start-up , It can also be started by external trigger ( Applicable to regular channels and injection channels ), At this time CONT Position as 0. Take regular channels as an example , Once the selected channel conversion is completed , The conversion result will exist ADC_DR In the register ,EOC( End of conversion ) The flag will be set , If set EOCIE, An interrupt is generated . then ADC Will stop , Until the next start .
》》 In continuous conversion mode ,ADC Start a new transformation immediately after you end a transformation .CONT Position as 1 when , Can be triggered by external or will be ADC_CR2 In register SWSTRT Location 1 To start this mode ( Only for regular channels ). It should be noted that : This mode cannot convert the injection channel continuously . The only exception to continuous mode is , Injection channel is configured to automatically convert after the rule channel ( Use JAUTO position ).
3、ADC Basic configuration steps
Next, let's introduce how to use library functions to ADC To configure . This is also writing
What must be understood in the program . The specific steps are as follows :(ADC The related library functions are in
stm32f10x_adc.c and stm32f10x_adc.h In file )
(1) Enable port clock and ADC The clock , Set pin mode to analog input
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AN; // Analog input mode
(2) Set up ADC The frequency division factor of
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
(3) initialization ADC Parameters , Include ADC Working mode 、 Regular sequence, etc
void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct);
typedef struct
{
uint32_t ADC_Mode; // ADC Working mode selection
FunctionalState ADC_ScanConvMode; /* ADC scanning ( Multichannel ) Or a single shot ( single channel ) Mode selection */
FunctionalState ADC_ContinuousConvMode; // ADC Single conversion or continuous conversion selection
uint32_t ADC_ExternalTrigConv; // ADC Switch trigger signal selection
uint32_t ADC_DataAlign; // ADC Data register alignment format
uint8_t ADC_NbrOfChannel; // ADC Number of acquisition channels
} ADC_InitTypeDef;
ADC_InitTypeDef ADC_InitStructure;
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;// Non scan mode
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;// Turn off continuous conversion
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;// Disable trigger detection , Use software to trigger
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;// Right alignment
ADC_InitStructure.ADC_NbrOfChannel = 1;//1 A transformation in a sequence of rules That is, just convert the rule sequence 1
ADC_Init(ADC1, &ADC_InitStructure);//ADC initialization
(4) Can make ADC And calibration
void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState);
ADC_Cmd(ADC1, ENABLE);// Turn on AD converter
The method of performing reset calibration is :
ADC_ResetCalibration(ADC1);
perform ADC The method of calibration is :
ADC_StartCalibration(ADC1); // Start specifying ADC1 Calibration status of
while(ADC_GetResetCalibrationStatus(ADC1)); // Wait for the reset calibration to finish
while(ADC_GetCalibrationStatus(ADC1)); // Wait for the calibration to finish
(5) Read ADC Conversion value
The library functions for setting regular sequence channels and sampling periods are :
void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t
ADC_Channel,uint8_t Rank, uint8_t ADC_SampleTime);
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5 );
Set the regular sequence channel and sampling period , The next step is to start the conversion , Because we adopt
It is triggered by software , Library function
void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
After switching on , You can get it ADC Conversion result data , The library function called is :
uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx);
obtain AD The library function of the state information of the transition is :
FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t
ADC_FLAG);
For example, we have to judge ADC1 Whether the conversion of is over , The method is :
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC ));// Wait for the conversion to finish
3、 ... and 、MQ-5 Source code
1、rq.h The header file
#ifndef _RQ_H
#define _RQ_H
#include "stm32f10x.h"
#include "delay.h"
void RQ_Init(void);
u16 get_gas(u8 ch);
u16 get_gas_average(u8 ch,u8 times);
void get_gas_real_value(float* value);
#endif
2、rq.c Source file
#include "rq.h"
#include "stdio.h"
void RQ_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd ( RCC_APB2Periph_ADC3|RCC_APB2Periph_GPIOF, ENABLE ); // Can make ADC3 Channel clock
RCC_ADCCLKConfig(RCC_PCLK2_Div2);// Set up ADC Division factor 6 72M/6=12,ADC The maximum time cannot exceed 14M
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init ( GPIOF, & GPIO_InitStructure );
// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
// GPIO_Init ( GPIOF, & GPIO_InitStructure );
ADC_DeInit(ADC3); // Reset ADC3, Add peripherals ADC3 Reset all registers of to default value
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;// A / D conversion works in continuous conversion mode
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;//ADC Data right alignment
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;// The transformation is initiated by software rather than external triggers
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;//ADC Working mode :ADC1 and ADC2 Working in independent mode
ADC_InitStructure.ADC_NbrOfChannel = 1;// In order to change the rules ADC The number of channels
ADC_InitStructure.ADC_ScanConvMode = DISABLE;// Analog to digital conversion works in single channel mode
ADC_Init(ADC3, &ADC_InitStructure);
ADC_Cmd(ADC3, ENABLE);// Enable to designate ADC3
ADC_ResetCalibration(ADC3);// Enable reset calibration
while(ADC_GetResetCalibrationStatus(ADC3));// Wait for the reset calibration to finish
ADC_StartCalibration(ADC3);// Turn on ADC calibration
while(ADC_GetCalibrationStatus(ADC3));// Wait for the calibration to finish
}
u16 get_gas(u8 ch)
{
// Set the specified ADC The rule group channel for , A sequence , Sampling time
ADC_RegularChannelConfig(ADC3, ch, 3, ADC_SampleTime_239Cycles5 ); //ADC3,ADC passageway , The sampling time is 239.5 cycle
ADC_SoftwareStartConvCmd(ADC3, ENABLE); // Enable to designate ADC3 Software conversion start function
while(!ADC_GetFlagStatus(ADC3, ADC_FLAG_EOC ));// Wait for the conversion to finish
return ADC_GetConversionValue(ADC3); // Go back to the last time ADC3 Conversion result of rule group
}
// Multiple values , Averaging improves accuracy
u16 get_gas_average(u8 ch,u8 times)
{
u32 temp_val=0;
u8 t;
for(t=0;t<times;t++) //times=10
{
temp_val+= get_gas(ch);//temp_val=temp_val+get_gas(ch);
delay_ms(5);
}
return temp_val/times;// return ADC The average value of the collected data
}
void get_gas_real_value(float* value)
{
u16 gas_val=0;
gas_val = get_gas_average(ADC_Channel_6,10);// obtain ADC The average value obtained by the channel
*value = (gas_val/4096.0*3.3)*210+ 10;// The gas value calculation formula can be viewed MQ-5 Data manual
}
3、main.c The main function
/* This program is only for learning , Without the permission of the author , Do not use for other purposes ! open Hair plate : Puzhong STM32-F1 Development board Experimental projects : be based on STM32F103ZET6 Gas detection experiment do person :xxx// Old rules , If necessary, please contact the following email address Post box :[email protected] Japan period :2022 year 06 month 09 Japan copyright , Piracy must be investigated . */
#include"stm32f10x.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "rq.h"
#include "stdio.h"
float value = 0.0;
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);// Set interrupt priority group 2
delay_init(); // Delay function initialization
uart_init(9600); // The serial port is initialized to 9600
RQ_Init();
while(1)
{
get_gas_real_value(&value);
printf(" Gas value =%.4f\r\n",value);
delay_ms(1000);
}
}
边栏推荐
- Rsync transport exclusion directory
- How many smart bids does Google have?
- Cmake has no obvious error after compilation, but prompts that pthread cannot be found
- Gome's ambition of "folding up" app
- Introduction to common ROS commands
- 4、 Improvement of warehousing management function
- Wsl2 + vcxsrv + opengl3.3 configuration
- QT realizes mind mapping function (II)
- 水管工游戏
- Numpy multidimensional array transpose transpose
猜你喜欢
Introduction to Google unit testing tools GTEST and gmoke
[the third day of actual combat of smart lock project based on stm32f401ret6 in 10 days] communication foundation and understanding serial port
SQLserver2008 拒绝了对对象 '****' (数据库 '****',架构 'dbo')的 SELECT 权限
The commercial value of Kwai is being seen by more and more brands and businesses
(no plug-in) summary of vim basic shortcut keys
Devexpress implementation flow chart
[learning notes] xr872 audio driver framework analysis
When AI meets music, iFLYTEK music leads the industry reform with technology
Jeux de plombiers
Looking at Qianxin's "wild prospect" of network security from the 2021 annual performance report
随机推荐
(no plug-in) summary of vim basic shortcut keys
Delphi7 compressed pictures (BMP, JPG, PNG)
SWD debugging mode of stm32
Parameter measurement method of brushless motor
反爬虫策略(ip代理、设置随机休眠时间、哔哩哔哩视频信息爬取、真实URL的获取、特殊字符的处理、时间戳的处理、多线程处理)
dfs与bfs解决宝岛探险
Interruption of 51 single chip microcomputer learning notes (external interruption, timer interruption, interrupt nesting)
Torch. Distributions. Normal
Stm32 mpu6050 servo pan tilt support follow
Stm32 3*3 matrix key (register version)
uniapp 预览功能
华为设备配置CE双归属
VI keyboard diagram
What is solid angle
Stm32+ze-08 formaldehyde sensor tutorial
[arithmetic, relation, logic, bit, compound assignment, self increasing, self decreasing and other] operators (learning note 4 -- C language operators)
Devaxpress Chinese description --tcxpropertiesstore (property store recovery control)
Devaxpress Chinese description --tcximagelist (enhanced image list control)
[work notes] the problem of high leakage current in standby mode of dw7888 motor driver chip
[work notes] xr872 codec driver migration and application program example (with chip debugging method)