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();
}
}