Creating a Touch Listener

This is where you talk about the NXJ software itself, installation issues, and programming talk.

Moderators: roger, 99jonathan, imaqine

Creating a Touch Listener

Postby butmonkey98 » Wed Dec 26, 2012 11:03 am

I am starting to learn Java, I have recently got a LEGO Mindstorms set. I was wondering, what is needed to main a Touch Listener. I just want the NXT to beep when a touch sensor is pressed. This is what I have so far, what more do I need to put in, What do I have that doesn't need to be there?
Code: Select all
import lejos.nxt.SensorPort;
import lejos.nxt.Sound;
import lejos.nxt.TouchSensor;
import lejos.robotics.Touch;

public class Main implements Touch{
    public static void main(String args[]){
        TouchSensor ts = new TouchSensor(SensorPort.S1);
    }
    public void addTouchListener(TouchListener touchListener) {

    }
    @Override
    public boolean isPressed() {
        Sound.beep();
        return false;
    }

    public class TouchListener{

    }
}

Thanks :)
butmonkey98
New User
 
Posts: 2
Joined: Wed Dec 26, 2012 10:56 am

Re: Creating a Touch Listener

Postby TechnoX » Tue Jan 01, 2013 4:49 pm

lejos.nxt.TouchSensor doesn't implement a sensor listener ...
And the ListenerThread-class is private so you can't write your own implementation of a sensorListener for the TouchSensor.
You would normally just do a loop that checks if the sensor is pressed.


But if you want to have a listener you can use the analog SensorPortListener, like this:
Code: Select all
import lejos.nxt.*;

public class Program {
   
   public static void main(String[] args) throws InterruptedException {
      
      SensorPort.S1.addSensorPortListener(new SensorPortListener(){
         @Override
         public void stateChanged(SensorPort source, int oldValue,   int newValue) {
            if(newValue>1000)
               LCD.drawString("Released", 0, 0);
            else
               LCD.drawString("Pressed ", 0, 0);
         }
      });
      
      Button.waitForAnyPress();
   }
}
TechnoX
Novice
 
Posts: 51
Joined: Tue May 03, 2011 5:57 pm
Location: Sweden

Re: Creating a Touch Listener

Postby gloomyandy » Tue Jan 01, 2013 5:32 pm

However I would not recommend that you do this. Search the forum and you will find lots of posts from me explaining why the listener model is not a good one. With touch sensors you will see the listener fire multiple times due to contact bounce within the hardware, there are also lots of other reasons not to use this interface...

Andy
User avatar
gloomyandy
leJOS Team Member
 
Posts: 3004
Joined: Fri Sep 28, 2007 2:06 pm
Location: UK

Re: Creating a Touch Listener

Postby butmonkey98 » Mon Jan 07, 2013 6:44 am

Thankyou very much :) this was helpful
butmonkey98
New User
 
Posts: 2
Joined: Wed Dec 26, 2012 10:56 am


Return to NXJ Software

Who is online

Users browsing this forum: No registered users and 1 guest

more stuff