Serial.read(); is saving in the intager i use to diffine the lenght of char i want to store in

char z[]={};
int e = 0;
int e2 = 0;


void setup() {
  
  for (int i =2; i < 7; i++){
    pinMode (i, OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  Serial.print("give me a 5 digit binary number\n");
  // put your main code here, to run repeatedly:
  while(!Serial.available()){}
  if(Serial.available()){
    ;
    do{
      z[e]=Serial.read();  

      Serial.flush();
      e++;
      
    }while(Serial.available()); 
    
    e2= e-e2;
    z[e]='\0';  
    //Serial.print(z);
    if(e2 > 5){
      Serial.print("number is not allowed to be longer than 5 digits\n");
    }
    if((e2 <= 5) && (e > 0)){
      
      for(int i = 5; i>0; i--){
        
        if(z[e2-i] == 1){
          digitalWrite(7-i, HIGH);
          Serial.print("1");
        }
        else if(z[e2-i] == 0){
          digitalWrite(7-i, LOW);
          Serial.print("0");
        }
      }
      
    }
    e2 = e;
  }
}

why is at line 22 "z[e]=Serial.read();" storing the nuber from buffer in e?
i know the code is not realy efficient and has manny weak points

take a look here
https://www.arduino.cc/reference/en/language/functions/communication/serial/readstringuntil/

1 Like

thanks i think that could be a workaround, but I would like to know why serialread is storing in e?

char z[]={};
. . .
z[e]=Serial.read(); 

This will not behave as you expect and I can imagine that it is causing the problem you appear to be reporting. You have to define a size for array z[ ].

but i need an undefined lenght because everytime the loop goes through the lenght goes +5

Then there must be a maximum size. Specify that and see if your problem goes away.
If you don’t, it will simply overwrite storage until something breaks.

Yeh but my first Problem is that the return of serial read is being stored in e and not z[e ] so I would like to know why

Exactly. Because you have not defined the storage for array z[ ] correctly, anything you put in z[ ] will start overwriting other variables like, for instance, variable e.

Try this. As far as I can see, you actually need only 6 bytes to hold those 5 binary digits.
char z[ 10 ] = { 0 } ;