# rpi - SPI read and write to fram MB85RS64 status register
# 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

# ==================== class Fram =====================

class Fram:
    
    def __init__(self, spi, bus_nr=0, device_nr=0, speed=1_000_000):
        spi.open(bus_nr, device_nr)
        self.spi         = spi
        spi.max_speed_hz = speed
        spi.mode         = 0x00			# idle SCK = 0 and pos edge
        
    
    # return fram status byte
    def getStatus(self):
        data_tx = [RDSR, 0x0F]
        data_rx = self.spi.xfer(data_tx)
        return(data_rx[1])
        

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

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

def test():
    fram = Fram(spi)
    print(fram.getStatus())
    fram.writeProtect(False)		# set sts.1 is WEL
    print(fram.getStatus())
    fram.writeProtect(True)			# reset sts.1 is WEL
    print(fram.getStatus())
    fram.writeProtect(False)		# set sts.1 is WEL
    print(fram.getStatus())
    fram.writeProtect(True)			# reset sts.1 is WEL
    print(fram.getStatus())
    
 
try:
    test()
except:
    print('Test aborted')
spi.close()
    
# ====================== End ==========================
