int fputc(int ch, FILE *fp) { if (fp == &__stdout) LCD1602_WriteData(ch); return ch; }
uint8_t PCF8591_ADC(void) { uint8_t temp; I2C1->CR1 |= I2C_CR1_START; // 开始信号 while ((I2C1->SR1 & I2C_SR1_SB) == 0); I2C1->DR = 0x90; // 地址码(写) while ((I2C1->SR1 & I2C_SR1_ADDR) == 0); // PB6~7必须接外部上拉电阻, 否则程序会卡死在这里 temp = I2C1->SR2; // 读SR2, 清ADDR I2C1->DR = 0x04; // 四路单输入, 通道0, 自动增益 while ((I2C1->SR1 & I2C_SR1_TXE) == 0); I2C1->CR1 |= I2C_CR1_START; // 重新发送开始信号 while ((I2C1->SR1 & I2C_SR1_SB) == 0); I2C1->DR = 0x91; // 地址码(读) while ((I2C1->SR1 & I2C_SR1_ADDR) == 0); temp = I2C1->SR2; // 读SR2, 清ADDR while ((I2C1->SR1 & I2C_SR1_RXNE) == 0); temp = I2C1->DR; I2C1->CR1 |= I2C_CR1_STOP; // 停止信号 while (I2C1->CR1 & I2C_CR1_STOP); return temp; }
int main(void) { uint8_t value; RCC->APB1ENR = RCC_APB1ENR_DACEN | RCC_APB1ENR_I2C1EN; RCC->APB2ENR = RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN; GPIOA->CRL = 0x00000333; GPIOB->CRL = 0xff000000; // PB6~7设为复用开漏50MHz输出 GPIOC->CRL = 0x33333333; I2C1->CR2 = 36; // FREQ=100100(36MHz) I2C1->CCR = 90; // CCR=FREQ/2f, f=200kHz I2C1->CR1 = I2C_CR1_PE; // 启动总线 LCD1602_Init(); while (1) { value = PCF8591_ADC(); LCD1602_WriteCmd(0x80); printf("Value:%d ", value); delay2(); } }
|