wahahahehehe

Tips:

1. 博客内容主要为博主的学习笔记,引用已表明出处,如有侵犯请联系我删除;

2. 如有错误请指出,万分感谢;

3. 博主邮箱:yukai_tao@163.com。

赤菟V307与Matlab的串口通信

赤菟V307与Matlab的串口通信

赤菟V307(CH32V307)是一款RISC-V内核的MCU,搭载的是沁恒自研RISC-V内核青稞V4F,最高主频144MHz,支持单精度浮点运算(FPU)。

Matlab支持串口通信,可以接收串口的数据,并进行数据处理,本文主要讲解赤菟V307与Matlab的串口通信,并进行快速傅里叶变换。

1、定义串口协议

为了更好的接收并处理串口数据,需要定制一定的传输协议:

  • 每个数据以‘,’(ASCII:44)结束

  • 整组数据以‘$’(ASCII:36)结束

  • 浮点统一放大到整数

2、赤菟V307端程

赤菟V307发送一段信号,该信号由幅度为0.4的直流信号+幅度为0.5,频率为50Hz的信号+幅度为,频率为100Hz的信号+幅度为0.5,频率为150Hz的信号组成,采样率为1000Hz,一共发送1000个采样值。

#define  PI  3.14
#define  FS  1000         //Sampling frequency
#define  L   1000         //Length of signal
#define  MAGNI 1000000    //data magnification

int main(void)
{
    Delay_Init();
    USART_Printf_Init(115200);
    //    printf("SystemClk:%d\r\n",SystemCoreClock);

    for(uint16_t i=0;i<L;i++)
    {
        //printf("%d,",(int32_t)(0.5*cos( 2*PI*150* i/FS)*MAGNI));
        //                                         f = 50                 f = 100                  f = 150
        printf("%d,",(int32_t)(  ( 0.4 + 0.5*cos( 2*PI*50* i/FS)+ 1*cos( 2*PI*100* i/FS)+0.5*cos( 2*PI*150* i/FS))*MAGNI));
    }

    printf("$\r\n");
    while(1);
}

3、Matlab端程序设计

matlab支持串口接收数据,根据定义的协议,解析数据,支持正负整数。具体代码如下:

	close all;

	Fs = 1000; % Sampling frequency  
	L = 1000;  % Length of signal
	Magin = 1000000; % Data magnification

	delete(instrfindall);

	recData = zeros(1,20);
	calcData = zeros(1,L);

	delete(instrfindall);

	scom = serialport("COM3",115200);
	i = 1;
	j = 1;
	temp = 0;

	while 1
		recData(i) = read(scom,1,"uint8");
		if recData(i) == '$'
			break;
		end

		%数字
		if recData(i)>='0' && recData(i)<='9'
			 recData(i) = recData(i)-'0';
		end

		if recData(i) ==','
			%负数
			if recData(1) == '-'
				temp = 0;
				for k=2:1:i-1
					temp = temp + recData(k)*10^(i-k-1);
				end
				calcData(j) = temp*(-1)/Magin;
			%正数
			else
				temp = 0;
				for k=1:1:i-1
					temp = temp + recData(k)*10^(i-k-1);
				end
			   calcData(j) = temp/Magin;
			end
			i = 0;
			j = j + 1;
		end

	   i=i+1;

	end

	delete(scom);   %
	%plot(calcData);  

	Y = fft(calcData,L);
	P2 = abs(Y/L);
	P1 = P2(1:L/2+1);
	P1(2:end-1) = 2*P1(2:end-1); 
	f = Fs*(0:(L/2))/L;
	plot(f,P1) 
	title('Single-Sided Amplitude Spectrum of X(t)')
	xlabel('f (Hz)')
	ylabel('|P1(f)|')
	drawnow;

4、结果验证

Matlab接收数据显示如下:

image

经过Matlab的快速傅里叶变换结果如下:

image

打通了赤菟V307和Matlab之间的“任督二脉”,后面可以愉快的验证赤菟V307的FFT以及相关的数字信号处理算法啦~~~~

posted on 2022-02-28 19:27  Wahahahehehe  阅读(415)  评论(0编辑  收藏  举报

导航