微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我可以使用 python 代码来控制连接到 Raspberry 的 LED,但使用 C 它不起作用

如何解决我可以使用 python 代码来控制连接到 Raspberry 的 LED,但使用 C 它不起作用

我只是使用标准示例。所以代码肯定是正确的。但我不知道为什么 C 代码不起作用

 /**********************************************************************
* Filename    : 1.Blinking_LED
* Description : Make an led blinking.
* Author      : Robot
* E-mail      : support@rexqualis.com
* website     : www.rexqualis.com
* Update      : Tim   2019/12/02
**********************************************************************/
#include <wiringpi.h>  
#include <stdio.h>
#define LedPin      0   //the pin to connect the led
int main(void)
{
    // When initialize wiring Failed,print message to screen
    if(wiringpiSetup() == -1){
        printf("setup wiringpi Failed !");   //catch error and break
        return 1;
    }
    pinMode(LedPin,OUTPUT);// Set LedPin as output to write value to it.
    while(1){
        // LED on
        digitalWrite(LedPin,LOW);  //write Low to ledPin
        printf("...LED on\n");   //log the led on
        delay(1000); //1000ms delay to blink
        // LED off
        digitalWrite(LedPin,HIGH); //write high to ledPin
        printf("LED off...\n"); //log the led off 
        delay(1000);   //1000ms delay to blink
    }
    return 0;
}
#!/usr/bin/env python3
import RPi.GPIO as GPIO  #the pin libaray of raspBerry
import time  #the time libaray of system time
LedPin = 17  #the BCM pin connect to LED
def setup():
    # Set the GPIO modes to BCM Numbering
    GPIO.setmode(GPIO.BCM) 
    # Set LedPin's mode to output,and initial level to High(3.3v)
    GPIO.setup(LedPin,GPIO.OUT,initial=GPIO.HIGH)
# Define a main function for main process
def main():
    while True:
        print ('...LED ON')
        # Turn on LED
        GPIO.output(LedPin,GPIO.LOW)
        time.sleep(1)
        print ('LED OFF...')
        # Turn off LED
        GPIO.output(LedPin,GPIO.HIGH)
        time.sleep(1)
# Define a destroy function for clean up everything after the script finished
def destroy():
    # Turn off LED
    GPIO.output(LedPin,GPIO.HIGH)
    # Release resource
    GPIO.cleanup()
# If run this script directly,do:
if __name__ == '__main__':
    setup()
    try:
        main()
    # When 'Ctrl+C' is pressed,the program destroy() will be  executed.
    except KeyboardInterrupt:
        destroy()

以上是C代码和python代码

C 代码的编译和编译也是标准的:

gcc 1.Blinking_LED.c -o Blinking_LED.out -lwiringpi
sudo ./Blinking_LED.out

代码应该使 LED 灯闪烁。当我运行python代码时,一切正常。但是当运行 C 代码时,在终端上一切正常。印刷都很好。没有任何意外发生。但是 LED 什么也不做。

这个问题我已经解决了,是GPIO权限的问题。如此链接 https://www.raspberrypi.org/documentation/usage/gpio/ .

使用这个命令

sudo usermod -a -G gpio <username>

另外,运行代码

./Blinking_LED.out

代替

sudo ./Blinking_LED.out

不过,我很奇怪为什么python没有这个问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。