|
楼主 |
发表于 2014-5-21 11:31:37
|
显示全部楼层
#define PORT S1
#define Adresse (0x68<<1)
#define OFFSET_SAMPLES 200
byte init1[] = {Adresse, 0x6B, 0x80};
byte init2[] = {Adresse, 0x6B, 0x03};
byte init3[] = {Adresse, 0x1A, 0x00};
byte init4[] = {Adresse, 0x1B, 0x18};
byte read_gyro[] = {Adresse, 0x43};
byte nbytes;
byte data[];
int angle_speed_0= 0;
int angle_speed=0;
int angle=0;
float angle_P=1.2;
float angle_D=10;
int last_angle_error=0;
int route=0;
float route_P_factor=0.1;
float route_D_factor=25;
int last_route_error=0;
void GetGyroOffset()
{
float gSum;
int i, gMin, gMax, g;
ClearScreen();
TextOut(0, LCD_LINE1, " 6050 Segway ");
TextOut(0, LCD_LINE4, "Lay robot down");
TextOut(0, LCD_LINE5, "flat to get gyro");
TextOut(0, LCD_LINE6, "offset.");
gSum = 0.0;
gMin = 1000;
gMax = -1000;
for (i=0; i<OFFSET_SAMPLES; i++) {
I2CWrite(PORT, 6, read_gyro);
while(I2CStatus(PORT, nbytes)>0);
if (nbytes == 6)
{
I2CRead(PORT, 6, data);
g = (((data[0]<<8) | data[1])) ;
}
if (g > gMax)
gMax = g;
if (g < gMin)
gMin = g;
gSum += g;
Wait(5);
}
angle_speed_0 = gSum / OFFSET_SAMPLES +0.8;
}
task main()
{
SetSensorLowspeed(PORT);
Wait(25);
I2CWrite(PORT, 0, init1);
while(I2CStatus(PORT, nbytes)>0);
I2CWrite(PORT, 0, init2);
while(I2CStatus(PORT, nbytes)>0);
I2CWrite(PORT, 0, init3);
while(I2CStatus(PORT, nbytes)>0);
I2CWrite(PORT, 0, init4);
while(I2CStatus(PORT, nbytes)>0);
Wait(50);
GetGyroOffset();
Wait(50);
ResetRotationCount(OUT_B);
while (1)
{
I2CWrite(PORT, 6, read_gyro);
while(I2CStatus(PORT, nbytes)>0);
if (nbytes == 6)
{
I2CRead(PORT, 6, data);
angle_speed = (((data[0]<<8) | data[1])) - angle_speed_0;
angle_speed/=50;
}
angle += angle_speed;
int error_angle = 0 - angle;
int angle_PTerm = error_angle * angle_P;
int angle_DTerm = angle_speed * angle_D;
route = (MotorRotationCount(OUT_B));
int error_route = 0 - route;
int route_PTerm = error_route * route_P;
int route_DTerm = (error_route - last_route_error) * route_D;
last_route_error = error_route;
int PD = angle_PTerm - angle_DTerm - route_PTerm - route_DTerm;
if (PD >100) {PD = 100;}
if (PD < -100) {PD = -100;}
OnFwd(OUT_BC, PD);
}
} |
|