# include "stm32f10x.h"
# include "stdio.h"
#define PCF8591_ADDR 0x90
void PCF8591_Write(uint8_t channel){
I2C_GenerateSTART(I2C1,ENABLE);
while(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT)==ERROR);
I2C_Send7bitAddress(I2C1,PCF8591_ADDR,I2C_Direction_Transmitter);
while(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)==ERROR);
I2C_SendData(I2C1,0x10| channel);
while(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_BYTE_TRANSMITTED)==ERROR);
I2C_GenerateSTOP(I2C1,ENABLE);
}
uint8_t PCF8591_Read(uint8_t channel){
uint8_t tmp;
I2C_GenerateSTART(I2C1,ENABLE);
while(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_MODE_SELECT)==ERROR);
I2C_Send7bitAddress(I2C1,PCF8591_ADDR,I2C_Direction_Receiver);
while(I2C_CheckEvent(I2C1,I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)==ERROR);
tmp=I2C_ReceiveData(I2C1);
I2C_GenerateSTOP(I2C1,ENABLE);
return tmp;
}
void USART1_Config(){
GPIO_InitTypeDef Pin;
USART_InitTypeDef Rs232;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO|RCC_APB2Periph_USART1,ENABLE );
Pin.GPIO_Mode=GPIO_Mode_AF_PP;
Pin.GPIO_Pin=GPIO_Pin_9;
Pin.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&Pin);
Pin.GPIO_Mode=GPIO_Mode_IN_FLOATING;
Pin.GPIO_Pin=GPIO_Pin_10;
GPIO_Init(GPIOA,&Pin);
Rs232.USART_BaudRate=9600;
Rs232.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
Rs232.USART_Mode=USART_Mode_Tx| USART_Mode_Rx;
Rs232.USART_Parity=USART_Parity_No;
Rs232.USART_StopBits=USART_StopBits_1;
Rs232.USART_WordLength=USART_WordLength_8b;
USART_Init(USART1,&Rs232);
USART_Cmd(USART1,ENABLE);
}
int fputc(int ch,FILE *f){
USART_SendData(USART1,(uint8_t)ch);
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); //等待发送完毕
return ch;
}
void I2C1_PCF8591_Config(){
GPIO_InitTypeDef Pin;
I2C_InitTypeDef IIC;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_AFIO,ENABLE );
//SCL
Pin.GPIO_Mode=GPIO_Mode_AF_OD;
Pin.GPIO_Pin=GPIO_Pin_6;
Pin.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&Pin);
//SDA
Pin.GPIO_Pin=GPIO_Pin_7;
GPIO_Init(GPIOB,&Pin);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1,ENABLE);
IIC.I2C_ClockSpeed=400000;
IIC.I2C_Mode=I2C_Mode_I2C;
IIC.I2C_DutyCycle=I2C_DutyCycle_2;
IIC.I2C_OwnAddress1=0x7F;
IIC.I2C_Ack=I2C_Ack_Enable;
IIC.I2C_AcknowledgedAddress=I2C_AcknowledgedAddress_7bit;
I2C_Init(I2C1,&IIC);
I2C_Cmd(I2C1,ENABLE);
}
int main(){
uint8_t value;
USART1_Config();
printf("
This is a I2C Test
");
I2C1_PCF8591_Config();
I2C_GenerateSTART(I2C1,ENABLE);
while(1){
PCF8591_Write(0);
value=PCF8591_Read(0);
printf("
channel 0 value = %d
",value);
PCF8591_Write(1);
value=PCF8591_Read(1);
printf("
channel 1 value = %d
",value);
PCF8591_Write(2);
value=PCF8591_Read(2);
printf("
channel 2 value = %d
",value);
}
}
只能读取通道0 的数据,通道1,2 的数据读不出来。
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>