I will copy some of your relevant code here, for more experienced C coders to comment.
Here's the initialization of the variables that will receive data from AI2 via Bluetooth:
int x_n=100, y_n=0;
int x_d=0, y_d=100;
int y_d_dc,x_n_dc;
int y_d_cn=100, x_n_cn=100;
and here's the loop receiving the data:
void loop() {
gyro_signals();
timer_overflow();
while( Serial1.available() >=2 )
{
y_d = Serial1.read();
delay(1);
x_n = Serial1.read();
}
// x_N=100, y_N=0;
// x_D=0, y_D=100;
if( y_d> 99 && y_d<101&& x_n>99 && x_n<101){gocCBx = 0; congy = 0;}
if(y_d<y_d_cn){
// tính bước giảm của y dọc
y_d_dc = y_d_cn - y_d;
//cong y tương ứng với y dọc giảm
congy += y_d_dc;
// cập nhật giá trị y dọc đi lên
y_d_cn = y_d;
}
else{
//kiểm tra xem y_d có tăng so với giá trị trước đó không
if(y_d>y_d_cn){
// tính bước tăng của y dọc
y_d_dc = y_d - y_d_cn;
//trừ y tương ứng với y dọc giảm
congy -= y_d_dc;
// cập nhật giá trị y dọc đi xuống
y_d_cn = y_d;
}
}
if(x_n>99 && x_n <101){
if(x_n<99){gocCBx+=1;if(gocCBx>=3)gocCBx=3;}
else if(x_n>101){gocCBx-=1;if(gocCBx<=-3)gocCBx=-3;}
}
}
(I checked the two procedures gyro_signals and timer_overflow for Serial1 data traffic. There is none.)
I see you checking if there are at least 2 bytes available on Serial1, and reading them consecutively into int variables y_d and x_n:
while( Serial1.available() >=2 )
{
y_d = Serial1.read();
delay(1);
x_n = Serial1.read();
}
Because of the while() loop, you are only keeping the last 2 bytes.
You are also assuming the byte pairs are arriving interleaved, in x and y pairs judging by your variable names.
Then you do some range checking:
if( y_d> 99 && y_d<101&& x_n>99 && x_n<101){gocCBx = 0; congy = 0;}
if(y_d<y_d_cn){
// tính bước giảm của y dọc
y_d_dc = y_d_cn - y_d;
//cong y tương ứng với y dọc giảm
congy += y_d_dc;
// cập nhật giá trị y dọc đi lên
y_d_cn = y_d;
}
else{
//kiểm tra xem y_d có tăng so với giá trị trước đó không
if(y_d>y_d_cn){
// tính bước tăng của y dọc
y_d_dc = y_d - y_d_cn;
//trừ y tương ứng với y dọc giảm
congy -= y_d_dc;
// cập nhật giá trị y dọc đi xuống
y_d_cn = y_d;
}
}
if(x_n>99 && x_n <101){
if(x_n<99){gocCBx+=1;if(gocCBx>=3)gocCBx=3;}
else if(x_n>101){gocCBx-=1;if(gocCBx<=-3)gocCBx=-3;}
}
I don't see any places where you check for negative incoming values, so at first I thought that you should have been sending UnsignedBytes from AI2, but a check of the Bluetooth Blocks Pallette has no such block. (It turns out that Ai2 send unsigned bytes 0-255, and I guessed wrong.)
But there is something we can do to force interleaving of x and y values, by sending lists of (y,x) bytes. I am going to assume 100 is the midpoint value of one coordinate while you are sending the other value.
There is a 50% probability I an sending these pairs in the wrong order. Testing should reveal if I got lucky or not.
Instead of these:
I am guessing you instead need these:
control_slider (1).aia (79.9 KB)