作业16:界面和应用编程[FabNotes033]

这周的作业是

为输入/输出设备写一个应用程序

为之前做的这个检测光线的板子做个小应用好了。

先试着让板子跟串口通讯,看看元件是不是正常传送检测值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "SoftwareSerial.h"

const int analogInPin = A3; // Analog input pin that the potentiometer is attached to
int sensorValue = 0; // value read from the pot

const int Rx = 2; // this is physical pin 7
const int Tx = 7; // this is physical pin 6
SoftwareSerial mySerial(Rx, Tx);

void setup() {
pinMode(Rx, INPUT);
pinMode(Tx, OUTPUT);
mySerial.begin(9600); // send serial data at 9600 bits/sec
}

void loop(){
sensorValue = analogRead(analogInPin);
mySerial.println(sensorValue);
delay(500);
}

光电晶体管工作正常。

Video

下一步,在 processing 里面写界面的程序。当检测到光线变暗时,界面提示 “-_- It’s dark!” ,如果光线变亮,提示 “it’s getting light ”:

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import processing.serial.*;
Serial myPort;
int lf = 10;

void setup(){
size(300,300);
myPort = new Serial(this,"/dev/tty.usbserial-A400gwhT",9600);
textAlign(CENTER, CENTER);
fill(255);
textSize(20);
}

void draw(){
while(myPort.available() > 0){
String str = myPort.readStringUntil(lf);

if(str!=null){
int value = Integer.parseInt(trim(str));

if (value >900) {
print("it's dark ");
println(value);
background(0,0,0);
text("-_- It's dark! ",150,120);
text(value,150,200);
}
else{
print("it's getting light ");
println(value);
background(204,153,0);
text(":P It's getting light ",150,120);
text(value,150,200);
}
}
}
}

课程资源

kidult00 wechat
扫码关注 00 的公众号
如果文章帮您节省时间或者解答疑问,不妨打个赏 :)