learing:examples:serialcallresponse
Serial Call and Response (handshaking)(串口应答,握手)
这个例子演示了使用握手方法从arduino到电脑的多个字符的传输
程序重复发送ASCII的A,得到电脑串口的回应之后,以单字节发送三个传感器的值,等待电脑回应
你可以使用arduino的串口监视器查看发送的数据。
MangoII
硬件要求
Arduino板 |
2个模拟传感器 |
按键或开关 |
3个10k欧姆电阻 |
连接线 |
面包板 |
软件要求
Processing
分别用10k欧姆分压电阻连接模拟传感器到A0和A1。用10k欧姆连接开关到数字口2,接地。
代码
/* Serial Call and Response */ int firstSensor = 0; // 第一个传感器 int secondSensor = 0; // 第二个传感器 int thirdSensor = 0; // 数字传感器 int inByte = 0; // 收到的串口数据 void setup() { // 开始串口通讯 Serial.begin(9600); while (!Serial) { ; // 等待串口连接,只有Leonardo板需要这一步 } pinMode(2, INPUT); // 数字口2为输入 establishContact(); // 发送字符,接收到应答之后建立连接 } void loop() { // 如果得到有效的字符,读取模拟输入 if (Serial.available() > 0) { // 获取接收数据 inByte = Serial.read(); // 读取第一个模拟输入,除以四使它在0-255之间 firstSensor = analogRead(A0) / 4; // 延时10秒使ADC稳定 delay(10); // 读取第二个模拟输入,同样除以四 secondSensor = analogRead(1) / 4; // 读取按键,映射到0-255 thirdSensor = map(digitalRead(2), 0, 1, 0, 255); // 发送传感器值 Serial.write(firstSensor); Serial.write(secondSensor); Serial.write(thirdSensor); } } void establishContact() { while (Serial.available() <= 0) { Serial.print('A'); // 发送大写字母 delay(300); } }
Processing 代码
import processing.serial.*; int bgcolor; // 背景色 int fgcolor; //填充色 Serial myPort; // 串口 int[] serialInArray = new int[3]; // 保存接收数据 int serialCount = 0; // 串口计数 int xpos, ypos; // 设置球的位置 boolean firstContact = false; // 连接微控器的位置 void setup() { size(256, 256); // 画布大小 noStroke(); // 没有线条填充色 // 设置球位置在中间 xpos = width/2; ypos = height/2; // 打印串口列表。如果使用processing2.1或者后面的版本,就使用Serial.printArray() println(Serial.list()); // 我使用了第一个串口,我知道这是我的ftdi使用的串口。根据你的需要选择你的正确的串口。 String portName = Serial.list()[0]; myPort = new Serial(this, portName, 9600); } void draw() { background(bgcolor); fill(fgcolor); // 画形状 ellipse(xpos, ypos, 20, 20); } void serialEvent(Serial myPort) { // 读取串口数据 int inByte = myPort.read(); // 如果第一个数据是A,清空串口缓冲区,此时你已经连接上了微控器,否则,把接收到的数据存到数组中 if (firstContact == false) { if (inByte == 'A') { myPort.clear(); // 清空串口缓冲区 firstContact = true; // 第一次连接上微控器 myPort.write('A'); // 获取更多 } } else { // 把从串口最新接收到的数据到数组 serialInArray[serialCount] = inByte; serialCount++; // 如果有三个字节的数据 if (serialCount > 2 ) { xpos = serialInArray[0]; ypos = serialInArray[1]; fgcolor = serialInArray[2]; // 打印到串口 println(xpos + "\t" + ypos + "\t" + fgcolor); // 发送大写字母A寻请求的传感器值 myPort.write('A'); // 重置串口计数 serialCount = 0; } } }
Processing Code
改变模拟传感器的值,球就会在屏幕上移动。只有按下按键之后,球才会出现。
learing/examples/serialcallresponse.txt · 最后更改: 2023/06/07 04:23 由 127.0.0.1