Moderators: roger, 99jonathan, imaqine
public int sendData(int register, byte [] buf, int len) {
// AS Fix to allow write to work correctly. Avoid using the
// automatic internal address. Instead send the address as
// part of the data
if (len >= byteBuff.length) return -1;
for(int i=0; i < len; i++ )
byteBuff[i+1] = buf[i];
byteBuff[0] = (byte)register;
int ret = port.i2cStart(address, 0, 0, byteBuff, len+1, 1);
if (ret != 0) return ret;
while (port.i2cBusy() != 0) {
Thread.yield();
}
return 0;
}
import java.io.*;
import java.util.Vector;
import lejos.nxt.comm.*;
import lejos.nxt.*;
/**
*
* Abstraction for a NXT Ultrasonic Sensor.
*
*/
class UltrasonicSensor extends I2CSensor
{
byte[] buf = new byte[1];
public UltrasonicSensor(SensorPort port)
{
super(port);
}
/**
* Return distance of object.
*
* @return distance or 255 if no object in range
*/
public int getDistance()
{
int ret = getData(0x42, buf, 1);
return (ret == 0 ? (buf[0] & 0xff) : 255);
}
/**
* Return array of 8 echo distances
*
* @return 0 for success <> 0 otherwise
*/
public int getDistance(byte dist[])
{
if (dist.length < 8) return -1;
int ret = getData(0x42, dist, 8);
return ret;
}
/**
* Send a single ping
*
* @return 0 if ok <> 0 otherwise
*
*/
public int ping()
{
buf[0] = 0x1;
int ret = sendData(0x41, buf, 1);
return ret;
}
/**
* Switch to continuous ping mode
*
* @return 0 if ok <> 0 otherwise
*
*/
public int continuous()
{
buf[0] = 0x2;
int ret = sendData(0x41, buf, 1);
return ret;
}
/**
* Turn off ping mode
*
* @return 0 if ok <> 0 otherwise
*
*/
public int off()
{
buf[0] = 0x0;
int ret = sendData(0x41, buf, 1);
return ret;
}
/**
* Reset the device
*
* @return 0 if ok <> 0 otherwise
*
*/
public int reset()
{
buf[0] = 0x4;
int ret = sendData(0x41, buf, 1);
return ret;
}
}
public class ustest
{
public static void main(String[] args) throws Exception
{
UltrasonicSensor us = new UltrasonicSensor(SensorPort.S2);
byte[] dist = new byte[8];
// Turn things off for now
us.off();
while (!Button.LEFT.isPressed())
{
us.ping();
try{Thread.sleep(20);}catch(Exception e){}
us.getDistance(dist);
for(int i = 0; i < 8; i++)
LCD.drawInt(dist[i], 3, (i%4)*4, i/4);
LCD.refresh();
try{Thread.sleep(500);}catch(Exception e){}
}
LCD.drawString("Exit", 0, 4);
LCD.refresh();
}
}

CoBB wrote:This is quite interesting. If you look at the extra readings, it is possible to determine the relative angle of the surface to some extent, because the closer it is to being perpendicular to the line of sight, the more readings you get back and they seem to form a nearly arithmetic sequence if they are generated by the same object.

gloomyandy wrote:One question do you think all of the methods should be in the one class, or do you think it is worth keeping some of the more esoteric methods (like the calibration functions etc.) in an extended class since it is likely that most people will not need them?

Users browsing this forum: No registered users and 2 guests