4

我想编写 ac 代码来生成脉冲,但似乎无法将我的头脑围绕在实现它的逻辑上。我来自强大的 Verilog 背景并且知道如何在 verilog 中执行此操作(使用 xor 查找状态变化并使用该脉冲,如果需要,通过多次注册来延长它)

我应该如何在 C 中做到这一点?我想做类似的事情

while(1)
{
   switch(state)
   case 0: // generate single pulse
   case 1: // dont generate 
   case 2: // dont gererate
   case 3: // generate single pulse
   usleep(1000) // I want a 1ms pulse
}  

状态由运行在 FPGA 上的代码修改,因此它会根据某些逻辑而改变。
似乎无法做到这一点。一些指导将不胜感激

4

3 回答 3

3

你需要一个稍微强大一点的状态机,它可以做入口动作。

假设

  • 状态机在脉冲时失明是可以的
  • 循环内的变量state更改(例如,可能是易失性的并且可能从 ISR 更新)
  • 或状态在循环内以某种方式更新(存在伪代码)

您在聊天中表示您可以控制变量何时state更改。这很重要。要么使用updatestate()从伪代码行调用的轮询函数;或以某种方式确保变量不会在// enter protection ...和之间变化// leave protection ...
但是,状态机仍然无法识别之间的变化,尤其是在usleep(1000);. 如果这是一个问题,您需要明显更复杂的机制。

伪代码提案:

// somewhere before
volatile int state = 0; // somehow changing within the loop 

int statecopy = 0;  
int statebefore = state,

while(1)
{
    // updatestate(); // if that is necessary

    // Note that the state machine is blind for changes to state
    // between executions of these initial lines.
    // I.e. changes are noticed only when executing the update above
    // or the critical section below this comment. (depending on how
    // the variable state changes.

    // enter protection for critical section
    statebefore = statecopy;
    statecopy   = state;
    // leave protection for critical section

    switch(statecopy )
    {
        case 0: // generate single pulse
            if (statecopy != statebefore)
            {
                // switch high
                usleep(1000); // I want a 1ms pulse
                // switch low
            }
            break;
        case 1: // dont generate 
            break;
        case 2: // dont gererate
            break;
        case 3: // generate single pulse
            if (statecopy != statebefore)
            {
                // switch high
                usleep(1000); // I want a 1ms pulse
                // switch low
            }
            break;
        default:
            break;
    }
}
于 2017-07-22T11:10:15.060 回答
1

You just need to implement little logic for state changing and action for each state, like this:

int state = 0;
while(1) {
  switch(state) {
    case 0: // generate single pulse
       start_pulse();
       usleep(1000);
       stop_pulse();
       break;
    case 1: // dont generate , wait 1ms?
       usleep(1000);
       break;
    case 2: // dont generate, wait 1ms?
       usleep(1000);
       break;
    case 3: // generate single pulse
       start_pulse();
       usleep(1000);
       stop_pulse();
       break;
  }
  state = (state+1)%3; // next state: 0, 1, 2, 3, 0, 1, 2,...
} 
于 2017-07-22T12:32:21.003 回答
0

简化开关示例

switch( state ) {
case 1:
case 2:
  usleep(1000);
  break;
case 0:
case 3:
  /* pulse high */
  usleep(1000);
  /* pulse low */
}

更多是可能的,但可能不值得,让编译器弄清楚。

于 2017-07-22T20:34:32.740 回答