-1

I'm fairly new to coding, and I've been trying to write something to write a placeholder to a text document whenever a button attached to a GPIO pin on my RasPi is pressed:

//Write date function//
void record() {

    ofstream myFile;
    myFile.open("report.txt");
    myFile << "Input at SPAM \n";
    myFile.close();

}

//myRead function//
void myRead(int i){

    if((digitalRead(4) == HIGH) && (i<5)) {
        record();
        digitalWrite(14, HIGH);
        delay(500);
        digitalWrite(14, LOW);  
        ++i;
        delay(500);
        myRead(i);
    }   
    else{
        if((digitalRead(4) != HIGH) && (i<5)){      
            myRead(i);
        }
    }

}   

int main() {
    wiringPiSetup();
    pinMode(12, OUTPUT);
    pinMode(14, OUTPUT);
    pinMode(4, INPUT);
    digitalWrite(12, HIGH);
    digitalWrite(14, LOW);

    myRead(1);
    digitalWrite(14, HIGH);
    delay(5000);
    digitalWrite(14, LOW);

    return 0;
}

The code compiles without any complaints, but if I run it in terminal without a sudo command, I get a "segmentation fault" error.
When I run it with a sudo command, the program starts and then ends almost immediately.

For reference:

  • Pin 12 is providing power to a potential divider on the breadboard.
  • Pin 4 should take the input from this divider.
  • Pin 14 causes an LED to light whenever there is an input on pin 4.

Whenever I run the program and VERY QUICKLY press the button on the potential divider, the LED will light if I hold the button.

How can I get this to run properly without it stopping as soon as it starts?

4

1 回答 1

0

我认为有几个可能的问题myRead

一个小的重写可能是:

void myRead(int i)
{
    if((digitalRead(4) == HIGH) && (i<5)) {
        record();
        digitalWrite(14, HIGH);
        delay(500);
        digitalWrite(14, LOW);  
        ++i;
        delay(500);
        myRead(i);
    } else if((digitalRead(4) != HIGH) && (i<5)) {
        myRead(i);
    }
}

请注意,您有两个调用digitalRead- 这可能会导致问题,因为第一个 my return something different fromHIGH并且第二个可能 return HIGH,这意味着两个条件都不成立。

您在替代分支中使用与原始调用myRead相同的调用。i如果多次digitalRead返回不同的东西,你的堆栈将很快满,你会得到一个段错误。HIGH

我将提出一个不同的版本,它应该是相同的(排除我的任何误解):

void myRead(int i)
{
    // as long as i is less than 5
    while (i < 5) {
        // busy wait for digitalRead(4) to be HIGH
        while (digitalRead(4) != HIGH);
        // do the main thing
        record();
        digitalWrite(14, HIGH);
        delay(500);
        digitalWrite(14, LOW);  
        ++i;
        delay(500);
    }
}

另请注意,这只是普通的 C,而不是 C++(好吧,从技术上讲,它是有效的 C++,但它没有使用 C++)

于 2017-07-26T13:30:34.450 回答