I have had a problem making a simple sketch to KeyChainino. The problem was that if I put the code below on the basic sketch to just blinking one LED of the matrix, the LED only turns OFF and never goes ON.

void loop() {
  matrixState[0][0] = 1;
  delay(1000);
  matrixState[0][0] = 0;
  delay(1000);
}

It’s very strange because I don’t nothing different compared to the other games sketches. Looking forward on this problem I discovered that the problem was the interrupt used for Charlieplexing matrix.

Probably, when I set a bit of the matrixState and an interrupt occurs, the microcontroller doesn’t set that bit. The instruction is truncated.

I discovered that, by hacking the code in this way:

void loop() {
  for (byte i = 0; i < 10; i++) {
    matrixState[0][0] = 1;
    delay(1);
  }
  delay(1000);
  matrixState[0][0] = 0;
  delay(1000);
}

If I set 10 times the matrixState it will finally works. But it’s not a clean solution of the problem, so I tried this one:

void loop() {
  cli();
  matrixState[0][0] = 1;
  sei();
  delay(1000);
  matrixState[0][0] = 0;
  delay(1000);
}

The two functions cli() and sei() are used to stop and start the interrupt. In this way I’m able to do this:

  • Stop the interrupt
  • set the bit of the matrixState
  • start the interrupt

This solution works perfectly. So I made two function in order to set and clear a single bit on the matrixState.

void loop() {
  setMatrixStateBit(0,0);
  delay(1000);
  clearMatrixStateBit(0,0);
  delay(1000);
}

//here we set or clear a single bit on the matrixState. We use this funciton in order
//to really set or clear the matrix's bit when an interrupt occours. To do that we disable the
//interrupt -> set or clear the bit -> enable interrupt

void setMatrixStateBit(byte i, byte j) {
  cli();
  matrixState[i][j] = 1;
  sei();
}
void clearMatrixStateBit(byte i, byte j) {
  cli();
  matrixState[i][j] = 0;
  sei();
}

So I added these functions on all KeyChainino’s sketches.

If you want to know something more, please leave a comment below.

Alessandro

Some changes on the basic sketch

Comments

comments

Leave a Reply

Your email address will not be published. Required fields are marked *