Xiao ESP32C3使用oled 0.96实现下雪的功能
-
- 雪花下落的时候, 随机生成半径和位置 sandR和sandX,sandY
-
- 保存雪花下落位置的时候, 将其周边一圈设置为-1, 标记为有雪花
-
- 其他雪花下落的时候, 其他雪花的一圈如果遇到-1, 则停止下落, 并重复2
#include "oled.h"
void setup() {
Serial.begin(115200);
oled_init();
randomSeed(micros());
print_vulnerability_init();
}
void run900msTasks() {
oled.clearDisplay();
playSnowing();
oled.display();
}
#ifndef __OLED_H_
#define __OLED_H_
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
static Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
void oled_init() {
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;)
;
}
Serial.println(F("SSD1306 allocation success!!!"));
oled.display();
delay(500);
oled.setTextSize(1);
oled.setTextColor(WHITE);
oled.setRotation(0);
oled.clearDisplay();
delay(1000);
}
void oled_println(int16_t x, int16_t y, const char *msg) {
oled.setCursor(x, y);
oled.println(msg);
}
struct snow {
int numPoints = 10;
int snows[SCREEN_WIDTH][SCREEN_HEIGHT];
int sandX = 0;
int sandY = 0;
int sandR = 1;
void init() {
for (int i=0; i<SCREEN_WIDTH; i++) {
for(int j=0; j<SCREEN_HEIGHT; j++) {
snows[i][j] = 0;
}
}
random_snow_pos();
}
void setSnow(int x, int y, int r) {
sandX = x;
sandY = y;
sandR = r;
}
void random_snow_pos() {
setSnow(0, random(0, SCREEN_HEIGHT), random(2, 5));
}
void snowToSnows() {
snows[sandX][sandY] = sandR;
}
void move(int distance) {
sandX+=distance;
}
bool collideBorder() {
if(sandX >= SCREEN_WIDTH || sandY >= SCREEN_HEIGHT) return true;
for (int i = 0; i < numPoints; i++) {
float theta = (float)i / numPoints * 2 * PI;
int x = sandX + sandR * cos(theta);
int y = sandY + sandR * sin(theta);
if(x>=0 && y>=0 && snows[x][y] != 0) return true;
}
return false;
}
void setSnowEdge() {
for (int i = 0; i < numPoints; i++) {
float theta = (float)i / numPoints * 2 * PI;
int x = sandX + sandR * cos(theta);
int y = sandY + sandR * sin(theta);
snows[x][y] = -1;
}
}
} snow;
void print_vulnerability_init() {
for(int i=0; i<SCREEN_HEIGHT; i++) {
snow.snows[SCREEN_WIDTH-1][i] = 1;
}
snow.snows[60][10] = 1;
snow.random_snow_pos();
}
void print_snow() {
for (int i=0; i<SCREEN_WIDTH; i++) {
for(int j=0; j<SCREEN_HEIGHT; j++) {
if(snow.snows[i][j] <= 0) {
continue;
} else {
oled.fillCircle(i, j, snow.snows[i][j], WHITE);
}
}
}
}
void playSnowing() {
int while_i = 0;
Serial.print(",");
Serial.print(snow.sandX);
Serial.print(",");
Serial.println(snow.sandY);
while(snow.collideBorder()) {
snow.snowToSnows();
snow.setSnowEdge();
snow.random_snow_pos();
while_i ++ ;
if(while_i == 100) {
snow.init();
break;
}
}
oled.fillCircle(snow.sandX, snow.sandY, snow.sandR, WHITE);
snow.move(1);
print_snow();
}
#endif