2015년 12월 11일 금요일

stm32 I2C UART 예제

#include "stm32f10x.h"//헤더
#include "stm32f10x_i2c.h" //헤더
#include "stm32f10x_usart.h"
typedef enum { FAILED = 0, PASSED = !FAILED} TestStatus;
#define I2C1_SLAVE_ADDRESS7 0x30//I2c1주소
#define I2C2_SLAVE1_ADDRESS7   0x30//I2c2주소 주소가 있어야 통신이 가능
#define BufferSize 4
#define ClockSpeed 200000
I2C_InitTypeDef I2C_InitStructure; //i2c 설정 구조체
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
uint8_t I2C1_Buffer1_Tx[BufferSize]={1,2,3,4}; //i2c1 버퍼
uint8_t I2C2_Buffer1_Rx[BufferSize];
uint8_t Tx_Idx=0,Rx_Idx=0;
uint8_t countx=0;
char cbuffer[4]={0,};
volatile TestStatus TransferStatus1=FAILED; //하드웨어 값을 폴링할 때 사용가능
void RCC_Configuration(void); //클럭
void GPIO_Configuration(void);//GPIO 설정
void I2C_Configuration(void);
void USART_Configuration(void);
void SerialPutChar(uint8_t c);
void Serial_PutString(uint8_t *s);
TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength); //리턴값이 스테이터스인 함수 버퍼 비교

int main(void)
{
 RCC_Configuration(); //클럭 활성화
  GPIO_Configuration();//gp 활성화
 USART_Configuration();
 I2C_Cmd(I2C1, ENABLE); // i2c1 활성화
  I2C_Cmd(I2C2, ENABLE); // i2c2 활성화
 I2C_Configuration();
 
 /*----- First transmission Phase -----*/
  /* Send I2C1 START condition */
  I2C_GenerateSTART(I2C1, ENABLE);//마스터에서 시작
  /* Test on I2C1 EV5 and clear it */
  while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)); //i2c1 레지스터 비우고 이벤트 발생
  /* Send I2C2 slave Address for write */
  I2C_Send7bitAddress(I2C1, I2C2_SLAVE1_ADDRESS7, I2C_Direction_Transmitter);//1에서 2로 보낸다는 7비트 주소 입력
  /* Test on I2C2 EV1 and clear it */
  while(!I2C_CheckEvent(I2C2, I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED));  //2에서 레지스터 비우고 주소 이벤트 체크
  /* Test on I2C1 EV6 and clear it */
  while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)); //1에서 보내기 준비
  /* Send data */
  while (Rx_Idx < BufferSize)
  {
    /* Send I2C1 data */
    I2C_SendData(I2C1, I2C1_Buffer1_Tx[Tx_Idx++]); //1에서 버퍼에있는 내용을 보냄
    /* Test on I2C2 EV2 and clear it */
    while(!I2C_CheckEvent(I2C2, I2C_EVENT_SLAVE_BYTE_RECEIVED));  //2에서 리시브 이벤트
    /* Store received data on I2C2 */
    I2C2_Buffer1_Rx[Rx_Idx++] = I2C_ReceiveData(I2C2); //받은 데이터를 버퍼에 적제
  cbuffer[countx]=I2C2_Buffer1_Rx[countx];
  countx++;
    /* Test on I2C1 EV8 and clear it */
    while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)); //1에서 보내기 준비
 
  }

  I2C_GenerateSTOP(I2C1, ENABLE); //1에서 스탑
  /* Test on I2C2 EV4 and clear it */
  while(!I2C_CheckEvent(I2C2, I2C_EVENT_SLAVE_STOP_DETECTED));  //2번도 스탑
  /* Clear I2C2 STOPF flag: read operation to I2C_SR1 followed by a
     write operation to I2C_CR1 */
  (void)(I2C_GetFlagStatus(I2C2, I2C_FLAG_STOPF));//플래그 지정
  I2C_Cmd(I2C2, ENABLE);    //2번을 활성화
  /* Check the corectness of written data */
  TransferStatus1 = Buffercmp(I2C1_Buffer1_Tx, I2C2_Buffer1_Rx, BufferSize); //올바로 갔는지 비교
  /* TransferStatus1 = PASSED, if the transmitted and received data
     are equal */
  /* TransferStatus1 = FAILED, if the transmitted and received data
     are different */
 while (1)               
  {
  SerialPutChar(cbuffer[0]);
 SerialPutChar(cbuffer[1]);
 SerialPutChar(cbuffer[2]);
 SerialPutChar(cbuffer[3]);
  }
}
void USART_Configuration(void)
{

 RCC_APB2PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE); //pwr 클럭 생성
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//usart 클럭 생성

 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;    /*UART1_TX*/
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;    /*UART1_RX*/
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure); 

 USART_InitStructure.USART_BaudRate = 115200;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
  NVIC_Init( &NVIC_InitStructure );

 USART_Init(USART1, &USART_InitStructure);   
  USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
  USART_Cmd(USART1, ENABLE);
}
void I2C_Configuration(void)
{
   /* I2C1 configuration ------------------------------------------------------*/
  I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
  I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
  I2C_InitStructure.I2C_OwnAddress1 = I2C1_SLAVE_ADDRESS7;
  I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
  I2C_InitStructure.I2C_ClockSpeed = ClockSpeed;
  I2C_Init(I2C1, &I2C_InitStructure);//마스터
  /* I2C2 configuration ------------------------------------------------------*/
  I2C_InitStructure.I2C_OwnAddress1 = I2C2_SLAVE1_ADDRESS7;
  I2C_Init(I2C2, &I2C_InitStructure);//술레이브
}
void RCC_Configuration(void) //클럭 설정
{
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);//지피 아이오 B 단자의 클럭 활성화을 설정
  /* I2C1 and I2C2 Periph clock enable */
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1 | RCC_APB1Periph_I2C2, ENABLE);// i2c1 i2c2 클럭 활성화을 설정
}
void GPIO_Configuration(void)//지피아이오 설정함수
{
 GPIO_InitTypeDef GPIO_InitStructure; //지피아이오를 설정한다 I2C1, I2C2를 핀 6,7 | 10,11에 배정한다, 마스터
 /* Configure I2C1 pins: SCL(시리얼 클럭:마스터 단반향) and SDA(시리얼 데이터 양방향) ----------------------------------------*/
  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_6 | GPIO_Pin_7;//6TX 7RX
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//클럭스피드
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;//alternate fuction 모드로 설정해서 i2c할때 사용한다.
  GPIO_Init(GPIOB, &GPIO_InitStructure);//설정된 값을 이니트
  /* Configure I2C2 pins: SCL and SDA ----------------------------------------*/
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;//이전에 설정한 값을 그대로 따르고 핀만 바꾼다. 슬레이브
  GPIO_Init(GPIOB, &GPIO_InitStructure); //10TX 11 RX

}
TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength)
{
  while(BufferLength--)
  {
    if(*pBuffer1 != *pBuffer2)
    {
      return FAILED;
    }
    pBuffer1++;
    pBuffer2++;
  }
  return PASSED; 
}
void SerialPutChar(uint8_t c)
{
 USART_SendData(USART1,c);
 while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);
}
void Serial_PutString(uint8_t *s)
{
 while(*s !='\0')
 {
  SerialPutChar(*s);
  s++;
 }
}
#ifdef  USE_FULL_ASSERT //어썰트 페일이 일어날때 함수
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif

댓글 없음:

댓글 쓰기