1

I have a functon that creates a instance of KeyReport and I want to fill statically the KeyReport.keys array. I'm new in the Arduino world so I'll put a example to explain it better:

void sendKey(byte keys[6], byte modifiers)
{
  KeyReport report = {0};

  report.keys = keys; // This is my main trouble
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

void setup(){
delay(3000);
sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
}

void loop(){}

1 Answer 1

1
report.keys = keys; // This is my main trouble

You can't assign the contents of one array to the contents of another array. You can only copy the contents manually from one to the other.

The simplest way is with a loop:

for (int i = 0; i < 6; i++) {
    report.keys[i] = keys[i];
}

There is a helper function - memcpy() - which can do it for you if you prefer:

memcpy(report.keys, keys, 6);

It effectively does exactly the same thing - copy 6 bytes starting from the address of keys into the addresses starting at report.keys.

As for the "hard coded" reports I suggest you create some const arrays in the global context - and even use PROGMEM to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data. It may be simpler to split the report into 6 individual variables and pass each byte separately:

void sendKey(byte k0, byte k1, byte k2, byte k3,
             byte k4, byte k5, byte modifiers)
{
  KeyReport report = {0};

  report.keys[0] = k0;
  report.keys[1] = k1;
  report.keys[2] = k2;
  report.keys[3] = k3;
  report.keys[4] = k4;
  report.keys[5] = k5;
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.

3
  • +35: Really good answer. Your last method is the best for me.
    – 0x2b3bfa0
    Oct 20, 2015 at 14:15
  • One last question: Is ok to use a for loop to clear the report.keys array?
    – 0x2b3bfa0
    Oct 20, 2015 at 14:19
  • Yep, perfectly fine. for (int i = 0; i < 6; i++) { report.keys[i] = 0; }
    – Majenko
    Oct 20, 2015 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.