Delta_G:
cast the struct to an array of bytes
Man! As simple and straight-forward as Delta_G's suggestion seemed (which I definitely appreciate), I've spent three quarters of a day finding a way to do what he said. Usually, Googling brings up a good answer in a few minutes. But this time, I landed on page after page after page of info "about" the answer, without anything ever pointing specifically to how I can cast a struct as an array. FINALLY, I found this page, which gives a simple, two-line example of exactly what I need to use for casting:
char* buf= (char*)&your_struct);
fwrite(buf, sizeof(your_struct), 1, socket_stream);
But even THEIR code gives an error message, unless "your_struct" is an instance of the struct you've made, rather than the name of the struct itself. (That took another hour to figure out.)
So for anyone else who needs an example that works, I'm pasting my successful test sketch here:
#include <SD.h>
void ee(String s)
{
Serial.println(s);
}
void ee(long n)
{
Serial.println(n);
}
void ee()
{
Serial.println();
}
void ee(String s, unsigned long n)
{
Serial.print(s+":");
Serial.print(n);
Serial.println(" ");
}
void ee(String s, String n)
{
Serial.print(s+":");
Serial.print(n);
Serial.println(" ");
}
File myFile;
struct oneMinSt
{
byte heartRate;
byte motion;
byte temperature;
byte skin;
} oneMin;
void showStruct()
{
ee("heartRate",oneMin.heartRate);
ee("motion",oneMin.motion);
ee("temperature",oneMin.temperature);
ee("skin",oneMin.skin);
}
void setup()
{
Serial.begin(9600);
byte* oneMinAr = (byte*)&oneMin;
pinMode(SS,OUTPUT);
ee("SD.begin(SS)",SD.begin(SS));
ee("myFile",myFile = SD.open("test.123",FILE_WRITE));
oneMin.heartRate = 11;
oneMin.motion = 22;
oneMin.temperature = 33;
oneMin.skin = 44;
ee();
showStruct();
ee();
ee("write",myFile.write(oneMinAr,sizeof(oneMinSt)));//sizeof(oneMin)
oneMin.heartRate = 0;
oneMin.motion = 0;
oneMin.temperature = 0;
oneMin.skin = 0;
ee();
showStruct();
ee();
myFile.seek(0);
ee("read",myFile. read(oneMinAr,sizeof(oneMinSt))); //sizeof(oneMin)
ee();
showStruct();
myFile.close();
}
void loop()
{
}
The Serial Monitor window will then show:
SD.begin(SS):1
myFile:1
heartRate:11
motion:22
temperature:33
skin:44
write:4
heartRate:0
motion:0
temperature:0
skin:0
read:4
heartRate:11
motion:22
temperature:33
skin:44
It shows that:
(1) Values are placed in my struct.
(2) The struct is saved as a byte array.
(3) The values in my struct are all set to zero.
(4) The saved values are read back into my struct.
(5) The returned values in my struct are shown.
(The ee() functions at the top are what I use to easily see what's happening, and where, and to what, any place in my sketches.)
And thanks again to Delta_G for pointing out the problem, and what I need to do about it.