3

So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter. I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:

#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile
RH_ASK driver; //use this driver for transmitter



#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );



void setup()
{
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{

    char key = keypad.getKey();

    if (key){
      Serial.println(key);//outputs correct key
      //transmitter part
//      const char *msg = "Hello World!";
      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg));
      driver.waitPacketSent();
      Serial.println(key);//outputs correct key
      Serial.println("packet_sent");
    }
}
VE7JRO
  • 2,515
  • 19
  • 27
  • 29
Milos Tosic
  • 45
  • 1
  • 1
  • 4

1 Answers1

3

The problem is you send a character of type char, thus exactly one byte. However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.

Also, you can get rid of the special msg pointer and instead of

  const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
  driver.send((uint8_t *)msg, strlen(msg

use

  driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus

  driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.

Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.

Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58