Go Down

### Topic: bitWrite, bitSet and bitClear to alter bytes in an array (Read 79 times)previous topic - next topic

#### Moshtaraq

##### Aug 24, 2019, 06:36 pm
Hi again,

I'm trying to make a snake game but running into some problems.

(There are probably better ways to make a snake game but I don't want to copy someone elses script, I try to learn and run into problems so I can solve them and progress)

My intent:

I have an array of 8 bytes called 'field' and an array with the coordinates of the body of the snake called 'tail' e.g.:

x: 1,1,1
y: 1,2,3

tail[]={{1,1,1},{1,2,3}}

I expect the following to happen:
take the coordinates and set those bits in the field(later they become dots on a led matrix)

so for the coordinates above it would look like:

11100000
00000000
00000000
00000000
00000000
00000000
00000000
00000000

And I wrote a function to do that called update_field(), in this function I use bitWrite to set the bit on those coordinates but the updated field returns empty.

Code: [Select]
`byte field[8] = {  B10000000,  B00000000,  B00000000,  B00000000,  B00000000,  B00000000,  B00000000,  B00000000,};int const snake_length = 3;int tail[2][snake_length] = {  {1, 2, 3},  {2, 4, 6}}; //1 indexed coordinatesint x = 0;int y = 0;void update_field() {  for (int i = 0; i < 8; i++) {//clears the whole field    field[i] = B00000000;  }  for (int i = 0; i < snake_length; i++) {    x = tail[1][i] - 1; //reads coordinate    y = tail[2][i] - 1; //0 indexed array    bitWrite(field[x], y,HIGH);//sets bit nr. y of row nr. x to 1    Serial.print("row for x = ");    Serial.println(x);    Serial.println(field[x]);  }}void setup() {  Serial.begin(9600);}void loop() {  update_field();  Serial.println("updated field : ");  for (int i = 0; i < 8; i++) {    for (int j = 0; j < 8; j++) {      Serial.print(bitRead(field[i], j));    }    Serial.print('\n');  }  delay(1000);}`

my serial print output looks like:
Code: [Select]
`row for x = 10row for x = 30row for x = 50updated field : 0000000000000000000000000000000000000000000000000000000000000000`

since the script compiles and uploads I assume the function bitWrite is used correctly? (I also tried bitSet but same result)

#### pert

#1
##### Aug 24, 2019, 07:01 pm
Code: [Select]
`int tail[2][snake_length] = {  {1, 2, 3},  {2, 4, 6}}; //1 indexed coordinates`
...
Code: [Select]
`    x = tail[1][i] - 1; //reads coordinate    y = tail[2][i] - 1; //0 indexed array`
You forgot that the first dimension of the array is zero indexed. There is no tail[2], so you're reading some random memory and then writing HIGH to that bit position.

#### Moshtaraq

#2
##### Aug 24, 2019, 07:14 pm
And I thought I was being carefull with the indexing
Thanks! Works fine now.

#### pert

#3
##### Aug 24, 2019, 07:23 pm
You're welcome. I'm glad to hear it's working now. Enjoy!
Per

Go Up