Kaynağa Gözat

Clean project.

Vladimir N. Shilov 1 yıl önce
ebeveyn
işleme
9da112faab
7 değiştirilmiş dosya ile 1 ekleme ve 751 silme
  1. 1 5
      ReadMe.txt
  2. 0 94
      lib/htu21.c
  3. 0 17
      lib/htu21.h
  4. 0 229
      lib/i2c.c
  5. 0 33
      lib/i2c.h
  6. 0 329
      lib/i2c_master_poll.c
  7. 0 44
      lib/i2c_master_poll.h

+ 1 - 5
ReadMe.txt

@@ -1,5 +1 @@
-Спроба приєднати сенсор HTU-21D та виводити температуру та вологість.
-Аналоги сенсору - Si-7021, SHT-21...
-
-Мій HTU-21D виявився дохлим - показник вологості постійно 119, температура - 
-якась мачня. Якщо не знайду в себе аналогу то буду пробувати інший датчик.
+Спроба приєднати сенсор AHTxx та виводити температуру та вологість.

+ 0 - 94
lib/htu21.c

@@ -1,94 +0,0 @@
-#include "stm8s.h"
-#include "htu21.h"
-#include "i2c.h"
-#include "i2c_master_poll.h"
-#include "delay.h"
-
-#define HTU_T_MEASURE 0xF3
-#define HTU_H_MEASURE 0xF5
-
-static uint8_t buf[3];
-static const uint8_t addr = 0x40;
-static t_i2c_status i2cs = I2C_SUCCESS;
-static uint32_t val;
-
-static uint8_t CalcSht21Crc(uint8_t *data, uint8_t nbrOfBytes);
-
-htu_err_t htu_GetTemperature(int16_t * temperature) {
-  buf[0] = HTU_T_MEASURE;
-  i2cs = i2c_wr_data(addr, 1, buf);
-  //I2C_WriteBytes(addr, 1, buf);
-  if (i2cs == 0) {
-    Delay(100);
-    i2c_rd_data(addr, 3, buf);
-    //I2C_ReadBytes(addr, 3, buf);
-    if(buf[2] == CalcSht21Crc(buf,2)) {
-      val = buf[0];
-      val <<= 8;
-      val |= (buf[1] & 0xfc);
-      // Temp = val * 175.72 / 2^16 - 46.85
-      val *= 4393; // 175.72/4*100
-      val *= 100; // for .xx degree
-      val += 819200; // for round
-      val /= 1638400; // 2^16/4*100
-      *temperature = val - 4685;
-      return HTU_OK;
-    } else {
-      *temperature = 1100;
-      return HTU_CRC_Temp;
-    }
-  } else {
-    *temperature = 9900;
-    return HTU_I2C;
-  }
-}
-
-htu_err_t htu_GetHumidity(uint16_t * humidity) {
-  buf[0] = HTU_H_MEASURE;
-  i2cs = i2c_wr_data(addr, 1, buf);
-  //I2C_WriteBytes(addr, 1, buf);
-  if (i2cs == 0) {
-    Delay(100);
-    i2c_rd_data(addr, 3, buf);
-    //I2C_ReadBytes(addr, 3, buf);
-    if(buf[2] == CalcSht21Crc(buf,2)) {
-      val = buf[0];
-      val <<= 8;
-      val |= (buf[1] & 0xfc);
-      // Humidity = val * 125 / 2^16 - 6
-      val *= 125;
-      //val *= 10; // for .x %H
-      val += 32768; // for round
-      val /= 65536;
-      *humidity = val - 6;
-      return HTU_OK;
-    } else {
-      *humidity = 1100;
-      return HTU_CRC_Humidity;
-    }
-  } else {
-    *humidity = 9900;
-    return HTU_I2C;
-  }
-}
-
-static uint8_t CalcSht21Crc(uint8_t *data, const uint8_t nbrOfBytes) {
-	// CRC
-	//const u16t POLYNOMIAL = 0x131; //P(x)=x^8+x^5+x^4+1 = 100110001
-	
-	uint8_t byteCtr,bit,crc;
-
-	crc = 0;
-
-	//calculates 8-Bit checksum with given polynomial
-	for (byteCtr = 0; byteCtr < nbrOfBytes; ++byteCtr)
-	{ 
-		crc ^= (data[byteCtr]);
-		for (bit = 8; bit > 0; --bit)
-		{
-			if (crc & 0x80) crc = (crc << 1) ^ 0x131;
-				else 		crc = (crc << 1);
-		}
-	}
-	return(crc);
-}

+ 0 - 17
lib/htu21.h

@@ -1,17 +0,0 @@
-#pragma once
-#ifndef HTU21_H
-#define HTU21_H
-
-#include "stm8s.h"
-
-typedef enum {
-  HTU_OK = 0,
-  HTU_I2C,
-  HTU_CRC_Temp,
-  HTU_CRC_Humidity
-} htu_err_t;
-
-htu_err_t htu_GetTemperature(int16_t * temperature);
-htu_err_t htu_GetHumidity(uint16_t * humidity);
-
-#endif // HTU21_H

+ 0 - 229
lib/i2c.c

@@ -1,229 +0,0 @@
-/******************************************************************************
-* Драйвер модуля I2C микроконтроллера STM8S003F
-*
-* Автор: Осипов Андрей
-* Дата:  17 июля 2014
-* URL:   http://hamlab.net/mcu/stm8/i2c.html
-******************************************************************************/
-
-#include "i2c.h"
-
-/* Таймаут ожидания события I2C */
-extern __IO uint8_t I2C_timeout;
-
-/* Ожидание наступления события event в течении времени timeout в мс */
-#define wait_event(event, timeout) I2C_timeout = timeout;\
-                                   while(event && I2C_timeout);\
-                                   if(!I2C_timeout) return I2C_TIMEOUT;
-#define set_I2C_timeout_ms(time)  I2C_timeout = time
-
-/**
- * @brief Инициализация I2C интерфейса
- */
-void i2c_master_init(void) {
-  uint16_t ccr;
-
-  /* Настройка GPIO SDA SCL - HiZ, Open drain, Fast */
-  GPIOB->DDR |= (GPIO_PIN_4 | GPIO_PIN_5);
-  GPIOB->ODR |= (GPIO_PIN_4 | GPIO_PIN_5);
-  GPIOB->CR2 |= (GPIO_PIN_4 | GPIO_PIN_5);
-
-  //Частота тактирования периферии MHz
-  I2C->FREQR = (uint8_t)(F_MASTER_MHZ);
-
-  //Отключаем I2C
-  I2C->CR1 &= (uint8_t)(~I2C_CR1_PE);
-
-  //Выбираем режим
-#ifdef I2C_FAST
-  I2C->CCRH = I2C_CCRH_FS; // | I2C_CCRH_DUTY;
-#else
-  I2C->CCRH = 0;
-#endif
-
-  //CCR = Fmaster/2*Fiic = 16MHz/2*100kHz = 80
-  ccr = (uint16_t)(F_MASTER_HZ / (2 * F_I2C_HZ));
-
-  //Set Maximum Rise Time: 1000ns max in Standard Mode
-  //= [1000ns/(1/InputClockFrequencyMHz.10e6)]+1
-  //= InputClockFrequencyMHz+1
-  I2C->TRISER = (uint8_t)(F_MASTER_MHZ + 1);
-  I2C->CCRL = (uint8_t)ccr;
-  I2C->CCRH |= (uint8_t)((uint8_t)(ccr >> 8) & I2C_CCRH_CCR);
-
-  //Включаем I2C
-  I2C->CR1 |= I2C_CR1_PE;
-
-  //Разрешаем подтверждение в конце посылки
-  I2C->CR2 |= I2C_CR2_ACK;
-}
-
-/**
- * @brief Send data to slave device.
- */
-t_i2c_status i2c_wr_data(const uint8_t address, const uint8_t num_bytes_to_wr, uint8_t * data) {
-  uint8_t adr = address << 1;
-  uint8_t length = num_bytes_to_wr;
-
-  //Ждем освобождения шины I2C
-  wait_event((I2C->SR3 & I2C_SR3_BUSY), 10);
-    
-  //Генерация СТАРТ-посылки
-  I2C->CR2 |= I2C_CR2_START;
-  //Ждем установки бита SB
-  wait_event(!(I2C->SR1 & I2C_SR1_SB), 5);
-  
-  //Записываем в регистр данных адрес ведомого устройства
-  I2C->DR = adr;
-  //Ждем подтверждения передачи адреса
-  wait_event(!(I2C->SR1 & I2C_SR1_ADDR), 5);
-  //Очистка бита ADDR чтением регистра SR3
-  I2C->SR3;
-  
-  //Отправка данных
-  while (length--) {
-    //Ждем освобождения регистра данных
-    wait_event(!(I2C->SR1 & I2C_SR1_TXE), 5);
-    //Отправляем адрес регистра
-    I2C->DR = *data++;
-  }
-  
-  //Ловим момент, когда DR освободился и данные попали в сдвиговый регистр
-  wait_event(!((I2C->SR1 & I2C_SR1_TXE) && (I2C->SR1 & I2C_SR1_BTF)), 5);
-  
-  //Посылаем СТОП-посылку
-  I2C->CR2 |= I2C_CR2_STOP;
-  //Ждем выполнения условия СТОП
-  wait_event((I2C->CR2 & I2C_CR2_STOP), 5);
-  
-  return I2C_SUCCESS;
-}
-
-/**
- * @brief Чтение регистра slave-устройства
- * @note Start -> Slave Addr -> Reg. addr -> Restart -> Slave Addr <- data ... -> Stop
- */
-t_i2c_status i2c_rd_data(const uint8_t address, const uint8_t num_bytes_to_rd, uint8_t * data) {
-  uint8_t addr = (address << 1) | 1;
-  uint8_t length = num_bytes_to_rd;
-
-  //Ждем освобождения шины I2C
-  wait_event((I2C->SR3 & I2C_SR3_BUSY), 10);
-    
-  //Разрешаем подтверждение в конце посылки
-  I2C->CR2 |= I2C_CR2_ACK;
-  
-  //Генерация СТАРТ-посылки
-  I2C->CR2 |= I2C_CR2_START;
-  //Ждем установки бита SB
-  wait_event(!(I2C->SR1 & I2C_SR1_SB), 2);
-  
-  //Записываем в регистр данных адрес ведомого устройства и переходим
-  //в режим чтения (установкой младшего бита в 1)
-  I2C->DR = addr;
-  
-  //Дальше алгоритм зависит от количества принимаемых байт
-  //N=1
-  if(length == 1){
-    //Запрещаем подтверждение в конце посылки
-    I2C->CR2 &= ~I2C_CR2_ACK;
-    //Ждем подтверждения передачи адреса
-    wait_event(!(I2C->SR1 & I2C_SR1_ADDR), 2);
-    
-    //Заплатка из Errata
-    disableInterrupts();
-    //Очистка бита ADDR чтением регистра SR3
-    I2C->SR3;
-    
-    //Устанавлием бит STOP
-    I2C->CR2 |= I2C_CR2_STOP;
-    //Заплатка из Errata
-    enableInterrupts();
-    
-    //Ждем прихода данных в RD
-    wait_event(!(I2C->SR1 & I2C_SR1_RXNE), 2);
-    
-    //Читаем принятый байт
-    *data = I2C->DR;
-  } 
-  //N=2
-  else if (length == 2) {
-    //Бит который разрешает NACK на следующем принятом байте
-    I2C->CR2 |= I2C_CR2_POS;
-    //Ждем подтверждения передачи адреса
-    wait_event(!(I2C->SR1 & I2C_SR1_ADDR), 2);
-    //Заплатка из Errata
-    disableInterrupts();
-    //Очистка бита ADDR чтением регистра SR3
-    I2C->SR3;
-    //Запрещаем подтверждение в конце посылки
-    I2C->CR2 &= ~I2C_CR2_ACK;
-    //Заплатка из Errata
-    enableInterrupts();
-    //Ждем момента, когда первый байт окажется в DR,
-    //а второй в сдвиговом регистре
-    wait_event(!(I2C->SR1 & I2C_SR1_BTF), 2);
-    
-    //Заплатка из Errata
-    disableInterrupts();
-    //Устанавлием бит STOP
-    I2C->CR2 |= I2C_CR2_STOP;
-    //Читаем принятые байты
-    *data++ = I2C->DR;
-    //Заплатка из Errata
-    enableInterrupts();
-    *data = I2C->DR;
-  } 
-  //N>2
-  else if (length > 2) {
-    //Ждем подтверждения передачи адреса
-    wait_event(!(I2C->SR1 & I2C_SR1_ADDR), 2);
-    
-    //Заплатка из Errata
-    disableInterrupts();
-    
-    //Очистка бита ADDR чтением регистра SR3
-    I2C->SR3;
-    
-    //Заплатка из Errata
-    enableInterrupts();
-    
-    while (length-- > 3 && I2C_timeout) {
-      //Ожидаем появления данных в DR и сдвиговом регистре
-      wait_event(!(I2C->SR1 & I2C_SR1_BTF), 2);
-      //Читаем принятый байт из DR
-      *data++ = I2C->DR;
-    }
-    //Время таймаута вышло
-    if (!I2C_timeout) return I2C_TIMEOUT;
-    
-    //Осталось принять 3 последних байта
-    //Ждем, когда в DR окажется N-2 байт, а в сдвиговом регистре
-    //окажется N-1 байт
-    wait_event(!(I2C->SR1 & I2C_SR1_BTF), 2);
-    //Запрещаем подтверждение в конце посылки
-    I2C->CR2 &= ~I2C_CR2_ACK;
-    //Заплатка из Errata
-    disableInterrupts();
-    //Читаем N-2 байт из RD, тем самым позволяя принять в сдвиговый
-    //регистр байт N, но теперь в конце приема отправится посылка NACK
-    *data++ = I2C->DR;
-    //Посылка STOP
-    I2C->CR2 |= I2C_CR2_STOP;
-    //Читаем N-1 байт
-    *data++ = I2C->DR;
-    //Заплатка из Errata
-    enableInterrupts();
-    //Ждем, когда N-й байт попадет в DR из сдвигового регистра
-    wait_event(!(I2C->SR1 & I2C_SR1_RXNE), 2);
-    //Читаем N байт
-    *data++ = I2C->DR;
-  }
-  
-  //Ждем отправки СТОП посылки
-  wait_event((I2C->CR2 & I2C_CR2_STOP), 2);
-  //Сбрасывает бит POS, если вдруг он был установлен
-  I2C->CR2 &= ~I2C_CR2_POS;
-
-  return I2C_SUCCESS;
-}

+ 0 - 33
lib/i2c.h

@@ -1,33 +0,0 @@
-#pragma once
-#ifndef I2C_H
-#define I2C_H
-
-#include "stm8s.h"
-
-#define I2C_FAST        1
-#define F_MASTER_MHZ    16UL
-#define F_MASTER_HZ     16000000UL
-#ifdef I2C_FAST
-//400 кГц
-#define F_I2C_HZ        400000UL
-#else
-//100 кГц
-#define F_I2C_HZ        100000UL
-#endif // I2C_FAST
-
-//Результат выполнения операции с i2c
-typedef enum {
-    I2C_SUCCESS = 0,
-    I2C_TIMEOUT,
-    I2C_ERROR
-} t_i2c_status;
-
-// Инициализация I2C интерфейса
-void i2c_master_init(void);
-
-// Wrie 1 byte
-t_i2c_status  i2c_wr_data(uint8_t address, uint8_t num_bytes_to_wr, uint8_t * data);
-
-// Read 3 bytes
-t_i2c_status  i2c_rd_data(uint8_t address, uint8_t num_bytes_to_rd, uint8_t * data);
-#endif // I2C_H

+ 0 - 329
lib/i2c_master_poll.c

@@ -1,329 +0,0 @@
-/**
-  ******************************************************************************
-  * @file    i2c_master_poll.c
-  * @author  MCD Application Team
-  * @version V0.0.3
-  * @date    Oct 2010
-  * @brief   This file contains optimized drivers for I2C master
-  ******************************************************************************
-  * @copy
-  *
-  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
-  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
-  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
-  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
-  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
-  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
-  *
-  * <h2><center>&copy; COPYRIGHT 2009 STMicroelectronics</center></h2>
-  */ 
-
-#include "i2c_master_poll.h"
-
-/* Таймаут ожидания события I2C */
-extern __IO uint8_t I2C_timeout;
-
-/* flag clearing sequence - uncoment next for peripheral clock under 2MHz */
-#define dead_time() { /* _asm("nop"); _asm("nop"); */ }
-#define tout()            (I2C_timeout)
-#define set_tout_ms(a)    { I2C_timeout = a; }
-
-/******************************************************************************
-* Function name : I2C_Init
-* Description 	: Initialize I2C peripheral
-* Input param 	: None
-* Return 		    : None
-* See also 		  : None
-*******************************************************************************/
-void I2C_Init(void) {
-  //define SDA, SCL outputs, HiZ, Open drain, Fast
-  GPIOB->ODR |= (GPIO_PIN_4 | GPIO_PIN_5);
-  GPIOB->DDR |= (GPIO_PIN_4 | GPIO_PIN_5);
-  GPIOB->CR2 |= (GPIO_PIN_4 | GPIO_PIN_5);
-
-#ifdef FAST_I2C_MODE
-  I2C->FREQR = 16;               // input clock to I2C - 16MHz 
-  I2C->CCRL = 15;                // 900/62.5= 15, (SCLhi must be at least 600+300=900ns!)
-  I2C->CCRH = 0x80;              // fast mode, duty 2/1 (bus speed 62.5*3*15~356kHz)
-  I2C->TRISER = 5;               // 300/62.5 + 1= 5  (maximum 300ns)
-#else
-  I2C->FREQR = 8;                // input clock to I2C - 8MHz
-  I2C->CCRL = 40;                // CCR= 40 - (SCLhi must be at least 4000+1000=5000ns!)
-  I2C->CCRH = 0;                 // standard mode, duty 1/1 bus speed 100kHz
-  I2C->TRISER = 9;               // 1000ns/(125ns) + 1  (maximum 1000ns)
-#endif
-  I2C->OARL = 0xA0;              // own address A0;
-  I2C->OARH |= 0x40;
-  //I2C->ITR = 1;                  // enable error interrupts
-  I2C->CR2 |= 0x04;              // ACK=1, Ack enable
-  I2C->CR1 |= 0x01;              // PE=1
-}
-
-/******************************************************************************
-* Function name : I2C_ReadRegister
-* Description 	: Read defined number bytes from slave memory starting with defined offset
-* Input param 	: offset in slave memory, number of bytes to read, starting address to store received data
-* Return 		    : None
-* See also 		  : None
-*******************************************************************************/
-void I2C_ReadRegister(u8 u8_regAddr, u8 u8_NumByteToRead, u8 *ReadBuffer)
-{
-  /*--------------- BUSY? -> STOP request ---------------------*/
-	while(I2C->SR3 & I2C_SR3_BUSY && tout())	  				// Wait while the bus is busy
-  {
-		I2C->CR2 |= I2C_CR2_STOP;                   				// Generate stop here (STOP=1)
-    while(I2C->CR2 & I2C_CR2_STOP && tout()); 				// Wait until stop is performed
-	}
-  I2C->CR2 |= I2C_CR2_ACK;                      				// ACK=1, Ack enable
-  /*--------------- Start communication -----------------------*/  
-  I2C->CR2 |= I2C_CR2_START;                    				// START=1, generate start
-  while((I2C->SR1 & I2C_SR1_SB)==0 && tout());				// Wait for start bit detection (SB)
-  /*------------------ Address send ---------------------------*/      
-  if(tout())
-  {
-    I2C->DR = (u8)(SLAVE_ADDRESS << 1);   						// Send 7-bit device address & Write (R/W = 0)
-  }
-  while(!(I2C->SR1 & I2C_SR1_ADDR) &&  tout()); 				// test EV6 - wait for address ack (ADDR)
-  dead_time();                                  				// ADDR clearing sequence
-  I2C->SR3;
-  /*--------------- Register/Command send ----------------------*/
-  while(!(I2C->SR1 & I2C_SR1_TXE) &&  tout());  				// Wait for TxE
-  if(tout())
-  {  
-    I2C->DR = u8_regAddr;                         			// Send register address
-  }                                            					// Wait for TxE & BTF
-  while((I2C->SR1 & (I2C_SR1_TXE | I2C_SR1_BTF)) != (I2C_SR1_TXE | I2C_SR1_BTF) && tout()); 
-  dead_time();                                  				// clearing sequence
-  /*-------------- Stop/Restart communication -------------------*/  
-  #ifdef NO_RESTART																		// if 7bit address and NO_RESTART setted
-    I2C->CR2 |= I2C_CR2_STOP;                     		// STOP=1, generate stop
-    while(I2C->CR2 & I2C_CR2_STOP && tout());   		// wait until stop is performed
-  #endif // NO_RESTART
-  /*--------------- Restart communication ---------------------*/  
-  I2C->CR2 |= I2C_CR2_START;                     				// START=1, generate re-start
-  while((I2C->SR1 & I2C_SR1_SB)==0 && tout()); 				// Wait for start bit detection (SB)
-  /*------------------ Address send ---------------------------*/      
-  if(tout())
-  {
-    I2C->DR = (u8)(SLAVE_ADDRESS << 1) | 1;         	// Send 7-bit device address & Write (R/W = 1)
-  }
-  while(!(I2C->SR1 & I2C_SR1_ADDR) && tout());  			// Wait for address ack (ADDR)
-  /*------------------- Data Receive --------------------------*/
-  if (u8_NumByteToRead > 2)                 						// *** more than 2 bytes are received? ***
-  {
-    I2C->SR3;                                     			// ADDR clearing sequence    
-    while(u8_NumByteToRead > 3 && tout())       			// not last three bytes?
-    {
-      while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 				// Wait for BTF
-			*ReadBuffer++ = I2C->DR;                   				// Reading next data byte
-      --u8_NumByteToRead;																		// Decrease Numbyte to reade by 1
-    }
-																												//last three bytes should be read
-    while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 			// Wait for BTF
-    I2C->CR2 &=~I2C_CR2_ACK;                      			// Clear ACK
-    disableInterrupts();                          			// Errata workaround (Disable interrupt)
-    *ReadBuffer++ = I2C->DR;                     		// Read 1st byte
-    I2C->CR2 |= I2C_CR2_STOP;                       		// Generate stop here (STOP=1)
-    *ReadBuffer++ = I2C->DR;                     		// Read 2nd byte
-    enableInterrupts();																	// Errata workaround (Enable interrupt)
-    while(!(I2C->SR1 & I2C_SR1_RXNE) && tout());			// Wait for RXNE
-    *ReadBuffer++ = I2C->DR;                   			// Read 3rd Data byte
-  }
-  else
-  {
-   if(u8_NumByteToRead == 2)                						// *** just two bytes are received? ***
-    {
-      I2C->CR2 |= I2C_CR2_POS;                      		// Set POS bit (NACK at next received byte)
-      disableInterrupts();                          		// Errata workaround (Disable interrupt)
-      I2C->SR3;                                       	// Clear ADDR Flag
-      I2C->CR2 &=~I2C_CR2_ACK;                        	// Clear ACK 
-      enableInterrupts();																// Errata workaround (Enable interrupt)
-      while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 		// Wait for BTF
-      disableInterrupts();                          		// Errata workaround (Disable interrupt)
-      I2C->CR2 |= I2C_CR2_STOP;                       	// Generate stop here (STOP=1)
-      *ReadBuffer++ = I2C->DR;                     	// Read 1st Data byte
-      enableInterrupts();																// Errata workaround (Enable interrupt)
-			*ReadBuffer = I2C->DR;													// Read 2nd Data byte
-    }
-    else                                      					// *** only one byte is received ***
-    {
-      I2C->CR2 &=~I2C_CR2_ACK;;                     		// Clear ACK 
-      disableInterrupts();                          		// Errata workaround (Disable interrupt)
-      I2C->SR3;                                       	// Clear ADDR Flag   
-      I2C->CR2 |= I2C_CR2_STOP;                       	// generate stop here (STOP=1)
-      enableInterrupts();																// Errata workaround (Enable interrupt)
-      while(!(I2C->SR1 & I2C_SR1_RXNE) && tout()); 		// test EV7, wait for RxNE
-      *ReadBuffer = I2C->DR;                     		// Read Data byte
-    }
-  }
-  /*--------------- All Data Received -----------------------*/
-  while((I2C->CR2 & I2C_CR2_STOP) && tout());     		// Wait until stop is performed (STOPF = 1)
-  I2C->CR2 &=~I2C_CR2_POS;                          		// return POS to default state (POS=0)
-}
-
-/******************************************************************************
-* Function name : I2C_WriteRegister
-* Description 	: write defined number bytes to slave memory starting with defined offset
-* Input param 	: offset in slave memory, number of bytes to write, starting address to send
-* Return 		    : None.
-* See also 		  : None.
-*******************************************************************************/
-void I2C_WriteRegister(u8 u8_regAddr, u8 u8_NumByteToWrite, u8 *ReadBuffer)
-{
-  while((I2C->SR3 & 2) && tout())       									// Wait while the bus is busy
-  {
-    I2C->CR2 |= 2;                        								// STOP=1, generate stop
-    while((I2C->CR2 & 2) && tout());      								// wait until stop is performed
-  }
-  
-  I2C->CR2 |= 1;                        									// START=1, generate start
-  while(((I2C->SR1 & 1)==0) && tout()); 									// Wait for start bit detection (SB)
-  dead_time();                          									// SB clearing sequence
-  if(tout())
-  {
-    I2C->DR = (u8)(SLAVE_ADDRESS << 1);   							// Send 7-bit device address & Write (R/W = 0)
-  }
-  while(!(I2C->SR1 & 2) && tout());     									// Wait for address ack (ADDR)
-  dead_time();                          									// ADDR clearing sequence
-  I2C->SR3;
-  while(!(I2C->SR1 & 0x80) && tout());  									// Wait for TxE
-  if(tout())
-  {
-    I2C->DR = u8_regAddr;                 								// send Offset command
-  }
-  if(u8_NumByteToWrite)
-  {
-    while(u8_NumByteToWrite--)          									
-    {																											// write data loop start
-      while(!(I2C->SR1 & 0x80) && tout());  								// test EV8 - wait for TxE
-      I2C->DR = *ReadBuffer++;           								// send next data byte
-    }																											// write data loop end
-  }
-  while(((I2C->SR1 & 0x84) != 0x84) && tout()); 					// Wait for TxE & BTF
-  dead_time();                          									// clearing sequence
-  
-  I2C->CR2 |= 2;                        									// generate stop here (STOP=1)
-  while((I2C->CR2 & 2) && tout());      									// wait until stop is performed  
-}
-
-/**
- * @brief 
- * 
- * @param NumByteToRead 
- * @param ReadBuffer 
- */
-void I2C_ReadBytes(const u8 Addr, const u8 NumByteToRead, u8 *ReadBuffer) {
-  u8 adr = Addr << 1;
-  u8 n = NumByteToRead;
-  set_tout_ms(10);
-
-  /*--------------- BUSY? -> STOP request ---------------------*/
-	while(I2C->SR3 & I2C_SR3_BUSY && tout())	  			// Wait while the bus is busy
-  {
-		I2C->CR2 |= I2C_CR2_STOP;                   		// Generate stop here (STOP=1)
-    while(I2C->CR2 & I2C_CR2_STOP && tout()); 			// Wait until stop is performed
-	}
-  I2C->CR2 |= I2C_CR2_ACK;                      		// ACK=1, Ack enable
-  /*--------------- Start communication -----------------------*/  
-  I2C->CR2 |= I2C_CR2_START;                    		// START=1, generate start
-  while((I2C->SR1 & I2C_SR1_SB)==0 && tout());			// Wait for start bit detection (SB)
-  /*------------------ Address send ---------------------------*/      
-  if(tout())
-  {
-    I2C->DR = (adr | 1);         	                  // Send 7-bit device address & Write (R/W = 1)
-  }
-  while(!(I2C->SR1 & I2C_SR1_ADDR) && tout());  		// Wait for address ack (ADDR)
-  /*------------------- Data Receive --------------------------*/
-  if (n > 2)                 						            // *** more than 2 bytes are received? ***
-  {
-    I2C->SR3;                                     	// ADDR clearing sequence    
-    while(n > 3 && tout())       			              // not last three bytes?
-    {
-      while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 	// Wait for BTF
-			*ReadBuffer++ = I2C->DR;                   		// Reading next data byte
-      --n;																		      // Decrease Numbyte to reade by 1
-    }
-																										//last three bytes should be read
-    while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 		// Wait for BTF
-    I2C->CR2 &=~I2C_CR2_ACK;                      	// Clear ACK
-    disableInterrupts();                          	// Errata workaround (Disable interrupt)
-    *ReadBuffer++ = I2C->DR;                     		// Read 1st byte
-    I2C->CR2 |= I2C_CR2_STOP;                       // Generate stop here (STOP=1)
-    *ReadBuffer++ = I2C->DR;                     		// Read 2nd byte
-    enableInterrupts();															// Errata workaround (Enable interrupt)
-    while(!(I2C->SR1 & I2C_SR1_RXNE) && tout());		// Wait for RXNE
-    *ReadBuffer++ = I2C->DR;                   			// Read 3rd Data byte
-  }
-  else
-  {
-   if(n == 2)                						            // *** just two bytes are received? ***
-    {
-      I2C->CR2 |= I2C_CR2_POS;                      // Set POS bit (NACK at next received byte)
-      disableInterrupts();                          // Errata workaround (Disable interrupt)
-      I2C->SR3;                                     // Clear ADDR Flag
-      I2C->CR2 &=~I2C_CR2_ACK;                      // Clear ACK 
-      enableInterrupts();														// Errata workaround (Enable interrupt)
-      while(!(I2C->SR1 & I2C_SR1_BTF) && tout()); 	// Wait for BTF
-      disableInterrupts();                          // Errata workaround (Disable interrupt)
-      I2C->CR2 |= I2C_CR2_STOP;                     // Generate stop here (STOP=1)
-      *ReadBuffer++ = I2C->DR;                     	// Read 1st Data byte
-      enableInterrupts();														// Errata workaround (Enable interrupt)
-			*ReadBuffer = I2C->DR;												// Read 2nd Data byte
-    }
-    else                                      			// *** only one byte is received ***
-    {
-      I2C->CR2 &=~I2C_CR2_ACK;;                     // Clear ACK 
-      disableInterrupts();                          // Errata workaround (Disable interrupt)
-      I2C->SR3;                                     // Clear ADDR Flag   
-      I2C->CR2 |= I2C_CR2_STOP;                     // generate stop here (STOP=1)
-      enableInterrupts();														// Errata workaround (Enable interrupt)
-      while(!(I2C->SR1 & I2C_SR1_RXNE) && tout());  // test EV7, wait for RxNE
-      *ReadBuffer = I2C->DR;                     		// Read Data byte
-    }
-  }
-  /*--------------- All Data Received -----------------------*/
-  while((I2C->CR2 & I2C_CR2_STOP) && tout());     	// Wait until stop is performed (STOPF = 1)
-  I2C->CR2 &= ~I2C_CR2_POS;                         // return POS to default state (POS=0)
-}
-/**
- * @brief write defined number bytes to slave device
- * 
- * @param Addr 
- * @param NumByteToWrite 
- * @param DataBuffer 
- */
-void I2C_WriteBytes(const u8 Addr, const u8 NumByteToWrite, u8 *DataBuffer) {
-  u8 adr = Addr << 1;
-  u8 n = NumByteToWrite;
-  set_tout_ms(10);
-
-  while((I2C->SR3 & 2) && tout())       				// Wait while the bus is busy
-  {
-    I2C->CR2 |= 2;                        			// STOP=1, generate stop
-    while((I2C->CR2 & 2) && tout());      			// wait until stop is performed
-  }
-  
-  I2C->CR2 |= 1;                        				// START=1, generate start
-  while(((I2C->SR1 & 1)==0) && tout()); 				// Wait for start bit detection (SB)
-  dead_time();                          				// SB clearing sequence
-  if(tout())
-  {
-    I2C->DR = adr;   							              // Send 7-bit device address & Write (R/W = 0)
-  }
-  while(!(I2C->SR1 & 2) && tout());     				// Wait for address ack (ADDR)
-  dead_time();                          				// ADDR clearing sequence
-  I2C->SR3;
-  if(n)
-  {
-    while(n--)          									
-    {																						// write data loop start
-      while(!(I2C->SR1 & 0x80) && tout());  		// test EV8 - wait for TxE
-      I2C->DR = *DataBuffer++;           				// send next data byte
-    }																						// write data loop end
-  }
-  while(((I2C->SR1 & 0x84) != 0x84) && tout()); // Wait for TxE & BTF
-  dead_time();                          				// clearing sequence
-  
-  I2C->CR2 |= 2;                        				// generate stop here (STOP=1)
-  while((I2C->CR2 & 2) && tout());      				// wait until stop is performed  
-}

+ 0 - 44
lib/i2c_master_poll.h

@@ -1,44 +0,0 @@
-/**
-  ******************************************************************************
-  * @file    i2c_opt.h
-  * @author  MCD Application Team
-  * @version V0.0.3
-  * @date    Feb 2010
-  * @brief   This file contains definitions for optimized I2C software
-  ******************************************************************************
-  *
-  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
-  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
-  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
-  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
-  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
-  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
-  *
-  *                     COPYRIGHT 2009 STMicroelectronics  
-  */ 
-
-/* Define to prevent recursive inclusion */
-#ifndef __I2C_OPT_H
-#define __I2C_OPT_H
-
-#include "stm8s.h"
-
-// ************************** I2C Configuration Variables **************************
-/* definition of fast or default standard mode (bus speed up to 400 or 100 kHz) */
-#define FAST_I2C_MODE
-
-/* uncomment next line when stop request is required between device address sent and read data */
-//#define NO_RESTART
-
-#define SLAVE_ADDRESS  0x40
-
-// ************************* Function Declaration ***************************
-void I2C_Init(void);
-void I2C_ReadRegister(u8 u8_regAddr, u8 u8_NumByteToRead, u8 *u8_ReadBuffer);
-void I2C_WriteRegister(u8 u8_regAddr, u8 u8_NumByteToWrite, u8 *u8_DataBuffer);
-void I2C_ReadBytes(u8 Addr, u8 NumByteToRead, u8 *ReadBuffer);
-void I2C_WriteBytes(u8 Addr, u8 NumByteToWrite, u8 *DataBuffer);
-
-#endif /* __I2C_OPT_H */
-
-/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/