单片机常用函数整理(一)

 1 void ComDataSendStr(const unsigned char str[])
 2 {
 3     unsigned char i = 0;
 4     for (i = 0; str[i] != '\0'; i++)
 5     {
 6         TXREG = str[i];
 7         TXEN = 1;
 8         while(!TRMT);
 9         TXEN = 0;
10     }
11 }
1 void ComDataSendChar(unsigned char cDbuf)
2 {
3     TXREG = cDbuf;
4     TXEN = 1;
5     while(!TRMT);
6     TXEN = 0;
7 }

PIC单片机中发送字符和字符串的函数功能。

 1 void ComDataSendNumInt_3bits(unsigned int str)
 2 {
 3     unsigned char cDbuf[3];
 4     unsigned char i;
 5 
 6     cDbuf[0] = str / 100 + 0x30;
 7     cDbuf[1] = str % 100 / 10 + 0x30;
 8     cDbuf[2] = str % 10 + 0x30;
 9 
10     for (i = 0; i < 3; i++)
11     {
12         TXREG = cDbuf[i];
13         TXEN = 1;
14         while(!TRMT);
15         TXEN = 0;
16     }
17 }

上面是发送时整形数字的函数

 1 void ComDataSendNumfloat(unsigned int str)
 2 {
 3     unsigned char cDbuf[4];
 4     unsigned char i;
 5 
 6     cDbuf[0] = str / 100 + 0x30;
 7     cDbuf[1] = '.';
 8     cDbuf[2] = str % 100 / 10 + 0x30;
 9     cDbuf[3] = str % 10 + 0x30;
10 
11     for (i = 0; i < 4; i++)
12     {
13         TXREG = cDbuf[i];
14         TXEN = 1;
15         while(!TRMT);
16         TXEN = 0;
17     }
18 }

应该是扩大100倍后的数字,发送浮点函数功能。

下面的函数是采样并滤波的函数。去max、min后求平均

 1 unsigned int sample_10bit(unsigned char channel_register)
 2 {
 3     unsigned char i=0;
 4     int sample_variable[10],min=0,max=0,SUM=0;
 5     while(i<10)
 6     {
 7         ADCON0=channel_register;
 8         ADFM=1;
 9         delay30us();
10         ADGO=1;
11         while(ADGO==1)
12         {
13             ;
14         }
15         sample_variable[i]=((ADRESH&0x03)<<8)+ADRESL;
16         if(i==0)
17         {
18             min=sample_variable[0];
19             max=sample_variable[0];
20             SUM=sample_variable[0];
21         }
22         else
23         {
24             min=(sample_variable[i]<min ?sample_variable[i]:min);
25             max=(sample_variable[i]>max ?sample_variable[i]:max);
26             SUM=SUM+sample_variable[i];
27         }
28         ADFM=0;
29         i++;
30     }
31     return (SUM-max-min)/8;
32 }

以上是pic16F787中用到的函数,特此整理。

 

posted @ 2019-03-31 21:09  wdliming  阅读(2158)  评论(0编辑  收藏  举报