@@ -238,3 +238,69 @@ bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data,
238238 }
239239 return true;
240240}
241+
242+ // transfer
243+ bool shared_module_bitbangio_spi_transfer (bitbangio_spi_obj_t * self , const uint8_t * dout , uint8_t * din , size_t len ) {
244+ if (len > 0 && (!self -> has_mosi || !self -> has_miso ) ) {
245+ nlr_raise (mp_obj_new_exception_msg (& mp_type_ValueError ,
246+ "Cannot transfer without MOSI and MISO pins." ));
247+ }
248+ uint32_t delay_half = self -> delay_half ;
249+
250+ // only MSB transfer is implemented
251+
252+ // If a port defines MICROPY_PY_MACHINE_SPI_MIN_DELAY, and the configured
253+ // delay_half is equal to this value, then the software SPI implementation
254+ // will run as fast as possible, limited only by CPU speed and GPIO time.
255+ #ifdef MICROPY_PY_MACHINE_SPI_MIN_DELAY
256+ if (delay_half <= MICROPY_PY_MACHINE_SPI_MIN_DELAY ) {
257+ for (size_t i = 0 ; i < len ; ++ i ) {
258+ uint8_t data_out = dout [i ];
259+ uint8_t data_in = 0 ;
260+ for (int j = 0 ; j < 8 ; ++ j , data_out <<= 1 ) {
261+ common_hal_digitalio_digitalinout_set_value (& self -> mosi , (data_out >> 7 ) & 1 );
262+ common_hal_digitalio_digitalinout_set_value (& self -> clock , 1 - self -> polarity );
263+ data_in = (data_in << 1 ) | common_hal_digitalio_digitalinout_get_value (& self -> miso );
264+ common_hal_digitalio_digitalinout_set_value (& self -> clock , self -> polarity );
265+ }
266+ din [i ] = data_in ;
267+
268+ if (dest != NULL ) {
269+ dest [i ] = data_in ;
270+ }
271+ }
272+ return true;
273+ }
274+ #endif
275+
276+ for (size_t i = 0 ; i < len ; ++ i ) {
277+ uint8_t data_out = dout [i ];
278+ uint8_t data_in = 0 ;
279+ for (int j = 0 ; j < 8 ; ++ j , data_out <<= 1 ) {
280+ common_hal_digitalio_digitalinout_set_value (& self -> mosi , (data_out >> 7 ) & 1 );
281+ if (self -> phase == 0 ) {
282+ common_hal_mcu_delay_us (delay_half );
283+ common_hal_digitalio_digitalinout_set_value (& self -> clock , 1 - self -> polarity );
284+ } else {
285+ common_hal_digitalio_digitalinout_set_value (& self -> clock , 1 - self -> polarity );
286+ common_hal_mcu_delay_us (delay_half );
287+ }
288+ data_in = (data_in << 1 ) | common_hal_digitalio_digitalinout_get_value (& self -> miso );
289+ if (self -> phase == 0 ) {
290+ common_hal_mcu_delay_us (delay_half );
291+ common_hal_digitalio_digitalinout_set_value (& self -> clock , self -> polarity );
292+ } else {
293+ common_hal_digitalio_digitalinout_set_value (& self -> clock , self -> polarity );
294+ common_hal_mcu_delay_us (delay_half );
295+ }
296+ }
297+ din [i ] = data_in ;
298+
299+ // Some ports need a regular callback, but probably we don't need
300+ // to do this every byte, or even at all.
301+ #ifdef MICROPY_EVENT_POLL_HOOK
302+ MICROPY_EVENT_POLL_HOOK ;
303+ #endif
304+ }
305+ return true;
306+ }
0 commit comments