https://www.tutorialspoint.com/arduino/index.htm
指撥開關
sw1file
先側殿為
int sw=7;
int swv;
void setup() {
// put your setup code here, to run once:
pinMode(sw,INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
swv=digitalRead(sw);
Serial.println(swv);
delay(2000);
}
================================
只播開關控制LED燈
int sw1=2;
int sw2=3;
int led1=7;
int led2=8;
int swv1;
int swv2;
void setup() {
// put your setup code here, to run once:
pinMode(sw1,INPUT_PULLUP);
pinMode(sw2,INPUT_PULLUP);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
swv1=digitalRead(sw1);
swv2=digitalRead(sw2);
if(swv1==0)
{
digitalWrite(led1,HIGH);
}
else
{
digitalWrite(led1,LOW);
}
if(swv2==0)
{
digitalWrite(led2,HIGH);
}
else
{
digitalWrite(led2,LOW);
}
}
=======================
//超音波感測器
#include <Ultrasonic.h>
Ultrasonic ultrasonic(12,13);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(ultrasonic.Ranging(CM));
Serial.println(" cm");
delay(3000);
}
=======================
//超音波感測器控制LED燈蜂鳴器
#include <Ultrasonic.h>
Ultrasonic ultrasonic(12,13);
int led=7;
int bee=2;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int dic=ultrasonic.Ranging(CM);
Serial.print(dic);
if (dic<=20)
{
digitalWrite(led,HIGH);
for(int i=0;i<10;i++)
{
tone(bee,1000);
delay(50);
tone(bee,500);
delay(50);
}
}
else
{
digitalWrite(led,LOW);
noTone(bee);
}
delay(3000);
}
==============================
中斷服務系統
(1)attachInterrupt():用來指定外部服務函數
attachinterrupt(interrupt,function,mode);
(a)interrupt:外部中斷編號(int0,int1)D2 and D3
(b)function:中斷服務函數
(c)mode:中斷觸發信號
LOW:
CHANGE:HIGH-LOW,LOW-HIGH
RISING:LOW_HIGH
FALLING:HIGH-LOW
==============
int in=0;
int pb1=2;
int led=8;
volatile boolean state=false;
void setup() {
// put your setup code here, to run once:
pinMode(led,INPUT);
pinMode(pb1,INPUT);
attachInterrupt(in,fun1,RISING);
}
void fun1()
{
state=!state;
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(led,LOW);
if (state)
{
digitalWrite(led,HIGH);
delay(2000);
digitalWrite(led,LOW);
delay(50);
}
else
{
digitalWrite(led,LOW);
}
}
==================
#define pb1 2
#define pb2 3
#define led1 8
#define led2 9
volatile boolean s1=false;
volatile boolean s2=false;
void setup() {
// put your setup code here, to run once:
pinMode(led1,INPUT);
pinMode(led2,INPUT);
pinMode(pb1,INPUT);
pinMode(pb2,INPUT);
attachInterrupt(0,chin1,RISING);
attachInterrupt(1,chin2,RISING);
}
void chin1()
{
s1=true;
s2=false;
}
void chin2()
{
s1=false;
s2=true;
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
if (s1)
{
digitalWrite(led1,HIGH);
}
if (s2)
{
digitalWrite(led2,HIGH);
}
delay(3000);
}
==========================
沒有留言:
張貼留言