# rpi - SPI read fram MB85RS64 status register while toggle write protect
# provided by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-12-28  initial release

import	time
from	spidev	import	SpiDev

# ===================== Constants =====================

WREN	= 0x06						# MB85R64 set   write enable latch
WRDI	= 0x04						# MB85R64 reset write enable latch
RDSR	= 0x05						# MB85R64 read  status register
WRSR	= 0x01						# MB85R64 write status register, protected by /WP = gnd
READ	= 0x03						# MB85R64 read  date
WRITE	= 0x02						# MB85R64 write data

# ================== Hardware setup ===================

spi	= SpiDev()						# instantiate object for SPI communication

# ================== Fram functions ===================

# Open fram communication on bus 0, device 0
def framOpen(spi):
    spi.open(0, 0)					# /dev/spidev0.0
    spi.max_speed_hz = 1_000_000	# 1 MHz
    spi.mode         = 0x00			# idle SCK = 0 and pos edge
    
    
# return fram status byte
def framGetStatus(spi):
    data_tx = [RDSR, 0x0F]
    data_rx = spi.xfer(data_tx)
    return(data_rx[1])
        

# set fram write enable latch to protect
def framWriteProtect(spi, protect=True):
    data_tx = [WRDI] if protect else [WREN]
    spi.xfer(data_tx)

# ==================== test ========================

def test():
    framOpen(spi)
    print(framGetStatus(spi))
    framWriteProtect(spi, False)		# set sts.1 is WEL
    print(framGetStatus(spi))
    framWriteProtect(spi, True)			# reset sts.1 is WEL
    print(framGetStatus(spi))
    framWriteProtect(spi, False)		# set sts.1 is WEL
    print(framGetStatus(spi))
    framWriteProtect(spi, True)			# reset sts.1 is WEL
    print(framGetStatus(spi))
    
 
try:
    test()
except:
    print('Test aborted')
spi.close()
    
# ====================== End ==========================
