这是我弄的一个数据采集上传到电脑的程序,传到电脑的是乱码,不知是怎么回事,还有我不太清楚波特率的具体应用和要求,不知是不是波特率的问题,不知谁能指点一下. #include <iom16v.h> #define uchar unsigned char #define uint unsigned int #define BAUD 9600 //波特率采用9600bps #define CRYSTAL 4000000 //系统时钟4MHz
//计算和定义波特率设置参数 #define BAUD_SETTING (unsigned int)((unsigned long)CRYSTAL/(16*(unsigned long)BAUD)-1) #define BAUD_H (unsigned char)(BAUD_SETTING>>8) #define BAUD_L (unsigned char)(BAUD_SETTING)
#define FRAMING_ERROR (1<<FE) #define PARITY_ERROR (1<<PE) #define DATA_OVERRUN (1<<DOR) #define DATA_REGISTER_EMPTY (1<<UDRE)
uchar Table[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; uchar Data[4]={0,0,0,0};
void DelayMs(uint i) //0.25ms {uchar j; for(;i!=0;i--) {for(j=250;j!=0;j--) {;}} }
void Display(unsigned char *p) //间隔5ms显示 {uchar i,sel=0x10; for(i=0;i<4;i++) {PORTD=sel; if(i==0) { PORTB=0xff-Table[p]+0x80; } else PORTB=0xff-Table[p]; DelayMs(10); sel=sel<<1; } }
uint ADC_Convert(void) {uint temp1,temp2; temp1=(uint)ADCL; temp2=(uint)ADCH; temp2=(temp2<<8)+temp1; return(temp2); }
void Process(uint i,uchar *p) {unsigned char h; p[0]=(uint)(((unsigned long)((unsigned long)i*5000))/1024)/1000; h=(uint)(((unsigned long)((unsigned long)i*5000))/1024); i=(uint)(((unsigned long)((unsigned long)i*5000))/1024)%1000; p[1]=i/100; i=i%100; p[2]=i/10; i=i%10; p[3]=i; } void USART_Transmit(unsigned char data) { while (!(UCSRA & DATA_REGISTER_EMPTY)); // 等待发送寄存器空 UDR = data; // 发送数据 }
void main(void) {uint i,h; PORTD = 0x03; // TXD(PD1)输出 DDRD = 0x02; // RXD(PD0)输入,上拉有效 UCSRA = 0x00; // USART初始化 UCSRB=(1<<RXEN)|(1<<TXEN);//允许发送和接收 //UCSRB = 0x98; UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0); // 8 Data, 1 Stop, No Parity UBRRH = BAUD_H; // 设置波特率 UBRRL = BAUD_L; DDRA=0x00; //设置A口为不带上拉输入; PORTA=0x00; DDRB=0xff; //设置B口为推挽1输出; PORTB=0xff; DDRD=0xff; //设置C口为推挽1输出; PORTD=0xff; PORTB=0x00; //B口初始化输出1;C口初始化输出0;点亮全部数码管; PORTD=0xff; ADMUX=0x01; //选择第二通道ADC1; ADCSR=0xe6; //125K转换速率,自由转换模式;启动AD转换器; DelayMs(3000); //延时待系统稳定; while(1) {i=ADC_Convert(); Process(i,Data); USART_Transmit(h); Display(Data); DelayMs(30000); } }
|