【Arduino】基础传感器使用

双色LED灯

//双色led交替闪烁
int redPin =10;
int greenPin =11;
int num;
void setup() 
{
  // put your setup code here, to run once:
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
  Serial.begin(9600);
  
}

void loop() 
{
  // put your main code here, to run repeatedly:
  for(num =255;num>0;num--)
  {
     analogWrite(redPin,num);
     analogWrite(greenPin,255-num);
     Serial.println(num,DEC);
     delay(30);//30ms
     
  }
  for(int num =0;num<255;num++)
  {
    analogWrite(redPin,num);
     analogWrite(greenPin,255-num);
     Serial.println(num,DEC);
     delay(30);//30ms
  }
}

接线图

在这里插入图片描述
pinMode()
通过pinMode()函数,你可以将Arduino的引脚配置为以下三种模式:
1.输出(OUTPUT)模式
2.输入(INPUT)模式
3.输入上拉(INPUT_PULLUP)模式 (仅支持Arduino 1.0.1以后版本)
在输入上拉(INPUT_PULLUP)模式中,Arduino将开启引脚的内部上拉电阻,实现上拉输入功能。一旦将引脚设置为输入(INPUT)模式,Arduino内部上拉电阻将被禁用。

Serial.begin(speed)
串口波特率的设置:通常我们使用Serial.begin(speed)来完成串口的初始化,这种方式,只能配置串口的波特率。
使用Serial.begin(speed, config)可以配置数据位、校验位、停止位等。例如Serial.begin(9600,SERIAL_8E2)是将串口波特率设为9600,数据位8,偶校验,停止位2。
Serial.begin()官方详解

analogWrite()
将模拟值(PWM wave)写入引脚。可用于以不同的亮度点亮LED或以各种速度驱动电动机。调用之后analogWrite(),该引脚将生成指定占空比的稳定矩形波,直到同一引脚上的下一次调用analogWrite()(或调用digitalRead()或digitalWrite())为止。
analogWrite()官方详解

Serial.println(data)
从串行端口输出数据,跟随一个回车(ASCII 13, 或 ‘r’)和一个换行符(ASCII 10, 或 ‘n’)。
Serial.println()解释


RGB LED

//RGB LED 
int redPin =11;
int greenPin =10;
int bluePin =9;
void setup() 
{

  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
  pinMode(bluePin,OUTPUT);
  
}

void loop() 
{
   color(255,0,0);//red
   delay(1000);//1s
   color(0,255,0);//green
   delay(1000);
   color(0,0,255);//blue
   delay(1000);
   color(0,255,0); //red
   delay(1000);   
   color(255,0,0);//orange
   delay(1000); 
   color(0,128,255);//yellow
   delay(1000); 
   color(255,128,0);//green
   delay(1000); 
   color(255,0,128);//blue
   delay(1000); 
   color(128,0,255);
   delay(1000); 
   color(0,0,0);
   delay(1000); 
}
void color(unsigned char red,unsigned char green,unsigned char blue)
{
  analogWrite(redPin,red);
  analogWrite(bluePin,blue);
  analogWrite(greenPin,green);
}

在这里插入图片描述


继电器


const int relayPin =7; //the "s" of relay module attach to

void setup()
{
  pinMode(relayPin, OUTPUT); //initialize relay as an output
}

void loop()
{
  digitalWrite(relayPin, HIGH); //Close the relay
  delay(500); //wait for 1 second
  digitalWrite(relayPin, LOW); //disconnect the relay 
  delay(500); //wait for 1 second
}

SIG=IN,VCC=DC+,GND=DC-
SIG=IN,VCC=DC+,GND=DC-
在这里插入图片描述
继电器是一种用于响应施加的输入信号而在两个或设备之间提供连接设备。换句话说,继电器提供了控制器和设备之间的隔离,因为我们知道设备可以在AC和DC上工作。但是,他们从微控信号接收信号,因此我们需要一个继电器来弥补差距。当需要用小电信号控制大量电流或电压时,继电器非常有用。


激光 摩斯信号


#include "retrieval.h"

const int laserPin = 7; //laser attach to 

static int dotDelay = 200; //

void setup()
{
  pinMode(laserPin, OUTPUT);  //initialize laser as an output
  Serial.begin(9600);  
}

void loop()
{
  char ch = 0; //store the  character or digit read from the serial monitor
  if(Serial.available() > 0) //is there anything to be read
  {
    ch = Serial.read(); //read a single letter from serial monitor
  }
  morseSignal(ch); //flashes depend on the letter 
}
//
void flashDot(char cha)
{
  digitalWrite(laserPin, HIGH); //turn the laser on
  if(cha == '.') //
  {
    delay(dotDelay);
  }
  else
  {
    delay(dotDelay * 3);  //gap between letters
  }
  digitalWrite(laserPin, LOW);
  delay(dotDelay);  //gap between flashes
}
//
void flashSequence(char *sequence)
{
  int i = 0;
  while(sequence[i] != NULL)
  {
    flashDot(sequence[i]);
    i++;
  }
  delay(dotDelay * 3);
}
//
void morseSignal(char ch)
{
  if(ch >= 'a' && ch <= 'z')  
  {
    flashSequence(letters[ch - 'a']);
  }
  else if(ch >= 'A' && ch <= 'Z')
  {
    flashSequence(letters[ch - 'A']);
  }
  else if(ch >= '0' && ch <= '9')
  {
    flashSequence(numbers[ch - '0']);
  }
  else if(ch == ' ')
  {
    delay(dotDelay * 4);  //gap between words
  }
}


#ifndef __RETRIEVAL_H__
#define __RETRIEVAL_H__

char* letters[] = {
  ".-",  //A
  "-...",  //B
  "-.-.",  //C
  "-..",  //D
  ".",  //E
  "..-.",  //F
  "--.",  //G
  "....",  //H
  "..",  //I
  ".---",  //J
  "-.-",  //K
  ".-..",  //L
  "--",  //M
  "-.",  //N
  "---",  //O
  ".--.",  //P
  "--.-",  //Q
  ".-.",  //R
  "...",  //S
  "-",  //T
  "..-",  //U
  "...-",  //V
  ".--",  //W
  "-..-",  //X
  "-.--",  //Y
  "--.."  //Z
};
char* numbers[] = {
  "-----",  //0
  ".----",  //1
  "..---",  //2
  "...--",  //3
  "....-",  //4
  ".....",  //5
  "-....",  //6
  "--...",  //7
  "---..",  //8
  "----."   //9
};

#endif

在这里插入图片描述
打开串口监视器
在这里插入图片描述
输入字母发送莫斯密码
在这里插入图片描述
在这里插入图片描述
Serial.available();
获取可用于从串行端口读取的字节数(字符)。这是已经到达并存储在串行接收缓冲区(包含64个字节)中的数据。
Serial.available()从Stream实用程序类继承。
Serial.read()
读取传入的串行数据。


轻触开关


//Turns on and off a LED ,when pressings button attach to pin7
/**********************************/
const int keyPin = 7; //the number of the key pin
const int ledPin = 13;//the number of the led pin
/**********************************/
void setup()
{
  pinMode(keyPin,INPUT);//initialize the key pin as input 
  pinMode(ledPin,OUTPUT);//initialize the led pin as output
}
/**********************************/
void loop()
{
  
  boolean Value=digitalRead(keyPin);//read the state of the key value
  //and check if the kye is pressed
  //if it is,the state is HIGH 
  if(Value ==HIGH )
  {
    digitalWrite(ledPin,LOW);//turn on the led
  }
  else
  {
    digitalWrite(ledPin,HIGH);//turn off the led
  }
}
/************************************/

板子上的led连的是13I/O口,开关连接7口 按下开关leo获得高电平亮

在这里插入图片描述
在这里插入图片描述
digitalRead()
从指定的数字引脚(HIGH或LOW)读取值。
解释

digitalWrite()
将HIGH或LOW值写入数字引脚。
如果将引脚配置为OUTPUTwith pinMode(),则其电压将设置为相应的值:5V(在3.3V板上为3.3V)HIGH,0V(接地)LOW。
如果该引脚配置为INPUT,digitalWrite()将启用(HIGH)或禁用(LOW)输入引脚上的内部上拉电阻。建议将设置为pinMode(),INPUT_PULLUP以启用内部上拉电阻。有关更多信息,请参见“ 数字引脚”教程。
如果您未将设置pinMode()为OUTPUT,而是将LED连接到引脚,则在调用时digitalWrite(HIGH),LED可能会变暗。如果未明确设置pinMode(),digitalWrite()将启用内部上拉电阻,其作用类似于大限流电阻。
解释


倾斜式开关

const int sigPin =7;
const int ledPin =13;
boolean sigState =0;

void setup()
{
    pinMode(ledPin,OUTPUT);
    pinMode(sigPin,INPUT);
    Serial.begin(9600);
}

void loop()
{
  sigState =digitalRead(sigPin);
  Serial.println(sigState);

  if(sigState==HIGH)
  {
    //trun LED off
    digitalWrite(ledPin,LOW); 
  }
  else
  {
    //turn LED on
    digitalWrite(ledPin,HIGH);
  }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

倾斜式开关:在倾斜开关中球以不同的倾斜角度以制造触发器电路原理。倾斜开关模块使用双向传导的球形倾斜开关。当它向任一侧倾斜时,只要倾斜和力满足条件,开关就会通电;输出低电平信号。


震动开关

int vibswPin =8;
int ledPin =13;
int val =0;
void setup()
{
  pinMode(vibswPin,INPUT);
  pinMode(ledPin,OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  val = digitalRead(vibswPin);
  Serial.println(val);
  if(val == LOW)
  {
    //trun ON the led
    digitalWrite(ledPin,HIGH);
    delay(500);
  }
  else
  {
    //trun OFF the led
    digitalWrite(ledPin,LOW);
  }
}

在这里插入图片描述
在这里插入图片描述
从串口监视里可以看到当传感器受到震动时,收到高电平信号。
在这里插入图片描述


干簧管传感器

/*****************************************************
 * name:Reed Switch
 * function:use a magnet to approach the reed switch, and the LED on the reed switch module and that on the Arduino board light up. 
 * Move the magnet farther and the LED will go out.
 **************************************************/

const int digitalInPin = 7;// reed switch attach to pin7
const int ledPin = 13;// pin13 built-in led

void setup()
{
  pinMode(digitalInPin,INPUT);// set digitalInPin as INPUT
  pinMode(ledPin,OUTPUT); // set ledPin as OUTPUT
}

void loop()
{
  boolean stat = digitalRead(digitalInPin);//read the value of pin7 to stat
  if(stat == HIGH)// if it it HIGH
  { 
    digitalWrite(ledPin,LOW);// then turn off the led
  }
  else //else
  {
    digitalWrite(ledPin,HIGH); // turn on the led
  } 
}

在这里插入图片描述
干簧管传感器是一种通过磁信号实现控制的线路开关组件,它能感应磁铁的存在。这里的“开关”是指干簧管,它是一种结构简单,体积小,控制方便的接触式无源电子开关元件,干簧管壳体一般为密封玻璃管,配备弹性簧片电镀,并填充惰性气体,通常玻璃管中由特殊材料制成的两个簧片是分开的,但当磁性物质靠近玻璃管时,玻璃管中的两个簧片被磁化吸引其他的在磁场线的作用下接触,这样两个簧片就会拉在一起。
在外部磁力消失后,两个簧片由于具有相同的磁性而相互分离,因此电路也断开。因此作为通过在磁信号控制的线路开关部件,干簧管可以作传感器来计数,限制位置等,广泛用于通讯设备。
在这里插入图片描述


U型光电传感器


/**********************************/
const int photoPin = 7; //the number of the key pin
const int ledPin = 13;//the number of the led pin
/**********************************/
void setup()
{
  pinMode(photoPin,INPUT); 
  pinMode(ledPin,OUTPUT);//initialize the led pin as output
}
/**********************************/
void loop()
{
  
  boolean Value=digitalRead(photoPin);
 
  //if it is,the state is HIGH 
  if(Value ==HIGH )
  {
    digitalWrite(ledPin,LOW);//turn on the led
  }
  else
  {
    digitalWrite(ledPin,HIGH);//turn off the led
  }
}

在这里插入图片描述
U型光电传感器由两部分组成:发射器和接收器。发射器(例如LED,激光器)发出的光,然后光线进入接收器。如果发射器和接受器之间的光束被障碍物挡住,接收器即使在一瞬间也将检测不到射光,并且输出电平将会改变。

在这里插入图片描述
在这里插入图片描述


PCF8591模数转换器

/***********************************************
name:Analog-Digital Converter -PCF8591
function:the indicator light D2 on the  PCF8591 gradually lights up and goes out alternately.
The same happens to the LED attached to pin 13 of the Arduino Uno board 
***************************************************/

#include "Wire.h" //Wire库
#define PCF8591 (0x90 >> 1) // I2C总线的地址
void setup()
{
 Wire.begin();
 Serial.begin(9600);
 Serial.println(sin(PI/2));
 
}
void loop()
{
 for (int i=0; i<256; i++)
 {
 Wire.beginTransmission(PCF8591); // 唤醒 PCF8591
 Wire.write(0x40); // control byte - turn on DAC (binary 01000000),analog OUTPUT DAC转换
 Wire.write(i); // value to send to DAC
 Wire.endTransmission(); // end tranmission
 delay(10*sin(i/256.0*90/180*PI));
 Serial.println(100*sin(i/256.0*90/180*PI));
 }

 for (int i=255; i>=0; --i)
 {
 Wire.beginTransmission(PCF8591); // wake up PCF8591
 Wire.write(0x40); // control byte - turn on DAC (binary 1000000)
 Wire.write(i); // value to send to DAC
 Wire.endTransmission(); // end tranmission
 delay(10*sin(i/256.0*90/180*PI));
 Serial.println(100*sin(i/256.0*90/180*PI));
 }
}

在这里插入图片描述
PCF8591是一种具有I2C总线接口的A/D转换芯片。在与CPU的信息传输过程中仅靠时钟线SCL和数据线SDA就可以实现。
PCF8591是具有I2C总线接口的8位A/D及D/A转换器。有4路A/D转换输入,1路D/A模拟输出。这就是说,它既可以作A/D转换也可以作D/A转换。A/D转换为逐次比较型。
在这里插入图片描述
在这里插入图片描述


雨滴探测传感器

/******************************************************
name:Raindrop Detection
function:drop some water onto the sensor,
When the quantities of the raindrops exceeds the threshold,
the LED on the raindrop sensor module and that hooked up with pin 13 of the Arduino Uno board light up
*******************************************************/

const int analogPin=A0; //the AO of the module attach to A0
const int digitalPin=7;  //D0 attach to pin7
const int ledPin=13;  //pin 13 built-in led
int Astate=0; //store the value of A0
boolean Dstate=0;  //store the value of D0

void setup() 
{
 pinMode(ledPin,OUTPUT); //set the ledPin as OUTPUT 
 pinMode(digitalPin,INPUT);  //set digitalPin as INPUT
 Serial.begin(9600);  //initialize the serial monitor
}

void loop() 
{
  Astate=analogRead(analogPin);  //read the value of A0
  Serial.print("A0: ");
  Serial.println(Astate);  //print the value in the serial monitor
  Dstate=digitalRead(digitalPin);  //read the value of D0
  Serial.print("D0: ");
  Serial.println(Dstate);
  if(Dstate==HIGH)  
  {
   digitalWrite(ledPin,LOW);
  }
  else //if the value of D0 is LOW
  {
  digitalWrite(ledPin,HIGH); //turn on the led
  }
}

在这里插入图片描述
没有水滴时
在这里插入图片描述
有水滴时
在这里插入图片描述
arduino板上的13引脚led和传感器上的led灯都亮起。
水越多,AO处值越低,当水滴数量超过设定的阈值时,7引脚由高电平变低电平,相应的LED将亮起。


PS2操纵杆

/*********************************************
 * name:Joystick PS2
 * function:push the joystick and the coordinates of X and Y axes displayed on Serial Monitor will change accordingly; 
 * press down the joystick, and the coordinate of Z=0 will also be displayed.
 connection:
 Joystick PS2                 Arduino Uno R3
 GND	                      GND
 VCC	                      5V
 SW	                      7
 x	                      A0
 y	                      A1
 ***********************************************/

const int xPin = A0;     //X attach to A0
const int yPin = A1;     //Y attach to A1
const int btPin = 7;     //Bt attach to digital 7

void setup()
{
  pinMode(btPin,INPUT); //set btpin as INPUT
  digitalWrite(btPin, HIGH); //and HIGH
  Serial.begin(9600); //initialize serial
}

void loop()
{
  Serial.print("X: ");//print "X: "
  Serial.print(analogRead(xPin),DEC); //read the value of A0 and print it in decimal
  Serial.print("\tY: "); //print "Y: "
  Serial.print(analogRead(yPin),DEC); //read the value of A1 and print it in decimal
  Serial.print("\tZ: "); //print "Z: "
  Serial.println(digitalRead(btPin)); read the value of pin7 and print it
  delay(100);//delay 100ms
}

在这里插入图片描述
打开串口监视器移动摇杆可以看到x,y,z的位置变化。
在这里插入图片描述
在这里插入图片描述
该模块具有两个模拟输出(对应于X和Y坐标)和一个数字输出,表示是否在Z轴上按下。


电位器

模拟电位器是模拟电子元器件。数字电位器仅指开/关,高/低电平两种状态,即0或1,而模拟电位器支持1至1000之间的模拟信号。信号值随时间变化而不是保持一个确切的数字。模拟信号包括光强度,湿度,温度等。
在本实验中,将电位器模块的引脚SIG连接到Arduino Uno电路板的AO,检查AO的值。然后使用该值来控制与Uno板的针脚13连接的LED闪烁时间间隔。旋转电位器的轴,LED闪烁间隔将增加或减少。


const int analogPin = A0;//the analog input pin attach to
const int ledPin =13;//the led attach to
int inputValue = 0;//variable to store the value coming from sensor
/******************************************/
void setup()
{
  pinMode(ledPin,OUTPUT);
  Serial.begin(9600);
}
/******************************************/
void loop()
{
  inputValue = analogRead(analogPin);//read the value from the sensor
  //Serial.println(inputValue);
  digitalWrite(ledPin,HIGH);
  delay(inputValue);
  digitalWrite(ledPin,LOW);
  delay(inputValue);
}
/*******************************************/

在这里插入图片描述
在这里插入图片描述


模拟霍尔传感器

模拟霍尔传感器由霍尔元件,线性放大器和射极跟随器组成,输出模拟值。如果在模拟霍尔传感器上增加比较器就可以组成数字开关霍尔传感器和模拟霍尔传感器一体,他可以输出模拟值和数字信号。
当传感器靠近磁体,引脚A0的值将改变。当该值超过电位器设定的阈值之前,D0將输出低电平,相应的LED亮起。


//Analog Hall Sensor
//using an LM393 Low Power Low Offset Voltage Dual Comparator
/*******************************
 * Analog Hall Sensor     Uno R3
 * A0                     A0
 * D0                     7
 * VCC                    5V
 * GND                    GND
 *******************************/

const int ledPin = 13;//the led attach to pin13
int sensorPin = A0;    // select the input pin for the potentiometer
int digitalPin=7;   //D0 attach to pin7

int sensorValue = 0;// variable to store the value coming from A0
boolean digitalValue=0;// variable to store the value coming from pin7

void setup() 
{
  pinMode(digitalPin,INPUT);//set the state of D0 as INPUT
  pinMode(ledPin,OUTPUT);//set the state of pin13 as OUTPUT
  Serial.begin(9600); // initialize serial communications at 9600 bps

}

void loop() 
{ 
  sensorValue = analogRead(sensorPin);  //read the value of A0
  digitalValue=digitalRead(digitalPin);  //read the value of D0
  Serial.print("Sensor Value "); // print label to serial monitor 
  Serial.println(sensorValue);  //print the value of A0
  Serial.print("Digital Value "); // print label to serial monitor 
  Serial.println(digitalValue);  //print the value of D0 in the serial
  if( digitalValue==HIGH )//if the value of D0 is HIGH
  {
    digitalWrite(ledPin,LOW);//turn off the led
  }
  if( digitalValue==LOW)//else
  {
    digitalWrite(ledPin,HIGH);//turn on the led
  }
  delay(1000);//delay 200ms
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


温度传感器


//Analog Temperature Sensor
const int digitalPin = 7;     // Analog Temperature Sensor pin D0 to pin7
int analogPin = A0;           // Analog Temperature Sensor pin A0 to pin A0
const int ledPin =  13;      // pin 13 built-in LED light

// variables will change:
boolean Dstate = 0;          // variable for reading status of D0
int Astate = 0;            // variable for reading status of A0
void setup() 
{
  pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:     
  pinMode(digitalPin, INPUT);  // initialize Analog Temperature Sensor D0 pin as an input
  Serial.begin(9600); // initialize serial communications at 9600 bps 

}

void loop()
{
  Astate = analogRead(analogPin);  // read Analog Temperature Sensor A0 value (set point)
  Dstate = digitalRead(digitalPin);  // read state of Analog Temperature Sensor D0
  Serial.print("D0: ");
  Serial.println(Dstate);//print the value of D0
  Serial.print("A0:");
  Serial.println(Astate);//print the value of A0
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (Dstate == HIGH)    // check if Analog Temperature Sensor D0 is HIGH
  {     
    // turn off  LED :    
    digitalWrite(ledPin, LOW);  
  } 
  else 
  {
    // turn  on LED :
    digitalWrite(ledPin, HIGH); 
  }
  delay(1000);                // controls speed of Analog Temperature Sensor and Serial Monitor display rate
}


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
通过调节传感器上的电位器来设定一个阈值。


声音传感器

/***************************************************
name:Rotary Encoder
function:you can see the angular displacement of the rotary encoder printed on Serial Monitor.
When the rotary encoder rotates clockwise, the angular displacement increases; when it does counterclockwise, the value decreases.
Press the switch on the rotary encoder, the value will return to zero.
********************************************************/

const int ledPin = 13; //pin13 built-in led
const int soundPin = A0;  //sound sensor attach to A0

void setup()
{
  pinMode(ledPin,OUTPUT);//set ledPin as OUTPUT
  Serial.begin(9600); //initialize the serial communication as 9600 bps
}

void loop()
{
  int value = analogRead(soundPin); //read the value of sound sensor
  Serial.println(value);//print it
  if(value > 600)//if the vallue of sound sensor is greater than 600
  {
    digitalWrite(ledPin,HIGH); //turn on the led
    delay(200); //delay 200ms
  }
  else //elae 
  {
    digitalWrite(ledPin,LOW); //turn off the led
  }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


光敏传感器

/*****************************************************
 *  湖南创乐博智能科技有限公司
 * name:Photoswitch
 * function: hold the photoresistor with your fingers and check the value at A0 on Serial Monitor. 
 * You can see when the resistance is up to 400ohm,
 * the normally open contact of the relay is closed and the LED connected to pin 13 on the Arduino Uno board lights up;
 * or else, it keeps out.
 ************************************************/
const int photocellPin = A0; //photoresistor module attach to A0
const int ledPin = 13;      //pin 13 built-in led
const int relayPin=8;      //relay module attach to digital 8
int outputValue = 0;
/*************************************************/
void setup()
{
  pinMode(relayPin,OUTPUT); //set relayPin as OUTPUT
  pinMode(ledPin,OUTPUT); //set ledPin as OUTPUT
  Serial.begin(9600); //initialize the serial communication as 9600bps
}
/*************************************************/
void loop()
{
  outputValue = analogRead(photocellPin);//read the value of photoresistor
  Serial.println(outputValue); //print it in serial monitor
  if(outputValue <= 200) //if the value of photoreisitor is greater than 400
  {
    digitalWrite(ledPin,HIGH); //turn on the led 
    digitalWrite(relayPin,LOW); //relay connected
  }
  else //else
  {
    digitalWrite(ledPin,LOW); //turn off the led
    digitalWrite(relayPin,HIGH); //and relay disconnected
  }
  delay(1000); //delay 1s
}
/*************************************************/

在这里插入图片描述
当用手电照射光敏电阻时,电阻大于200欧,继电器的常开触点闭合,Arduino Uno 电路板上的13号引脚LED点亮。
在这里插入图片描述
在这里插入图片描述


摇杆控制OLED屏幕

/*
   OLED_JoyStick
   摇杆控制OLED移动显示
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET     4
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
#define pinX  A0
#define pinY  A1

//定义圆心和半径变量
int xCircle = 0;
int ycircle = 0;
int radius = 4;

void setup()
{
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.setTextColor(WHITE);//开像素点发光
  display.clearDisplay();//清屏
}

void loop()
{
  xCircle = map(analogRead(pinX), 1023, 0, radius, 128 - radius); //将X轴获取的AD值映射到oled的X显示方向
  ycircle = map(analogRead(pinY), 1023, 0, radius, 64 - radius); //将Y轴获取的AD值映射到oled的Y显示方向

  display.drawRect(0, 0, 128, 64, 1);//画矩形
  display.drawCircle(xCircle, ycircle , radius, 1); //画圆
  display.display();//开显示
  display.clearDisplay();//清屏
}

在这里插入图片描述


步进电机

/****************************************
* name:Stepper Motor
* function:you should see the rocker arm of the stepper motor spin clockwise and counterclockwise alternately. 
* Stepper Motor Arduino Uno R3
* IN1 11
* IN2 10
* IN3 9
* IN4 8
*****************************************/
const int IN1=11;
const int IN2=10;
const int IN3=9;
const int IN4=8;
//正转顺序
const char tab1[] =
{
  0x01, 0x03, 0x02, 0x06, 0x04, 0x0c, 0x08, 0x09
};
//反转的顺序
const char tab2[] =
{
  0x01, 0x09, 0x08, 0x0c, 0x04, 0x06, 0x02, 0x03
};
void setup() 
{
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
}
void loop()
{
  // put your main code here, to run repeatedly:
  ctlStepMotor(360, 1);
  StepMotorStop();
  delay(1000);
  ctlStepMotor(-360, 1);
  StepMotorStop();
  delay(1000);
}
void ctlStepMotor(int angle, char speeds )
{
  for (int j = 0; j < abs(angle) ; j++)
  {
    if (angle > 0)
    {
      for (int i = 0; i < 8; i++)
      {
        digitalWrite(IN1, ((tab1[i] & 0x01) == 0x01 ? true : false));
        digitalWrite(IN2, ((tab1[i] & 0x02) == 0x02 ? true : false));
        digitalWrite(IN3, ((tab1[i] & 0x04) == 0x04 ? true : false));
        digitalWrite(IN4, ((tab1[i] & 0x08) == 0x08 ? true : false));
        delay(speeds);
      }
    }
    else
    {
      for (int i = 0; i < 8 ; i++)
      {
        digitalWrite(IN1, ((tab2[i] & 0x01) == 0x01 ? true : false));
        digitalWrite(IN2, ((tab2[i] & 0x02) == 0x02 ? true : false));
        digitalWrite(IN3, ((tab2[i] & 0x04) == 0x04 ? true : false));
        digitalWrite(IN4, ((tab2[i] & 0x08) == 0x08 ? true : false));
        delay(speeds);
      }
    }
  }
}
void StepMotorStop()
{
  digitalWrite(IN1, 0);
  digitalWrite(IN2, 0);
  digitalWrite(IN3, 0);
  digitalWrite(IN4, 0);
}

在这里插入图片描述


LCD屏显示文字滚动


// include the library code
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
/**********************************************************/
char array1[]=" Arduino                  ";  //the string to print on the LCD
char array2[]="hello, world!             ";  //the string to print on the LCD
int tim = 500;  //the value of delay time
// initialize the library with the numbers of the interface pins
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27  0x3F for a 16 chars and 2 line display
/*********************************************************/
void setup()
{
  lcd.init();  //initialize the lcd
  lcd.backlight();  //open the backlight 
}
/*********************************************************/
void loop() 
{
    lcd.setCursor(15,0);  // set the cursor to column 15, line 0
    for (int positionCounter1 = 0; positionCounter1 < 26; positionCounter1++)
    {
      lcd.scrollDisplayLeft();  //Scrolls the contents of the display one space to the left.
      lcd.print(array1[positionCounter1]);  // Print a message to the LCD.
      delay(tim);  //wait for 250 microseconds
    }
    lcd.clear();  //Clears the LCD screen and positions the cursor in the upper-left corner.
    lcd.setCursor(15,1);  // set the cursor to column 15, line 1
    for (int positionCounter = 0; positionCounter < 26; positionCounter++)
    {
      lcd.scrollDisplayLeft();  //Scrolls the contents of the display one space to the left.
      lcd.print(array2[positionCounter]);  // Print a message to the LCD.
      delay(tim);  //wait for 250 microseconds
    }
    lcd.clear();  //Clears the LCD screen and positions the cursor in the upper-left corner.
}
/************************************************************/

在这里插入图片描述


超声波测距传感器

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

// include the library code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <NewPing.h>

LiquidCrystal_I2C lcd(0x27,16,2);//0x27   0x3F

#define TRIGGER_PIN  2  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     3  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  lcd.init(); 
  lcd.backlight();
}

void loop() {
  delay(100);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  lcd.setCursor(0, 0);
  lcd.print("Distance:");
  lcd.setCursor(0, 1);
  lcd.print("             ");
  lcd.setCursor(9, 1);
  lcd.print(uS / US_ROUNDTRIP_CM);
  lcd.setCursor(12, 1);
  lcd.print("cm");
}

在这里插入图片描述
在这里插入图片描述


温度传感器

/****************************************************
name:Digital Temperature Sensor-ds18b20
function:you can see the value of current temperature displayed on the LCD.
****************************************************/
/****************************************/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 and 0x3F for a 16 chars and 2 line display
#define ONE_WIRE_BUS 7 //ds18b20 module attach to pin7
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  sensors.begin(); // initialize the bus
  lcd.init(); //initialize the lcd
  lcd.backlight(); //turn on the backlight
}
void loop(void)
{ 
  // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  //Serial.print("Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  lcd.setCursor(0, 0);
  lcd.print("TemC: "); //print "Tem: " on lcd1602
  lcd.print(sensors.getTempCByIndex(0));//print the temperature on lcd1602
  //Serial.print("Tem: ");
  //Serial.print(sensors.getTempCByIndex(0));
  //Serial.println(" C");
  lcd.print(char(223));//print the unit" ℃ "
  lcd.print("C");
  lcd.setCursor(0, 1);
  lcd.print("TemF: ");
  lcd.print(1.8*sensors.getTempCByIndex(0) + 32.0);//print the temperature on lcd1602
  lcd.print(char(223));//print the unit" ℉ "
  lcd.print(" F");
  //Serial.print("Tem: ");
  //Serial.print(1.8*sensors.getTempCByIndex(0) + 32.0);
  //Serial.println(" F");
  //Serial.println("");
  //Serial.print("Temperature for the device 1 (index 0) is: ");
  //Serial.println(sensors.getTempCByIndex(0));  //print the temperature on serial monitor
}

在这里插入图片描述
在这里插入图片描述


直流电机风扇

//Small Fan
/****************************************************************
 * As explained above, the amount of times you press the button should change the rotation speed of the fan. 
 * Pressing it once will cause it to rotate slowly,
 * while pressing it three times will cause it to rotate quickly, and pressing it four times will cause it to stop.
 ****************************************************************/

// constants won't change. They're used here to 
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin
const int motorIn1 = 9;
const int motorIn2 = 10;
int stat = 0; 
#define rank1 150
#define rank2 200
#define rank3 250
// Variables will change:
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
/******************************************************************************/
void setup() 
{
  //set theled,motors as OUTPUT,button as INPUT
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  pinMode(motorIn1,OUTPUT);
  pinMode(motorIn2,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState)// If the button state is different from last time 
  {   
    lastDebounceTime = millis();// reset the debouncing timer
  } 
  if ((millis() - lastDebounceTime) > debounceDelay) 
  { 
    if (reading != buttonState) 
    {
      buttonState = reading; // Store the state of button in buttonState 
      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH)
      {
        digitalWrite(ledPin, HIGH); //turn on the LED
        stat = stat + 1;
        if(stat >= 4)// When stat>=4, set it as 0. 
        {
          stat = 0;
        }
      }
      else
        digitalWrite(ledPin, LOW);
    }
  } 
  switch(stat)
  {
  case 1:
    clockwise(rank1);// When stat=1, set the rotate speed of the motor as rank1=150
    break;
  case 2:
    clockwise(rank2);// When stat=2, set the rotate speed of the motor as rank1=200
    break;
  case 3:
    clockwise(rank3);// When stat=3, set the rotate speed of the motor as rank1=250
    break;
  default:
    clockwise(0);// else, set the rotate speed of the motor as rank1=150
  }
  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}
/***********************************************************/
void clockwise(int Speed)//
{
  analogWrite(motorIn1,0);
  analogWrite(motorIn2,Speed);
}
/***********************************************************/

在这里插入图片描述
在这里插入图片描述


DS1302时钟模块

/*****************************************************
 * 湖南创乐博智能科技有限公司
 * name:Real-time Clock Module 
 * function:you can see the current date and time displayed on the I2C LCD1602.
 ******************************************************/

//include the libraries
#include <stdio.h>
#include <string.h>
#include <DS1302.h>
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 and0x3F for a 16 chars and 2 line display

uint8_t RST_PIN   = 5;  //RST pin attach to
uint8_t SDA_PIN   = 6;  //IO pin attach to
uint8_t SCL_PIN = 7;  //clk Pin attach to
/* Create buffers */
char buf[50];
char day[10];

String comdata = "";
int numdata[7] ={ 0}, j = 0, mark = 0;
/* Create a DS1302 object */
DS1302 rtc(RST_PIN, SDA_PIN, SCL_PIN);//create a variable type of DS1302


void print_time()
{
  /* Get the current time and date from the chip */
  Time t = rtc.time();
  /* Name the day of the week */
  memset(day, 0, sizeof(day));
  switch (t.day)
  {
  case 1: 
    strcpy(day, "Sun"); 
    break;
  case 2: 
    strcpy(day, "Mon"); 
    break;
  case 3: 
    strcpy(day, "Tue"); 
    break;
  case 4: 
    strcpy(day, "Wed"); 
    break;
  case 5: 
    strcpy(day, "Thu"); 
    break;
  case 6: 
    strcpy(day, "Fri"); 
    break;
  case 7: 
    strcpy(day, "Sat"); 
    break;
  }
  /* Format the time and date and insert into the temporary buffer */
  snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec);
  /* Print the formatted string to serial so we can see the time */
  Serial.println(buf);
  lcd.setCursor(2,0);
  lcd.print(t.yr);
  lcd.print("-");
  lcd.print(t.mon/10);
  lcd.print(t.mon%10);
  lcd.print("-");
  lcd.print(t.date/10);
  lcd.print(t.date%10);
  lcd.print(" ");
  lcd.print(day);
  lcd.setCursor(4,1);
  lcd.print(t.hr);
  lcd.print(":");
  lcd.print(t.min/10);
  lcd.print(t.min%10);
  lcd.print(":");
  lcd.print(t.sec/10);
  lcd.print(t.sec%10);
}


void setup()
{
  Serial.begin(9600);
  rtc.write_protect(false);
  rtc.halt(false);
  lcd.init();  //initialize the lcd
  lcd.backlight();  //open the backlight 
  Time t(2018, 6, 23, 18, 41, 50, 7);//initialize the time
  /* Set the time and date on the chip */
  rtc.time(t);
}

void loop()
{

  /*add the data to comdata when the serial has data  */
  while (Serial.available() > 0)
  {
    comdata += char(Serial.read());
    delay(2);
    mark = 1;
  }
  /* Use a comma to separate the strings of comdata,
   and then convert the results into numbers to be saved in the array numdata[] */
  if(mark == 1)
  {
    Serial.print("You inputed : ");
    Serial.println(comdata);
    for(int i = 0; i < comdata.length() ; i++)
    {
      if(comdata[i] == ',' || comdata[i] == 0x10 || comdata[i] == 0x13)
      {
        j++;
      }
      else
      {
        numdata[j] = numdata[j] * 10 + (comdata[i] - '0');
      }
    }
    /* The converted numdata add up to the time format, then write to DS1302*/
    Time t(numdata[0], numdata[1], numdata[2], numdata[3], numdata[4], numdata[5], numdata[6]);
    rtc.time(t);
    mark = 0;
    j=0;
    /* clear comdata ,in order to wait for the next input  */
    comdata = String("");
    /* clear numdata */
    for(int i = 0; i < 7 ; i++) numdata[i]=0;
  }

  /* print the current time */
  print_time();
  delay(1000);
}

在这里插入图片描述
在这里插入图片描述


  • 9
    点赞
  • 108
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值