โจทย์
ให้อ่านค่าเซ็นเซอร์แสงจาก Slave มาแสดงผลทางฝั่ง Master โดยพิมพ์ค่าออกทางหน้าจอของคอมพิวเตอร์ และ Master ใช้ค่านี้ในการควบคุมการเปิดไฟหลอด LED ตามโจทย์โคมไฟอัตโนมัติเดิม (มืดติด สว่างดับ)
จุดประสงค์การเรียนรู้
ได้ฝึกเขียนโปรแกรมอ่านค่าจาก I2C Slave
แนวทางการปฏิบัติ
ให้จับคู่สองกลุ่มเช่นเดิม แล้วสลับกันเป็น Master และ Slave
ฝั่ง Slave: ให้ค่อยอ่านค่า sensor แสงแล้วนำค่าไปเก็บไว้ใน register ที่ตกลงกันไว้กับทาง Master อย่าลืมว่าค่า sensor นั้นมีขนาดมากกว่า 1 ไบท์ ดังนั้นจะต้องมีการเก็บในหน่วยความจำสองตำแหน่ง
ฝั่ง Master: ต้องคอยอ่านค่าจาก Slave ในตำแหน่งที่ตกลงกันไว้ และต้องอ่านทีละสองไบท์เนื่องจากค่าเซ็นเซอร์นั้นมีขนาดเกิน 8 บิท โปรแกรมต่อไปนี้สาธิตการใช้งาน Master ตามแนวที่กำหนด
int16 Value;
i2c_start();
i2c_write(TARGET_ADDRESS | 0) ;
// send a register address where // we want to read two bytes from it. i2c_write(RegisterAddress);
i2c_start(); i2c_write(TARGET_ADDRESS | 1); // bit zero = 1 to indicate a Slave -> Master operation delay_us(100); /// wait for the slave to process our request. If data // from slave is corrupted. Try increasing this delay Value = i2c_read() << 8; // read the high byte. This will read from register location "RegisterAddress" Value += i2c_read(0); // read the low byte. This will read from register "Register Address+1"
// Note. The last read operation must use parameter "0"
i2c_stop();