2015-08-04 5 views
0

Цель: Запись во внутренний буфер из значений элементов структуры.Использование указателя для доступа к typedef struct

У меня есть структура, которая содержит элементы типа Uint16 (unsigned int); вот небольшая часть его:

typedef unsigned int Uint16; 
typedef struct 
{ 
    Uint16 ee_Speed_Control_Mode; 
    Uint16 ee_Motor_Type; 
    Uint16 ee_Max_Electrical_Speed; 
    Uint16 ee_Carrier_Frequency; 
    Uint16 ee_Rated_Motor_Frequency; 
    Uint16 ee_Rated_Motor_Current; 
    Uint16 ee_Rs; // extern 
    Uint16 ee_Rr; // extern 
    Uint16 ee_L_lkg; // extern 
    Uint16 ee_Lm; // extern 
    Uint16 ee_No_Load_Current; 
    Uint16 ee_Phase_Reversal; 
    ..... 
    ..... 
} EEPROM_PARAMETERS; 

EEPROM_PARAMETERS eepromParameters; 

Моя попытка:

Вот функция, которая предназначена для записи в ЭСППЗУ: (Большинство из них не показан для простоты, фокус происходит в «для» петли

void eeprom_write(Uint16 address, Uint32 *data, Int16 len) 
{ 
    Uint16 i; 

    // Multiple bytes will be written 
    // Page Write operation will be used 
    // Page Write bits to be sent: 

    // bit 0: Start condition, a high-to-low transition of SDA with SCL high 
    startCondition(); 

    // bits 1-8: Device address 
    I2caRegs.I2CDXR = DEVICE_ADDRESS_WRITE; 

    // bit 9: EEPROM outputs 0 as ACK bit 
    // Check for ACK bit 
    while (I2caRegs.I2CDRR != 0) 
    { 
     wait(); 
    } 

    // bits 10-17, bit 18 (ACK) and bits 19-26: two 8-bit word addresses 
    I2caRegs.I2CDXR = address; 

    // After setting the address, page write is capable of writing 64 bytes without stopping 
    // The EEPROM will respond with a zero after each data word has been received 
    // The data word address lower 6 bits are internally incremented following the receipt of each data word 
    // If more than 64 data words are written, data word addresses will "roll over" and previous data will be overwritten 

    for (i = 0; i < len; i++) 
    { 
     // How to increment address in data structure? 
     I2caRegs.I2CDXR = *data++; 
    } 

    // After page write operation is complete, execute stop condition 
    stopCondition(); 
} 

Когда я пытаюсь вызвать эту функцию с моими параметрами ..

eeprom_write(0, &eepromParameters, sizeof(eepromParameters)); 

Я получаю несовместимый тип ошибки:

error #169: argument of type "EEPROM_PARAMETERS *" is incompatible with parameter of type "Uint16 *" 

Моя следующая мысль была бы, что мне нужен средний человек, чтобы собрать их вместе и сделать его совместимым матч. Любые советы, пожалуйста, что я могу попробовать? Спасибо

+0

Как определяется 'I2caRegs'? – dbush

+2

Почему бы не объявить как 'void eeprom_write (адрес Uint16, данные eepromParameters *, Int16 len)'? –

+0

'Uint32 * data' для' eepromParameters * data'. Тип, который вы передали, несовместим. – ameyCU

ответ

0

Проблема заключается в декларации и использовании данных. Если вы объявляете его как

void eeprom_write(Uint16 address, EEPROM_PARAMETERS* data, Int16 len); 

и называют его

eeprom_write(0, &eepromParameters, sizeof(eepromParameters)); 

Он будет падать в

*data++ 

, поскольку она будет увеличиваться на величину EEPROM_PARAMTERS. Если прототип объявлен

void eeprom_write(Uint16 address, UInt16* data, Int16 len); 

Он должен называться

eeprom_write(0, &eepromParameters.ee_Speed_Control_Mode, sizeof(eepromParameters)/sizeof(Uint16)); 

Это предполагает, что все в EEPROM_PARAMETERS является UInt16. Другой способ сделать это - использовать перечисления.

enum EEOffsets 
{ 
    ee_Speed_Control_Mode, 
    ee_Motor_Type, 
    ee_Max_Electrical_Speed, 
    ee_Carrier_Frequency, 
    ... 
    ee_Max 
}; 

// Initialize the parameters 
Uint16 eepromParameters[ee_Max] = { ... }; 

// If you need to assign 
eepromParameters[ee_Carrier_Frequency] = 85; 
... 
eeprom_write(0, eepromParameters, ee_Max); 
+0

Второе предложение (даже с учетом вашего предположения) вызывает неопределенное поведение посредством множественных нарушений. Последний пример, однако, является правильным решением. – this

Смежные вопросы