From a7df8adc5c9b3aa3f1cf0a908a12a7ba6e8048bf Mon Sep 17 00:00:00 2001
From: Robert Harft <roberthart56@gmail.com>
Date: Sun, 15 Jan 2023 10:27:38 -0500
Subject: [PATCH] add material

---
 README.md                     |  6 +++++
 code/SPI_23K256/SPI_23K256.py | 41 ++++++++++++++++++++++++++++++-----
 2 files changed, 41 insertions(+), 6 deletions(-)

diff --git a/README.md b/README.md
index bc91143..d2e11b8 100644
--- a/README.md
+++ b/README.md
@@ -43,6 +43,12 @@ pulses cease and CS is deasserted."
 
 ##23K256 memory chip as an example of SPI
 
+The 23K256 is a 32KByte memory device with a limited set of commands and registers.  Good exercise for doing SPI at a low-ish level, using the MicroPython machine functions and referring to eh chip's datasheet.
+
 [Datasheet for 23K256:](https://ww1.microchip.com/downloads/en/DeviceDoc/22100F.pdf)
 
 Set Polarity equal to zero for this chip.  This is the level of the idle clock.  See [SPI spec for MicroPython](https://docs.micropython.org/en/latest/library/machine.SPI.html)
+
+[Here is a code that works](./code/SPI_23K256/SPI_23K256.py) to store and retrieve numbers from the 23K256.  All operations are written out.  Next step would be to put them in functions and create a library file for this chip. 
+
+This is a nice example of a simple but non-trivial protocol for SPI. 
diff --git a/code/SPI_23K256/SPI_23K256.py b/code/SPI_23K256/SPI_23K256.py
index 7e31dfd..575b2ca 100644
--- a/code/SPI_23K256/SPI_23K256.py
+++ b/code/SPI_23K256/SPI_23K256.py
@@ -4,15 +4,23 @@ import time
 ###############################################################################
 # Constants
 
+#commands
 READ = 0x03
 WRITE = 0x02
 READ_S_R = 0x05
 WRITE_S_R = 0x01
 
+# Bits to determine mode
 SEQ_RW = 0x01 << 6		#B6 is 1
 BYTE_RW = 0x00 << 6		#zeros		
 PAGE_RW = 0x02 << 6		#B7 is 1
 
+#address
+ADDR_HIGH = 0x00
+ADDR_LOW = 0x00
+
+#content
+value_stored = 255
 
 ########################################################
 
@@ -33,25 +41,46 @@ spi = machine.SPI(0,
                   miso=machine.Pin(4))
 
 
-#write to status register
+#write to status register to set mode.
 cs.value(1)
 
 msg = bytearray()
 msg.append(WRITE_S_R)
-msg.append(SEQ_RW)
-print(msg)
+msg.append(BYTE_RW)
+#print(msg)
 cs.value(0)
 spi.write(msg)   
 cs.value(1)
 
 
-#read status register
+#read status register, to check mode.
 msg = bytearray()
 msg.append(READ_S_R)
-
 cs.value(0)
 spi.write(msg)   
 data = spi.read(1)
 cs.value(1)
-print(data)
+print("mode=",data)
+
+#form address
+msg = bytearray([WRITE, ADDR_HIGH, ADDR_LOW])
+
+#form writing array
+val = bytearray([value_stored])
+print("number stored =",val)
+
+#Write to address
+cs.value(0)
+spi.write(msg)
+spi.write(val)   
+cs.value(1)
+
+time.sleep(0.01)
 
+#Read from address
+msg = bytearray([READ, ADDR_HIGH, ADDR_LOW])
+cs.value(0)
+spi.write(msg)   #same address
+data = spi.read(1)   
+cs.value(1)
+print('number read = ',data)
\ No newline at end of file
-- 
GitLab