基于Java语言的51单片机串口通讯PC机程序
图1硬件电路图
串口通讯硬件部分电路,收发器件采用max232,5V供电。J31接一单片机如AT89C52,单片机的串口与max232的10和11脚相连。
max232与微机通过9针接头相连。
本文的实验环境是AT89C52,单片机的内部程序是用KeilC语言编写的,程序功能非常简单,检测到开始信号后从串口读数据,然后把读入的数据发送给串口,遇到结束符停止。C语言代码如下供大家参考。在uv3中含有两个文件comm.h和comm.c,代码分别为:
//
/* comm.h*/
/* serial port define, only use in comm project */
//
#define ucharunsigned char
#define uint unsigned int
#define length0x0F //数据包长度
ucharCR = 0x0D;
ucharLF = 0x0A;
ucharESC = 0x1B;
ucharSYNC = 0x01; //数据包启始符
ucharPID = 0x00; //数据包标示字
ucharADDR; //串口接收外部命令(片内地址)
ucharDATA; //串口返回片内数据
ucharENDP = 0x00; //数据包结束符
ucharACK = 0x06; //串口确认
ucharERROR = 0x18; //串口错误
ucharwrong[] = "Bad command";
/*END*/
/*/
/*comm..c*/
/* Write time is 2005.4.15,By Gooseli*/
/* Copyright is changsha HUNU unversity gooseli.com */
/* Cpu is At89C51,Fclk is 11.059MHz */
/* Compiler is keilC51 compiler */
/*/
#include
#include
#include
#include
void commInit(){
////
// 8051串口初始化//
////
SCON = 0x52;
PCON = 0x80;
TMOD = 0x21;
TH1 = 0x0FA;
TL1 = 0x0FA;
TCON = 0x40;
//*//
//串口控制器工作于方式1,8位,频率可变。接收允许//
//串口波特率系数SMOD = 1 //
//定时器1工作于方式1,8位自动装载。定时器0方式1,16位//
// 11.059M晶振,波特率= 9600,TH1 = 0x0FA;//
//19200 0x0FD //
//57600 0x0FF //
// 3.6864M晶振9600 0x0FE //
//19200 0x0FF //
// #3.6864M晶振工作于方式2 //
// #在SMOD = 1时,波特率= 115200//
//开中断TR1 = 1//
//*//
}
uchar flag;
uchar readln();
void println( uchar *str );
main(){
commInit(); //初始化串口
while(1){
flag = readln();
}
}
uchar readln(){
uchar a;
uchar str[length];
int i;
scanf("%c",&a); //寻找起始符,回车则开始
if( a==SYNC || a==LF ){
while(1){
printf("n>>");
//printf(">>");
scanf("%c",&a);
if( a==ENDP || a == ESC ){ //如果ESC则对话结束
break;
}
for( i="0"; i //读入数据包,如果溢出或者回车则结束 str[i] = a; scanf("%c",&a); } str[i] = ENDP; //为数据包添加结束符,“