main_pikacar.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import machine
  2. time = machine.Time()
  3. # init adc pin
  4. pa2 = machine.ADC()
  5. pa2.setPin('PA2')
  6. pa2.enable()
  7. # init motor pin
  8. def pin_init(pin, pin_name):
  9. pin.setPin(pin_name)
  10. pin.setMode('out')
  11. pin.enable()
  12. pin.low()
  13. pa6 = machine.GPIO()
  14. pa7 = machine.GPIO()
  15. pb0 = machine.GPIO()
  16. pb1 = machine.GPIO()
  17. pin_init(pa6,'PA6')
  18. pin_init(pa7,'PA7')
  19. pin_init(pb0,'PB0')
  20. pin_init(pb1,'PB1')
  21. # init sensor
  22. pa2 = machine.ADC()
  23. pa2.setPin('PA2')
  24. pa2.enable()
  25. # car functions
  26. def read_sensor():
  27. if pa2.read() > 2.5:
  28. return 0
  29. else:
  30. return 1
  31. def motor(cmd):
  32. if cmd == 'f' :
  33. pa6.low()
  34. pa7.high()
  35. pb0.high()
  36. pb1.low()
  37. elif cmd == 'b':
  38. pa6.high()
  39. pa7.low()
  40. pb0.low()
  41. pb1.high()
  42. elif cmd == 'r':
  43. pa6.high()
  44. pa7.low()
  45. pb0.high()
  46. pb1.low()
  47. elif cmd == 'l':
  48. pa6.low()
  49. pa7.high()
  50. pb0.low()
  51. pb1.high()
  52. print('hardware init ok ')
  53. while True:
  54. if read_sensor():
  55. motor('r')
  56. time.sleep_s(1)
  57. else:
  58. motor('f')