51单片机控制matlab写的俄罗斯方块
将单片机的程序下载好之后,取消串口的占用(可直接插拔一下),
然后运行matlab的俄罗斯方块程序即可开始控制。亲测有效。
单片机主程序
#include<reg52.h>
//******************** 函数声明 *******************
void SendByte(unsigned char dat);
void SendStr(unsigned char *s);
void ConfigTimer0(unsigned int ms);
void ConfigUART(unsigned int baud);
//******************** 主函数 *******************
#define uchar unsigned char
extern KeyDriver();
extern KeyScan();
unsigned char T0RH = 0; //T0重载值的高字节
unsigned char T0RL = 0; //T0重载值的低字节
void main (void)
{
EA = 1;
ConfigTimer0(1); //配置T0定时1ms
ConfigUART(9600); //配置波特率为9600
while(1)
{
KeyDriver();
}
}
void ConfigTimer0(unsigned int ms)
{
unsigned long tmp; //临时变量
tmp = 11059200 / 12; //定时器计数频率
tmp = (tmp * ms) / 1000; //计算所需的计数值
tmp = 65536 - tmp; //计算定时器重载值
tmp = tmp + 13; //补偿中断响应延时造成的误差
T0RH = (unsigned char)(tmp>>8); //定时器重载值拆分为高低字节
T0RL = (unsigned char)tmp;
TMOD &= 0xF0; //清零T0的控制位
TMOD |= 0x01; //配置T0为模式1
TH0 = T0RH; //加载T0重载值
TL0 = T0RL;
ET0 = 1; //使能T0中断
TR0 = 1; //启动T0
}
/* 串口配置函数,baud-通信波特率 */
void ConfigUART(unsigned int baud)
{
SCON = 0x50; //配置串口为模式1
TMOD &= 0x0F; //清零T1的控制位
TMOD |= 0x20; //配置T1为模式2
TH1 = 256 - (11059200/12/32)/baud; //计算T1重载值
TL1 = TH1; //初值等于重载值
ET1 = 0; //禁止T1中断
ES = 1; //使能串口中断
TR1 = 1;
}
//******************* 发送一个字节 *******************
void SendByte(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
//**************** 发送一个字符串 *******************
void SendStr(unsigned char *s)
{
while(*s!='\0') // \0表示字符串结束标志,通过检测是否字符串末尾
{
SendByte(*s);
s++;
}
}
void InterruptTimer0() interrupt 1
{
TH0 = T0RH; //重新加载重载值
TL0 = T0RL;
KeyScan();
}
//****************** 串口中断程序 *******************
void UART_SER (void) interrupt 4
{
if(RI) //判断是接收中断产生
RI=0;
}
matlab部分程序
function chuankou() % 创建函数
delete(instrfindall) % 关闭串口,此句十分重要,下篇再详细解释
clear s;
global s; % 全局变量,供串口中断函数使用
s = serial('com4'); %使用默认设置创建串口s
fopen(s); %打开串口
set(s,'BytesAvailableFcnMode','Terminator'); %设置中断触发方式
set(s,'Terminator','H');
s.BytesAvailableFcn =@ReceiveCallback; % 定义中断响应函数对象
end
function ReceiveCallback( ~,~) %创建中断响应函数
global s a;
global piece plane max_column max_row
a = fscanf(s) ; % 接收数据并显示(无分号)
fprintf(a);
k = a;
switch k
case 'bH'
piece = rot90(piece);
halt = false;
topl = member(plane,2);
shift_h = 0;
shift_v = 0;
if ~empty(size(piece),5)
[topl_x,topl_y] = ind2sub([max_row,max_column],topl(3));
if topl(2)-topl(1) == 1
shift_h =-2;
shift_v =-1;
else
shift_h = 0;
end
else
[topl_x,topl_y] = ind2sub([max_row,max_column],topl(1));
end
for a = topl_x:1:size(piece,1)+topl_x-1
for b = topl_y:1:size(piece,2)+topl_y-1
if a > size(plane,1) || b > size(plane,2)
halt = true;
break
elseif plane(a+shift_v,b+shift_h) == 1
halt = true;
end
end
end
if ~halt
plane(ismember(plane,2)) = 0;
for a = topl_x:1:size(piece,1)+topl_x-1
for b = topl_y:1:size(piece,2)+topl_y-1
plane(a+shift_v,b+shift_h) = piece(a-topl_x+1,b-topl_y+1);
end
end
end
case 'aH'
arrow_key(-1);
case 'cH'
arrow_key(1);
case 'dH'
move();
end
render();
end