Shop OBEX P1 Docs P2 Docs Learn Events
Prop C Learn - SD Card Date - can't store the value — Parallax Forums

Prop C Learn - SD Card Date - can't store the value

bsnatubsnatu Posts: 7
edited 2013-10-08 03:36 in Learn with BlocklyProp
I modify the program from http://learn.parallax.com/propeller-c-simple-devices/sd-card-data to store the value.
The terminal display the value "val=500" that is correct.
But when I open the "test.txt" file, I see gibberish...it's "?" not the value "500".
what's wrong with my program?
#include "simpletools.h" 

[COLOR=#333333][FONT=Lucida Console]int DO = 22, CLK = 23, DI = 24, CS = 25;[/FONT][/COLOR] // SD card pins on Propeller BOE
int val=500; 
int main(void) 
{
  sd_mount(DO, CLK, DI, CS);                  // Mount SD card
  FILE* fp = fopen("test.txt", "w");          // Open a file for writing
 
  fwrite(&val, sizeof(val), 1, fp);
  fclose(fp);                                 // Close the file
  
  fp = fopen("test.txt", "r");                // Reopen file for reading                    
  fread(&val, 4, 1, fp);
  print("val = %d\n", val);
  fclose(fp);
}  

Comments

  • Mike GMike G Posts: 2,702
    edited 2013-10-07 05:15
    SD cards store data as a byte array. A text files generally store data as a character byte array. Each byte of data is encoded, usually ASCII, and represents a character. See the ASCII table in the following link.
    http://www.asciitable.com/

    The value 500 requires two bytes; 0x01F4. IF the bytes 0x01 and 0xF4 are stored on an SD card and later read using a text editor, then yes the character representations may be a "?" or some strange looking character.

    If you want to see 500 in text editor based terminal you'll need to convert 500 to a string, save the string on the SD card or send it to the terminal. However, if you need to manipulate 500, you'll need to convert the string "500" back to an integer.
  • jazzedjazzed Posts: 11,803
    edited 2013-10-07 09:36
    The best way at the moment to convert an integer to a string is to use itoa(). Functions atoi() and strtol() can be used for string to int.

    int n;
    char s[80];
    itoa(500, s, 10);
    n = atoi(s); // convert a string to a natural number to a string.
    n = strtol(s,0,10); // convert a string to a number with any base.

    It is also possible to use the Simple Library #include "simpletext.h" functions "sprint" which works like sprintf and "sscan" which works like sscanf.

    Don't use ANSI standard fprintf, fscanf, printf, sprintf because they are just too big for Propeller.
  • bsnatubsnatu Posts: 7
    edited 2013-10-08 03:36
    Thanks Mike G & jazzed solved my question, it's very useful for me.
    I forgot the text files store the characte
    r is usually ASCII code.
Sign In or Register to comment.