cicciocb / Annex32_examples

MIT License
0 stars 0 forks source link

External EEPROM support #14

Closed cicciocb closed 1 month ago

cicciocb commented 1 month ago

Write and read external EEPROM / Flash to store permanent parameters

cicciocb commented 1 month ago

Finally item closed with an example in basic:

'library for reading / writing to eeproms
'this library works with a athyc532 
'that is a 24C32N with 32 bytes page write mode. 
'This eeprom can be found on the cheap RTC / EEprom modules
I2C.SETUP 47,21   'Pins as shown
EE_ADDR = &h50 'I2C address of the eeprom

'write at several address
write_eeprom 0, "Annex32 RDS"
write_eeprom 100, "Stored"
write_eeprom 200, "Into"
write_eeprom 300, "External"
write_eeprom 400, "EEprom"

'and read back from the eeprom
r$ =""
read_eeprom 0, r$
wlog r$
read_eeprom 100, r$
wlog r$
read_eeprom 200, r$
wlog r$
read_eeprom 300, r$
wlog r$
read_eeprom 400, r$
wlog r$
end

'==============================================================
'write an eeprom using pages of 32 bytes, and 5ms of write time
'use a buffer of 32 bytes (this is function of the eeprom)
'==============================================================
sub write_eeprom(address, msg$)
  local k, z, ad, le, bk, ofs, m$
  local buf_size
  buf_size = 32
  m$ = msg$ + chr$(255)
  le = len(m$)
  'write the first block that could not be aligned
  ofs = address mod buf_size
  bk = buf_size - ofs
  i2c.begin EE_ADDR
  ad = address
  i2c.write ad >> 8
  i2c.write ad and 255
  for z=1 to bk
      i2c.write asc(mid$(m$, z, 1))
  next z
  le = le - bk
  i2c.end
  pause 5 ' time for writing
  'write the remaining part of the message    
  k = 1
  while le > 0
    i2c.begin EE_ADDR
    ad = k*buf_size + (address and (65536 - buf_size))
    i2c.write ad >> 8
    i2c.write ad and 255
    if (le > buf_size) then bk = buf_size else bk = le
    for z=1 to bk
      i2c.write asc(mid$(m$, z + k*buf_size - ofs, 1))
    next z
    le = le - buf_size
    i2c.end
    'print "writing block "; k
    pause 5 ' time for writing
    k = k + 1
  wend
end sub

'==============================================================
'read from an external eeprom
' consider the eeprom of max 4096 bytes
'==============================================================
sub read_eeprom(address, msg$)
  local k, z, ad, le, bk, c
  msg$=""
  le = 4096 'size max (in bytes) of the eeprom
  i2c.begin EE_ADDR
  i2c.write address >> 8
  i2c.write address and 255
  i2c.end
  for k = 0 to int(le/128)
    if (le > 128) then bk = 128 else bk = le
    i2c.reqfrom EE_ADDR, bk
    for z=1 to bk
      c = i2c.read
      if c <> 255 then
        msg$ = msg$ + chr$(c)
      else 'exit from the loops
        k = 9999
        z = 9999
      end if
    next z
    le = le - 128
  next k
  i2c.end
end sub