/* Set the TWI bus speed in conjunction with the clock frequency.  */
status_code_t twim_set_speed(Twim *twim, uint32_t speed, uint32_t clk, uint8_t cycles)
/* Set the TWI bus speed in conjunction with the clock frequency.  */
status_code_t twim_set_speed(Twim *twim, uint32_t speed, uint32_t clk, uint8_t cycles)
{
	uint32_t f_prescaled;
	uint8_t cwgr_exp = 0;
	f_prescaled = (clk / speed / 2);
	while ((f_prescaled > 0xFF) && (cwgr_exp <= 0x7)) {
		cwgr_exp++;
		f_prescaled /= 2;
	}
	if (cwgr_exp > 0x7) {
		return ERR_INVALID_ARG;
	}
	twim->TWIM_CWGR = TWIM_CWGR_LOW(f_prescaled / 2)
			| TWIM_CWGR_HIGH(f_prescaled - f_prescaled / 2)
			| TWIM_CWGR_EXP(cwgr_exp)
			| TWIM_CWGR_DATA(cycles)
			| TWIM_CWGR_STASTO(f_prescaled);
	return STATUS_OK;
}