
1   #include <Arduino.h>            // Arduino {API
2   #include <Wire.h>               // I2C ʐM
3   #include "freertos/FreeRTOS.h"  // FreeRTOS {
4   #include "freertos/semphr.h"    // FreeRTOS Z}tH
5   void i2c_write(uint8_t reg, uint8_t val){ 
6     Wire.beginTransmission(0x0E); // I2C 0x0E
7     Wire.write(reg); Wire.write(val); // f[^
8     Wire.endTransmission();
9   }
10  void i2c_read(uint8_t reg, uint8_t *d ){ 
11    Wire.beginTransmission(0x0E); // I2C 0x0E
12    Wire.write(reg); Wire.endTransmission(false); 
13    Wire.requestFrom(0x0E, 6);    // 6oCgǂݎ
14    for(uint8_t i=0;i<6;i++) d[i]=Wire.read();
15  }
16  SemaphoreHandle_t  sampleSem;   // ^XNʒmp̃oCiZ}tH
17  hw_timer_t *timer=nullptr;      // 1kHz n[hEFA^C}
18  void samplingTask(void*){       // 1kHz TvO^XN
19    const float SENS_uT_PER_LSB=0.042f;   // BM1422AGMVx[uT/LSB]
20    while(1){
21      xSemaphoreTake(sampleSem, portMAX_DELAY);   // 1kHzƂɋN
22      uint8_t xyz[6];     // f[^i[p6oCg
23      i2c_read(0x10,xyz); // Cf[^ǂݏo
24      int16_t x=xyz[0]|(xyz[1]<<8);   // f[^ϊ
25      int16_t y=xyz[2]|(xyz[3]<<8);
26      int16_t z=xyz[4]|(xyz[5]<<8);
27      i2c_write(0x1D,0x40);   // JnipgKj
28      double dx = (double)x * SENS_uT_PER_LSB;    // uTɕϊ
29      double dy = (double)y * SENS_uT_PER_LSB;
30      double dz = (double)z * SENS_uT_PER_LSB;
31      Serial.printf("%f,%f,%f\n",dx,dy,dz);   // VAo
32    }
33  }
34  void IRAM_ATTR onTimerISR(){    // ^C}荞݁i1kHzj
35    BaseType_t hp=pdFALSE; 
36    if(sampleSem) xSemaphoreGiveFromISR(sampleSem,&hp);   // Z}tH҂
37    if(hp) portYIELD_FROM_ISR();  // Dx(hp)^XNΐؑ
38  }
39  void setup() {
40    Serial.begin(921600);     // VAݒ
41    Wire.begin(); // I2C
42    Wire.setClock(400000);    // I2C clock 400kHz
43    i2c_write(0x1B,0xDA);     // CTRL1: Active=1,14bit,Single
44    delay(2);
45    i2c_write(0x5D,0x00); // CTRL4 Reset
46    i2c_write(0x1C,0x0c); // CTRL2:DRDY enable, DRDY activeH
47    i2c_write(0x40,0x00); // AVE_A:4񕽋
48    i2c_write(0x1D,0x40); // CNTL3 Jn
49    sampleSem=xSemaphoreCreateBinary();  // ^C}^XNʒmZ}tH
50    timer=timerBegin(0,80,true);  // ^C}0 801MHz
51    timerAttachInterrupt(timer,&onTimerISR,true); // ISRo^iGbWC^vgj
52    timerAlarmWrite(timer,1000,true); // 1000JEgƁi1msjɊ荞
53    xTaskCreatePinnedToCore(samplingTask,"sampler",8192,nullptr,3,nullptr,1);
54    timerAlarmEnable(timer);  // ^C}Jn  TvOX^[g
55  }
56  void loop() {}  // C[v͖gpi^XNISRŋ쓮j

