メモリ テクノロジー デバイスからの読み取りと書き込みは、他のタイプの IO とそれほど違いはありませんが、書き込む前にセクターを消去する必要がある (ブロックを消去する) 必要があります。
自分で物事を簡単にするために、コードを書く必要なく、いつでも mtd-utils (消去、読み取り、書き込み用の 、 、flash_erase
などnanddump
)を使用できます。nandwrite
ただし、実用的にやりたい場合は、ここに例を示します。詳細をすべて記載しているので、必ずすべてのコメントを読んでください。
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <mtd/mtd-user.h>
int main()
{
mtd_info_t mtd_info; // the MTD structure
erase_info_t ei; // the erase block structure
int i;
unsigned char data[20] = { 0xDE, 0xAD, 0xBE, 0xEF, // our data to write
0xDE, 0xAD, 0xBE, 0xEF,
0xDE, 0xAD, 0xBE, 0xEF,
0xDE, 0xAD, 0xBE, 0xEF,
0xDE, 0xAD, 0xBE, 0xEF};
unsigned char read_buf[20] = {0x00}; // empty array for reading
int fd = open("/dev/mtd0", O_RDWR); // open the mtd device for reading and
// writing. Note you want mtd0 not mtdblock0
// also you probably need to open permissions
// to the dev (sudo chmod 777 /dev/mtd0)
ioctl(fd, MEMGETINFO, &mtd_info); // get the device info
// dump it for a sanity check, should match what's in /proc/mtd
printf("MTD Type: %x\nMTD total size: %x bytes\nMTD erase size: %x bytes\n",
mtd_info.type, mtd_info.size, mtd_info.erasesize);
ei.length = mtd_info.erasesize; //set the erase block size
for(ei.start = 0; ei.start < mtd_info.size; ei.start += ei.length)
{
ioctl(fd, MEMUNLOCK, &ei);
// printf("Eraseing Block %#x\n", ei.start); // show the blocks erasing
// warning, this prints a lot!
ioctl(fd, MEMERASE, &ei);
}
lseek(fd, 0, SEEK_SET); // go to the first block
read(fd, read_buf, sizeof(read_buf)); // read 20 bytes
// sanity check, should be all 0xFF if erase worked
for(i = 0; i<20; i++)
printf("buf[%d] = 0x%02x\n", i, (unsigned int)read_buf[i]);
lseek(fd, 0, SEEK_SET); // go back to first block's start
write(fd, data, sizeof(data)); // write our message
lseek(fd, 0, SEEK_SET); // go back to first block's start
read(fd, read_buf, sizeof(read_buf));// read the data
// sanity check, now you see the message we wrote!
for(i = 0; i<20; i++)
printf("buf[%d] = 0x%02x\n", i, (unsigned int)read_buf[i]);
close(fd);
return 0;
}
write()
これの良いところは、他のデバイスと同じように標準のユーティリティを使用できるため、何を、、、何を行いopen()
、read()
何を期待するかを簡単に理解できることです。
たとえば、使用中write()
に値を取得した場合、次のEINVAL
ことを意味する可能性があります。
fd が、書き込みに適していないオブジェクトに関連付けられています。または、ファイルが O_DIRECT フラグで開かれ、buf で指定されたアドレス、count で指定された値、または現在のファイル オフセットが適切に配置されていません。