2020年12月14日 星期一

Sunnnnnnnnnnnnnn

 Week14


一開始用這個程式碼配上可變電阻(旋鈕)
接上5V,A0,GND
就可以發出聲音
-----
程式碼:
#define buzzer 2
#define buzzer 8
void setup() {
  // put your setup code here, to run once:
pinMode(13,OUTPUT);
pinMode(8,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
int now = analogRead(A0);
tone(8,now);
}
-----


這個程式碼可以讓燈隨著旋鈕變多變少
-----
程式碼:
void setup() {
  for (int i = 2; i <= 13; i++) {
    pinMode(i, OUTPUT);
  }

}
void loop() {
  int now = analogRead(A0);
  int level = now / (512 / 13);
  for (int i = 2; i <= 13; i++) {
    if (i < level) digitalWrite(i, HIGH);
    else digitalWrite(i, LOW);
  }

}
-----

一樣是控制燈多少
可以配合joystick改變
-----
程式碼:
void setup() {
  for (int i = 2; i <= 13; i++) {
    pinMode(i, OUTPUT);
  }
Serial.begin(9600);
}
void loop() {
  int now = analogRead(A0);
  int level = now / (1024 / 13);
  for (int i = 2; i <= 13; i++) {
    if (i < level) digitalWrite(i, HIGH);
    else digitalWrite(i, LOW);
  }
Serial.write(('A'+level));
delay(100);
}

-----

-----
紅色進度條多少
Processing程式碼:
import processing.serial.*;
Serial myPort;
void setup(){
 size(700,100);
 myport = new Serial(this,"COM4",9600);
}
int level=0;
void draw(){
 background(255);
 fill(255,0,0);
 rect(0,0,level*50,100);
 if( myPort.available()>0){
  int now = myPort.read();
  if(now=='A') level=0;
  if(now=='B') level=1;
  if(now=='C') level=2;
  if(now=='D') level=3;
  if(now=='E') level=4;
  if(now=='F') level=5;
  if(now=='G') level=6;
  if(now=='H') level=7;
  if(now=='I') level=8;
  if(now=='J') level=9;
  if(now=='K') level=10;
  if(now=='L') level=11;
  if(now=='M') level=12;
  if(now=='N') level=13;
 }
}


or
import processing.serial.*;
Serial myPort;
void setup(){
 size(700,100);
 myport = new Serial(this,"COM4",9600);
}
int level=0;
void draw(){
 background(255);
 fill(255,0,0);
 rect(0,0,level*50,100);
 if( myPort.available()>0){
  int now = myPort.read();
level = now-'A';
 }
}
-----

Processing 更精簡靈活的程式碼
-----
  import processing.serial.*;
  Serial myPort;
  void setup(){
   size(700,100);
   myport = new Serial(this,"COM4",9600);
  }
  int level=0;
  void draw(){
   background(255);
   fill(255,0,0);
   rect(0,0,level*3,100);
   if( myPort.available()>0){
    int now = myPort.read();
    level = now;
   }
  }
-----
Arduino版本
-----
程式碼:
void setup() {
  for (int i = 2; i <= 13; i++) {
    pinMode(i, OUTPUT);
  }
Serial.begin(9600);
}
void loop() {
  int now = analogRead(A0);
  int level = now/4;
  for (int i = 2; i <= 13; i++) {
    if (i < level) digitalWrite(i, HIGH);
    else digitalWrite(i, LOW);
  }
//Serial.write(('A'+level));
Serial.write(level);
delay(20);
}

-----









沒有留言:

張貼留言