Integration on arduino

Hi:

Im trying to implement a space-state control on arduino and I'm trying to figure out how to implement the integrator (the same integrator that Matlab has) as per my research the integrator should be like this:

double Yn = 0;
double Yn1 = 0;
double Xn = 0;
double Xn1 = 0;


void setup(){
  Serial.begin(9600);
}

void loop(){
  
  double Xn = 1000;
  Yn=Yn1+0.5*(Xn-Xn1);
  Xn1=Xn;
  Yn1=Yn;
  
  Serial.println(Xn1);
  delay(1);
  
}

where Xn is the independent variable (value). Is there anyone that has implemented such control succesfully?

  double Xn = 1000;

The variable is defined as a double, and assigned an int value. Why?

The variable is a local variable with the same name as a global variable. Why?

  Yn=Yn1+0.5*(Xn-Xn1);
  Xn1=Xn;
  Yn1=Yn;

Spacesaregood.

Well, the 1000 is an arbitrary value, in fact that Xn is value that is supposed to be read from the analog pin 0. In regards to the second question is not understood (I apologize for the ignorance)

In regards to the second question is not understood

Do you mean that you don't know the difference between a global variable and a local variable?

i guess @Gilgamesh90 doesn't realize that having "double Xn = 1000;" inside the loop creates another variable that is separate from the one created before setup().

The variables created before setup() are global variables.

If it's intended to be a different variable within loop() it would be much better to give then different names from the global variables.

...R

Robin2: i guess @Gilgamesh90 doesn't realize that having "double Xn = 1000;" inside the loop creates another variable that is separate from the one created before setup().

The variables created before setup() are global variables.

If it's intended to be a different variable within loop() it would be much better to give then different names from the global variables.

...R

Sorry for that, I do know the difference between global and local variables, what I dont exactly know is how they work exactly. What could be the difference (speaking of functionality)?

What could be the difference (speaking of functionality)?

Functionally, they are the same. The difference is one of scope - where the variable can be seen. A local variable can only been seen in the function or block in which it is defined. Global variables can be seen anywhere in the compilation unit (typically the whole sketch).

The problem comes when you think one variable is in scope, when, in reality, another one is. Never define two variables with the same name and that won't be a problem.