/*
*/
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#define BTN_PIN 5
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
typedef int16_t fp_t;
#define FP_FRACTBITS 8
#define FP_FACTOR ((fp_t)1 << FP_FRACTBITS)
#define FLOAT2FP(f) ((fp_t)((f) * FP_FACTOR))
#define FP2FLOAT(fp) (fp * 1.0f/FP_FACTOR)
#define FP_MUL(a, b) ((a) * (b) / FP_FACTOR)
#define FP_DIV(a, b) ((a) * FP_FACTOR / (b))
void setup() {
pinMode(BTN_PIN, INPUT_PULLUP);
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Start");
Serial.begin(115200);
Serial.printf("Start !\n");
}
void loop() {
drawMandelbrot();
delay(100);
}
int mandelbrotPixel(fp_t cRe_fp, fp_t cIm_fp) {
fp_t zRe_fp = cRe_fp;
fp_t zIm_fp = cIm_fp;
int n;
const int MAX_ITER = 255;
for (n = 0; n < MAX_ITER; n++) {
fp_t zRe2_fp = FP_MUL(zRe_fp, zRe_fp);
fp_t zIm2_fp = FP_MUL(zIm_fp, zIm_fp);
if (zRe2_fp + zIm2_fp > FLOAT2FP(4.0))
break;
zIm_fp = 2 * FP_MUL(zRe_fp, zIm_fp) + cIm_fp;
zRe_fp = zRe2_fp - zIm2_fp + cRe_fp;
}
return n;
}
void drawMandelbrot() {
const int WIDTH = 320;
const int HEIGHT = 240;
uint16_t framebuffer[WIDTH * HEIGHT];
fp_t minRe_fp = FLOAT2FP(-2.0);
fp_t maxRe_fp = FLOAT2FP(1.0);
fp_t minIm_fp = FLOAT2FP(-1.2);
fp_t maxIm_fp = minIm_fp + (maxRe_fp - minRe_fp) * HEIGHT / WIDTH;
unsigned long startTime = micros();
Serial.printf("Start drawing at %ul \n", startTime);
for (int y = 0; y < HEIGHT; y++) {
fp_t cIm_fp = map(y, 0, HEIGHT-1, maxIm_fp, minIm_fp);
for (int x = 0; x < WIDTH; x++) {
fp_t cRe_fp = map(x, 0, WIDTH-1, minRe_fp, maxRe_fp);
int n = mandelbrotPixel(cRe_fp, cIm_fp);
uint16_t color = tft.color565((n % 32) * 8, (n % 64) * 4, (n % 128) * 2);
//tft.drawPixel(x, y, color);
framebuffer[y * WIDTH + x] = color;
}
}
tft.drawRGBBitmap(0, 0, framebuffer, WIDTH, HEIGHT);
unsigned long endTime = micros();
unsigned long computationTime = endTime - startTime;
Serial.printf("Done in %ul ms \n", computationTime / 1000);
tft.fillRect(0, 0, 320, 20, ILI9341_BLACK);
tft.setCursor(0, 0);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Time: ");
tft.print(computationTime/1000000.0);
tft.print(" s");
}