If I had a project that contained two controllers and made communication between them using SPI and I configured one of them as a master and the other as a slave, then changed the master to a slave, can the slave find out by itself that he has to become the master?
2 Answers
if changed the master to a slave can the slave find out by himself that he has to become the master ?
No. SPI is a very simple protocol specification. Or maybe "protocol" is too much - it's a specification how to transfer bits. The master initiates the transfer and provides clock signal. Without clock there's no communication. Without master there's no clock. Without master there's no communication. Two connected slaves will never talk to each other.
can the slave find out by itself that he has to become the master?
Sure it can. You can create your own protocol and/or mechanisms to do that, build on top or separately with SPI protocol.
The simple solution is to require a "heart-beat" from the master whereby the master guarantees to initiate a regular transaction - this could be real or some dummy "keep-alive" transaction, or even simply activity on the slave-select line with no data at all. If the current master wants to swap roles, it simply becomes a slave, and waits for the previous slave to timeout and switch to the master role.
To swap back, the new master simply becomes a slave and waits for the slave device to timeout and become master.
When first switching form master to slave, the new slave should wait indefinitely for the other node to timeout and become master and start a data exchange, after the initial data exchange it should set the timeout.
The disadvantage of the timeout solution is the necessary latency in switching roles. If you are sending data continuously (even if it is dummy data) the timeout and therefore the switch could be rather short.
A rather more elegant method would be to use additional GPIO lines for handshaking and arbitration. However that is probably unnecessary. If the problem you are trying to solve is that you need the slave to initiate a data transfer then you do not need role switching at all, you simply have a single transfer request (TXFER_REQ) control line that is a GPIO output from the slave and an input or interrupt on the master. When the slave wants to send data, it sets the TXFER_REQ signal, and the master responds by initiating a data exchange. That is how intrinsically bi-directional SPI devices such as an SPI UART work for example. Check the data sheet for such a device to see how it works and emulate that behaviour rather then inventing something new, more complex and potentially flawed.