2023-09-22 02:36 AM - edited 2023-09-22 02:40 AM
Hello,
I'm trying to build a setup to test SPI communication between a master and a slave.
The master side works well, when the master ask for a read, it sends a byte of register address and ask for 2 byte of reading (I can see 16 clock ticks for the reading).
Unfortunately my slave code doesn't work as intended, it's receiving correctly the register address but when it comes to the transmission it always fails, nothing is getting outputted on the MISO line.
Here's the code for the SLAVE spi part:
int main(void)
{
/* USER CODE BEGIN 1 */
uint8_t spi_buf[3];
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_SPI1_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4) == GPIO_PIN_RESET){
if (HAL_SPI_Receive(&hspi1, spi_buf, 1, 1000) != HAL_OK) {
Error_Handler();
}
// Check if it's a read operation
if ((spi_buf[0] & 0x02) == 0x02) {
// It's a write operation
uint8_t registerAddress = spi_buf[0] >> 2;
HAL_SPI_Receive(&hspi1, spi_buf, 2, 1000);
} else {
// It's a read operation
uint8_t registerAddress = spi_buf[0] >> 2;
if (registerAddress == 0x00){
if (HAL_SPI_Transmit(&hspi1, (uint8_t *) {0x00, 0x81}, 2, 1000) != HAL_OK){
Error_Handler();
}
} else if (registerAddress == 0x14){
HAL_SPI_Transmit(&hspi1, (uint8_t *) {0x00, 0x01}, 2, 1000);
}
}
}
}
/* USER CODE END 3 */
}
And the configuration of the slave SPI:
The master side is of course configure the same way:
I think this is a programming issue but I don't get which one.
Thanks in advance for your help,
Sidius
2023-09-22 03:13 AM - edited 2023-09-22 03:28 AM
Hello,
This might not help but are you sure you want Full Duplex mode? Can you try with Half Duplex and see if that allows you to transmit after you have received?
Also, you might want to look at HAL_SPI_TransmitReceive() and read this thread then compare against what you are actually trying to achieve:
2023-09-22 03:17 AM - edited 2023-09-22 03:19 AM
Hello @Sidius
Can you try to define the array before passing it to the transmission function:
uint8_t data_to_transmit[] = {0x00, 0x01};
HAL_SPI_Transmit(&hspi1,(uint8_t *)&data_to_transmit, 2,1000);
Else, try to start from a ready to use exemple from the STM32Cubexx firmware.
Best regards.
II
2023-09-22 04:31 AM
Perhaps the master code is not waiting long enough between events (CS down, sending first byte) to let the slave sync. Master and slave need to be in sync with each other. Show the master code.