Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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(){}
share|improve this question
up vote 2 down vote accepted
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.

share|improve this answer
    
+35: Really good answer. Your last method is the best for me. – Helio Oct 20 '15 at 14:15
    
One last question: Is ok to use a for loop to clear the report.keys array? – Helio Oct 20 '15 at 14:19
    
Yep, perfectly fine. for (int i = 0; i < 6; i++) { report.keys[i] = 0; } – Majenko Oct 20 '15 at 14:19
    
Thank you very much! – Helio Oct 20 '15 at 14:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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