First draft HMC5883 magnetometer sensor using physical quantities, outputting via serial port using std::cout on mbed os 5
Diff: hmc5883.cpp
- Revision:
- 3:2834be4e10ef
- Parent:
- 2:9ffb2f18756b
- Child:
- 7:5d14da0b4c95
--- a/hmc5883.cpp Tue Mar 24 15:21:34 2020 +0000 +++ b/hmc5883.cpp Tue Mar 24 22:43:44 2020 +0000 @@ -5,6 +5,34 @@ #include <quan/out/magnetic_flux_density.hpp> #include <quan/three_d/out/vect.hpp> +/* + + MySensor sensor; + + "HMC5883" -> HMC5883 + I2C -> + list of I2CBuses + I2CBusID -> I2C(I2C_SCL,I2C_SDA) + I2CAddress -> "0x3d" atoi -> 0x3D + + if (!sensor.open("HMC5883L.I2C[I2CBusID,0x3d]")){ + loop_forever("failed to open \"HMC5883L.I2C[I2CBusID,0x3d]\""); + } + sensor.Attach(50.0_Hz, onMagDataUpdated); + sensor.run(); + + template <typename Quantity> + struct Sensor{ + static bool open(Sensor& sensor, const char* name); + bool connected()const; + bool running() const; + bool idle() const + void close(); + bool read(Quantity & q); + setUpdateCallback(void(*pFun)()); + }; +*/ + namespace { /* 00 Configuration Register A R/W @@ -36,7 +64,9 @@ bool mag_set_reg_idx(uint8_t idx_in) { char const idx = static_cast<char>(idx_in); - bool const result = (i2c.write(i2c_addr,&idx,1) == 0); + i2c.lock(); + bool const result = i2c.write(i2c_addr,&idx,1) == 0; + i2c.unlock(); if(result) { return true; } else { @@ -50,7 +80,9 @@ bool mag_write_reg(uint8_t idx, uint8_t val) { char ar[2] = {idx,val}; - bool const result = (i2c.write(i2c_addr,ar,2) == 0); + i2c.lock(); + bool const result = i2c.write(i2c_addr,ar,2) == 0; + i2c.unlock(); if(result) { return true; } else { @@ -64,9 +96,12 @@ bool mag_get_reg(uint8_t idx_in, uint8_t& result) { if ( mag_set_reg_idx(idx_in)) { - char result1 = 0; - if (i2c.read(i2c_addr,&result1,1) == 0) { - result = result1; + char temp_result = 0; + i2c.lock(); + bool const success = i2c.read(i2c_addr,&temp_result,1) == 0; + i2c.unlock(); + if (success) { + result = temp_result; return true; } else { std::cout << "mag_get_reg read failed\n"; @@ -99,7 +134,10 @@ { if ( mag_set_reg_idx(id_regA) ) { char id_input[4]; - if(i2c.read(i2c_addr,id_input,3) == 0) { + i2c.lock(); + bool success = i2c.read(i2c_addr,id_input,3) == 0; + i2c.unlock(); + if(success) { id_input[3] = '\0'; bool const is_hmc = (strcmp(id_input,"H43") == 0); if (is_hmc) { @@ -312,7 +350,10 @@ { if( mag_set_reg_idx(dout_reg)) { char arr[7]; - if(i2c.read(i2c_addr,arr,7) == 0) { + i2c.lock(); + bool success= i2c.read(i2c_addr,arr,7) == 0; + i2c.unlock(); + if(success) { // TODO check status reg arr[6] // if quan::three_d::vect<int16_t> temp;