Fork me on GitHub

Arduino初体验


自从退了问题求解之后,感觉一身轻松,每天只有一个字:“闲”。这两天大佬们都走上了ACM远征的道路,留下我们这批小佬暗自神伤。不过还算好,Arduino这个新伙伴让我开心了几天。

小灯+蜂鸣器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void setup() {
// initialize digital pin LED_BUILTIN as an output.
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(3, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
Serial.println("ok");
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
long frequency = 300; //频率, 单位Hz
//用tone()函数发出频率为frequency的波形
tone(3, frequency );
delay(1000); //等待1000毫秒
noTone(3);//停止发声
delay(2000); //等待2000毫秒
}

舵机自动旋转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

rotation sensor控制舵机

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <Servo.h> // 声明调用Servo.h库
Servo myservo; // 创建一个舵机对象
int potpin = 0; // 连接到模拟口0
int val; //变量val用来存储从模拟口0读到的值
void setup() {
Serial.begin(9600);
myservo.attach(9); //将引脚9上的舵机与声明的舵机对象连接起来
}
void loop() {
val = analogRead(potpin); //从模拟口0读值,并通过val记录
val = map(val, 0, 1023, 0, 179); //通过map函数进行数值转换
myservo.write(val); // 给舵机写入角度
Serial.println("OK");
delay(15); // 延时15ms让舵机转到指定位置
}

PS:md竟然不支持Arduino语法。。我用的c++实现高亮。。

​ 在此特别鸣谢两位白羊座小朋友提供的技术支持!

donate the author