SPI Communication with STM32 and ADS1118 using CubeMx

Now let's get started.
I will use STM32F042 and ADS1118 for communication. ADS1118 is an Analog to Digital converter. We will fetch the values of all connected potentiometer values to our STM32F042 via ADS1118.
I HIGHLY RECOMMEND TO READ ADS1118 DATASHEET FIRST.
You can reach the datasheet via here.


Now according to above picture we will create a register struct to manage ADS1118. We will send the parameters and set some configurations like speed, which adc port to read.
typedef union
{
struct
{
volatile unsigned char RESV :1; //it does not matter 0 or 1
volatile unsigned char NOP :2;
volatile unsigned char PULLUP :1;
volatile unsigned char TS_MODE :1;
volatile unsigned char DR :3;
volatile unsigned char MODE :1;
volatile unsigned char PGA :3;
volatile unsigned char MUX :3;
volatile unsigned char OS :1; //high
} stru;
volatile unsigned int word;
volatile unsigned char byte[2];
} ADS_InitTypeDef;
//ADS1118 Configuration Registers
ADS_InitTypeDef adsConfigReg;
Later now we need to configurate our ADS1118, to do this we have send variables to microchips' built-in registers with above structure. Below code block will do it.
//ADS Structure variable
ADS_InitTypeDef ConfigReg;
//We will use it as single-shot mode
adsConfigReg.stru.OS = 0x1; //high
// 0x4 enables AIN0 , 0x5 enables AIN1,0x6 enables AIN2 and 0x7 enables AIN3 .
adsConfigReg.stru.MUX = 0x4;
//Programmable Gain amplifier
adsConfigReg.stru.PGA = 0x1; // FSR 4.096V
//Continuous mode or single-shot mode
adsConfigReg.stru.MODE = 0x1;
//Data Rate register
adsConfigReg.stru.DR = 0x4;
//If you want to use this chip as a temperature sensor set this as 1.
adsConfigReg.stru.TS_MODE = 0x0;
//Enable built-in pull-up resistors.
adsConfigReg.stru.PULLUP = 0x1;
//Command mode. Set this always as 0x01.
adsConfigReg.stru.NOP = 0x1;
//Reserved register. It does not matter this register is 1 or 0.
adsConfigReg.stru.RESV = 0x1;
Assign the values into one word belong to global variable defined above.
adsConfigReg.word=ConfigReg->word;
HAL_Delay(100);
I want to say something about MUX register: With this register we will set the built-in multiplexer inside the ADS1118. This multiplexer allows whic adc will be sent to the master. Also we can read differance of Analog inputs. You can get the much more information from the datasheet of ADS1118.
Now we are ready to send the parameters and get the value of selected analog input.
//Below function will send the data to the chip and fetch the result data
HAL_SPI_TransmitReceive(&hspi1,(uint8_t*)(adsConfigReg.byte), (uint8_t*) aRxBuffer, 2, 100);
//Wait a little bit
HAL_Delay(100);
//and load the data into variable.
int deger = aRxBuffer[0] | aRxBuffer[1] << 8;
//you can make the conversations for your own usage.
float voltage_brake = deger * 0.250;
Now we are ready to use the ADS1118.
Have a good Analog to Digital Converting :D
Burak Hamdi TUFAN