hsiaochung 发表于 2013-7-25 16:42:58

超音波传感器得到信息 , 请问要如何输出成 4位数值

我从超音波传感器得到信息
她的数值从 个位数 , 十位数 , 百位数都有
如果我想要输出为 4 位数 , 请问要如何处理

例如
      5 ---> 0005
       15---> 0015
      150---> 0150

mxhhaixin 发表于 2013-7-25 17:10:50

自己写一个转换成四位数的函数。

hsiaochung 发表于 2013-7-25 17:28:22

请问哪里有范例可参考

奇点 发表于 2013-7-25 18:10:36

void Convert(int num, char str)
{
        unsigned int numIndex = 0;
        unsigned int numCount = 0;
        int tempNum = 0;

        if (num > 10000 || num <= 0)
        {
                return;
        }

        tempNum = num;
        while (tempNum)
        {
                numCount++;
                tempNum /= 10;
        }

        for (numIndex = 0; numIndex < numCount; numIndex++)
        {
                str = num%10 + '0';
                num /= 10;
        }
}

remond 发表于 2013-7-25 21:03:23

sprintf(str,"%04d",data)

hsiaochung 发表于 2013-7-25 22:30:52

下面程序 compiler 有误 , 请问如何修改
sketch_jul25a.ino: In function 'int Convert(int, char*)':
sketch_jul25a:26: error: return-statement with no value, in function returning 'int'

int num;
char str;
void setup()
{
}

void loop()
{
num = 999;
Convert(num,str);
Serial.print(num);
}





int Convert(int num, char str)
{
         unsigned int numIndex = 0;
         unsigned int numCount = 0;
         int tempNum = 0;

         if (num > 10000 || num <= 0)
         {
               return;
         }

         tempNum = num;
         while (tempNum)
         {
               numCount++;
               tempNum /= 10;
         }

         for (numIndex = 0; numIndex < numCount; numIndex++)
         {
               str = num%10 + '0';
               num /= 10;
         }
         return num;
}

奇点 发表于 2013-7-26 09:35:25

楼主还是自己多研究一下c语音吧:lol

hsiaochung 发表于 2013-7-26 14:30:51

奇点
   谢谢你的帮忙,终于完成我的程序
读取超音波信息,范围从 4cm 到 300cm
我稍微修改一下你教我的程序代码
使得输出统整为4位数
int num;
const int pingPin = 11;
unsigned int duration, cm;

char str="0000";
void setup()
{
   Serial.begin(9600);
}

void loop()
{
   pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
digitalWrite(pingPin, LOW);      // Ensure pin is low
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);       // Start ranging
delayMicroseconds(5);            //   with 5 microsecond burst
digitalWrite(pingPin, LOW);      // End ranging
pinMode(pingPin, INPUT);         // Set pin to INPUT
duration = pulseIn(pingPin, HIGH); // Read echo pulse
cm = duration / 74 / 2*2.54;      // Convert to inches
Convert(cm);
delay(200);                           // Short delay
}


void Convert(int num)
{
   int numIndex = 0;
   int numCount = 3;
            
      
for (numIndex = 0; numIndex < numCount; numIndex++)
{
   str = num%10 + '0';
   num /= 10;
}
for (numIndex = 0; numIndex <5; numIndex++)
{
Serial.print(str);
}
}         

hsiaochung 发表于 2013-7-26 14:33:07

str = num%10 + '0';

请问一下 , 为何要加上 '0'      
页: [1]
查看完整版本: 超音波传感器得到信息 , 请问要如何输出成 4位数值