C#,从USART中提取double,接收char缓冲区

时间:2012-03-26 21:26:43

标签: c embedded

我的USART从“黑匣子”接收一个字符串,该字符串包含两个双精度值和几个十六进制值。该字符串放在我的缓冲区rbuf.buf中,总大小为32个字符。通常我会收到19个字符,但最后会收到几个额外的错误字符。缓冲区通常如下所示(十六进制):

0x31,0x32,0x33,0x2e,0x34,0x35,0x20,0x36,0x37,0x2e,0x38,0x39,0x20,0x37,0x41,0x41,0x20,0x0a,0x0d,0x00,...

我想提取两个双打123.45和67.89,并尝试以下几个例子:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

...

void buffer_to_float(void)
{
static char string1[10] = "";
char *string2;
for(uint8_t i=0;i<6;i++)
  {
  char c = rbuf.buf[i];  // this is a char but how do I make it a pointer?
  string2 = strcat ( string1, c );  // ... "char" is incompatible with "char*" ...
  }

double R = atof(string2);
printf("%lf\n", R);
}

我知道我在做什么傻事但是什么? 我使用一个中断例程来接收字符串,我应该在那里进行提取还是应该尽可能短/快?

感谢告诉我我有多傻,我想我需要它; - )

1 个答案:

答案 0 :(得分:1)

您可以使用sscanf功能阅读两个float值:

char bla[] = {0x31, 0x32, 0x33, 0x2e,
              0x34, 0x35, 0x20, 0x36,
              0x37, 0x2e, 0x38, 0x39,
              0x20, 0x37, 0x41, 0x41,
              0x20, 0x0a, 0x0d, 0x00};

float a, b;

sscanf(bla, "%f %f", &a, &b);
printf("%f %f\n", a, b);