|
//在Stc單片機(jī)上利用串口實(shí)現(xiàn)人機(jī)交互例(改編自KEIL C51 V7.0)
#include"STC8AXX.h"
#include<stdio.h>
#include"types.h"
#include"Qport.h"
#include"delay.h"
#define uchar unsigned char
#define uint unsigned int
#define FOSC 11059200UL
#define BAUD1 9600UL
#define BRT1 (65536 - FOSC / BAUD1 / 4) //FEE0
uchar code *s ="Please input the following commands:\n"
"Inport p (read port)\n"
"Outport p nnn (write port)\n"
" where p=0..3, nnn=0..255\n"
"Help or ? (display this text)\n";
uchar help(){
printf( "\n%s\n", Q );
return 0;
}
uchar Inport( uchar idata *rbuf ) {
uint p;
uchar v;
if( sscanf( rbuf, "%i", &p ) != 1 )
return 1;
case 0: v=P0; break;
case 1: v=P1; break;
case 2: v=P2; break;
case 3: v=P3; break;
case 4: v=P4; break;
case 5: v=P5; break;
case 6: v=P6; break;
case 7: v=P7; break;
default: return 2;
}
printf( "Port P%d = %02X\n", p, (uint)v );
return 0;
}
uchar Outport( uchar idata *rbuf ) {
uint p, v;
if( sscanf( rbuf, "%i%i", &p, &v ) != 2 )
return 1;
switch( p ){
case 0: P0=v; break;
case 1: P1=v; break;
case 2: P2=v; break;
case 3: P3=v; break;
case 4: P4=v; break;
case 5: P5=v; break;
case 6: P6=v; break;
case 7: P7=v; break;
default: return 2;
}
return 0;
}
void main( void ) {
uchar idata buf[41];
uchar elevel;
uchar mjs;
Qport_init();
//SCON:SM0 SM1 SM2 REN TB8 RB8 TI RI
// 0 1 0 1 X X 1 0
SCON = TI_+REN_+SM1_; //0x52
//TMOD: T1_GATE T1_C/T T1_M1 T1_M0 T1_GATE T0_C/T T0_M1 T0_M0
// 0 0 0 0 0 0 0 0
//
TMOD = 0x00;
//AUXR: T0x12 T1x12 UART_M0x6 T2R T2_C/T T2x12 EXTRAM S1ST2
// 1 1 0 0 0 0 0 0
AUXR = 0xc0;
TL1 = BRT1;
TH1 = BRT1 >> 8;
TR1 = 1;
for(;;){
// if(!P30) IAP_CONTR=0x60;
// WDT_CONTR|=0x10;
for(mjs=0;mjs<=2;mjs++){
DelayMs(200);
// LED1=!LED1;
LED2=!LED2;
LED3=!LED3;
// LED4=!LED4;
}
help();
putchar('>');
gets(buf,20);
switch( elevel = command( buf ) ){
case 0: break;
default: printf( "Error %d\n\n", (uint)elevel );}
}
}
//命令解析
#include<stdlib.h>
#include<types.h>
typedef struct {
uchar code *name;
uchar (code *func)(uchar idata *);
}comm_struct;
comm_struct code comm_tab[] = {
"Inport", Inport,
"Outport", Outport,
"help", help,
"?", help,
"", NULL
};
uchar command( uchar idata *buf ) {
uchar i, j;
for( i = 0;; )
for( j = 0;; ){
if( comm_tab[i].name[j] != 0 ){
if( ((comm_tab[i].name[j] ^ buf[j]) & 0x5F) == 0 ){
j++;
continue;
}
i++;
break;
}
if( j == 0 ) return 255;
return comm_tab[i].func( buf+j );
}
}
|
|