github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/examples/flash/main.go (about)

     1  package main
     2  
     3  import (
     4  	"machine"
     5  	"time"
     6  )
     7  
     8  var (
     9  	err     error
    10  	message = "1234567887654321123456788765432112345678876543211234567887654321" +
    11  		"1234567887654321123456788765432112345678876543211234567887654321" +
    12  		"1234567887654321123456788765432112345678876543211234567887654321" +
    13  		"1234567887654321123456788765432112345678876543211234567887654321"
    14  )
    15  
    16  func main() {
    17  	time.Sleep(3 * time.Second)
    18  
    19  	// Print out general information
    20  	println("Flash data start:      ", machine.FlashDataStart())
    21  	println("Flash data end:        ", machine.FlashDataEnd())
    22  	println("Flash data size, bytes:", machine.Flash.Size())
    23  	println("Flash write block size:", machine.Flash.WriteBlockSize())
    24  	println("Flash erase block size:", machine.Flash.EraseBlockSize())
    25  	println()
    26  
    27  	original := make([]byte, len(message))
    28  	saved := make([]byte, len(message))
    29  
    30  	// Read flash contents on start (data shall survive power off)
    31  	println("Reading original data from flash:")
    32  	_, err = machine.Flash.ReadAt(original, 0)
    33  	checkError(err)
    34  	println(string(original))
    35  
    36  	// erase flash
    37  	println("Erasing flash...")
    38  	needed := int64(len(message)) / machine.Flash.EraseBlockSize()
    39  	if needed == 0 {
    40  		// have to erase at least 1 block
    41  		needed = 1
    42  	}
    43  
    44  	err := machine.Flash.EraseBlocks(0, needed)
    45  	checkError(err)
    46  
    47  	// Write the message to flash
    48  	println("Writing new data to flash:")
    49  	_, err = machine.Flash.WriteAt([]byte(message), 0)
    50  	checkError(err)
    51  	println(string(message))
    52  
    53  	// Read back flash contents after write (verify data is the same as written)
    54  	println("Reading data back from flash: ")
    55  	_, err = machine.Flash.ReadAt(saved, 0)
    56  	checkError(err)
    57  	if !equal(saved, []byte(message)) {
    58  		println("data verify error")
    59  	}
    60  
    61  	println(string(saved))
    62  	println("Done.")
    63  }
    64  
    65  func equal(a, b []byte) bool {
    66  	if len(a) != len(b) {
    67  		return false
    68  	}
    69  	for i, v := range a {
    70  		if v != b[i] {
    71  			return false
    72  		}
    73  	}
    74  	return true
    75  }
    76  
    77  func checkError(err error) {
    78  	if err != nil {
    79  		for {
    80  			println(err.Error())
    81  			time.Sleep(time.Second)
    82  		}
    83  	}
    84  }