接线图
将 ESP8266 的 D5 引脚作为 SCL 时钟线,D6 引脚作为 SDA 数据线,连接到 AS6221


AS6221 Arduino 库
可以在 Github 找到:Chasbrot/AS6221: Arduino library for the AMS AS6221 temperature sensor
这个库可直接用在 ESP8266 上
程序编写
简单编写了一个程序,可以通过网页中的按钮切换 AS6221 的模式(连续读取、休眠、单次读取)
#include "AS6221.h"
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>
AS6221 temp;
ESP8266WiFiMulti wifiMulti;
ESP8266WebServer esp8266_server(80);
unsigned int as6221_mode = 0;
void setup() {
Wire.begin(D6, D5);
Serial.begin(9600);
wifiMulti.addAP("CMCC-xxx", "password");
Serial.println("Connecting Wifi...");
int i = 0;
while(wifiMulti.run() != WL_CONNECTED) {
delay(1000);
Serial.print(i++);
Serial.print(' ');
}
Serial.println('\n');
Serial.print("Connected to ");
Serial.println(WiFi.SSID());
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());
Serial.println("Please click the button to start reading data...");
esp8266_server.begin();
esp8266_server.on("/", HTTP_GET, handleRoot);
esp8266_server.on("/MODE", HTTP_POST, handleMODE);
esp8266_server.onNotFound(handleNotFound);
as6221_config_t conf = {
.cr = AS6221_CONV_RATE4,
.state = AS6221_STATE_ACTIVE,
.alert_mode = AS6221_ALERT_INTERRUPT,
.alert_polarity = AS6221_ALERT_ACTIVE_LOW,
.cf = AS6221_CONSEC_FAULTS2
};
temp.init(AS6221_DEFAULT_ADDRESS, conf);
temp.setAlertLimits(27, 29);
}
void loop() {
delay(1000);
esp8266_server.handleClient();
if(as6221_mode % 4 != 0)
Serial.println(temp.getTemp(), 7);
}
void handleRoot() {
esp8266_server.send(200, "text/html", "<form action=\"/MODE\" method=\"POST\"><input type=\"submit\" style=\"height: 50px; display: block; margin: auto;\" value=\"Change Mode\"></form>");
}
void handleMODE() {
as6221_mode++;
if(as6221_mode % 4 == 1) { // 默认模式(连续读取)
temp.ccMode();
Serial.println("Default Mode");
}
else if(as6221_mode % 4 == 2) { // 休息模式
temp.sleepMode();
Serial.println("Sleep Mode");
}
else if(as6221_mode % 4 == 3) { // 单次读取
temp.triggerSingleShot();
Serial.print("Trigger Single Shot: ");
Serial.println(temp.getTemp(), 7);
as6221_mode++;
}
esp8266_server.sendHeader("Location","/");
esp8266_server.send(303);
}
void handleNotFound() {
esp8266_server.send(404, "text/plain", "404: Not found");
}在 AS6221 评估板上有两组跳线帽,按照丝印修改跳线帽的位置可以修改 AS6221 的地址,默认情况下的地址是 0x48,可在初始化时修改
void init(uint8_t address, as6221_config_t conf)效果图
烧录程序到 ESP8266 后,开发板连接到 WiFi 会自动启用网站服务,进入串口监视器中显示的 IP 即可看到按钮
Connected to CMCC-422
IP address: 192.168.1.6
Please click the button to start reading data...
点击按钮可以改变模式,分别是:连续读取(默认)、休眠模式、单次读取
Connected to CMCC-422
IP address: 192.168.1.6
Please click the button to start reading data...
Default Mode
24.5781250
24.5781250
24.5546875
24.5390625
24.5390625
Sleep Mode
24.5312500
24.5312500
24.5312500
24.5312500
24.5312500
Trigger Single Shot: 24.5312500串口绘图仪绘制的温度曲线:
下载 Demo
以 GUN GPLv3 协议发布,点此下载:AS6221 Demo

