Skip to content

Instantly share code, notes, and snippets.

@sekcompsci
Last active August 4, 2016 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sekcompsci/19e9dd948d49851dda011304522a41f5 to your computer and use it in GitHub Desktop.
Save sekcompsci/19e9dd948d49851dda011304522a41f5 to your computer and use it in GitHub Desktop.
#include <EEPROM.h>
int addr = 0;
float val = 0;
/*****************************************************************************
* Union คือชุดข้อมูลที่ตัวแปรแต่ละตัวใช้พื้นที่ร่วมกัน
* ซึ่งในกรณีนี้ เราอยากเก็บค่า Float ซึ่งใช้ 4 Byte เราก็ต้องสร้าง Byte ซึ่งใช้ 4 Byte มา 4 ตัว
*****************************************************************************/
union u_tag {
byte b[4];
float f;
} u;
void setup()
{
delay(3000); // หน่วงเวลา 3 วินาที ก่อนเริ่มทำงานโปรแกรม
Serial.begin(115200);
while(!Serial) ;
EEPROM.begin(512); // กำหนดขนาด EEPROM ให้มีขนาด 512 Byte
// วนลูปอ่านค่า Byte ต่าง ๆ จาก EEPROM
for(int i = 0; i < 4; i++){
u.b[i] = EEPROM.read(addr + i);
}
Serial.println("---------- EEPROM Read -----------");
}
void loop()
{
Serial.println(u.f);
delay(1000); // หน่วงเวลา 1 วินาที ก่อนจบการทำงานของรอบนี้
}
#include <EEPROM.h>
int addr = 0;
float val = 0;
/*****************************************************************************
* Union คือชุดข้อมูลที่ตัวแปรแต่ละตัวใช้พื้นที่ร่วมกัน
* ซึ่งในกรณีนี้ เราอยากเก็บค่า Float ซึ่งใช้ 4 Byte เราก็ต้องสร้าง Byte ซึ่งใช้ 4 Byte มา 4 ตัว
*****************************************************************************/
union u_tag {
byte b[4];
float f;
} u;
void setup()
{
delay(3000); // หน่วงเวลา 3 วินาที ก่อนเริ่มทำงานโปรแกรม
Serial.begin(115200);
while(!Serial) ;
EEPROM.begin(512); // กำหนดขนาด EEPROM ให้มีขนาด 512 Byte
}
void loop()
{
Serial.println(val); // แสดงค่าล่าสุดของตัวแปร val
u.f = val; // กำหนดค่า u.f ให้มีค่าเท่ากับ val
// วนลูปบันทึกค่า Byte ต่างๆของ Float ลงใน EEPROM
for(int i = 0; i < 4; i++){
EEPROM.write(address + i , u.b[i]);
}
EEPROM.commit(); // บันทึกการเปลี่ยนแปลงทั้งหมด
Serial.println("---------- EEPROM Write ----------");
val++; // เพิ่มค่าตัวแปร val ทุกครั้งที่วนลูป
delay(1000); // หน่วงเวลา 1 วินาที ก่อนจบการทำงานของรอบนี้
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment