Hi everyone,
I want to build a simple step sequencer. I want to store the sequence of notes in a pointer, which points to an array. I wrote this function
void ext(int n) {
int newSeq[seqLength+1];
for(int i=0; i < seqLength;i++)
newSeq[i] = sequence[i];
newSeq[seqLength] = n;
Serial.println(n);
free(sequence);
sequence = newSeq;
seqLength++;
for(int i=0; i < seqLength;i++) {
Serial.println(sequence[i]);
delay(10);
}
}
and have the global variables
int *sequence = 0;
int seqLength=0;
I added a button which calls the function with an random value. But only the newly added value is correctly printed, the others are wrong.
What is wrong here. Do I need to store newSeq globaly too? I would like t avoid that... for memory reasons.
Thanks for any help.
The complete code is here. A button is attached to digital pin 2.
int *sequence = 0;
int seqLength=0;
const byte button1 = 2;
byte b1State = LOW;
void setup() {
pinMode(button1, INPUT);
Serial.begin(9600);
/*
int a[2];
Serial.println(sequence[0]);
Serial.println(sequence[1]);
Serial.println(sequence[2]);
int b[3] = {
5,6,7 };
sequence = b;
Serial.println(sequence[0]);
Serial.println(sequence[1]);
Serial.println(sequence[2]);
*/
}
void ext(int n) {
int newSeq[seqLength+1];
for(int i=0; i < seqLength;i++)
newSeq[i] = sequence[i];
newSeq[seqLength] = n;
Serial.println(n);
free(sequence);
sequence = newSeq;
seqLength++;
for(int i=0; i < seqLength;i++) {
Serial.println(sequence[i]);
delay(10);
}
}
void loop() {
// button 1
int reading = digitalRead(button1);
if (reading == HIGH && !(b1State&2)) {// check pressed && last loop not: 2nd bit == 0
b1State = b1State ^ 1; // set 1st bit = 1 > state = ON
int z = (int)random(100);
Serial.println("add");
ext(z);
}
bitWrite(b1State, 1, reading); // set 2nd bit = reading (for next loop)
}
Sorry for the cryptic button thing. It's my way to check a simple button push in just one byte
