文章目录
嵌入式实验代码
- 大四嵌入式实验代码
2-Blink_an_LED
void setup(){
pinMode(13, OUTPUT);
}
void loop(){
digitalWrite(13, HIGH); // Turn on the LED
delay(1000); // Wait for one second
digitalWrite(13, LOW); // Turn off the LED
delay(1000); // Wait for one second
}
3-Push_Button
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
4-Potentiometer
// the setup routine runs once when you press reset:\
void setup() {
// initialize serial communication at 9600 bits per second:
pinMode(13, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
if(sensorValue > 400){
digitalWrite(13, HIGH);
}else{
digitalWrite(13, LOW);
}
delay(1); // delay in between reads for stability
}
5-Fade_an_LED
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() { // declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() { // set the brightness of pin 9:
analogWrite(led, brightness); // change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
6-Scrolling_LED
int timer = 100; // The higher the number, the slower the timing.
void setup() { // use a for loop to initialize each pin as an output:
for (int thisPin = 2; thisPin < 8; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 8; thisPin++) { // turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer); // turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) { // turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer); // turn the pin off:
digitalWrite(thisPin, LOW);
}
}
7-Bar_Graph
// these constants won't change:
const int analogPin = A0; // the pin that the potentiometer is attached to
const int ledCount = 10; // the number of LEDs in the bar graph
int ledPins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
// an array of pin numbers to which LEDs are attached
void setup() {
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
// read the potentiometer:
int sensorReading = analogRead(analogPin);
// map the result to a range from 0 to the number of LEDs:
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
// loop over the LED array:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// if the array element's index is less than ledLevel,
// turn the pin for this element on:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}
// turn off all pins higher than the ledLevel:
else {
digitalWrite(ledPins[thisLed], LOW);
}
}
}
8-Multiple_LEDs
int ledPins[] = {2,3,4,5,6,7,8,9}; // Defines an array to store the pin numbers of the 8 LEDs.
// An array is like a list variable that can store multiple numbers.
// Arrays are referenced or "indexed" with a number in the brackets [ ]. See the examples in
// the pinMode() functions below.
void setup() {
// setup all 8 pins as OUTPUT - notice that the list is "indexed" with a base of 0.
pinMode(ledPins[0],OUTPUT); // ledPins[0] = 2
pinMode(ledPins[1],OUTPUT); // ledPins[1] = 3
pinMode(ledPins[2],OUTPUT); // ledPins[2] = 4
pinMode(ledPins[3],OUTPUT); // ledPins[3] = 5
pinMode(ledPins[4],OUTPUT); // ledPins[4] = 6
pinMode(ledPins[5],OUTPUT); // ledPins[5] = 7
pinMode(ledPins[6],OUTPUT); // ledPins[6] = 8
pinMode(ledPins[7],OUTPUT); // ledPins[7] = 9
}
void loop(){
// This loop() calls functions that we've written further below.
// We've disabled some of these by commenting them out (putting
// "//" in front of them). To try different LED displays, remove
// the "//" in front of the ones you'd like to run, and add "//"
// in front of those you don't to comment out (and disable) those
// lines.
//oneAfterAnother(); // Light up all the LEDs in turn
//oneOnAtATime(); // Turn on one LED at a time
//pingPong(); // Same as oneOnAtATime() but change direction once LED reaches edge
//marquee(); // Chase lights like you see on theater signs
randomLED(); // Blink LEDs randomly
}
/******************************************************************
* oneAfterAnother()
*
* This function turns all the LEDs on, pauses, and then turns all
* the LEDS off. The function takes advantage of for() loops and
* the array to do this with minimal typing.
/*****************************************************************/
void oneAfterAnother()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
// make this smaller for faster switching
// Turn all the LEDs on:
for(index = 0; index <= 7; index = ++index) // step through index from 0 to 7
{
digitalWrite(ledPins[index], HIGH);
delay(delayTime);
}
// Turn all the LEDs off:
for(index = 7; index >= 0; index = --index) // step through index from 7 to 0
{
digitalWrite(ledPins[index], LOW);
delay(delayTime);
}
}
/*****************************************************************
* oneOnAtATime()
*
* This function will step through the LEDs, lighting only one at
* a time. It turns each LED ON and then OFF before going to the
* next LED.
/****************************************************************/
void oneOnAtATime()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
// make this smaller for faster switching
for(index = 0; index <= 7; index = ++index) // step through the LEDs, from 0 to 7
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}}
/*****************************************************************
* pingPong()
*
* This function will step through the LEDs, lighting one at at
* time in both directions. There is no delay between the LED off
* and turning on the next LED. This creates a smooth pattern for
* the LED pattern.
/****************************************************************/
void pingPong()
{
int index;
int delayTime = 100; // milliseconds to pause between LEDs
for(index = 0; index <= 7; index = ++index) // step through the LEDs, from 0 to 7
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
for(index = 7; index >= 0; index = --index) // step through the LEDs, from 7 to 0
{
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}}
/*****************************************************************
* marquee()
*
* This function will mimic "chase lights" like those around
* theater signs.
/****************************************************************/
void marquee()
{
int index;
int delayTime = 200; // milliseconds to pause between LEDs
// Step through the first four LEDs
// (We'll light up one in the lower 4 and one in the upper 4)
for(index = 0; index <= 3; index++) // Step from 0 to 3
{
digitalWrite(ledPins[index], HIGH); // Turn a LED on
digitalWrite(ledPins[index+4], HIGH); // Skip four, and turn that LED on
delay(delayTime); // Pause to slow down the sequence
digitalWrite(ledPins[index], LOW); // Turn the LED off
digitalWrite(ledPins[index+4], LOW); // Skip four, and turn that LED off
}}
/*****************************************************************
* randomLED()
*
* This function will turn on random LEDs. Can you modify it so it
* also lights them for random times?
/****************************************************************/
void randomLED()
{
int index;
int delayTime;
index = random(8); // pick a random number between 0 and 7
delayTime = 100;
digitalWrite(ledPins[index], HIGH); // turn LED on
delay(delayTime); // pause to slow down
digitalWrite(ledPins[index], LOW); // turn LED off
}
9-RGB_LED
const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;
const int DISPLAY_TIME = 1000; // used in mainColors() to determine the
// length of time each color is displayed.
void setup() //Configure the Arduino pins to be outputs to drive the LEDs
{
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
void loop()
{
//mainColors(); // Red, Green, Blue, Yellow, Cyan, Purple, White
showSpectrum(); // Gradual fade from Red to Green to Blue to Red
}
/******************************************************************
* void mainColors()
* This function displays the eight "main" colors that the RGB LED
* can produce. If you'd like to use one of these colors in your
* own sketch, you can copy and paste that section into your code.
/*****************************************************************/
void mainColors()
{
// all LEDs off
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
delay(DISPLAY_TIME);
// Red
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, LOW);
delay(DISPLAY_TIME);
// Green
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);
delay(DISPLAY_TIME);
// Blue
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);
delay(DISPLAY_TIME);
// Yellow (Red and Green)
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, LOW);
delay(DISPLAY_TIME);
// Cyan (Green and Blue)
digitalWrite(RED_PIN, LOW);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);
delay(DISPLAY_TIME);
// Purple (Red and Blue)
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, LOW);
digitalWrite(BLUE_PIN, HIGH);
delay(DISPLAY_TIME);
// White (turn all the LEDs on)
digitalWrite(RED_PIN, HIGH);
digitalWrite(GREEN_PIN, HIGH);
digitalWrite(BLUE_PIN, HIGH);
delay(DISPLAY_TIME);
}
/******************************************************************
* void showSpectrum()
*
* Steps through all the colors of the RGB LED, displaying a rainbow.
* showSpectrum() calls a function RGB(int color) that translates a number
* from 0 to 767 where 0 = all RED, 767 = all RED
*
* Breaking down tasks down into individual functions like this
* makes your code easier to follow, and it allows.
* parts of your code to be re-used.
/*****************************************************************/
void showSpectrum() {
for (int x = 0; x <= 767; x++)
{
RGB(x); // Increment x and call RGB() to progress through colors.
delay(10); // Delay for 10 ms (1/100th of a second) - to help the "smoothing"
}}
/******************************************************************
* void RGB(int color)
*
* RGB(###) displays a single color on the RGB LED.
* Call RGB(###) with the number of a color you want
* to display. For example, RGB(0) displays pure RED, RGB(255)
* displays pure green.
*
* This function translates a number between 0 and 767 into a
* specific color on the RGB LED. If you have this number count
* through the whole range (0 to 767), the LED will smoothly
* change color through the entire spectrum.
*
* The "base" numbers are:
* 0 = pure red
* 255 = pure green
* 511 = pure blue
* 767 = pure red (again)
*
* Numbers between the above colors will create blends. For
* example, 640 is midway between 512 (pure blue) and 767
* (pure red). It will give you a 50/50 mix of blue and red,
* resulting in purple.
/*****************************************************************/
void RGB(int color)
{
int redIntensity;
int greenIntensity;
int blueIntensity;
color = constrain(color, 0, 767); // constrain the input value to a range of values from 0 to 767
// if statement breaks down the "color" into three ranges:
if (color <= 255) // RANGE 1 (0 - 255) - red to green
{
redIntensity = 255 - color; // red goes from on to off
greenIntensity = color; // green goes from off to on
blueIntensity = 0; // blue is always off
}
else if (color <= 511) // RANGE 2 (256 - 511) - green to blue
{
redIntensity = 0; // red is always off
greenIntensity = 511 - color; // green on to off
blueIntensity = color - 256; // blue off to on
}
else // RANGE 3 ( >= 512)- blue to red
{
redIntensity = color - 512; // red off to on
greenIntensity = 0; // green is always off
blueIntensity = 767 - color; // blue on to off
}
// "send" intensity values to the Red, Green, Blue Pins using analogWrite()
analogWrite(RED_PIN, redIntensity);
analogWrite(GREEN_PIN, greenIntensity);
analogWrite(BLUE_PIN, blueIntensity);
}
10-Photoresistor
const int sensorPin = A0;
const int ledPin = 9;
// We'll also set up some global variables for the light level:
int lightLevel;
int calibratedlightLevel; // used to store the scaled / calibrated lightLevel
int maxThreshold = 0; // used for setting the "max" light level
int minThreshold = 1023; // used for setting the "min" light level
void setup(){
pinMode(ledPin, OUTPUT); // Set up the LED pin to be an output.
Serial.begin(9600);
}
void loop(){
lightLevel = analogRead(sensorPin); // reads the voltage on the sensorPin
Serial.print(lightLevel);
//autoRange(); // autoRanges the min / max values you see in your room.
calibratedlightLevel = map(lightLevel, 0, 1023, 0, 255); // scale the lightLevel from 0 -1023 range to 0 - 255 range.
// the map() function applies a linear scale / offset.
// map(inputValue, fromMin, fromMax, toMin, toMax);
Serial.print("\t"); // tab character
Serial.print(calibratedlightLevel); // println prints an CRLF at the end (creates a new line after)
analogWrite(ledPin, calibratedlightLevel); // set the led level based on the input lightLevel.
}
/******************************************************************
* void autoRange()
* This function sets a minThreshold and maxThreshold value for the
* light levels in your setting. Move your hand / light source / etc
* so that your light sensor sees a full range of values. This will
* "autoCalibrate" to your range of input values.
/*****************************************************************/
void autoRange()
{
if (lightLevel < minThreshold) // minThreshold was initialized to 1023 -- so, if it's less, reset the threshold level.
minThreshold = lightLevel;
if (lightLevel > maxThreshold)
// maxThreshold was initialized to 0 -- so, if it's bigger, reset the threshold level.
maxThreshold = lightLevel;
// Once we have the highest and lowest values, we can stick them
// directly into the map() function.
//
// This function must run a few times to get a good range of bright and dark values in order to work.
lightLevel = map(lightLevel, minThreshold, maxThreshold, 0, 255);
lightLevel = constrain(lightLevel, 0, 255);
}
11-Temp.Sensor
// We'll use analog input 0 to measure the temperature sensor's
// signal pin.
const int temperaturePin = A0;
void setup(){
Serial.begin(9600); //Initialize serial port & set baud rate to 9600 bits per second (bps)
}
void loop(){
float voltage, degreesC, degreesF; //Declare 3 floating point variables
voltage = getVoltage(temperaturePin); //Measure the voltage at the analog pin
degreesC = (voltage - 0.5) * 100.0; // Convert the voltage to degrees Celsius
degreesF = degreesC * (9.0 / 5.0) + 32.0; //Convert degrees Celsius to Fahrenheit
//Now print to the Serial monitor. Remember the baud must be 9600 on your monitor!
// These statements will print lines of data like this:
// "voltage: 0.73 deg C: 22.75 deg F: 72.96"
Serial.print("voltage: ");
Serial.print(voltage);
Serial.print(" deg C: ");
Serial.print(degreesC);
Serial.print(" deg F: ");
Serial.println(degreesF);
delay(1000); // repeat once per second (change as you wish!)
}
float getVoltage(int pin) //Function to read and return
//floating-point value (true voltage)
//on analog pin
{
return (analogRead(pin) * 0.004882814);
// This equation converts the 0 to 1023 value that analogRead()
// returns, into a 0.0 to 5.0 value that is the true voltage
// being read at that pin.
}
// Other things to try with this code:
// Turn on an LED if the temperature is above or below a value.
// Read that threshold value from a potentiometer - now you've
// created a thermostat!
12-Tone_Melody
/* Melody
Plays a melody
circuit:
* 8-ohm speaker on digital pin 8
*/
#include<pitches.h>
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}}
void loop() { // no need to repeat the melody.
}
13-Servo
#include <Servo.h> // servo library
Servo servo1; // servo control object
void setup(){
servo1.attach(9, 900, 2100); //Connect the servo to pin 9
//with a minimum pulse width of
//900 and a maximum pulse width of
//2100.
}
void loop(){
int position;
// To control a servo, you give it the angle you'd like it
// to turn to. Servos cannot turn a full 360 degrees, but you
// can tell it to move anywhere between 0 and 180 degrees.
// Change position at full speed:
servo1.write(90); // Tell servo to go to 90 degrees
delay(1000); // Pause to get it time to move
servo1.write(180); // Tell servo to go to 180 degrees
delay(1000); // Pause to get it time to move
servo1.write(0); // Tell servo to go to 0 degrees
delay(1000); // Pause to get it time to move
// Tell servo to go to 180 degrees, stepping by two degrees each step
for(position = 0; position < 180; position += 2)
{
servo1.write(position); // Move to next position
delay(20); // Short pause to allow it to move
}
// Tell servo to go to 0 degrees, stepping by one degree each step
for(position = 180; position >= 0; position -= 1)
{
servo1.write(position); // Move to next position
delay(20); // Short pause to allow it to move
}}
14-Motor
/********************************************************************
* SPINNING A MOTOR
* This example requires that you drive your motor using a switching
* transistor. The Arduino is only capable of sourcing about 40 mA of
* current per pin and a motor requires upwards of 150 mA.
* Look at the wiring diagram in the SIK Guide - Circuit #12 or read the
* notes in the readme tab for more information on wiring.
*******************************************************************/
const int motorPin = 9; // Connect the base of the transistor to pin 9.
// Even though it's not directly connected to the motor,
// we'll call it the 'motorPin'
void setup()
{
pinMode(motorPin, OUTPUT); // set up the pin as an OUTPUT
Serial.begin(9600); // initialize Serial communications
}
void loop()
{ // This example basically replicates a blink, but with the motorPin instead.
int onTime = 3000; // milliseconds to turn the motor on
int offTime = 3000; // milliseconds to turn the motor off
analogWrite(motorPin, 255); // turn the motor on (full speed)
delay(onTime); // delay for onTime milliseconds
analogWrite(motorPin, 0); // turn the motor off
delay(offTime); // delay for offTime milliseconds
// Uncomment the functions below by taking out the //. Look below for the
// code examples or documentation.
// speedUpandDown();
// serialSpeed();
}
// This function accelerates the motor to full speed,
// then decelerates back down to a stop.
void speedUpandDown()
{
int speed;
int delayTime = 20; // milliseconds between each speed step
// accelerate the motor
for(speed = 0; speed <= 255; speed++)
{
analogWrite(motorPin,speed); // set the new speed
delay(delayTime); // delay between speed steps
}
// decelerate the motor
for(speed = 255; speed >= 0; speed--)
{
analogWrite(motorPin,speed); // set the new speed
delay(delayTime); // delay between speed steps
}}
// Input a speed from 0-255 over the Serial port
void serialSpeed()
{
int speed;
Serial.println("Type a speed (0-255) into the box above,");
Serial.println("then click [send] or press [return]");
Serial.println(); // Print a blank line
// In order to type out the above message only once,
// we'll run the rest of this function in an infinite loop:
while(true) // "true" is always true, so this will loop forever.
{
// Check to see if incoming data is available:
while (Serial.available() > 0)
{
speed = Serial.parseInt(); // parseInt() reads in the first integer value from the Serial Monitor.
speed = constrain(speed, 0, 255); // constrains the speed between 0 and 255
// because analogWrite() only works in this range.
Serial.print("Setting speed to "); // feedback and prints out the speed that you entered.
Serial.println(speed);
analogWrite(motorPin, speed); // sets the speed of the motor.
}
}}
15-LCD_Screen
/*
SparkFun Inventor's Kit
Example sketch 15
LIQUID CRYSTAL DISPLAY (LCD)
A Liquid Crystal Display (LCD) is a sophisticated module
that can be used to display text or numeric data. The display
included in your SIK features two lines of 16 characters, and
a backlight so it can be used at night.
If you've been using the Serial Monitor to output data,
you'll find that a LCD provides many of the same benefits
without needing to drag a large computer around.
This sketch will show you how to connect an LCD to your Arduino
and display any data you wish.
*/// Load the LiquidCrystal library, which will give us
// commands to interface to the LCD:
#include <LiquidCrystal.h>
// Initialize the library with the pins we're using.
// (Note that you can use different pins if needed.)
// See http://arduino.cc/en/Reference/LiquidCrystal
// for more information:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup(){
lcd.begin(16, 2); //Initialize the 16x2 LCD
lcd.clear(); //Clear any old data displayed on the LCD
lcd.print("hello, world!"); // Display a message on the LCD!
}
void loop(){
lcd.setCursor(0, 1); //Set the (invisible) cursor to column 0,
// row 1.
lcd.print(millis() / 1000); //Print the number of seconds
//since the Arduino last reset.
}
7-segment
void setup() {// define pin modes
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop() { // loop to turn leds od seven seg ON
for(int i=2;i<9;i++) {
digitalWrite(i,HIGH);
delay(600); }
// loop to turn leds od seven seg OFF
for(int i=2;i<9;i++) {
digitalWrite(i,LOW);
delay(600); }
delay(1000);
}
7-segment(1到9)
/* A
---
F | | B
| G |
---
E | | C
| |
---
D
8
*/
int a = 2; //For displaying segment "a"
int b = 3; //For displaying segment "b"
int c = 4; //For displaying segment "c"
int d = 5; //For displaying segment "d"
int e = 6; //For displaying segment "e"
int f = 8; //For displaying segment "f"
int g = 9; //For displaying segment "g"
void setup() {
pinMode(a, OUTPUT); //A
pinMode(b, OUTPUT); //B
pinMode(c, OUTPUT); //C
pinMode(d, OUTPUT); //D
pinMode(e, OUTPUT); //E
pinMode(f, OUTPUT); //F
pinMode(g, OUTPUT); //G
}
void displayDigit(int digit)
{
if(digit!=1 && digit != 4) //Conditions for displaying segment a
digitalWrite(a,HIGH);
if(digit != 5 && digit != 6) //Conditions for displaying segment b
digitalWrite(b,HIGH);
if(digit !=2) //Conditions for displaying segment c
digitalWrite(c,HIGH);
if(digit != 1 && digit !=4 && digit !=7) //Conditions for displaying segment d
digitalWrite(d,HIGH);
if(digit == 2 || digit ==6 || digit == 8 || digit==0) //Conditions for displaying segment e
digitalWrite(e,HIGH);
if(digit != 1 && digit !=2 && digit!=3 && digit !=7) //Conditions for displaying segment f
digitalWrite(f,HIGH);
if (digit!=0 && digit!=1 && digit !=7)
digitalWrite(g,HIGH);
}
void turnOff(){
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
}
void loop() {
for(int i=0;i<10;i++) {
displayDigit(i);
delay(1000);
turnOff();
}
}
7-segment(另一种实现)
int num_array[10][7] = { { 1,1,1,1,1,1,0 }, // 0
{ 0,1,1,0,0,0,0 }, // 1
{ 1,1,0,1,1,0,1 }, // 2
{ 1,1,1,1,0,0,1 }, // 3
{ 0,1,1,0,0,1,1 }, // 4
{ 1,0,1,1,0,1,1 }, // 5
{ 1,0,1,1,1,1,1 }, // 6
{ 1,1,1,0,0,0,0 }, // 7
{ 1,1,1,1,1,1,1 }, // 8
{ 1,1,1,0,0,1,1 }}; // 9
void Num_Write(int); //function header
void setup() { // set pin modes
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void loop() { //counter loop
for (int counter = 10; counter > 0; --counter) {
delay(1000);
Num_Write(counter-1); }
delay(3000);}
// this functions writes values to the sev seg pins
void Num_Write(int number) {
int pin= 2;
for (int j=0; j < 7; j++) {
digitalWrite(pin, num_array[number][j]);
pin++;
}}
控制4个7-segment(0-1000)
#define ASeg 2
#define BSeg 3
#define CSeg 4
#define DSeg 5
#define ESeg 6
#define FSeg 7
#define GSeg 8
#define CA1 9
#define CA2 10
#define CA3 11
#define CA4 12
int delay_time = 1;
void setup() {
pinMode(ASeg, OUTPUT);
pinMode(BSeg, OUTPUT);
pinMode(CSeg, OUTPUT);
pinMode(DSeg, OUTPUT);
pinMode(ESeg, OUTPUT);
pinMode(FSeg, OUTPUT);
pinMode(GSeg, OUTPUT);
pinMode(CA1, OUTPUT);
pinMode(CA2, OUTPUT);
pinMode(CA3, OUTPUT);
pinMode(CA4, OUTPUT);
}
void loop() {
for (unsigned int number = 0; number < 1001; number++) {
unsigned long startTime = millis();
for (unsigned long elapsed=0; elapsed < 1000; elapsed = millis() - startTime) {
pickDigit(1);
pickNumber(number%10);
delay(delay_time);
pickDigit(2);
pickNumber((number/10)%10);
delay(delay_time);
pickDigit(3);
pickNumber((number/100)%10);
delay(delay_time);
pickDigit(4);
pickNumber((number/1000)%10);
delay(delay_time);
}
}
}
void pickDigit(int x) {
digitalWrite(CA1, LOW);
digitalWrite(CA2, LOW);
digitalWrite(CA3, LOW);
digitalWrite(CA4, LOW);
switch(x) {
case 1: digitalWrite(CA1, HIGH); break;
case 2: digitalWrite(CA2, HIGH); break;
case 3: digitalWrite(CA3, HIGH); break;
case 4: digitalWrite(CA4, HIGH); break;
}
}
void pickNumber(int x) {
switch(x) {
case 1: one(); break;
case 2: two(); break;
case 3: three(); break;
case 4: four(); break;
case 5: five(); break;
case 6: six(); break;
case 7: seven(); break;
case 8: eight(); break;
case 9: nine(); break;
default: zero(); break;
}
}
void one() {
digitalWrite(ASeg, HIGH);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, HIGH);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, HIGH);
digitalWrite(GSeg, HIGH);
}
void two() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, HIGH);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, LOW);
digitalWrite(FSeg, HIGH);
digitalWrite(GSeg, LOW);
}
void three() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, HIGH);
digitalWrite(GSeg, LOW);
}
void four() {
digitalWrite(ASeg, HIGH);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, HIGH);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, LOW);
}
void five() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, HIGH);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, LOW);
}
void six() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, HIGH);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, LOW);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, LOW);
}
void seven() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, HIGH);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, HIGH);
digitalWrite(GSeg, HIGH);
}
void eight() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, LOW);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, LOW);
}
void nine() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, HIGH);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, LOW);
}
void zero() {
digitalWrite(ASeg, LOW);
digitalWrite(BSeg, LOW);
digitalWrite(CSeg, LOW);
digitalWrite(DSeg, LOW);
digitalWrite(ESeg, LOW);
digitalWrite(FSeg, LOW);
digitalWrite(GSeg, HIGH);
}