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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
| // ============================================================
// 完整示例:基于STM32的温湿度监控系统
// ============================================================
#include <cstdint>
#include <array>
// -------------------------------------------
// 硬件抽象层
// -------------------------------------------
class Hardware {
public:
static void init() {
// 禁用所有中断
__asm volatile ("cpsid i" : : : "memory");
// 配置系统时钟
SystemClock_Config();
// 配置GPIO
GPIO_Config();
// 配置UART(用于调试输出)
UART1_Config();
// 配置I2C
I2C1_Config();
// 配置定时器(用于系统tick)
Timer2_Config();
// 启用中断
__asm volatile ("cpsie i" : : : "memory");
}
// 简化实现
static void SystemClock_Config() { /* 168MHz PLL */ }
static void GPIO_Config() { /* LED, Button, I2C pins */ }
static void UART1_Config() { /* 115200-8-N-1 */ }
static void I2C1_Config() { /* 100kHz */ }
static void Timer2_Config() { /* 1ms tick */ }
};
// -------------------------------------------
// 传感器驱动
// -------------------------------------------
class SI7021 {
public:
static constexpr uint8_t I2C_ADDR = 0x40;
static bool measure(float& humidity, float& temperature) {
uint8_t cmd = 0xF5; // Measure Humidity, Hold Master Mode
uint8_t data[2];
if (!I2C_WriteRead(I2C_ADDR, &cmd, 1, data, 2)) {
return false;
}
uint16_t humRaw = (data[0] << 8) | data[1];
humidity = (125.0f * humRaw / 65536.0f) - 6.0f;
// 读取温度
cmd = 0xE0; // Read Previous Temperature
if (!I2C_WriteRead(I2C_ADDR, &cmd, 1, data, 2)) {
temperature = 0;
return false;
}
uint16_t tempRaw = (data[0] << 8) | data[1];
temperature = (175.72f * tempRaw / 65536.0f) - 46.85f;
return true;
}
private:
static bool I2C_WriteRead(uint8_t addr, uint8_t* tx, size_t txLen,
uint8_t* rx, size_t rxLen);
};
// -------------------------------------------
// 数据存储(环形缓冲区)
// -------------------------------------------
template<typename T, size_t N>
class CircularDataBuffer {
public:
bool add(const T& item) {
if (isFull()) return false;
data_[tail_] = item;
tail_ = (tail_ + 1) % N;
return true;
}
T* get(size_t index) {
if (index >= size()) return nullptr;
return &data_[(head_ + index) % N];
}
bool isFull() const { return size() == N; }
bool isEmpty() const { return head_ == tail_; }
size_t size() const {
if (tail_ >= head_) return tail_ - head_;
return N - head_ + tail_;
}
void clear() { head_ = tail_ = 0; }
private:
std::array<T, N> data_;
size_t head_ = 0;
size_t tail_ = 0;
};
// -------------------------------------------
// 显示器(OLED SSD1306)
// -------------------------------------------
class OLED1306 {
public:
static void init() {
// 初始化序列
sendCommand(0xAE); // Display off
sendCommand(0xD5); sendCommand(0x80); // Clock
sendCommand(0xA8); sendCommand(0x3F); // Mux ratio
sendCommand(0xD3); sendCommand(0x00); // Display offset
sendCommand(0x40); // Start line
sendCommand(0x8D); sendCommand(0x14); // Charge pump
sendCommand(0xA1); // Segment remap
sendCommand(0xC8); // COM scan direction
sendCommand(0xDA); sendCommand(0x12); // COM pins
sendCommand(0x81); sendCommand(0xCF); // Contrast
sendCommand(0xD9); sendCommand(0xF1); // Pre-charge
sendCommand(0xDB); sendCommand(0x40); // VCOMH
sendCommand(0xA4); // Display ON
clear();
}
static void clear() {
for (int page = 0; page < 8; ++page) {
setCursor(0, page);
for (int col = 0; col < 128; ++col) {
sendData(0x00);
}
}
}
static void print(const char* str, uint8_t x, uint8_t y) {
setCursor(x, y);
while (*str) {
sendData(font5x7[*str - 32]);
++str;
}
}
static void printFloat(float val, uint8_t x, uint8_t y, int decimal = 2) {
char buf[16];
int len = snprintf(buf, sizeof(buf), "%.*f", decimal, val);
print(buf, x, y);
}
private:
static void sendCommand(uint8_t cmd);
static void sendData(uint8_t data);
static void setCursor(uint8_t x, uint8_t y);
static const uint8_t font5x7[95 * 5]; // 字体数据
};
// -------------------------------------------
// 主应用
// -------------------------------------------
class WeatherStation {
public:
WeatherStation()
: displayUpdateCounter_(0),
sensorErrorCount_(0),
lastHumidity_(0),
lastTemperature_(0) {}
void init() {
Hardware::init();
OLED1306::init();
OLED1306::print("Weather Station", 0, 0);
OLED1306::print("Initializing...", 0, 2);
// 传感器自检
if (!testSensors()) {
OLED1306::print("Sensor Error!", 0, 4);
while (true); // 停机
}
OLED1306::print("Ready!", 0, 4);
delay_ms(1000);
OLED1306::clear();
}
void run() {
// 读取传感器
if (readSensors()) {
// 数据有效,存储并显示
storeData();
updateDisplay();
} else {
// 传感器错误处理
handleSensorError();
}
}
private:
bool testSensors() {
float h, t;
return SI7021::measure(h, t);
}
bool readSensors() {
float h, t;
if (SI7021::measure(h, t)) {
lastHumidity_ = h;
lastTemperature_ = t;
sensorErrorCount_ = 0;
return true;
}
return false;
}
void storeData() {
Reading reading = {
getTick(),
lastTemperature_,
lastHumidity_
};
buffer_.add(reading);
}
void updateDisplay() {
if (++displayUpdateCounter_ >= 10) { // 每10次循环更新一次(约1秒)
displayUpdateCounter_ = 0;
OLED1306::clear();
OLED1306::print("Temperature:", 0, 0);
OLED1306::printFloat(lastTemperature_, 70, 0);
OLED1306::print("C", 110, 0);
OLED1306::print("Humidity:", 0, 2);
OLED1306::printFloat(lastHumidity_, 70, 2);
OLED1306::print("%", 110, 2);
OLED1306::print("Samples:", 0, 4);
char buf[16];
snprintf(buf, sizeof(buf), "%d", static_cast<int>(buffer_.size()));
OLED1306::print(buf, 70, 4);
// 如果有错误,显示警告
if (sensorErrorCount_ > 0) {
OLED1306::print("Err:", 0, 6);
snprintf(buf, sizeof(buf), "%d", sensorErrorCount_);
OLED1306::print(buf, 40, 6);
}
}
}
void handleSensorError() {
sensorErrorCount_++;
if (sensorErrorCount_ > 10) {
// 连续错误,尝试重启传感器
sensorErrorCount_ = 0;
// 复位I2C总线等
}
}
struct Reading {
uint32_t timestamp;
float temperature;
float humidity;
};
CircularDataBuffer<Reading, 64> buffer_;
uint32_t displayUpdateCounter_;
uint8_t sensorErrorCount_;
float lastHumidity_;
float lastTemperature_;
};
// -------------------------------------------
// 主函数
// -------------------------------------------
int main() {
WeatherStation station;
station.init();
while (true) {
station.run();
delay_ms(100);
}
return 0;
}
|