37种传感器-树莓派开发-4-激光发射器

风流意气都作罢 提交于 2020-03-08 09:37:19

C语言编程

原理和之前的继电器十分类似,都是导包,宏定义引脚,检测,设置引脚为输出型,然后就是利用while循环控制管脚的电频高低。

#include <wiringPi.h>
#include <stdio.h>

#define LaserPin    0

int main(void)
{
	if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
		printf("setup wiringPi failed !");
		return 1; 
	}
	//printf("linker LedPin : GPIO %d(wiringPi pin)\n",LedPin); //when initialize wiring successfully,print message to screen

	pinMode(LaserPin, OUTPUT);

	while(1){
		digitalWrite(LaserPin, HIGH);
		delay(500);
		digitalWrite(LaserPin, LOW);
		delay(500);
	}
	return 0;
}

Python编程

Python编程也是和上次的继电器差不多,都是定义引脚,引脚初始化(选定模式,设为输出),然后利用无限循环实现激光开关的控制。最后也有利用try函数进行检测,捕捉错误释放引脚。

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

LedPin = 11    # pin11

def setup():
	GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
	GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
	GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def loop():
	while True:
		print '...Laser on'
		GPIO.output(LedPin, GPIO.LOW)  # led on
		time.sleep(0.5)
		print 'Laser off...'
		GPIO.output(LedPin, GPIO.HIGH) # led off
		time.sleep(0.5)

def destroy():
	GPIO.output(LedPin, GPIO.HIGH)     # led off
	GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
	setup()
	try:
		loop()
	except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
		destroy()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!