PIC16F877單片機(jī)與PC機(jī)通訊的匯編程序
;PIC16F877單片機(jī)程序
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 ;波特率設(shè)置為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機(jī)命令
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 ;接收一個(gè)數(shù)據(jù)
GOTO WAIT1
MOVF RCREG,0
MOVWF COUNT
MOVWF TXREG
LOOPTX BTFSS PIR1,TXIF ;將接收到的數(shù)據(jù)送回PC機(jī)
GOTO LOOPTX
MOVF COUNT,0
MOVWF INDF
INCF FSR
DECFSZ TEMP
GOTO WAIT1
GOTO OVER ;處理完畢
TXW MOVLW 0X09 ;向PC機(jī)發(fā)送9個(gè)數(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 ;通信任務(wù)完成,關(guān)接受和發(fā)送允許
BSF STATUS,RP0
BCF TXSTA,TXEN
BCF STATUS,RP0
CALL LED ;調(diào)用顯示子程序,將發(fā)送(或接收)的數(shù)據(jù)顯示出來(lái)
END ;程序完
PC 機(jī)程序
PC采用Toubr C 進(jìn)行編寫。程序如下:
#includestdio.h>
#define port 0x3f8 /*利用串口1進(jìn)行通信*/
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); /*準(zhǔn)備設(shè)置波特率*/
outportb(port,0x0C); /*波特率設(shè)置為9 600 bps*/
outportb(port+1,0x00);
outportb(port+3,0x03); /*8位數(shù)據(jù)位,奇偶檢驗(yàn),1位停止位*/
outportb(port+1,0x00); /*關(guān)中斷*/
inportb(port+5); /*讀一次線路狀態(tài)寄存器,使其復(fù)位*/
{
printf("ttsend data or receive data: (s or r?)");
c=getchar();
switch(c)
{
case 's':
case 'S':
{
while(!(inportb(port+5)0x20)); /*發(fā)送保持器滿則等待*/
outportb(port,0x01); /*否則發(fā)送數(shù)據(jù)01通知單片機(jī)準(zhǔn)備接收*/
for(i=0;i6;i++) /*共發(fā)送6個(gè)數(shù)據(jù)*/
{
a=b[i];
while(!(inportb(port+5)0x20))
delay(100); /*發(fā)送保持器滿,等待*/
outportb(port,a); /*發(fā)送a*/
printf("%d",a); /*顯示a*/
while(!(inport(port+5)1)); /*接收單片機(jī)送回的數(shù)據(jù)*/
ch[i]=inport(port); /*保存*/
}
delay(10);
for(j=0;j8;j++) /*顯示接收的回送數(shù)據(jù)*/
printf("%d",ch[j]);
getch();
break;
}
case'r': /*接收數(shù)據(jù)*/
case'R':
{
while(!(inportb(port+5)0x20));
outportb(port,0x02); /*發(fā)送數(shù)據(jù)02通知單片機(jī)發(fā)送數(shù)據(jù)*/
for(j=0;j9;j++) /*共接收9個(gè)數(shù)據(jù)*/
{
while(!(inportb(port+5)1));
ch[j]=inportb(port);
}
for(j=0;j9;j++)
printf("%d",ch[j]);
getch();
break;
}
}
}
}
評(píng)論