So I put together the ChessBot and managed to get it to run through the program. So I moved to the Sejway.
I created the SejwayBad, downloaded it the brick and tried to run it.... the screen flashed? or more like drew a line on the LCD and then shut off. Here's the code I have.
- Code: Select all
import lejos.nxt.*;
public class Sejwaybad {
public static void main (String[] args) {
int NEUTRAL = 37;
int speed = 900;
LightSensor s = new LightSensor (SensorPort.S3, true);
Motor.B.setSpeed (speed);
Motor.C.setSpeed (speed);
while (!Button.ENTER.isPressed()) {
int SENS_VAL = s.readValue();
boolean forward = SENS_VAL > NEUTRAL;
if (forward) {
Motor.B.forward();
Motor.C.forward();
} else {
Motor.B.backward();
Motor.C.backward();
}
}
s.setFloodlight(false);
Motor.B.flt();
Motor.C.flt();
}
}
So I tried the Sejway. When I run this program the wheels just spin and the bot fall on its face and drives off. It also had to be shut off. Here is that code;
- Code: Select all
import lejos.nxt.*;
public class Sejway {
// PID constants
static final int KP = 28;
static final int KI = 4;
static final int KD = 33;
static final int SCALE = 18;
// Global vars:
int offset;
int prev_error;
float int_error;
LightSensor ls;
public Sejway() {
ls = new LightSensor(SensorPort.S2, true);
Motor.B.regulateSpeed(false);
Motor.C.regulateSpeed(false);
}
public void getBalancePos() {
// Wait for user to balance and press orange button
while (!Button.ENTER.isPressed()) {
// NXTway must be balanced.
offset = ls.readNormalizedValue();
LCD.clear();
LCD.drawInt(offset, 2, 4);
LCD.refresh();
}
}
public void pidControl() {
while (!Button.ESCAPE.isPressed()) {
int normVal = ls.readNormalizedValue();
// Proportional Error:
int error = normVal - offset;
// Adjust far and near light readings:
if (error < 0) error = (int)(error * 1.8F);
// Integral Error
int_error = ((int_error + error) * 2)/3;
// Derivative error:
int deriv_error = error - prev_error;
prev_error = error;
int pid_val = (int)(KP * error + KI * int_error + KD * deriv_error) / SCALE;
if (pid_val > 100)
pid_val = 100;
if (pid_val < -100)
pid_val = -100;
// Power derived from PID value:
int power = Math.abs(pid_val);
power = 55 + (power * 45) / 100; // NORMALIZE POWER
Motor.B.setPower(power);
Motor.C.setPower(power);
if (pid_val > 0) {
Motor.B.forward();
Motor.C.forward();
} else {
Motor.B.backward();
Motor.C.backward();
}
}
}
public void shutdown() {
// Shutdown LightSensor, motors
Motor.B.flt();
Motor.C.flt();
ls.setFloodlight(false);
}
public static void main(String[] args) {
Sejway sej = new Sejway();
sej.getBalancePos();
sej.pidControl();
sej.shutdown();
}
}
Is the code out date like some other areas of the book? Or is my sensor not working properly? And if not is there a way to calibrate it?
Thanks for any advice you have.

