接入教程
1. 注册Adafruit IO账户并获取API密钥
2. 在代码中配置API端点与认证信息
3. 使用HTTP请求发送/接收传感器数据
4. 创建数据流并设置触发动作
5. 通过仪表板可视化实时数据
6. 参考官方教程扩展物联网应用
Python 获取数据示例
python
import requests
base_url = 'https://io.adafruit.com/api/v2'
headers = {'X-AIO-Key': 'YOUR_API_KEY'}
# 获取用户信息
try:
response = requests.get(f'{base_url}/user', headers=headers)
response.raise_for_status()
print('User Info:', response.json())
except requests.exceptions.RequestException as e:
print('Error:', e)
PHP 发送数据示例
php
<?php
$baseUrl = 'https://io.adafruit.com/api/v2';
$apiKey = 'YOUR_API_KEY';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl . '/feeds/temperature/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-AIO-Key: ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['value' => '25.5']));
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
curl_close($ch);
?>
JavaScript 订阅数据示例
javascript
const baseUrl = 'https://io.adafruit.com/api/v2';
const apiKey = 'YOUR_API_KEY';
async function getFeedData(feedName) {
try {
const response = await fetch(`${baseUrl}/feeds/${feedName}/data`, {
headers: {
'X-AIO-Key': apiKey,
'Content-Type': 'application/json'
}
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log('Feed Data:', data);
return data;
} catch (error) {
console.error('Fetch Error:', error);
}
}
// 使用示例
getFeedData('temperature');
常见问题
如何获取API密钥?
登录Adafruit IO账户后,在控制台的'设置'或'API密钥'部分可以找到您的专属API密钥。请妥善保管,避免泄露。
API调用频率有限制吗?
是的,Adafruit IO对免费账户有每分钟30次调用的限制。如需更高频率,请考虑升级账户套餐。
支持哪些数据格式?
API支持JSON格式的数据交互,请求和响应通常使用application/json作为Content-Type。
Aitishiku.com