#define SD_CS 10
#define TFT_CS 6
#define TFT_RST 7
#define TFT_DC 8
#define ENC_CLK 2
#define ENC_DT 4
#define ENC_SW A5
#include <SD.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <SPI.h>
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
File file;
int file_idx = 1; // номер вибраного файла
volatile int enc_cnt=0;
#define MAX_CURSOR_Y 300
void setup() {
pinMode( ENC_CLK, INPUT);
pinMode( ENC_DT, INPUT);
pinMode( ENC_SW, INPUT_PULLUP);
attachInterrupt( 0, update_encoder, FALLING );
Serial.begin(9600);
tft.begin();
if ( SD.begin( SD_CS ) ) {
Serial.println("Card ok!");
while ( true ) {
get_num_file(); // вибрати робочий файл
show_pages(); // показати сторінки з файла
}
}
else {
Serial.println("No card");
while ( true ) ;
}
}
void show_pages(){
int enc_old = enc_cnt;
show_next_page();
while ( digitalRead(ENC_SW) == 1 ){
if ( enc_old < enc_cnt ){ // крутили вправо - наступна сторінка
enc_old = enc_cnt;
show_next_page();
}
if ( enc_old > enc_cnt ){ // крутили вліво - попередня сторінка
enc_old = enc_cnt;
}
}
tft.fillScreen( ILI9341_BLACK );
}
void show_next_page(){ // виводимо наступну сторінку
char c;
tft.setCursor(0,0);
tft.setTextSize(1);
tft.fillScreen( ILI9341_BLACK );
tft.println();
int font_size = tft.getCursorY();
tft.setCursor(0,0);
while ( file.available() ) {
c = file.read();
tft.write( c );
if ( tft.getCursorY() >= MAX_CURSOR_Y - font_size ) break;
}
tft.drawLine(0,MAX_CURSOR_Y, 239,MAX_CURSOR_Y, ILI9341_RED );
}
void update_encoder(){
if ( digitalRead(ENC_DT) == 1 ) enc_cnt++;
else enc_cnt--;
//Serial.println( enc_cnt );
}
void open_selected_file(){
int n=0;
File cat = SD.open("/"); // відкрити суперфайл - каталог
if ( cat ) {
while ( true ) {
file = cat.openNextFile();
if ( file ) {
if ( n == file_idx ) {
break;
}
n = n + 1;
file.close();
}
else {
break;
}
}
cat.close();
}
Serial.println( file.name() );
}
void get_num_file(){
int enc_old = enc_cnt;
show_catalog();
while ( digitalRead(ENC_SW) == 1 ){
if ( enc_old < enc_cnt ){ // крутили вправо
enc_old = enc_cnt;
file_idx++;
show_catalog();
}
if ( enc_old > enc_cnt ){ // крутили вліво
enc_old = enc_cnt;
file_idx--;
show_catalog();
}
}
open_selected_file();
}
void show_catalog(){
int n=0;
tft.setTextSize(2);
tft.setCursor(0,0);
File cat = SD.open("/"); // відкрити суперфайл - каталог
if ( cat ) {
while ( true ) {
file = cat.openNextFile();
if ( file ) {
if ( n == file_idx ) tft.setTextColor( ILI9341_WHITE );
else tft.setTextColor( ILI9341_BLACK );
tft.print("> ");
tft.setTextColor( ILI9341_WHITE );
tft.print( n );
tft.print(" ");
tft.println( file.name() );
n = n + 1;
file.close();
}
else {
break;
}
}
cat.close();
}
}
void loop() {
// put your main code here, to run repeatedly:
}