NTest_adc_env.lua 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. -- Walk the ADC through a stepped triangle wave using the attached voltage
  2. -- divider and I2C GPIO expander.
  3. local N = ...
  4. N = (N or require "NTest")("adc-env")
  5. -- TODO: Preflight test that we are in the correct environment with an I2C
  6. -- expander in the right place with the right connections.
  7. -- TODO: Use the mcp23017 module in the main tree rather than hand-coding
  8. -- the commands
  9. N.test('setup', function()
  10. -- Configure the ADC
  11. if adc.force_init_mode(adc.INIT_ADC)
  12. then
  13. node.restart()
  14. error "Must reboot to get to ADC mode"
  15. end
  16. -- Configure the I2C bus
  17. i2c.setup(0, 2, 1, i2c.FAST)
  18. -- Set the IO expander port B to channels 0 and 1 as outputs
  19. i2c.start(0)
  20. ok(i2c.address(0, 0x20, i2c.TRANSMITTER))
  21. i2c.write(0, 0x01, 0xFC)
  22. i2c.stop(0)
  23. end)
  24. -- set the two-bit voltage divider output value to v (in 0,1,2,3)
  25. local function setv(v)
  26. assert (0 <= v and v <= 3)
  27. i2c.start(0)
  28. i2c.address(0, 0x20, i2c.TRANSMITTER)
  29. i2c.write(0, 0x15, v)
  30. i2c.stop(0)
  31. end
  32. -- read out the ADC and compare to given range
  33. local function checkadc(min, max)
  34. local v = adc.read(0)
  35. return ok(min <= v and v <= max, ("read adc: %d <= %d <= %d"):format(min,v,max))
  36. end
  37. -- Since we have a rail-to-rail 4-tap DAC, as it were, give us some one-sided
  38. -- wiggle around either rail and some two-sided wiggle around both middle stops
  39. local vmin = { 0, 300, 700, 1000 }
  40. local vmax = { 24, 400, 800, 1024 }
  41. -- Set the DAC, wait a brief while for physics, and then read the ADC
  42. local function mktest(fs, i)
  43. N.test(fs:format(i), function()
  44. setv(i)
  45. tmr.delay(10)
  46. checkadc(vmin[i+1], vmax[i+1])
  47. end)
  48. end
  49. -- test all four stops on the way up, and the three to come back down
  50. for i=0,3 do mktest("%d up", i) end
  51. for i=2,0,-1 do mktest("%d down", i) end