[英]Interface M24512 EEPROM with Raspberry Pi on I2C: converting Python to C++
我必須在 I2C 總線上將 M24512 EEPROM IC 與 Raspberry pi 連接起來。它在地址 0x50 處顯示 i2cdetect -y 1
我讓它在 python-smbus 上工作:
import smbus
import time
bus=smbus.SMBus(1)
bus.write_i2c_block_data(0x50, 0x00, [0x00, 50, 51, 52, 53, 54])
time.sleep(0.5)
bus.write_i2c_block_data(0x50, 0x00, [0x00])
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
print bus.read_byte(0x50)
time.sleep(0.5)
顯示輸出
50
51
52
53
54
255
255
這十分完美。 但現在我想使用 WiringPi lib 將其轉換為 C++。
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int temp=0;
int a=0;
wiringPiSetup();
int fd = wiringPiI2CSetup(0x50);
cout << "file descriptor " << fd << endl ;
wiringPiI2CWriteReg8(fd, 0x00, 0x00);
delayMicroseconds(500000);
cout << wiringPiI2CWrite(fd, 100);
delayMicroseconds(500000);
wiringPiI2CWriteReg8(fd, 0x00, 0x00);
delayMicroseconds(500000);
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
a=wiringPiI2CRead(fd);
delayMicroseconds(500000);
cout<<a<<endl;
使用上面的代碼,EEPROM 讀取工作正常,但寫入不起作用..任何建議!
我在嘗試通過樹莓派上的 i2C 寫入 ON Semiconductor CAT24C32 時遇到了類似的問題。 數據表供參考。 我能夠使用 smbus2 庫gitub編寫一個 python 腳本來讀取/寫入 EEPROM,但是當我在我的 c++ 應用程序中實現它時,我無法將寫入寫入正確的地址(或根本沒有)在 EEPROM 內。
我對為什么 WiringPi 是一個問題的理解是因為兩個潛在因素。
我的解決方法是將地址拆分並將 [AddrLOW] 轉換為 [DataHIGH]。 這是因為 EEPROM 只有 8 位寄存器,所以每個數據字節永遠只有 8 位。
#include "wiringPiI2C.h"
#include <chrono>
#include <thread>
void WriteDataToEEPROM(int devId, int reg, std::vector<int> data) {
int fd = wiringPiI2CSetup(devId);
wiringPiI2CWriteReg8(fd, reg, reg); // Set the internal addres point
std::this_thread::sleep_for(std::chrono::milliseconds(10));
uint8_t i = reg;
for (const auto d : data) {
uint8_t addr[2];
addr[1] = i >> 8;
addr[0] = i;
int status = wiringPiI2CWriteReg16(fd, addr[1], (d << 8) | addr[0]);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
i++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.