cancel
Showing results for 
Search instead for 
Did you mean: 

Problem in communication 2 slaves and 1 master using SPI.

HAlau.1
Associate II

hello everyone, I have a problem in communication 2 slaves and 1 master using SPI.

master will send a code to activate one of the slaves and then the master will receive data from the slave, but sending the initial data is always wrong and only when the reset button is pressed the sending of data becomes correct and so on.

does anyone know where the error is? and please give me a solution.

thank you

19 REPLIES 19
S.Ma
Principal

How often you turn on a car radio just when a new song starts?

If you want a slave selector header byte, go for I2C

HAlau.1
Associate II

thank you

routine but for some slaves only occasionally,

I also use UART to send requests and display the results of receiving data on a serial monitor.

berendi
Principal

SPI has no start/stop bit like UART or I2C, so the master and slave should be synchronized by other means. The SPI protocol has the separate chip select (NSS) line for this purpose.

Take two GPIO pins on the master, connect each one to the NSS pin of a slave. Set both of them high (1) initially, and one of them low (0) when you want to talk to that slave.

HAlau.1
Associate II

I tried it but it still failed

	  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_7,GPIO_PIN_SET);
	  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_8,GPIO_PIN_SET);
	  if(input==1){
 
	  		__HAL_SPI_ENABLE(&hspi1);
	  		HAL_SPI_Transmit (&hspi1,txslave1, 6, 50);
 
	  		HAL_GPIO_WritePin(GPIOE, GPIO_PIN_7,GPIO_PIN_RESET);
	  		HAL_SPI_Receive (&hspi1, outputBuffer, 6, 50);
	  		HAL_GPIO_WritePin(GPIOE, GPIO_PIN_7,GPIO_PIN_SET);
	  		STM_Serial_Print("data Slave 1 = ");
	  		STM_Serial_Print(outputBuffer);
	  		STM_Serial_Print("\r\n");
	  	}
	  	else if(input==2){
	  		__HAL_SPI_ENABLE(&hspi1);
	  		HAL_SPI_Transmit (&hspi1,txslave2, 6, 50);
 
	  		STM_Serial_Print("wait..\n\r");
	  		HAL_GPIO_WritePin(GPIOE, GPIO_PIN_8,GPIO_PIN_RESET);
	  		HAL_SPI_Receive (&hspi1, outputBuffer2, 6, 50);
	  		HAL_GPIO_WritePin(GPIOE, GPIO_PIN_8,GPIO_PIN_SET);
	  		STM_Serial_Print("data Slave 2 = ");
	  		STM_Serial_Print(outputBuffer2);
	  		STM_Serial_Print("\r\n");
	  	}

low (0) when you want to talk to that slave.

HAlau.1
Associate II

thank you,

if you wish, can you give a simple example of code? because I don't know, where should I put the code to activate NSS

thank you

Before talking to the slave.

Review the SPI chapter in the reference manual, or some general article in SPI.

HAlau.1
Associate II

like this?

  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_8,GPIO_PIN_RESET);

  HAL_SPI_Receive (&hspi1, outputBuffer2, 6, 50);

  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_8,GPIO_PIN_SET);

If you are only receiving, and never transmitting, yes.

There supposed to be some timing diagrams in the datasheet of the slaves.

You should understand the protocol requirements first, and plan the code accordingly, instead of shooting blindly.