Let’s talk about Question A of the 21st Electronic Competition and the signal knowledge involved

Table of contents

1 Introduction

2 Topic selection analysis

3 Pre-circuit design

4 Theoretical analysis

4.1 Basics of discrete Fourier transform

4.2 Determination of the number of sampling points and sampling frequency

4.3 Spectrum leakage and window function

4.4 Distortion calculation formula

5 code sharing

5.1 Sampling related code

5.2 FFT transformation code

5.3 Find the distortion degree

5.4 Others

5.5 Finished product

6 ending


1 Introduction

        The electronic competition, which was postponed for three months, finally took place on November 4-11.7. Now the results of each competition area have come out. It is a pity that I only got a second place in the province, but it doesn't matter, just treat it as a small episode in the boring life of senior year. Although I did not do very well, after all, there seemed to be many top players with perfect scores on this question, but I decided to record and share my thoughts, review the game, and draw a successful conclusion to the entire game.

2 Topic selection analysis

       Question: Design a distortion analyzer that only takes the first five harmonics for approximate calculation. It must be able to display the distortion, normalized amplitude and one cycle waveform on the screen, and be able to wirelessly transmit the results to the mobile phone display.

        Reason for choosing the topic: Because I happened to use ARM’s official DSP library during the summer vacation preparations, and I also had some understanding of FFT operations. I felt that question A should be easy to do, so I chose question A. (After all, other questions don’t know it either (dog head)

        Idea: The idea should be relatively clear. Use ADC to collect data for FFT analysis, get the amplitude of each harmonic and put it into the formula to calculate the distortion THD.

        Difficulty: Preamplifier circuit design, wireless transmission, and display are not difficult. The difficulty should be how to adjust the ADC and DMA of the Ti board and how to deal with FFT spectrum leakage to improve measurement accuracy.

       Implementation situation and complaints: I only have a version of Tiva on hand. After working on it for a long time, I finally adjusted the ADC, but the DMA has not been able to get it right. In the end, I had to use interrupts to read the ADC. Because the interruption takes a long time, the sampling rate cannot reach the nominal 1Msps. In fact, if the sampling rate is set to 600Ksps, the data will be confused, so the signal of our work is too high to be measured accurately. So we spent all our energy on dealing with spectrum leakage. In the end, signals within our frequency range (that is, the highest harmonic frequency is not higher than 300K) can be measured relatively accurately. The question requires that the error be less than 3%, and we can achieve it within 1%. . Unfortunately, only three sets of data were measured during the actual evaluation, with frequencies of 1K, 50K, and 100K respectively. Spectrum leakage may not occur at these frequency points, so our advantages cannot be demonstrated, and only three sets of data are too little. Well, we can't widen the gap. We can only test two groups, so it's not surprising that we got the second score, alas. If you can get the key points right, try to adjust DMA or get a better board such as tm4c1294 or msp432e series.

3 Pre-circuit design

        Before sampling, the signal first needs to be amplified to a suitable range to increase the sampling accuracy. The amplification circuit is shown in the figure below.

        The first part is a 100Hz high-pass filter used to filter out the DC component of the input signal, because if it is directly amplified with the DC component, the output result may exceed the ADC measurement range. In the actual evaluation, the signal did not have a DC component, so this filter can be removed.

        Next is a basic forward amplifier. Since the maximum input signal peak-to-peak value is 600mV and the range is 3.3V, it can only amplify up to 5 times. Due to the limitation of the capacitor and resistor in hand, the maximum amplification factor is

A=1+\frac{R_3}{R_1} =4.3

        I almost forgot to mention that since it is a distortion measurement, it is best to choose a low-distortion op amp. We had the THS3001 on hand and found that its parameters were pretty good, and the gain bandwidth product and slew rate were both sufficient, so we used it. .

        Since the ADC in the MCU cannot measure negative voltage, the signal voltage needs to be raised to the measurement range of the ADC after amplification. We use a voltage-dividing voltage boosting circuit. This circuit requires the input of the post-circuit (that is, adc) The resistance is large enough, otherwise the load effect may affect the size of the lift. Here, the two resistors divide the 5V voltage. Theoretically, the voltage rises to 1.56V. In practice, it rises to 1.54V. The error is not large.

4 Theoretical analysis

4.1 Basics of discrete Fourier transform

        Discrete Fourier Transform (DFT) is an important method for converting time domain signals to frequency domain analysis, and FFT is a fast algorithm of DFT. The operation result of N-point FFT is N-point complex number. Assuming the sampling frequency is Fs , then the frequency Fn  represented at the n-th point is:

Fn = (n-1) * Fs

        Let the nth amplitude of the FFT result be An , then its time domain amplitude Bn corresponding to the frequency satisfies:

Bn = An / N, when n=1

Bn = An * 2 / N, when n>1

        That is to say, when n is 1, that is, when the component is a DC component, the actual time domain amplitude is 1/N times the FFT amplitude. When n is not 1, the actual time domain amplitude is 2/N times the FFT amplitude. Times, let’s look at a simulation:

>> N = 1024;     % 1024点
>> Fs = 1000;    %  采样率1000Hz
>> T = 1/Fs;
>> t = (0:N-1)*T;
>> x = 10 + 15 * sin(2*pi*100*t) +  8 * sin(2*pi*200*t);  % 直流、100Hz、200Hz 
>> stem(abs(fft(x)))

        The result is as follows:

        From the FFT results, we know that the signal has three frequency points, namely

(1-1)*1000/1024 = 0Hz

(103-1)*1000/1024 = 99.6Hz

(206-1)*1000/1024 = 200.2Hz

        This is consistent with the frequency of our input signal. Looking at the amplitude again, according to the conversion method mentioned before, the time domain amplitude corresponding to the above three frequencies is

10280/1024=10.03

5823/512=11.37

3835/512=7.48

        Except for the calculated amplitude of 11.37 at the second frequency, which has a larger error than the actual amplitude of 15, the other amplitudes are consistent with the amplitude of our input signal.

        The causes of frequency error and amplitude error will be analyzed later in the article.

4.2 Determination of the number of sampling points and sampling frequency

        In the above simulation results, there is a slight error between the frequency we calculated from the results and the actual frequency. This is because of the existence of the fence effect.

        To understand the fence effect, we must first know the spectrum resolution. The spectrum resolution is the interval between two spectral lines. Assume that the sampling frequency is Fs , the sampling interval is Ts , the total sampling time is T0 , and the number of sampling points is N , then The spectrum resolution is:

F0 = Fs* \frac{1}{N}= \frac{1}{Ts} * \frac{1}{N} = \frac{1}{Ts*N} = \frac{1}{T0}

        For the above simulation example, the spectrum resolution is 1000/1024 = 0.9765Hz, that is, the interval between the two spectral lines is 0.9765Hz. Neither 100 nor 200 is a full multiple of this number, so we cannot directly see this in the spectral lines. Two frequency points, but 99.6Hz and 200.2Hz are seen near it.

        Maybe the error in the above example is not big. Let's take another exaggerated example. If the spectrum resolution is 40Hz, and the actual signal components are 400Hz and 420Hz, then in fact we may only be able to see the 400Hz spectrum line, 420Hz The spectral line is between 400 and 440, which we cannot see, so we may ignore this component during analysis.

        The spectral lines are like fences. We cannot see what is between the fences. This is the fence effect. In order to be able to see more, we have to narrow the distance between the fences, that is, increase the spectral resolution.

       How to improve spectral resolution:

        1. According to the formula of spectrum resolution, the more sampling points, the longer the total sampling time, and the higher the spectrum resolution; but the more sampling points, the more RAM space will be consumed for sample point storage and FFT operation.

        2. Another factor that affects the spectrum resolution is the sampling rate Fs. The smaller the Fs, the longer the total sampling time and the higher the spectrum resolution; however, due to the existence of the sampling theorem, Fs must be greater than twice the original signal frequency, generally at least It must be greater than five times the original signal frequency to restore the signal better.

        in conclusion:

        Increasing the number of points and reducing the sampling rate both have their drawbacks. After comprehensive consideration, we chose the number of sampling points to be 2048. The sampling rate uses a dynamic adjustment method. First, use the fastest rate to sample once and analyze to get the approximate fundamental frequency. Then based on this fundamental frequency, reduce the sampling rate while satisfying the sampling theorem. Use Sample again at this rate and perform FFT analysis. At this time, the resolution is high and the results will be more accurate.

        I also want to mention that at first I only thought of adjusting the sampling rate according to the fundamental frequency to make it accurate, but I didn’t think about how to measure the fundamental frequency. I considered making an F/V conversion circuit, or shaping the signal into a square wave for measurement. I came up with the pulse width, but gave up due to limited capabilities and modules. Later, I suddenly realized that although the frequency obtained by sampling at an extremely fast sampling rate is not accurate, it is OK to know a rough range and adjust it, so it became .

4.3 Spectrum leakage and window function

        Let’s go back to the simulation example at the beginning. It is clear that the input signal only has three components, but looking at the result picture, we find that there are many spectral lines near those three frequencies. Does this mean that the frequencies corresponding to these spectral lines also exist? Not so.

        Signals are often infinitely long, and we can only intercept part of them for spectrum analysis. When aperiodic truncation is performed, in addition to the main lobe that should be present in the spectrum, side lobes that should not be present will also appear. This phenomenon is spectrum leakage. Spectrum leakage will leak energy to nearby frequencies and affect our analysis, so spectrum leakage needs to be reduced.

        In the above example, the signal frequency is 100Hz, and the sampling rate is 1000Hz, that is, 10 points are collected in one cycle, and 1024 points are collected for a total of 102.4 cycles. Therefore, the signal is truncated non-periodic, and spectrum leakage occurs. .

        Now let's change the sampling rate to 1280 and see what the Fourier transform results of the same signal are:

>> Fs = 1280;    %  采样率1280Hz
>> T = 1/Fs;
>> N = 1024;     % 1024点
>> t = (0:N-1)*T;
>> x = 10 + 15 * sin(2*pi*100*t) +  8 * sin(2*pi*200*t); % 直流,100Hz,200Hz
>> stem(abs(fft(x)))

        WOW~ ⊙o⊙, very clean spectral lines. This is because it takes exactly 80 cycles to collect 1024 points, which is truncated. At this time, it is obvious that there is no so-called spectrum leakage.

        Use this result to analyze the signal again. Because the number of points has not increased and the spectrum resolution has not changed, the frequency of the obtained signal is still a little wrong, but the calculated amplitude becomes 10, 15, and 8, which is exactly the same as the original signal. !

        Then, there is such an idea. We use a certain method to accurately obtain the signal period, and then calculate a suitable sampling rate so that the signal period can be truncated, and then we can get accurate results! This method is called simultaneous sampling.

        However, as mentioned before, the fft method can only obtain a rough fundamental wave period range. Even if the signal period can be accurately known, the timer of the microcontroller may not be able to accurately set the sampling interval. For example, the calculated initial value of the counter is What to do with decimals? Synchronous sampling can be implemented using hardware circuits, but it is still difficult in digital systems, so there is no other way to reduce spectrum leakage. have! That is to use windows.

         There are many kinds of window functions, such as rectangular window (that is, no window), flat-top window, Haining window, Hamming window, triangular window, etc. Simply put, windowing is to multiply the sampled data by a weighted coefficient. According to signal theory, the original signal multiplied by a function behaves as convolution in the frequency domain. Taking the rectangular window (without windowing) as an example, it is the original Several clean spectral lines and the sinc function are rolled up, so there are spectral lines that should not be present on the spectrum, that is, spectrum leakage occurs. The degree of spectrum leakage is reflected in the relative size of the side lobes and the main lobe. The side lobes of the rectangular window are very large, so the leakage is relatively serious. Therefore, we need to choose a window function with small side lobes.

        Baidu told us that flat-top windows are suitable for scenarios that require high amplitude accuracy. In fact, we have simulated different window functions and found that Baidu is right. So let’s see what it looks like with flat-top windows:

>> N = 1024;     % 1024点
>> Fs = 1000;    %  采样率1000Hz
>> T = 1/Fs;
>> t = (0:N-1)*T;
>> x = 10 + 15 * sin(2*pi*100*t) +  8 * sin(2*pi*200*t);  % 直流、100Hz、200Hz 
>> w = flattopwin(length(x));  % 生成N点平顶窗序列
>> stem(abs(fft(x.*w')))  % 原函数和窗函数点乘后作fft并画图

        Hmm, it looks better than the first picture, at least it's not spread over such a wide range. But why do there seem to be more spectral lines with larger amplitudes? This is because the main lobe width and side lobe amplitude of the window function are a pair of contradictory points. The main lobe of the rectangular window is narrow and the side lobe amplitude is large. The side lobe amplitude of the flat-top window is small and the main lobe will become wider, so the main lobe will become wider. After removing the flat-top window, the spectral lines (main lobe) with larger amplitudes will increase, but it doesn't matter. In this case, what we value more is the amplitude accuracy, so let's see how the amplitude is calculated. . According to the old method, it is easy to calculate the time domain amplitude corresponding to the three frequencies:

2205/1024=2.15

1654/512=3.23

882.3/512=1.72

        emmm, this is too wrong... But don't worry, because this is the amplitude of the signal after adding the window. If you want the amplitude of the original signal, you have to multiply it by an amplitude correction coefficient K , I couldn’t find out what the K was, so I was confused at first about how to use this flat-top window. Now we might as well look at it another way:

frequency DC 100Hz 200Hz
cycle truncation 10/10 = 1 15/15 = 1 8/8 = 1
rectangular window 10.03/10 = 1.03 11.37/15 = 0.758 7.48/8 = 0.935
flat top window 2.15/10 = 0.215 3.23/15 = 0.2153

1.72/8 = 0.215 

        In the table above, we divide the calculated amplitude and the actual amplitude and find that the values ​​for the flat-top window are all around 0.215, while the three values ​​for the rectangular window are quite different, so there is indeed a constant K that can So that the amplitude we calculated has a perfect correspondence with the actual amplitude. This K should be the reciprocal of 0.215, which is about 4.651. Then calculate the amplitude again,

2205/1024*4.651=10.015

1654/512*4.651=15.024

882.3/512*4.651=8.014

        There is not much difference from reality. You can also try other windows. We tried it for a long time back then, so I am too lazy to do it again and post the code and pictures...

        In short, we used a flat-top window to reduce spectrum leakage and obtained accurate amplitudes, and the calculated distortion was also relatively accurate (but it does not add points....

4.4 Distortion calculation formula

        Paste the formula directly:

THD_x = \frac{\sqrt{U_o_2^2+U_o_3^2+U_o_4^2+U_o_5^2}}{U_o_1}

        Then it's very simple, just bring in the calculated amplitude. But is it really necessary to calculate the specific amplitude? Observing this formula, we find that if each amplitude is multiplied by the same coefficient, the result remains unchanged. So in order to be lazy and save time and trouble, the result obtained by our adc sampling is not converted into the actual voltage, but is directly added to the window to perform FFT transformation. The transformation result does not need to be converted into the actual amplitude, and it is ok to directly bring it into the formula. Of course, you have to be careful not to overflow the value when doing this.

5 code sharing

5.1 Sampling related code

        The method used is to interrupt the reading. The DMA cannot be adjusted. You can try it.

        The code mainly contains some configurations of adc and timer. After each count, a sampling is triggered. After conversion, an interrupt is triggered and the data is read in the interrupt. Remember to add the adc interrupt function to the interrupt vector table of the startup file, otherwise it will get stuck if the interrupt cannot be entered.

        By the way, since the calculated timer count value may not be an integer, the actual sampling rate will deviate slightly from the set one, so it is best to use the actual sampling rate when calculating the spectrum resolution later, that is:

F0 = SysCtlClockGet() / (SysCtlClockGet() / SampleRate) / N

void ConfigureADC(void)
{
    // 一些时钟和引脚配置
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
	MAP_GPIOPinTypeADC(GPIO_PORTE_BASE, GPIO_PIN_0);  //PE0  ADC0 Channel3
	ADCClockConfigSet(ADC0_BASE, ADC_CLOCK_SRC_PIOSC | ADC_CLOCK_RATE_FULL, 1);
    //先失能这个采样序列组和中断
	IntDisable(INT_ADC0SS3);
	ADCIntDisable(ADC0_BASE, 3);
	ADCSequenceDisable(ADC0_BASE, 3);
    //配置为定时器触发,使用采样序列组3,序列中只有一个ADC0 Channel3
	ADCSequenceConfigure(ADC0_BASE, 3, ADC_TRIGGER_TIMER, 0); 
	ADCSequenceStepConfigure(ADC0_BASE, 3, 0, ADC_CTL_CH3 | ADC_CTL_END | ADC_CTL_IE );
}

void ConfigureTIMER(void)
{
    //配置计数器时钟,位数,并且设置为可以触发ADC
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
	TimerConfigure(TIMER0_BASE, TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_PERIODIC);
	TimerControlTrigger(TIMER0_BASE, TIMER_A, true);
	IntMasterEnable();
}

void StartSampling(int SampleRate)
{
    // 根据采样率算出加载到计数器的值,启动ADC然后启动计数器,计数完就会触发一次采样
	TimerLoadSet(TIMER0_BASE, TIMER_A, (SysCtlClockGet()/SampleRate) - 1); 	
	IntEnable(INT_ADC0SS3);
	ADCIntEnable(ADC0_BASE, 3);
	ADCSequenceEnable(ADC0_BASE, 3);
	TimerEnable(TIMER0_BASE, TIMER_A);
}

void StopSampling()
{
    // 停止计数,失能ADC及中断
	TimerDisable(TIMER0_BASE, TIMER_A);
	IntDisable(INT_ADC0SS3);
	ADCIntDisable(ADC0_BASE, 3);
	ADCSequenceDisable(ADC0_BASE, 3);
}

// 这个函数要自己加到中断向量表里
void ADCSeq3Handler(void)
{
    // 转换完毕会进入中断,读取数据后存到数组里
	ADCSequenceDataGet(ADC0_BASE,3,SampleTemp);
	adcValues[SampleNum++] = SampleTemp[0];
	if(SampleNum>=N)
	{
		StopSampling();
		SampleisFinish = 1;
		SampleNum = 0;
	}
	ADCIntClear(ADC0_BASE, 3);
}

5.2 FFT transformation code

        It is very convenient to call ARM's official DSP library in keil. If it is in ccs, it seems to be troublesome to compile the source code yourself, so I use keil.

        The first step in the function is to find the average, with the purpose of removing the mainstream component. Observe the third simulation result. Because the main lobe of the flat-top window becomes wider, several vertical lines with large amplitudes also appear near the zero frequency. In order not to affect the subsequent finding of the fundamental frequency, each sample value is reduced. The DC component can be removed by averaging. Why can this remove the DC component? Because the DC component is the mean value of the sampled values, if the mean value is subtracted from the sampled values, then the mean value of the new sequence becomes 0, the DC component also becomes 0, and the other frequency amplitudes remain unchanged.

        Then add the window, and then initialize the FFT structure, using the rfft function, which is the real Fourier transform. This function internally converts the 2048-point real FFT into a 1024-point complex FFT for calculation, which takes up less space and speed. . Why can it be converted like this? In fact, there are proofs and examples of relevant properties in Teacher Cheng Peiqing's book Digital Signal Processing. Here we can just call the function directly.

//利用ARM库写的fft函数
void my_fft(uint16_t *adcValues,float *fftResults,uint8_t type)
{
	//求均值,去除直流分量
	float adcMean = 0;
	for(int i = 0; i < N; i++)
		adcMean += adcValues[i];
	adcMean = adcMean / N;
	
	//电压转换(其实不转换也可,所以这里没转),然后是加窗
	// 1 不加  2 汉宁  3 平顶
	float voltage[N];
	if(type == 1)
		for(int i = 0; i < N; i++)
			voltage[i] = ((adcValues[i]&0x0FFF) - adcMean);
	else if(type == 2)
		for(int i = 0; i < N; i++)
			voltage[i] = ((adcValues[i]&0x0FFF) - adcMean) * 0.5f * ( 1 - cos(2*PI*i/(N-1)) );
	else if(type == 3)
		for(int i = 0; i < N; i++)
			voltage[i] = ((adcValues[i]&0x0FFF) - adcMean) * ((1 - 1.93f * cos(2*PI*i/(N-1))) + 1.29f * cos(4*PI*i/(N-1)) - 0.388f * cos(6*PI*i/(N-1)) + 0.0322 * cos(8*PI*i/(N-1))) /4.634f;
	
	// 初始化FFT结构体
	arm_rfft_fast_instance_f32 S;
	arm_rfft_fast_init_f32(&S,N);
	
	// 调用fft函数得到结果
    // 结果将会按X[0]、X[N/2]、X[1]实部、X[1]虚部、X[2]实部、X[2]虚部...X[N/2-1]虚部的格式存进结果数组中,共N个值
	float output[N];    
	arm_rfft_fast_f32(&S,voltage,output,0);
	
	//求模值,只求了N/2个模值,这是因为由实数fft的性质就可知道后面的点跟前面的点是对称的
	arm_cmplx_mag_f32(output,fftResults,N/2);
}

5.3 Find the distortion degree

        Okay, after getting the modulus value of the fft result, you can proceed to the next step of calculation.

        Because the question stipulates that the distortion should not be greater than 50%, and we have removed the DC component before FFT, so the frequency corresponding to the maximum amplitude must be the fundamental frequency. First, sample once at the maximum sampling rate to get a rough fundamental frequency, and then adjust the sampling rate to a smaller rate according to the fundamental frequency and sample again. This can improve the spectrum resolution. Do an FFT on the second sampling result, and you can calculate the degree of distortion.

        In C language, the index starts from 0, so the frequency of a certain point is directly the index times the spectrum resolution. So does it mean that the index of the nth harmonic is n times the index of the fundamental wave? Not necessarily. For example, if the resolution is 24Hz, the index corresponding to 1KHz should be 41.66. The actual maximum index is 42, and the index corresponding to 5KHz is 208.33. The actual index is 208. The difference between 42 and 208 is more than 5 times 2. This error is Due to rounding, 41.66 is taken as 42, which is 0.38 more. When magnified five times, it is 1.9 more. Then if the frequency index of 1K is 41.49, the actual frequency index is 41, which is 0.49 less. Five times will result in a 2.45 less.

        According to the analysis in the above paragraph, the index of the nth harmonic is not necessarily n times the fundamental index, but it must be within the range of the left and right points near n times. Therefore, the n times itself and the left and right points will be found in the code. The maximum value among the five points in total is used as the modulus value of this harmonic.

        Of course, it is not necessary to be as complicated as above. You can sort the FFT module values ​​after removing the DC component and calculate the largest five.

        The key code for finding the degree of distortion is as follows:

my_fft(adcValues,fftResults,3);
un[0] = fftResults[0];
arm_max_f32(fftResults,N/2,&max,&max_idx);  //找出基波下标
for(int i = 1; i < 6; i++)					//找出谐波幅值
	arm_max_f32(&fftResults[max_idx*i-2],5,&un[i],NULL);   //这里要考虑数组溢出,我还没改
arm_sqrt_f32(un[2]*un[2]+un[3]*un[3]+un[4]*un[4]+un[5]*un[5],&THD[0]);
THD[0] = THD[0] / un[1] * 100.0f; 					//计算THD
for(int i = 0;i < 5; i++)
	un_rate[i] = un[i+1] / un[1];
F0 = SysCtlClockGet() / (SysCtlClockGet()/SampleRate) / Nf ;
Freq = max_idx * F0 / 1000.0f;					//计算基波频率

5.4 Others

        The code displayed by OLED is not attached. Just change the IO pins and transplant it.

        To display the waveform, you just need to pick out the points and draw lines to connect them. Well, of course, due to insufficient sampling rate, when the fundamental frequency is high, it may not be possible to collect a few points in one cycle, and direct connection will be ugly. Therefore, if the harmonic components can be correctly analyzed, the frequency and amplitude will be known. , you can write out the time domain expression yourself and then draw the picture...

        The classic HC-05 is used for wireless transmission. It can be transparently transmitted after being configured in AT mode. The mobile APP uses the bluetooth debugger of Master LazyDog. For details, please see: Bluetooth debugger-epoch-making wireless debugger_XLazyDog's blog- CSDN Blog_Bluetooth Debugger Bluetooth Debugger The audience for this article is young people with ideals in colleges and universities or electronic engineers who have already entered the society. This article aims to introduce an application that enables wireless debugging on Android devices by using the Bluetooth function. 1. Introduction to Bluetooth debugger This Bluetooth debugger took more than a month to develop. It is based on Android devices and realizes wireless debugging of microcontrollers through the Bluetooth communication function of Android devices. The main purpose of writing this software is to make profit. Well, of course it is for the vast number of microcontroller development enthusiasts to save them from the tedious debugging steps... https://blog.csdn.net/XLazyDog/article/details/99584735         We only need to replace the initialization function and serial port sending function in the stm32 routine of this app with tm4c, and then package and send according to the order requirements, as follows:

void initValuePack(int baudrate)
{
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
    ROM_GPIOPinConfigure(GPIO_PA0_U0RX);
    ROM_GPIOPinConfigure(GPIO_PA1_U0TX);
    ROM_GPIOPinTypeUART(GPIO_PORTA_BASE,GPIO_PIN_0|GPIO_PIN_1);
  	ROM_UARTClockSourceSet(UART0_BASE,UART_CLOCK_PIOSC);
    ROM_UARTConfigSetExpClk(UART0_BASE,16000000,baudrate,(UART_CONFIG_WLEN_8|UART_CONFIG_STOP_ONE|UART_CONFIG_PAR_NONE));
}

void sendBuffer(unsigned char *p,unsigned short length)
{
    for(int i=0;i<length;i++)
        ROM_UARTCharPut(UART0_BASE, p[i]); 
}

void SendBlueTooth(uint16_t adcValues,float THD,float Freq,float *un_rate)
{
	static uint8_t buffer[60];
	
	startValuePack(buffer);
	putShort(adcValues);
	putFloat(THD);
    putFloat(Freq);
	for(int i = 0 ; i < 5; i++)
		putFloat(un_rate[i]);
	
	sendBuffer(buffer,endValuePack());
}

5.5 Finished product

6 ending

        I wrote for two consecutive afternoons and finally finished it. I originally just wanted to share my thoughts a little bit, but I was afraid that I couldn't explain clearly, so I wrote a bit long-winded, but it almost turned into a tutorial... Although the national competition has not yet started, my e-sports career has come to an end. I am very grateful to the companionship of my friends for four days and three nights. This will be one of the most unforgettable memories of my undergraduate career.

        Today is November 20th. The last time I read a book was the last time . The last time I read a book was a month ago. After the competition, I have been anxiously waiting for the results and haven’t studied. It’s time to start again. I went to transcode hehe...

Guess you like

Origin blog.csdn.net/qq_43862401/article/details/121421568