sensor.py
1 # -*- coding: utf-8 -*-
2 
3 from time import sleep
4 import sys
5 from ev3dev import *
6 
7 color = [ '?', 'BLACK', 'BLUE', 'GREEN', 'YELLOW', 'RED', 'WHITE', 'BROWN' ]
8 
9 def _check_pressed( sn ):
10  if sn == SENSOR__NONE_:
11  ok, val = ev3_read_keys()
12  return ( ok and (( val & EV3_KEY_UP ) != 0 ))
13  else:
14  ok, val = get_sensor_value( 0, sn )
15  return ( ok and ( val != 0 ))
16 
17 if __name__ == '__main__':
18  print 'Waiting the EV3 brick online...'
19  if ev3_init() < 1: sys.exit( 1 )
20 
21  print '*** ( EV3 ) Hello! ***'
23 
24  print 'Found sensors:'
25  for i in range( SENSOR_DESC__LIMIT_ ):
26  type_inx = ev3_sensor_desc_type_inx( i )
27  if type_inx != SENSOR_TYPE__NONE_:
28  print ' type =', ev3_sensor_type( type_inx )
29  print ' port =', ev3_sensor_port_name( i )
30  ok, mode = get_sensor_mode( i, 256 )
31  if ok:
32  print ' mode =', mode
33  ok, n = get_sensor_num_values( i )
34  if ok:
35  for ii in range( n ):
36  ok, val = get_sensor_value( ii, i )
37  if ok:
38  print ' value%d = %d' % ( ii, val )
39 
40  ok, sn_ir = ev3_search_sensor( LEGO_EV3_IR )
41  if ok:
42  print 'IR sensor is found'
43  else:
44  print 'IR sensor is NOT found'
45 
46  ok, sn_touch = ev3_search_sensor( LEGO_EV3_TOUCH )
47  if ok:
48  print 'TOUCH sensor is found, press BUTTON for EXIT...'
49  else:
50  print 'TOUCH sensor is NOT found, press UP on the EV3 brick for EXIT...'
51 
52  ok, sn_color = ev3_search_sensor( LEGO_EV3_COLOR )
53  if ok:
54  print 'COLOR sensor is found, reading COLOR...'
55  set_sensor_mode( sn_color, 'COL-COLOR' )
56  while ( 1 ):
57  ok, val = get_sensor_value( 0, sn_color )
58  if not ok or ( val < 0 ) or ( val >= len( color )):
59  val = 0
60  sys.stdout.write( '\r(%s)' % ( color[ val ]))
61  sys.stdout.flush()
62  if _check_pressed( sn_touch ):
63  break
64  sleep( 0.2 )
65  sys.stdout.write( '\r ' )
66  sys.stdout.flush()
67  if _check_pressed( sn_touch ):
68  break
69  sleep( 0.2 )
70  else:
71  print 'COLOR sensor is NOT found'
72  while not _check_pressed( sn_touch ):
73  sleep( 0.1 )
74 
75  ev3_uninit()
76  print
77  print '*** ( EV3 ) Bye! ***'