Class: Sensor

Inherits:
Brick show all
Defined in:
lib/sensors/sensor.rb

Overview

Controls and reads an NXT sensor.

Constant Summary collapse

POLL_INTERVAL =
0.25

Instance Attribute Summary

Attributes inherited from Brick

#log, #port

Instance Method Summary collapse

Constructor Details

#initialize(nxt, port) ⇒ Sensor

Returns a new instance of Sensor.



32
33
34
35
# File 'lib/sensors/sensor.rb', line 32

def initialize(nxt, port)
  super(nxt, port)
  @port = port
end

Instance Method Details

#nameObject



37
38
39
# File 'lib/sensors/sensor.rb', line 37

def name
  "#{@port + 1}"
end

#offObject



88
89
90
91
# File 'lib/sensors/sensor.rb', line 88

def off
  # Turns off the sensor.
  set_input_mode(NXTComm::NO_SENSOR, NXTComm::RAWMODE)
end

#read_dataObject



45
46
47
48
49
50
# File 'lib/sensors/sensor.rb', line 45

def read_data
  data = @nxt.get_input_values(@port)
  
  debug(data.inspect, :read_data)
  return data
end

#set_input_mode(type, mode) ⇒ Object



41
42
43
# File 'lib/sensors/sensor.rb', line 41

def set_input_mode(type, mode)
  @nxt.set_input_mode(@port, type, mode)
end

#wait_for_event(expected = true, operator = nil) ⇒ Object

Continuously evalutes the given block until it returns at least the given value (that is, until the block returns a value equal or greater than the given argument). If no value is specified, the block will be continuously evaluated until it returns true. Optionally, a comparison operator can be specified as the second parameter, otherwise >= is used (or == if expected value is Boolean).

Simple example:

ts = TouchSensor.new(@nxt)
ts.wait_for_event { ts.is_pressed? }

Example with an expected value:

ls = LightSensor.new(@nxt)
ls.wait_for_event(0.55) do
	ls.get_light_level
end


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/sensors/sensor.rb', line 72

def wait_for_event(expected = true, operator = nil)
	if operator
		comp = operator
	elsif expected.respond_to? '>='.intern
		comp = ">="
	else
		comp = "=="
	end
	
	while true
		value = yield
		return value if eval("value #{comp} expected")
		sleep(POLL_INTERVAL)
	end
end