Nick: hatim E-mail: hatim@hatimak.me Board: unknown Contents: #include #include #define MAX_STATUS_REGISTER_BITS 25 enum status_register_bits { // Start from 1 (reason apparent in num_status_register() definition body. WIP = 1, WEL, BP4, BP3, BP2, BP1, BP0, LB3, LB2, LB1, CMP, WPS, SRP0, SRP1, RESV, QE, SUS1, SUS2, DRV0, DRV1, RST }; const char *status_register_bit_name[] = { [WIP] = "WIP", [WEL] = "WEL", [BP4] = "BP4", [BP3] = "BP3", [BP2] = "BP2", [BP1] = "BP1", [BP0] = "BP0", [LB3] = "LB3", [LB2] = "LB2", [LB1] = "LB1", [CMP] = "CMP", [WPS] = "WPS", [SRP0] = "SRP0", [SRP1] = "SRP1", [RESV] = "RESV", [QE] = "QE", [SUS1] = "SUS1", [SUS2] = "SUS2", [DRV0] = "DRV0", [DRV1] = "DRV1", [RST] = "RST" }; // SPI chip with more than 3 status registers not spotted till now, so 3 is max enum status_register_num { SR1, SR2, SR3 }; struct status_register_layout { // Each status register has exactly 8 bits enum status_register_bits bits[8]; }; struct flashchip { struct status_register_layout status_register[3]; int status_bit[MAX_STATUS_REGISTER_BITS]; uint8_t (*read_status)(struct flashchip *flash, enum status_register_num); int (*write_status)(struct flashchip *flash, int status); }; int num_status_register(struct flashchip *flash) { int num = 0; struct status_register_layout *status = flash->status_register; while (status[num++].bits[0] != 0) ; return --num; } void print_status_register(struct flashchip *flash, enum status_register_num sr) { printf("SR%d : ", sr + 1); for (int j = 0; j < 8; j++) printf("%s ", status_register_bit_name[flash->status_register[sr].bits[j]]); printf("\n"); } int bp_bitfield(struct flashchip *flash) { int mask = 0, i = 0; while (flash->status_register[SR1].bits[i] != BP0) i++; mask = 1 << i; i++; while (flash->status_register[SR1].bits[i] == BP4 | flash->status_register[SR1].bits[i] == BP3 | flash->status_register[SR1].bits[i] == BP2 | flash->status_register[SR1].bits[i] == BP1) mask = mask | (1 << (i++)); return mask; } int read_status_dummy(struct flashchip *flash, enum status_register_num sr) { // This will come from the chip int status = 0xA8; for (int i = 0; i < 8; i++) flash->status_bit[flash->status_register[sr].bits[i]] = (status & (1 << i)) >> i; return status; } int main(int argc, const char **argv) { struct flashchip flash = { .status_register = { [SR1] = { WIP, WEL, BP0, BP1, BP2, BP3, BP4, SRP0 }, [SR2] = { SRP1, QE, SUS2, LB1, LB2, LB3, CMP, SUS1 }, [SR3] = { RESV, RESV, WPS, RESV, RESV, DRV0, DRV1, RST } } }; printf("num_status_register = %d\n", num_status_register(&flash)); print_status_register(&flash, SR1); print_status_register(&flash, SR2); print_status_register(&flash, SR3); printf("BP mask = 0x%02x\n", bp_bitfield(&flash)); read_status_dummy(&flash, SR1); read_status_dummy(&flash, SR2); read_status_dummy(&flash, SR3); printf("%s=%d, %s=%d\n", status_register_bit_name[BP0], flash.status_bit[BP0], status_register_bit_name[LB1], flash.status_bit[LB1]); return 0; }