一個單片機與PC機通信的程序,pc機程序用c語言來編寫,單片機程序用匯編語言來編寫1. PC機編程
PC采用Toubr C 進行編寫。程序如下:
#include
#define port 0x3f8
int ch[15];
main ()
{
int a;
int i,j;
int b[6]={88,15,38,26,20,0};
char c;
clrscr();
outportb(port+3,0x80);
outportb(port,0x0C);
outportb(port+1,0x00);
outportb(port+3,0x03);
outportb(port+1,0x00);
inportb(port+5);
{
printf("ttsend data or receive data: (s or r?)nnn");
c=getchar();
switch(c)
{
case ’s’:
case ’S’:
{
while(!(inportb(port+5)&0x20));
outportb(port,0x01);
for(i=0;i<6;i++)
{
a=b[i];
while(!(inportb(port+5)&0x20))
delay(100);
outportb(port,a);
printf("%dn",a);
while(!(inport(port+5)&1));
ch[i]=inport(port);
}
delay(10);
for(j=0;j<8;j++)
printf("n%dn",ch[j]);
getch();
break;
}
case’r’:
case’R’:
{
while(!(inportb(port+5)&0x20));
outportb(port,0x02);
for(j=0;j<9;j++)
{
while(!(inportb(port+5)&1));
ch[j]=inportb(port);
}
for(j=0;j<9;j++)
printf("n %dn",ch[j]);
getch();
break;
}
}
}
}
2. 單片機與PC機通信之單片機程序
LIST P=16F876
#INCLUDE P16F876.INC
CBLOCK 0X24
COUNT
TEMP
ENDC
ORG 0X0000
NOP
START GOTO MAIN
ORG 0X020
MAIN MOVLW 0X30 ;將RAM單元初始化
MOVWF FSR
BCF STATUS,RP0
MOVLW 0X22
MOVWF COUNT
INTRAM MOVF COUNT,0
MOVWF INDF
INCF COUNT,1
INCF FSR,1
BTFSS FSR,7
GOTO INTRAM
BANKSEL TXSTA ;波特率設置為9 600 bps
MOVLW 0X19
MOVWF SPBRG ;異步高速方式
MOVLW 0X04
MOVWF TXSTA
BCF STATUS,RP0
MOVLW 0X80 ;串行口使能
MOVWF RCSTA
MOVLW 0X30
MOVWF FSR
BSF RCSTA,CREN ;接收允許
BSF STATUS,RP0
BSF TXSTA,TXEN ;發(fā)送允許
BCF STATUS,RP0
WAIT BTFSS PIR1,RCIF ;接收PC機命令
GOTO WAIT
MOVF RCREG,0
MOVWF TEMP
MOVWF INDF
INCF FSR
DECFSZ TEMP ;接收到的數(shù)據(jù)為1,則接收
GOTO TXW ;否則發(fā)送數(shù)據(jù)
MOVLW 0X06
MOVWF TEMP
WAIT1 BTFSS PIR1,RCIF ;接收一個數(shù)據(jù)
GOTO WAIT1
MOVF RCREG,0
MOVWF COUNT
MOVWF TXREG
LOOPTX BTFSS PIR1,TXIF ;將接收到的數(shù)據(jù)送回PC機
GOTO LOOPTX
MOVF COUNT,0
MOVWF INDF
INCF FSR
DECFSZ TEMP
GOTO WAIT1
GOTO OVER ;處理完畢
TXW MOVLW 0X09 ;向PC機發(fā)送9個數(shù)據(jù)
MOVWF TEMP
MOVLW 0X30
MOVWF FSR
TXW0 MOVF INDF,0
MOVWF TXREG
INCF FSR
TXW1 BTFSS PIR1,TXIF
GOTO TXW1
DECFSZ TEMP
GOTO TXW0
OVER BCF RCSTA,CREN ;通信任務完成,關(guān)接受和發(fā)送允許
BSF STATUS,RP0
BCF TXSTA,TXEN
BCF STATUS,RP0
CALL LED ;調(diào)用顯示子程序,將發(fā)送(或接收)的數(shù)據(jù)顯示出來
END ;程序完
本文引用地址:http://m.butianyuan.cn/article/201611/319704.htm
評論