Пример #1
0
static msg_t temp_thread(void *arg) {
	(void)arg;

	chRegSetThreadName("I2C Temp samp");

	uint8_t rxbuf[10];
	uint8_t txbuf[10];
	msg_t status = RDY_OK;
	systime_t tmo = MS2ST(5);
	i2caddr_t temp_addr = 0x48;

	hw_start_i2c();
	chThdSleepMilliseconds(10);

	for(;;) {
		if (i2c_running) {
			txbuf[0] = 0x00;
			i2cAcquireBus(&HW_I2C_DEV);
			status = i2cMasterTransmitTimeout(&HW_I2C_DEV, temp_addr, txbuf, 1, rxbuf, 2, tmo);
			i2cReleaseBus(&HW_I2C_DEV);

			if (status == RDY_OK){
				int16_t tempi = rxbuf[0] << 8 | rxbuf[1];
				float temp = (float)tempi;
				temp /= 128;

				temp_now = temp;
			} else {
				// Try to restore the i2c bus
				i2cAcquireBus(&HW_I2C_DEV);
				palSetPadMode(HW_I2C_SCL_PORT, HW_I2C_SCL_PIN,
						PAL_STM32_OTYPE_OPENDRAIN |
						PAL_STM32_OSPEED_MID1 |
						PAL_STM32_PUDR_PULLUP);

				for(int i = 0;i < 16;i++) {
					palClearPad(HW_I2C_SCL_PORT, HW_I2C_SCL_PIN);
					chThdSleep(1);
					palSetPad(HW_I2C_SCL_PORT, HW_I2C_SCL_PIN);
					chThdSleep(1);
				}

				palSetPadMode(HW_I2C_SCL_PORT, HW_I2C_SCL_PIN,
						PAL_MODE_ALTERNATE(HW_I2C_GPIO_AF) |
						PAL_STM32_OTYPE_OPENDRAIN |
						PAL_STM32_OSPEED_MID1 |
						PAL_STM32_PUDR_PULLUP);

				i2cStop(&HW_I2C_DEV);
				i2cStart(&HW_I2C_DEV, &i2cfg);
				i2cReleaseBus(&HW_I2C_DEV);
			}
		}

		chThdSleepMilliseconds(100);
	}

	return 0;
}
Пример #2
0
static msg_t temp_thread(void *arg) {
	(void)arg;

	chRegSetThreadName("I2C Temp samp");

	uint8_t rxbuf[10];
	uint8_t txbuf[10];
	msg_t status = RDY_OK;
	systime_t tmo = MS2ST(5);
	i2caddr_t temp_addr = 0x48;

	hw_start_i2c();
	chThdSleepMilliseconds(10);

	for(;;) {
		if (i2c_running) {
			txbuf[0] = 0x00;
			i2cAcquireBus(&HW_I2C_DEV);
			status = i2cMasterTransmitTimeout(&HW_I2C_DEV, temp_addr, txbuf, 1, rxbuf, 2, tmo);
			i2cReleaseBus(&HW_I2C_DEV);

			if (status == RDY_OK){
				int16_t tempi = rxbuf[0] << 8 | rxbuf[1];
				float temp = (float)tempi;
				temp /= 128;

				temp_now = temp;
			} else {
				hw_try_restore_i2c();
			}
		}

		chThdSleepMilliseconds(100);
	}

	return 0;
}