Question
ads1115 stm8 integration
hello,i am a beginner & i am trying integrate an external adc "ads1115" with stm8. the adc is an i2c device . i tried using peripheral library and also the register way. but its not working can anyone guide me the corect way to integrate this.this is my code
#include "main.h"
#include <stdio.h>
/*void I2C_Init(void);
void I2C_Write(uint8_t addr, uint8_t reg, uint8_t data);
void I2C_Read(uint8_t addr, uint8_t reg, uint8_t *data, uint8_t len);
void delay_ms(uint16_t ms);*/
#define ADS1115_ADDRESS 0x48
#define ADS1115_CONFIG_REG 0x01
uint8_t data[2];
int16_t adcValue=0;
uint8_t i=0;
void delay_ms(uint16_t ms) {
// Assuming a 16 MHz clock frequency
uint16_t cycles = (uint16_t)(16000 * ms);
while (cycles--) {
// Do nothing
}
}
void main(void) {
// Initialize I2C
GPIOC->DDR |= GPIO_Pin_0 | GPIO_Pin_1; // Set SDA and SCL as output
GPIOC->CR1 |= GPIO_Pin_0 | GPIO_Pin_1; // Set open-drain mode
GPIOC->CR2 |= GPIO_Pin_0 | GPIO_Pin_1; // Set fast mode
// Configure I2C
I2C1->FREQR = 16; // Set clock frequency to 16 MHz
I2C1->CR1 |= I2C_CR1_PE; // Enable I2C
// Set I2C clock control register
I2C1->CCRL = 0x50; // Set clock control register low-byte
I2C1->TRISER = 0x11; // Set maximum rise time in fast/standard mode
while (1) {
// Read ADC value from channel 0
I2C1->CR2 |= I2C_CR2_START;
while ((I2C1->SR1 & I2C_SR1_SB));
// Send device address for write
I2C1->DR = 0x48 << 1;
while (!(I2C1->SR1 & I2C_SR1_ADDR));
(void)I2C1->SR2;
// Send register address
I2C1->DR = 0x01;
while (!(I2C1->SR1 & I2C_SR1_TXE));
// Send data
I2C1->DR = 0xc3;
while (!(I2C1->SR1 & I2C_SR1_TXE));
// Generate stop condition
I2C1->CR2 |= I2C_CR2_STOP;
delay_ms(10); // Wait for the conversion to complete (approx. 8ms for single-shot mode)
I2C1->CR2 |= I2C_CR2_START;
while (!(I2C1->SR1 & I2C_SR1_SB));
// Send device address for write
I2C1->DR = 0x48<< 1;
while (!(I2C1->SR1 & I2C_SR1_ADDR));
(void)I2C1->SR2;
// Send register address
I2C1->DR = 0x01;
while (!(I2C1->SR1 & I2C_SR1_TXE));
// Generate repeated start condition
I2C1->CR2 |= I2C_CR2_START;
while (!(I2C1->SR1 & I2C_SR1_SB));
// Send device address for read
I2C1->DR = (0x48 << 1) | 1;
while (!(I2C1->SR1 & I2C_SR1_ADDR));
(void)I2C1->SR2;
// Receive data
for ( i = 0; i < 2; ++i) {
while (!(I2C1->SR1 & I2C_SR1_RXNE));
data[i] = I2C1->DR;
}
// Generate stop condition
I2C1->CR2 |= I2C_CR2_STOP;
adcValue = (data[0] << 8) | data[1];
// Print the result (you might want to use USART for proper communication)
printf("AIN0: %d\n", adcValue);
// Wait for a moment before the next reading
delay_ms(1000);
}
}
