c51 uart串口乱码调试

用timer2作串口波特率发生器,串口方式3做串口与电脑通讯,调试时接收乱码,发送乱码。

代码如下

</pre>void uart_init(void){<span style="white-space:pre">	</span>PCON  &=  0x00;/    SCON  = 0xf0;<span style="white-space:pre">	</span>T2CON&=0xF0;//EXEN2=0,TR2=0,C/T2=0;CP/RL2=0<span style="white-space:pre">	</span>T2CON|=0x34;//RCLK=1,,TCKL=1,TR2=1<span style="white-space:pre">	</span>RCAP2H = 0xff;<span style="white-space:pre">	</span>    RCAP2L = 0xdc; <span style="white-space:pre">	</span>          //´    EA = 1;    ES = 1;<span style="white-space:pre">		</span>} unsigned char count,recv_buf[10];void com_sd(unsigned char datap){<span style="white-space:pre">	</span>TB8 = 1;<span style="white-space:pre">	</span>SBUF = <span style="white-space:pre">	</span>datap;<span style="white-space:pre">	</span>while(!TI);<span style="white-space:pre">		</span><span style="white-space:pre">	</span>TI = 0;} void com_interrupt() interrupt 4 <span style="white-space:pre">	</span>using 2{     <span style="white-space:pre">	</span>      if(RI)                                    <span style="white-space:pre">	</span>{   <span style="white-space:pre">	</span>    unsigned char recv;   <span style="white-space:pre">		</span>RI = 0;<span style="white-space:pre">		</span>recv &= 0;<span style="white-space:pre">		</span>recv = recv_buf[count++];<span style="white-space:pre">		</span>com_sd(recv);<span style="white-space:pre">		</span>if(count >= 10)<span style="white-space:pre">		</span>{<span style="white-space:pre">			</span>count = 0;<span style="white-space:pre">		</span>}<span style="white-space:pre">		</span><span style="white-space:pre">	</span>}   }   void main(){<span style="white-space:pre">	</span> <span style="white-space:pre">	</span> unsigned char buf,i; <span style="white-space:pre">	</span> uart_init();<span style="white-space:pre">	</span> while(1)<span style="white-space:pre">	</span> {<span style="white-space:pre">	</span><span style="white-space:pre">		</span>buf = 0x55;<span style="white-space:pre">	</span> }<span style="white-space:pre">	</span>}<pre name="code" class="csharp"><span style="font-family: Arial, Helvetica, sans-serif;"></span>


经仔细研究串口资料,发现接收乱码是因为电脑串口发送软件设置问题,没有设置校验位,uart模式3中是11位 为开始位0 +8位数据位+TB8/RB8校验位+停止位,在串口软件选择校验位就成功接收了。

发送乱码经检查为while(!TI)TI = 0;这两句是发送不成功则while(!TI)一直等待成功清空TI,忘了在while(!TI)后加“:”,导致一直清TI产生乱码。

没有更多推荐了,返回首页