|
过直角弯已经没有问题,目前就是速度还不行,有空改进算法,争取高速过弯
程序代码见下:
package ev3;
import lejos.hardware.Button;
import lejos.hardware.Key;
import lejos.hardware.KeyListener;
import lejos.hardware.Sound;
import lejos.hardware.lcd.LCD;
import lejos.hardware.motor.Motor;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.*;
public class LineFollower {
static int status = 0;
static int Power = 100;
static float Gain = 5;
static EV3ColorSensor cs = new EV3ColorSensor(SensorPort.S1);
static float Light = 0;
static float LineMin = 1;
static float LineMax = 0;
static float LineMid = 0;
public static void main(String[] args) {
Thread T = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
// 光线强度
SensorMode mode=cs.getRedMode();
float[] samples=new float[mode.sampleSize()];
mode.fetchSample(samples, 0);
for(float v:samples)
Light=v;
// 初始化最大值和最小值
if (status == 1) {
if (LineMax < Light) {
LineMax = Light;
} else if (LineMin > Light) {
LineMin = Light;
}
LineMid = (float) (LineMax + LineMin) / 2;
}
LCD.drawString("Light="+Light, 0, 0);
LCD.drawString("LineMid="+LineMid,0, 1);
LCD.drawString("LineMin="+LineMin, 0, 2);
LCD.drawString("LineMax="+LineMax, 0, 3);
}
}
});
Button.ESCAPE.addKeyListener(new KeyListener() {
@Override
public void keyPressed(Key k) {
// TODO 自动生成的方法存根
}
@Override
public void keyReleased(Key k) {
// TODO 自动生成的方法存根
System.exit(0);
}
});
// 启动监控线程
t1.start();
// 显示欢迎信息
LCD.clear();
LCD.drawString("LineFollower", 0, 0);
LCD.drawString("WellCome", 0, 1);
Button.waitForAnyPress();
cs.setFloodlight(true);
status = 1;
Motor.B.setSpeed(120);// 左轮
Motor.C.setSpeed(120);// 右轮
Motor.B.rotateTo(720, true);
Motor.C.rotateTo(-720);
Motor.B.stop();
Motor.C.stop();
status = 2;
Motor.B.backward();
Motor.C.forward();
while ((Light-LineMid)/LineMid>0.1) {
}
Motor.B.stop(true);
Motor.C.stop();
Sound.beepSequenceUp();
Motor.B.setSpeed(1);
Motor.C.setSpeed(1);
Motor.B.forward();
Motor.C.forward();
float Range = LineMax - LineMin;
while (true) {
LCD.drawString("PowerGain="+10*((Light - LineMid) * Gain) / Range, 0,5);
float PowerGain = 30*((Light - LineMid) * Gain) / Range;
Motor.B.setSpeed(Power - PowerGain);
Motor.C.setSpeed(Power + PowerGain);
}
}
}
|
|