attiny85 memory

cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

Re: attiny85 memory

文章 cajhbb »

https://www.youtube.com/watch?v=FZLmSVf_AiY&t=56s
Repeat After Me.png
Repeat After Me.png (146 KiB) 已瀏覽 616 次

代碼: 選擇全部


#include <Servo.h>

#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_C5 523


#define CHOICE_OFF      0 //Used to control LEDs
#define CHOICE_NONE     0 //Used to check buttons
#define CHOICE_RED  (1 << 0)
#define CHOICE_GREEN    (1 << 3)
#define CHOICE_BLUE (1 << 1)
#define CHOICE_YELLOW   (1 << 2)

#define LED_RED     3
#define LED_GREEN   9
#define LED_BLUE    5
#define LED_YELLOW  7

// Button pin definitions
#define BUTTON_RED    2
#define BUTTON_GREEN  8
#define BUTTON_BLUE   4
#define BUTTON_YELLOW 6

// Buzzer pin definitions
#define BUZZER1  10
#define BUZZER2  12

// Define game parameters
#define ROUNDS_TO_WIN      12 //Number of rounds to succesfully remember before you win. 13 is do-able.
#define ENTRY_TIME_LIMIT   3000 //Amount of time to press a button before game times out. 3000ms = 3 sec

#define MODE_MEMORY  0
#define MODE_BATTLE  1
#define MODE_BEEGEES 2

// Game state variables
byte gameMode = MODE_MEMORY; //By default, let's play the memory game
byte gameBoard[32]; //Contains the combination of buttons as we advance
byte gameRound = 0; //Counts the number of succesful rounds the player has made it through

Servo myservo;

void setup()
{
  myservo.attach(11);
  //Setup hardware inputs/outputs. These pins are defined in the hardware_versions header file

  //Enable pull ups on inputs
  pinMode(BUTTON_RED, INPUT_PULLUP);
  pinMode(BUTTON_GREEN, INPUT_PULLUP);
  pinMode(BUTTON_BLUE, INPUT_PULLUP);
  pinMode(BUTTON_YELLOW, INPUT_PULLUP);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);

  pinMode(BUZZER1, OUTPUT);
  pinMode(BUZZER2, OUTPUT);

  //Mode checking
  gameMode = MODE_MEMORY; // By default, we're going to play the memory game

  // Check to see if the lower right button is pressed
  if (checkButton() == CHOICE_YELLOW) play_beegees();

  // Check to see if upper right button is pressed
  if (checkButton() == CHOICE_GREEN)
  {
    gameMode = MODE_BATTLE; //Put game into battle mode

    //Turn on the upper right (green) LED
    setLEDs(CHOICE_GREEN);
    toner(CHOICE_GREEN, 150);

    setLEDs(CHOICE_RED | CHOICE_BLUE | CHOICE_YELLOW); // Turn on the other LEDs until you release button

    while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

    //Now do nothing. Battle mode will be serviced in the main routine
  }

  play_winner(); // After setup is complete, say hello to the world
  myservo.write(90);  
}

void loop()
{
  attractMode(); // Blink lights while waiting for user to press a button

  // Indicate the start of game play
  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE | CHOICE_YELLOW); // Turn all LEDs on
  myservo.write(90);
  delay(1000);
  setLEDs(CHOICE_OFF); // Turn off LEDs
  delay(250);

  if (gameMode == MODE_MEMORY)
  {
    // Play memory game and handle result
    if (play_memory() == true) 
      play_winner(); // Player won, play winner tones
    else 
      play_loser(); // Player lost, play loser tones
  }

  if (gameMode == MODE_BATTLE)
  {
    play_battle(); // Play game until someone loses

    play_loser(); // Player lost, play loser tones
  }
}

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//The following functions are related to game play only

// Play the regular memory game
// Returns 0 if player loses, or 1 if player wins
boolean play_memory(void)
{
  randomSeed(millis()); // Seed the random generator with random amount of millis()

  gameRound = 0; // Reset the game to the beginning

  while (gameRound < ROUNDS_TO_WIN) 
  {
    add_to_moves(); // Add a button to the current moves, then play them back

    playMoves(); // Play back the current game board

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button(); // See what button the user presses

      if (choice == 0) return false; // If wait timed out, player loses

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses
    }

    delay(1000); // Player was correct, delay before playing moves
  }

  return true; // Player made it through all the rounds to win!
}

// Play the special 2 player battle mode
// A player begins by pressing a button then handing it to the other player
// That player repeats the button and adds one, then passes back.
// This function returns when someone loses
boolean play_battle(void)
{
  gameRound = 0; // Reset the game frame back to one frame

  while (1) // Loop until someone fails 
  {
    byte newButton = wait_for_button(); // Wait for user to input next move
    gameBoard[gameRound++] = newButton; // Add this new button to the game array

    // Then require the player to repeat the sequence.
    for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++)
    {
      byte choice = wait_for_button();

      if (choice == 0) return false; // If wait timed out, player loses.

      if (choice != gameBoard[currentMove]) return false; // If the choice is incorect, player loses.
    }

    delay(100); // Give the user an extra 100ms to hand the game to the other player
  }

  return true; // We should never get here
}

// Plays the current contents of the game moves
void playMoves(void)
{
  for (byte currentMove = 0 ; currentMove < gameRound ; currentMove++) 
  {
    toner(gameBoard[currentMove], 150);

    // Wait some amount of time between button playback
    // Shorten this to make game harder
    delay(150); // 150 works well. 75 gets fast.
  }
}

// Adds a new random button to the game sequence, by sampling the timer
void add_to_moves(void)
{
  byte newButton = random(0, 4); //min (included), max (exluded)

  // We have to convert this number, 0 to 3, to CHOICEs
  if(newButton == 0) newButton = CHOICE_RED;
  else if(newButton == 1) newButton = CHOICE_GREEN;
  else if(newButton == 2) newButton = CHOICE_BLUE;
  else if(newButton == 3) newButton = CHOICE_YELLOW;

  gameBoard[gameRound++] = newButton; // Add this new button to the game array
}

//The following functions control the hardware

// Lights a given LEDs
// Pass in a byte that is made up from CHOICE_RED, CHOICE_YELLOW, etc
void setLEDs(byte leds)
{
  if ((leds & CHOICE_RED) != 0)
    digitalWrite(LED_RED, HIGH);
  else
    digitalWrite(LED_RED, LOW);

  if ((leds & CHOICE_GREEN) != 0)
    digitalWrite(LED_GREEN, HIGH);
  else
    digitalWrite(LED_GREEN, LOW);

  if ((leds & CHOICE_BLUE) != 0)
    digitalWrite(LED_BLUE, HIGH);
  else
    digitalWrite(LED_BLUE, LOW);

  if ((leds & CHOICE_YELLOW) != 0)
    digitalWrite(LED_YELLOW, HIGH);
  else
    digitalWrite(LED_YELLOW, LOW);
}

// Wait for a button to be pressed. 
// Returns one of LED colors (LED_RED, etc.) if successful, 0 if timed out
byte wait_for_button(void)
{
  long startTime = millis(); // Remember the time we started the this loop

  while ( (millis() - startTime) < ENTRY_TIME_LIMIT) // Loop until too much time has passed
  {
    byte button = checkButton();

    if (button != CHOICE_NONE)
    { 
      toner(button, 150); // Play the button the user just pressed

      while(checkButton() != CHOICE_NONE) ;  // Now let's wait for user to release button

      delay(10); // This helps with debouncing and accidental double taps

      return button;
    }

  }

  return CHOICE_NONE; // If we get here, we've timed out!
}

// Returns a '1' bit in the position corresponding to CHOICE_RED, CHOICE_GREEN, etc.
byte checkButton(void)
{
  if (digitalRead(BUTTON_RED) == 0) return(CHOICE_RED); 
  else if (digitalRead(BUTTON_GREEN) == 0) return(CHOICE_GREEN); 
  else if (digitalRead(BUTTON_BLUE) == 0) return(CHOICE_BLUE); 
  else if (digitalRead(BUTTON_YELLOW) == 0) return(CHOICE_YELLOW);

  return(CHOICE_NONE); // If no button is pressed, return none
}

// Light an LED and play tone
// Red, upper left:     440Hz - 2.272ms - 1.136ms pulse
// Green, upper right:  880Hz - 1.136ms - 0.568ms pulse
// Blue, lower left:    587.33Hz - 1.702ms - 0.851ms pulse
// Yellow, lower right: 784Hz - 1.276ms - 0.638ms pulse
void toner(byte which, int buzz_length_ms)
{
  setLEDs(which); //Turn on a given LED

  //Play the sound associated with the given LED
  switch(which) 
  {
  case CHOICE_RED:
    buzz_sound(buzz_length_ms, 1136); 
    break;
  case CHOICE_GREEN:
    buzz_sound(buzz_length_ms, 568); 
    break;
  case CHOICE_BLUE:
    buzz_sound(buzz_length_ms, 851); 
    break;
  case CHOICE_YELLOW:
    buzz_sound(buzz_length_ms, 638); 
    break;
  }

  setLEDs(CHOICE_OFF); // Turn off all LEDs
}

// Toggle buzzer every buzz_delay_us, for a duration of buzz_length_ms.
void buzz_sound(int buzz_length_ms, int buzz_delay_us)
{
  // Convert total play time from milliseconds to microseconds
  long buzz_length_us = buzz_length_ms * (long)1000;

  // Loop until the remaining play time is less than a single buzz_delay_us
  while (buzz_length_us > (buzz_delay_us * 2))
  {
    buzz_length_us -= buzz_delay_us * 2; //Decrease the remaining play time

    // Toggle the buzzer at various speeds
    digitalWrite(BUZZER1, LOW);
    digitalWrite(BUZZER2, HIGH);
    delayMicroseconds(buzz_delay_us);

    digitalWrite(BUZZER1, HIGH);
    digitalWrite(BUZZER2, LOW);
    delayMicroseconds(buzz_delay_us);
  }
}

// Play the winner sound and lights
void play_winner(void)
{
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
  setLEDs(CHOICE_GREEN | CHOICE_BLUE);
  winner_sound();
  setLEDs(CHOICE_RED | CHOICE_YELLOW);
  winner_sound();
}

// Play the winner sound
// This is just a unique (annoying) sound we came up with, there is no magic to it
void winner_sound(void)
{
  // Toggle the buzzer at various speeds
  for (byte x = 250 ; x > 70 ; x--)
  {
    for (byte y = 0 ; y < 3 ; y++)
    {
      digitalWrite(BUZZER2, HIGH);
      digitalWrite(BUZZER1, LOW);
      delayMicroseconds(x);

      digitalWrite(BUZZER2, LOW);
      digitalWrite(BUZZER1, HIGH);
      delayMicroseconds(x);
    }
  }
}

// Play the loser sound/lights
void play_loser(void)
{
   myservo.write(0);
   
  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_RED | CHOICE_GREEN);
  buzz_sound(255, 1500);

  setLEDs(CHOICE_BLUE | CHOICE_YELLOW);
  buzz_sound(255, 1500);

 
}

// Show an "attract mode" display while waiting for user to press button.
void attractMode(void)
{
  while(1) 
  {
    setLEDs(CHOICE_RED);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_BLUE);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_GREEN);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;

    setLEDs(CHOICE_YELLOW);
    delay(100);
    if (checkButton() != CHOICE_NONE) return;
  }
  myservo.write(90);  
}


// Notes in the melody. Each note is about an 1/8th note, "0"s are rests.
int melody[] = {
  NOTE_G4, NOTE_A4, 0, NOTE_C5, 0, 0, NOTE_G4, 0, 0, 0,
  NOTE_E4, 0, NOTE_D4, NOTE_E4, NOTE_G4, 0,
  NOTE_D4, NOTE_E4, 0, NOTE_G4, 0, 0,
  NOTE_D4, 0, NOTE_E4, 0, NOTE_G4, 0, NOTE_A4, 0, NOTE_C5, 0};

int noteDuration = 115; // This essentially sets the tempo, 115 is just about right for a disco groove :)
int LEDnumber = 0; // Keeps track of which LED we are on during the beegees loop

// Do nothing but play bad beegees music
// This function is activated when user holds bottom right button during power up
void play_beegees()
{
  //Turn on the bottom right (yellow) LED
  setLEDs(CHOICE_YELLOW);
  toner(CHOICE_YELLOW, 150);

  setLEDs(CHOICE_RED | CHOICE_GREEN | CHOICE_BLUE); // Turn on the other LEDs until you release button

  while(checkButton() != CHOICE_NONE) ; // Wait for user to stop pressing button

  setLEDs(CHOICE_NONE); // Turn off LEDs

  delay(1000); // Wait a second before playing song

  digitalWrite(BUZZER1, LOW); // setup the "BUZZER1" side of the buzzer to stay low, while we play the tone on the other pin.

  while(checkButton() == CHOICE_NONE) //Play song until you press a button
  {
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 32; thisNote++) {
      changeLED();
      tone(BUZZER2, 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(BUZZER2);
    }
  }
}

// Each time this function is called the board moves to the next LED
void changeLED(void)
{
  setLEDs(1 << LEDnumber); // Change the LED

  LEDnumber++; // Goto the next LED
  if(LEDnumber > 3) LEDnumber = 0; // Wrap the counter if needed
}




cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

arduino 做記憶遊戲

文章 cajhbb »

https://copilot.microsoft.com/chats/CmN ... qURemHMfqr
用arduino寫一個記憶遊戲的程式,用led 按鈕 蜂鳴器組成電路,程式加註解
這裡有一個使用 Arduino 來實現簡單記憶遊戲的程式範例,使用 LED、按鈕和蜂鳴器組成電路。這個遊戲的基本原理是讓玩家記住並重現一串隨機亮起的LED序列。

所需元件:
Arduino 開發板(如 Arduino Uno)

4 個 LED

4 個按鈕

1 個蜂鳴器

10k Ω 電阻(用於按鈕上拉)

220 Ω 電阻(用於LED限流)

連接線

電路連接:
將 4 個 LED 的正極分別接到 Arduino 的數字引腳 2, 3, 4, 5。

將 4 個按鈕的一端接地,另一端分別接到數字引腳 6, 7, 8, 9 並用 10k Ω 電阻上拉到 5V。

將蜂鳴器的正極接到數字引腳 10,負極接地。

LED 的負極分別接 220 Ω 電阻,再接地。

程式碼:
cpp
#include <Arduino.h>

// LED 引腳
const int ledPins[] = {2, 3, 4, 5};

// 按鈕引腳
const int buttonPins[] = {6, 7, 8, 9};

// 蜂鳴器引腳
const int buzzerPin = 10;

// 遊戲參數
const int sequenceLength = 4;
int gameSequence[sequenceLength];
int playerSequence[sequenceLength];

// 初始化設置
void setup() {
Serial.begin(9600);

for (int i = 0; i < 4; i++) {
pinMode(ledPins, OUTPUT);
pinMode(buttonPins, INPUT_PULLUP);
}

pinMode(buzzerPin, OUTPUT);
randomSeed(analogRead(0)); // 使用未接的模擬引腳產生隨機種子

generateSequence();
playSequence();
}

// 生成隨機序列
void generateSequence() {
for (int i = 0; i < sequenceLength; i++) {
gameSequence = random(0, 4);
}
}

// 播放序列
void playSequence() {
for (int i = 0; i < sequenceLength; i++) {
digitalWrite(ledPins[gameSequence], HIGH);
delay(500);
digitalWrite(ledPins[gameSequence], LOW);
delay(500);
}
}

// 播放蜂鳴器音效
void playTone(int tone, int duration) {
tone(buzzerPin, tone, duration);
delay(duration * 1.30);
noTone(buzzerPin);
}

// 檢查玩家輸入
bool checkPlayerInput() {
for (int i = 0; i < sequenceLength; i++) {
while (true) {
for (int j = 0; j < 4; j++) {
if (digitalRead(buttonPins[j]) == LOW) {
playerSequence = j;
digitalWrite(ledPins[j], HIGH);
playTone(1000, 200); // 播放音效
delay(200);
digitalWrite(ledPins[j], LOW);
delay(300);

if (playerSequence != gameSequence) {
return false; // 玩家輸入錯誤
}
break;
}
}
}
}
return true; // 玩家輸入正確
}

void loop() {
if (checkPlayerInput()) {
playTone(2000, 500); // 播放勝利音效
delay(1000);
generateSequence(); // 生成新序列
playSequence(); // 播放新序列
} else {
playTone(500, 1000); // 播放失敗音效
delay(1000);
playSequence(); // 重新播放相同序列
}
}
說明:
setup() 函數初始化引腳和隨機序列生成。

generateSequence() 函數生成一個隨機LED序列。

playSequence() 函數播放生成的LED序列。

playTone() 函數控制蜂鳴器發出音效。

checkPlayerInput() 函數檢查玩家按下按鈕的順序,並與生成的序列比較。

loop() 函數包含遊戲的主要邏輯,包括檢查玩家輸入和播放音效。

希望這個範例對你有幫助!如果有任何問題或需要進一步的解釋,隨時告訴我哦!


cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

Re: attiny85 memory

文章 cajhbb »

宮(黃色)土,商(白色)金,角(綠色)木,徵(紅色)火,羽(黑色)水

代碼: 選擇全部

中國的五音(宮、商、角、徵、羽)在傳統音樂中非常常見。這些音階相當於西方音樂中的do, re, mi, sol, la。以下是一些常聽的、由這五音組成的樂曲:

1. **《茉莉花》**:這首著名的中國民歌,旋律優美,廣為人知。
2. **《小白菜》**:另一首經典的中國民歌,旋律簡單而動人。
3. **《漁舟唱晚》**:傳統的中國古典音樂作品,優雅且富有情感。
4. **《彩雲追月》**:這是一首經典的中國傳統樂曲,旋律流暢而富有詩意。
5. **《高山流水》**:這首古琴曲以其深沉的情感和優美的旋律著稱。

許多西方樂曲也會採用類似五聲音階的簡單旋律。這類音階通常被稱為“五聲音階”或“五音音階”。以下是一些西方樂曲的範例:

1. **《讚美詩100》(Amazing Grace)**:這首經典的讚美詩主要使用五聲音階。
2. **《艾琳·安·科瑞》(Auld Lang Syne)**:這首傳統的蘇格蘭民歌經常在新年時唱起,旋律簡單且使用五聲音階。
3. **《五聲音階之歌》(Pentatonic Scale Song)**:這是一首專門為教學而設計的歌曲,用來展示五聲音階的音調。
4. **《月河》(Moon River)**:這首由亨利·曼西尼作曲的經典歌曲也包含了五聲音階的元素。
5. **《奧夫巴赫的旋律》(Orff's Melody)**:卡爾·奧爾夫的某些作品中也可以找到五聲音階的例子。

當然可以,以下是更多的中、西樂曲例子,它們均採用五聲音階:

### 中國樂曲
1. **《黃河鋼琴協奏曲》**:這是一部中國鋼琴協奏曲,融合了五聲音階和西方交響樂的元素。
2. **《梁祝小提琴協奏曲》**:這首曲子以其動人的旋律和五聲音階結構而聞名。
3. **《花好月圓》**:這是一首經典的中國民樂,旋律優美流暢。
4. **《彎彎的月亮》**:這首現代中國民歌,運用了簡單而富有詩意的五聲音階旋律。

### 西方樂曲
1. **《瑞卡斯的貝多芬》(Beethoven's Für Elise)**:貝多芬的這首鋼琴小品有一部分旋律採用五聲音階。
2. **《冬季之旅》(Vivaldi's Winter from The Four Seasons)**:雖然維瓦爾第的這首作品是巴洛克音樂,但其中的某些段落使用了五聲音階。
3. **《黑暗騎士》(Knight Rider Theme)**:這首經典的電視主題曲使用了五聲音階的元素,旋律簡潔有力。
4. **《山寨老王》(House of the Rising Sun)**:這首美國民歌常以五聲音階演奏,旋律簡單而具有感染力。

這些樂曲展示了五聲音階在不同文化和音樂風格中的應用。希望你能從中找到喜愛的樂曲,並進一步探索五聲音階的魅力!如果你有特別感興趣的曲風或作曲家,告訴我,我可以給你更多相關的建議。
當然可以,以下是更多中、西樂曲例子,它們均採用五聲音階:

### 中國樂曲
1. **《鳳陽花鼓》**:這是一首傳統的中國民歌,旋律輕快且富有地方特色。
2. **《百鳥朝鳳》**:這首曲子運用了五聲音階,模仿鳥鳴聲,別具一格。
3. **《蘇武牧羊》**:這是一首古琴曲,運用了五聲音階,展現了蘇武的堅韌精神。
4. **《歡樂頌》**:這是一首中國古典音樂,旋律簡潔明快。
5. **《春江花月夜》**:這首曲子以其優美的旋律和五聲音階聞名。
6. **《紫竹調》**:這是一首江南絲竹樂,旋律優雅且富有詩意。
7. **《平湖秋月》**:這首廣東音樂作品運用了五聲音階,旋律流暢動人。
8. **《白蛇傳》**:這是一首戲曲音樂,運用了五聲音階,富有戲劇性。
9. **《梅花三弄》**:這是一首古琴曲,旋律優美且深情。
10. **《二泉映月》**:這是一首二胡曲,以其感人的旋律和五聲音階而著稱。

### 西方樂曲
1. **《聖誕鈴聲》(Jingle Bells)**:這首經典的聖誕歌曲運用了五聲音階,旋律簡單而有趣。
2. **《小星星》(Twinkle Twinkle Little Star)**:這首兒歌以五聲音階演奏,旋律簡單易記。
3. **《老黑奴》(Swing Low, Sweet Chariot)**:這首美國靈歌使用了五聲音階,旋律動人。
4. **《哦,我美麗的家鄉》(Home on the Range)**:這是一首經典的美國民歌,旋律優美。
5. **《老丹尼男孩》(Danny Boy)**:這首愛爾蘭民歌使用了五聲音階,旋律感人。
6. **《揮手道別》(Aloha Oe)**:這首夏威夷歌曲以五聲音階為基礎,旋律悠揚。
7. **《蘇珊娜》(Oh! Susanna)**:這首美國民歌運用了五聲音階,旋律輕快。
8. **《紅河谷》(Red River Valley)**:這首西部民歌以其簡單的旋律和五聲音階而著名。
9. **《家在天邊》(My Bonnie Lies Over the Ocean)**:這首蘇格蘭民歌旋律優美。
10. **《非洲聖歌》(African Hymn)**:這首聖歌使用了五聲音階,旋律獨特而感人。

希望這些樂曲能讓你更深入了解五聲音階在不同音樂文化中的應用!如果還有其他需求,隨時告訴我。
cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

arduino 演奏音樂

文章 cajhbb »

代碼: 選擇全部

/*註解 sizeof(melody)=100(宣告int佔4byte*25組),總數
       sizeof(melody[0])=4(陣列佔佔4byte),多少為一組,上下相除得組數=25組
*/

#define BUZZER_PIN 10

int melody[][2] = { //宣告int暫記憶體4byte * 25組=100
  {262, 200}, {262, 200}, {294, 700}, {262, 700}, {349, 700}, {330, 1600}, // 生日快樂歌 第一行
  {262, 200}, {262, 200}, {294, 700}, {262, 700}, {392, 700}, {349, 1600}, // 生日快樂歌 第二行
  {262, 200}, {262, 200}, {523, 700}, {440, 700}, {349, 700}, {330, 700}, {294, 1600}, // 生日快樂歌 第三行
  {466, 200}, {466, 200}, {440, 700}, {349, 700}, {392, 700}, {349, 1600}  // 生日快樂歌 第四行 
};

void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
 
  // 初始化串口通信,波特率為9600
  Serial.begin(9600);
  // 向串口輸出一條歡迎訊息

}

void loop() {
  for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
    int note = melody[i][0];
    int duration = melody[i][1];
    tone(BUZZER_PIN, note, duration);
    delay(duration * 1.2); // 延遲用來分開每個音符
  }
  delay(400); // 結束後的延遲
}

cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

5個音

文章 cajhbb »

故鄉的風

代碼: 選擇全部

Do, re, mi, sol, la,
故鄉的風,吹拂著我。
Do, re, mi, sol, la,
回憶如繁星,閃耀在夜空。
Do, re, mi, sol, la,
故鄉的風,永遠不變。
風箏

代碼: 選擇全部

Do, re, mi, sol, la,
風箏在天上飛,飄向遠方。
Do, re, mi, sol, la,
追隨著夢想,飛向那希望。
Do, re, mi, sol, la,
風箏在天上飛,自由翱翔。
小星星

代碼: 選擇全部

Do, do, sol, sol, la, la, sol,
Fais do-do, fais do-do.
Mi, mi, re, re, do, 
Mon p'tit Pierre, dors.
Sol, sol, fa, fa, mi, mi, re,
Fais do-do, fais do-do.
Sol, sol, fa, fa, mi, mi, re,
Mon p'tit Pierre, dors.

cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

五個音的音頻

文章 cajhbb »


#define BUZZER_PIN 10

void setup() {
pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
tone(BUZZER_PIN, 261); // 發出Do音
delay(1000); // 等待1秒
tone(BUZZER_PIN, 293); // 發出Re音
delay(1000);
tone(BUZZER_PIN, 329); // 發出Mi音
delay(1000);
tone(BUZZER_PIN, 392); // 發出Sol音
delay(1000);
tone(BUZZER_PIN, 440); // 發出La音
delay(1000);
noTone(BUZZER_PIN); // 停止蜂鳴器
delay(1000); // 等待1秒
}
cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

Re: attiny85 memory

文章 cajhbb »

jingle bell+happy birthday

代碼: 選擇全部

int melody[][2] = {
  {392, 250}, {392, 250}, {392, 500}, // Sol Sol Sol
  {392, 250}, {392, 250}, {392, 500}, // Sol Sol Sol
  {392, 250}, {440, 250}, {330, 500}, // Sol La Mi
  {349, 250}, {294, 500},             // Fa Re
  {262, 250}, {294, 250}, {392, 500}, // Do Re Sol
};

int melody[][2] = {
  {262, 250}, {262, 250}, {294, 500}, {262, 500}, {349, 500}, {330, 1000},  // 生日快樂歌 第一行
  {262, 250}, {262, 250}, {294, 500}, {262, 500}, {392, 500}, {349, 1000},  // 生日快樂歌 第二行
  {262, 250}, {262, 250}, {523, 500}, {440, 500}, {349, 500}, {330, 500}, {294, 1000},  // 生日快樂歌 第三行
  {466, 250}, {466, 250}, {440, 500}, {349, 500}, {392, 500}, {349, 1000}   // 生日快樂歌 第四行
};
亂數取函式
random(1, 6) 在Arduino中的意思是生成一個範圍在1(包含)到6(不包含)之間的隨機數。因此,這個範圍實際上生成的是1到5之間的亂數。

這是因為在Arduino的random()函數中,第二個參數是上限,但是這個上限是「不包含」的數值。所以當你設定為random(1, 6)時,生成的隨機數包括1、2、3、4和5,但不包括6。

代碼: 選擇全部

void function1() {
  Serial.println("Executing function 1");
}

void function2() {
  Serial.println("Executing function 2");
}

void function3() {
  Serial.println("Executing function 3");
}

void function4() {
  Serial.println("Executing function 4");
}

void function5() {
  Serial.println("Executing function 5");
}

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(0)); // 使用模擬讀取初始化亂數生成器
}

void loop() {
  int randomNumber = random(1, 6); // 生成1到5之間的亂數
  Serial.print("Random number: ");
  Serial.println(randomNumber);

  switch(randomNumber) {
    case 1:
      function1();
      break;
    case 2:
      function2();
      break;
    case 3:
      function3();
      break;
    case 4:
      function4();
      break;
    case 5:
      function5();
      break;
  }

  delay(2000); // 等待2秒後重新生成亂數
}

cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

Re: attiny85 memory

文章 cajhbb »

寫arduino程式,D1~D5接5個led燈,D0接蜂鳴器,程式開始,閃爍3下,並用柔和聲音提示!

代碼: 選擇全部

#define BUZZER_PIN 0
#define LED1_PIN 1
#define LED2_PIN 2
#define LED3_PIN 3
#define LED4_PIN 4
#define LED5_PIN 5

void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED1_PIN, OUTPUT);
  pinMode(LED2_PIN, OUTPUT);
  pinMode(LED3_PIN, OUTPUT);
  pinMode(LED4_PIN, OUTPUT);
  pinMode(LED5_PIN, OUTPUT);
}

void loop() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(LED1_PIN, HIGH);
    digitalWrite(LED2_PIN, HIGH);
    digitalWrite(LED3_PIN, HIGH);
    digitalWrite(LED4_PIN, HIGH);
    digitalWrite(LED5_PIN, HIGH);
    delay(500);
    digitalWrite(LED1_PIN, LOW);
    digitalWrite(LED2_PIN, LOW);
    digitalWrite(LED3_PIN, LOW);
    digitalWrite(LED4_PIN, LOW);
    digitalWrite(LED5_PIN, LOW);
    delay(500);
  }
  
  tone(BUZZER_PIN, 262, 200); // 發出Do音,持續200毫秒
  delay(400);
  tone(BUZZER_PIN, 294, 200); // 發出Re音,持續200毫秒
  delay(400);
  tone(BUZZER_PIN, 330, 200); // 發出Mi音,持續200毫秒
  delay(400);
  noTone(BUZZER_PIN); // 停止蜂鳴器

  // 繼續主循環
  while (true) {
    delay(1000); // 無限延遲
  }
}

cajhbb
系統管理員
文章: 993
註冊時間: 2018年 6月 30日, 02:16

字串與數字相加減

文章 cajhbb »

結果輸出字串為song1234
void setup() {
Serial.begin(9600);

int number = 1234; // 要轉換的整數
char buffer[6]; // 用於儲存轉換後的字串
char finalString[8]; // 用於儲存最終的合併字串

itoa(number, buffer, 10); // 將整數轉換為字串,10表示使用十進制
strcpy(finalString, "song"); // 將 "song" 字串複製到 finalString
strcat(finalString, buffer); // 將轉換後的數字字串連接到 finalString

Serial.print("The combined string is: ");
Serial.println(finalString); // 打印最終的字串 "song1234"
}

void loop() {
// 這裡可以放其他程式碼
}
回覆文章