我在 SDCC 3.4 上,这是一个乐器的 MIDI 项目,这几天我一直在努力解决这个问题……我什至觉得有点难以解释,所以在这里我试着做一个更好的例子。基本上,我正在扫描按钮按下、发送 MIDI 信息并相应地点亮 LED。我需要的是一种数据库,其中包含与每个按钮相关的所有数据,其中一部分必须是恒定的(按钮和 LED 的 ID),而一部分可以是可变的,因为用户可以改变。在初始化阶段,我需要将常量部分分配给结构并保持变量部分不变。当用户修改一个按钮的功能时,我需要覆盖可变部分,保持不变部分不变。
// A structure for the constant part
typedef struct
{
unsigned char btnID; // this holds the n. of input pin for the button
unsigned char ledID; // this holds the n. of output pin for the LED
} sBtnConst;
// A structure for the variable part
typedef struct
{
unsigned char CCnum; // this holds the CC number to send
unsigned char CCval; // this holds the CC value tu send
} sBtnVar;
// A structure containing all data
typedef struct
{
sBtnConst c;
sBtnVar v;
} sButton;
// Declare an array of button structures
// These will contain both the constant and the variable data
sButton Button[4];
// Now initialize a constant structure for the constant part
const sBtnConst cBtnDefinitions[4] =
{
{ 15, 0 },
{ 14, 1 },
{ 10, 8 },
{ 12, 5 },
};
现在,我需要做的是复制 to 的全部cBtnDefinitions[]
内容Button[]->c
。如果我做
memcpy(&Button->c, &cBtnDefinitions, sizeof(cBtnDefinitions));
数据按顺序复制到 c 和 v 中,而不仅仅是在成员 c 中。
主循环()中的其余代码如下所示:
void doButton(sButton *btn, unsigned char value)
{
LitLED(btn->c.ledID, !value);
SendMidiCC(btn->v.CCnum, btn->v.CCval);
}
// This is a callback function called every time a button has been pushed
void aButtonHasBeenPushed(unsigned char ID, unsigned char value)
{
unsigned char i;
for (i=0; i<NUM_OF_BUTTONS; ++i)
if (i == Button[i].c.btnID)
doButton(&Button[i], value);
}
当然,我可能有不同类型的按钮,所以我可以将 sButton 结构用于其他目的,并让它们都由相同的函数处理。