pio_dht11.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <stdio.h>
  2. #include "pico/stdlib.h"
  3. #include "hardware/pio.h"
  4. #include "dht11.pio.h"
  5. #define DHT11_SDA 16
  6. #define DHT11_START_PULSE_US (20 * 1000)
  7. volatile static uint temperature = 0;
  8. volatile static uint humidity = 0;
  9. void pio_irq_handler(void)
  10. {
  11. static int p = 0;
  12. static uint8_t buffer[5];
  13. // 1バイトの取り込みを行う
  14. if(pio_interrupt_get(pio0, 0)) {
  15. // 割り込みフラグ0クリア
  16. pio_interrupt_clear(pio0, 0);
  17. // データをpull
  18. buffer[p++] = pio_sm_get(pio0, 0) & 0xFF;
  19. }
  20. // 5バイト(40ビットの取り込み完了
  21. if(pio_interrupt_get(pio0,1)){
  22. // 割り込みフラグ1クリア
  23. pio_interrupt_clear(pio0, 1);
  24. p = 0; // ポインタ初期化
  25. uint8_t checksum = (buffer[0]+buffer[1]+buffer[2]+buffer[3]) & 0xFF;
  26. if( checksum == buffer[4]){
  27. // データ正常
  28. // DHT-11では小数部は切り捨ててしまう
  29. temperature = buffer[2];
  30. humidity = buffer[0];
  31. }
  32. }
  33. }
  34. // repeating_timerオブジェクト
  35. struct repeating_timer rtimer;
  36. bool update_dht11_data(__unused struct repeating_timer *t)
  37. {
  38. pio_sm_put(pio0, 0, DHT11_START_PULSE_US);
  39. return true; // falseを返すとリピート動作が終了
  40. }
  41. int main()
  42. {
  43. stdio_init_all();
  44. // CPUのPIO0_IRQ0に割り込みハンドラpio_irq_handlerを割り当てる
  45. irq_set_exclusive_handler(PIO0_IRQ_0, pio_irq_handler);
  46. // PIO0_IRQ0を有効化
  47. irq_set_enabled(PIO0_IRQ_0, true);
  48. // PIO0_IRQ0に割り込みフラグ0、1を割り当てる
  49. pio_set_irq0_source_enabled(pio0, pis_interrupt0, true);
  50. pio_set_irq0_source_enabled(pio0, pis_interrupt1, true);
  51. //
  52. uint offset = pio_add_program(pio0, &dht11_program);
  53. dht11_program_init(pio0, 0, offset, DHT11_SDA);
  54. pio_sm_set_enabled(pio0, 0, true);
  55. // 繰り返し実行する関数を登録する
  56. add_repeating_timer_ms(2*1000, update_dht11_data, NULL, &rtimer);
  57. while(true) {
  58. sleep_ms(2000);
  59. printf("hum = %d %%, temp = %d C\n", humidity, temperature);
  60. }
  61. }