射频传输十六进制字符串比较Vs嵌入字符串Arduino

时间:2014-10-27 04:07:19

标签: arduino

我在Arduino Micro上使用VirtualWire库。我在比较通过电路板引脚2上的rf模块接收的HEX字符串时遇到了麻烦。当达到stringOne == stringVal2时,LED3始终点亮。我不知道从这里去哪里或者从哪里开始阅读以确定将HEX转换为可读的比较器。

#include <VirtualWire.h>
#define RX 2
#define LED A0
#define LED2 PIND7
#define LED3 PIND6

void setup(){
  Serial.begin(9600);
  Serial.print("setup complete");
  pinMode(RX, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  vw_set_rx_pin(RX);
  vw_setup(2000);
  vw_rx_start();
}

void loop(){
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)){
    int i;
    Serial.print("Got:");
    for (i = 0; i < buflen; i++){
      //Serial.print(buf[i], HEX);
      //String stringVal = String('65'+'6c'+'6c'+'6f'+'20'+'*','\0');
      String stringVal2 = String('73'+'6F'+'20'+'6C'+'6F'+'6E'+'*', HEX);
      String stringOne = String(buf[i], HEX);
      Serial.print(stringOne);
      Serial.print(' ');
      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED,LOW);
      delay(1000);
      if (stringOne == stringVal2){
        digitalWrite(LED2, HIGH);
      }
      else{
        digitalWrite(LED3, HIGH);
      }
    }
    Serial.println();

  }
}

以下是我的发射器的代码。使用Adafruit Trinket5v 8Mhz

#include <VirtualWire.h>

const int TX  = 3;
const int LED = 2;
const int buttonPin = 0; //Yellow Button
const int buttonPin2 =4; //Red Button
int buttonState = 0;
int buttonState2 = 0;

void setup(){
  vw_set_tx_pin(TX);
 // vw_set_ptt_pin(txpin);
 // vw_set_ptt_inverted(false);
  vw_setup(2000);
  pinMode(LED, OUTPUT); //Signals button press/transmission being sent
  pinMode(buttonPin, INPUT);
}

byte count = 1;

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:    
    digitalWrite(LED, HIGH);
    char msg[7] = {'h','e','l','l','o',' ','#'};
    msg[6] = count;
    vw_send((uint8_t *)msg, 7);
    vw_wait_tx();
    count = count + 1;  
  } 
  else {
    // turn LED off:
    digitalWrite(LED, LOW); 
  }

  buttonState2 = digitalRead(buttonPin2);
  if (buttonState2 == HIGH){
    digitalWrite(LED, HIGH);
    char msg[7] = {'12','11','10','9','8','7','6'};
    msg[6] = count;
    vw_send((uint8_t *)msg, 7);
    vw_wait_tx();
    count = count + 1;
  }
  else {
    digitalWrite(LED, LOW);
  }
}

1 个答案:

答案 0 :(得分:0)

您正在将只是文本的字符串与字符数组进行比较。这些将永远无法正确评估

如果你想正确初始化stringVal2以直接比较它,你需要这样做:

char strVal[] = {0x73, 0x6f, 0x20, 0x6c, 0x6f, 0x6e};
String stringVal2 = String(strVal);

这与你带来的其他字符串相同。

此外,由于您基本上只是捕获一个char数组,因此您可以直接使用char数组来评估结果,并在需要输出到人类时转换为字符串