nrf24l01test.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. """Test for nrf24l01 module. Portable between MicroPython targets."""
  2. import sys
  3. import ustruct as struct
  4. import utime
  5. from machine import Pin, SPI
  6. from nrf24l01 import NRF24L01
  7. from micropython import const
  8. # Slave pause between receiving data and checking for further packets.
  9. _RX_POLL_DELAY = const(15)
  10. # Slave pauses an additional _SLAVE_SEND_DELAY ms after receiving data and before
  11. # transmitting to allow the (remote) master time to get into receive mode. The
  12. # master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
  13. _SLAVE_SEND_DELAY = const(10)
  14. if sys.platform == 'pyboard':
  15. cfg = {'spi': 2, 'miso': 'Y7', 'mosi': 'Y8', 'sck': 'Y6', 'csn': 'Y5', 'ce': 'Y4'}
  16. elif sys.platform == 'esp8266': # Hardware SPI
  17. cfg = {'spi': 1, 'miso': 12, 'mosi': 13, 'sck': 14, 'csn': 4, 'ce': 5}
  18. elif sys.platform == 'esp32': # Software SPI
  19. cfg = {'spi': -1, 'miso': 32, 'mosi': 33, 'sck': 25, 'csn': 26, 'ce': 27}
  20. else:
  21. raise ValueError('Unsupported platform {}'.format(sys.platform))
  22. pipes = (b'\xf0\xf0\xf0\xf0\xe1', b'\xf0\xf0\xf0\xf0\xd2')
  23. def master():
  24. csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
  25. ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
  26. if cfg['spi'] == -1:
  27. spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
  28. nrf = NRF24L01(spi, csn, ce, payload_size=8)
  29. else:
  30. nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)
  31. nrf.open_tx_pipe(pipes[0])
  32. nrf.open_rx_pipe(1, pipes[1])
  33. nrf.start_listening()
  34. num_needed = 16
  35. num_successes = 0
  36. num_failures = 0
  37. led_state = 0
  38. print('NRF24L01 master mode, sending %d packets...' % num_needed)
  39. while num_successes < num_needed and num_failures < num_needed:
  40. # stop listening and send packet
  41. nrf.stop_listening()
  42. millis = utime.ticks_ms()
  43. led_state = max(1, (led_state << 1) & 0x0f)
  44. print('sending:', millis, led_state)
  45. try:
  46. nrf.send(struct.pack('ii', millis, led_state))
  47. except OSError:
  48. pass
  49. # start listening again
  50. nrf.start_listening()
  51. # wait for response, with 250ms timeout
  52. start_time = utime.ticks_ms()
  53. timeout = False
  54. while not nrf.any() and not timeout:
  55. if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
  56. timeout = True
  57. if timeout:
  58. print('failed, response timed out')
  59. num_failures += 1
  60. else:
  61. # recv packet
  62. got_millis, = struct.unpack('i', nrf.recv())
  63. # print response and round-trip delay
  64. print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
  65. num_successes += 1
  66. # delay then loop
  67. utime.sleep_ms(250)
  68. print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
  69. def slave():
  70. csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
  71. ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
  72. if cfg['spi'] == -1:
  73. spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
  74. nrf = NRF24L01(spi, csn, ce, payload_size=8)
  75. else:
  76. nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)
  77. nrf.open_tx_pipe(pipes[1])
  78. nrf.open_rx_pipe(1, pipes[0])
  79. nrf.start_listening()
  80. print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')
  81. while True:
  82. if nrf.any():
  83. while nrf.any():
  84. buf = nrf.recv()
  85. millis, led_state = struct.unpack('ii', buf)
  86. print('received:', millis, led_state)
  87. for led in leds:
  88. if led_state & 1:
  89. led.on()
  90. else:
  91. led.off()
  92. led_state >>= 1
  93. utime.sleep_ms(_RX_POLL_DELAY)
  94. # Give master time to get into receive mode.
  95. utime.sleep_ms(_SLAVE_SEND_DELAY)
  96. nrf.stop_listening()
  97. try:
  98. nrf.send(struct.pack('i', millis))
  99. except OSError:
  100. pass
  101. print('sent response')
  102. nrf.start_listening()
  103. try:
  104. import pyb
  105. leds = [pyb.LED(i + 1) for i in range(4)]
  106. except:
  107. leds = []
  108. print('NRF24L01 test module loaded')
  109. print('NRF24L01 pinout for test:')
  110. print(' CE on', cfg['ce'])
  111. print(' CSN on', cfg['csn'])
  112. print(' SCK on', cfg['sck'])
  113. print(' MISO on', cfg['miso'])
  114. print(' MOSI on', cfg['mosi'])
  115. print('run nrf24l01test.slave() on slave, then nrf24l01test.master() on master')