We were previously working on the i.MX7 with TorizonCore, and the Python code for reading SPI data was functioning correctly. After porting the same Python script to a Raspberry Pi (as per harware), the SPI data reading no longer works as expected and returns random values. I have attached the current Python code used for SPI communication on the Raspberry Pi.
Pin Number 8 (BCM) for CS0.
Could you suggest modifications to the Python code to ensure correct SPI data acquisition on the Raspberry Pi?
Pin Number 8 (BCM) for CS0.
Code:
import spidev#import gpiodimport RPi.GPIO as GPIOimport timeCS_PIN = 8GPIO.setmode(GPIO.BCM) # Use BCM numberingGPIO.setup(CS_PIN, GPIO.OUT) # Set CS pin as outputGPIO.output(CS_PIN, GPIO.HIGH) # Default to HIGH (inactive)# ===== SPI setup =====spi = spidev.SpiDev()spi.open(0, 0) # /dev/spidev2.0spi.max_speed_hz = 500_000 # 10 MHzspi.mode = 0 # SpiMode=1 from your WinCE code spi.bits_per_word = 8 # 16-bit words like PackedModespi.lsbfirst = False# ===== Data patterns =====# Each number here is a 16-bit wordspiData_1_MIC = [0xD414, 0x0001]spiData_2_MIC = [0xD414, 0x0001]spiData_3_MIC = [0xD414, 0x0001]spiData_4_MIC = [0xD414, 0x0001]def trigger_pulse(): GPIO.output(CS_PIN, GPIO.LOW) time.sleep(0.00001) GPIO.output(CS_PIN, GPIO.HIGH) #time.sleep(0.000001) # settledef spi_transfer(word_list): # Convert 16-bit words to byte list tx_bytes = [] for w in word_list: tx_bytes.append((w >> 8) & 0xFF) # high byte tx_bytes.append(w & 0xFF) # low byte rx_bytes = spi.xfer2(tx_bytes) # Convert back to 16-bit words rx_words = [] for i in range(0, len(rx_bytes), 2): rx_words.append((rx_bytes[i+1] << 8) | rx_bytes[i]) return rx_wordsdef to_signed_16(val): """Convert unsigned 16-bit to signed short.""" if val & 0x8000: # if sign bit is set val -= 0x10000 return valcounter = 0try: while True: #input("Press Enter to trigger probe and read SPI...") # Exactly like WinCE loop: trigger_pulse() rx4 = spi_transfer(spiData_1_MIC) rx3 = spi_transfer(spiData_2_MIC) rx2 = spi_transfer(spiData_3_MIC) rx1 = spi_transfer(spiData_4_MIC) num_1_MIC = to_signed_16(rx1[0]) counter += 1 print(num_1_MIC,rx1,counter) time.sleep(0.001)except KeyboardInterrupt: passfinally: trigger_line.set_value(0) chip.close() spi.close()Could you suggest modifications to the Python code to ensure correct SPI data acquisition on the Raspberry Pi?
Statistics: Posted by industrialCoders — Wed Aug 13, 2025 10:00 am