Class: NXT::Connector::Input::Ultrasonic

Inherits:
Object
  • Object
show all
Extended by:
Utils::Accessors
Includes:
NXT::Command::Input, NXT::Command::LowSpeed, Utils::Assertions
Defined in:
lib/nxt/connector/input/ultrasonic.rb

Overview

Implements the “ultrasonic” sensor for the NXT 2.0 module.

Defined Under Namespace

Classes: UnmeasurableDistance

Constant Summary collapse

UNIT =
%i[centimeters inches].freeze

Constants included from NXT::Command::LowSpeed

NXT::Command::LowSpeed::COMMAND_IDENTIFIER

Constants included from NXT::Command::Input

NXT::Command::Input::COMMAND_IDENTIFIER, NXT::Command::Input::SENSOR_MODE, NXT::Command::Input::SENSOR_TYPE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils::Accessors

attr_setter

Methods included from Utils::Assertions

#assert_in, #assert_responds_to, #assert_type

Methods included from NXT::Command::LowSpeed

#command_type, #ls_clear_buffer, #ls_get_status, #ls_read, #ls_write

Methods included from NXT::Command::Input

#command_type, #input_values, #ls_get_status, #ls_read, #ls_write, #reset_input_scaled_value, #update_input_mode

Constructor Details

#initialize(port, interface) ⇒ Ultrasonic

Returns a new instance of Ultrasonic.



24
25
26
27
# File 'lib/nxt/connector/input/ultrasonic.rb', line 24

def initialize(port, interface)
  @port = port
  @interface = interface
end

Instance Attribute Details

#interfaceObject

Returns the value of attribute interface.



18
19
20
# File 'lib/nxt/connector/input/ultrasonic.rb', line 18

def interface
  @interface
end

#portObject

Returns the value of attribute port.



18
19
20
# File 'lib/nxt/connector/input/ultrasonic.rb', line 18

def port
  @port
end

Instance Method Details

#distanceObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nxt/connector/input/ultrasonic.rb', line 29

def distance
  ls_write(NXT::Protocols::I2C.read_measurement_byte_0)

  while ls_get_status < 1
    sleep(0.1)
    # TODO: implement timeout so we don't get stuck if the expected data never comes
  end

  distance = ls_read[0]

  if @unit == :centimeters
    distance.to_i
  else
    (distance * 0.3937008).to_i
  end
end

#distance!Object



46
47
48
49
50
51
# File 'lib/nxt/connector/input/ultrasonic.rb', line 46

def distance!
  d = distance
  raise UnmeasurableDistance if d == 255

  d
end

#startObject



53
54
55
56
57
58
59
60
61
62
# File 'lib/nxt/connector/input/ultrasonic.rb', line 53

def start
  sensor_type(:lowspeed_9v)
  sensor_mode(:raw)

  update_input_mode
  ls_clear_buffer

  # set sensor to continuously send pings
  ls_write(NXT::Protocols::I2C.continuous_measurement_command)
end