【问题标题】:Arduino: string to multiple variablesArduino:字符串到多个变量
【发布时间】:2015-12-02 22:09:45
【问题描述】:

我正在尝试通过 433MHz 无线电通信从两个传感器发送数据。我已经成功发送和接收字符串(char数组)“number1,number2”。

现在我尝试将这两个数字存储在单独的 int 变量中(值超过 256)。

我几乎尝试了所有方法(主要是 sscanf 和 atoi),但它似乎不起作用。

A0A1我已经连接了两个电位器,我想将它们的值存储在valorXvalorY 在接收器 arduino 中。

你有什么建议? 我不能保证我正确使用了 sscanf 和 atoi。

发射机代码:

#include <VirtualWire.h>

int xvalue;
int yvalue;

  void setup() {

  Serial.begin(9600);
  vw_set_ptt_inverted(true); //
  vw_set_tx_pin(12);
  vw_setup(4000);// speed of data transfer Kbps

}

void loop() {
  xvalue=analogRead(A0);
  yvalue=analogRead(A1);
  int envioX = map(xvalue, 0, 1023, 001, 1000); //I prefer to not send 0
  int envioY = map(yvalue, 0, 1023, 001, 1000);

//Mando los datos del joystic
  char envioXY[]="";
  sprintf(envioXY,"%d,%d",envioX,envioY); 
  EnviarDatos(envioXY); 
  delay(1000);
}

void EnviarDatos(char datos[]){
  vw_send((uint8_t *)datos, strlen(datos)); //vw_send(message, length)
  vw_wait_tx(); // Wait until the whole message is gone
}

收货人代码:

#include <VirtualWire.h>

char recibo[8]="";

int valorX;
int valorY;


  void setup(){
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_set_rx_pin(12);
    vw_setup(4000);  // Bits per sec
    vw_rx_start();       // Start the receiver PLL running
    Serial.begin(9600);
    Serial.println("setup");
  }
  void loop(){
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;
    if (vw_get_message(buf, &buflen)){ //check to see if anything has been received
      for(int i=0;i<buflen;i++){ 
        recibo[i]=char(buf[i]);
        Serial.print(recibo[i]);
      }
     recibo[buflen]=NULL; 
     //String str(recibo);

    //What here to get both int??  
    } 
  }

你有什么建议? 我不能保证我正确使用了 sscanf 和 atoi。

所以主要问题是如何将 "number1,number2" 转换为 int1=number1 和 int2=number2。

感谢和欢呼 加布里埃尔

【问题讨论】:

    标签: arrays string arduino type-conversion scanf


    【解决方案1】:

    发射机代码:

    您必须声明存储空间供sprintf 使用。您只声明了一个 1 字节数组,其中包含 NUL(0 字节)作为第一个也是唯一的元素 [0]:

    char envioXY[]="";
    

    改成这样,声明一个有24个元素的字符数组:

    char envioXY[ 24 ];
    

    虽然未初始化,sprintf 会在格式化您的 2 个整数时设置数组元素。

    接收方代码:

    recibo[buflen] = NULL;之后,你可以这样解析:

    sscanf( recibo, "%d,%d", &valorX, &valorY );
    

    格式字符串匹配sprintf格式,传入的是两个整数的地址,而不仅仅是两个整数。

    【讨论】:

    • 我现在完全爱你。我花了 4 个小时尝试接收器代码,但问题出在我发送的字符串的格式上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多