//reallocates the printing area on the SC2004CSWB by Usmar A Padow usmpadow@gmail.com and Greg Cox
#include<string.h>
#include <LiquidCrystal.h>
//LiquidCrystal lcd(12,11,2,3,4,5,6,7,8,9); // my setup (matches original 4-bit example)
LiquidCrystal lcd(A0, A1, 6, 7, 8, 9, A2, A3, A4, A5);
char buffer[20*4+1]=" ";//20*4 spaces
int pos=0;
void render_realloc() {
//clear screen
lcd.clear();
//print in correct order
for(int pos2=0;pos2<20;pos2++) lcd.print(buffer[pos2]);
for(int pos2=40;pos2<60;pos2++) lcd.print(buffer[pos2]);
for(int pos2=20;pos2<40;pos2++) lcd.print(buffer[pos2]);
for(int pos2=60;pos2<80;pos2++) lcd.print(buffer[pos2]);
}
void print2(char str[]) {
int pos2,pos3,strpo,b,spos2,posa,strpos,line;
int len = strlen(str);
//int overrun = pos+len-79;
int overrun = pos+len-80;
if(overrun>0) {
if(len>=80) {//if buffer will fill the whole screen
//for(strpo=len-79, b=0;strpo<len;strpo++, b++) {
for(strpo=len-80, b=0;strpo<len;strpo++, b++) {//fill the screen with the last 80 characters
buffer[b]=str[strpo];
}
//greg put thisbuffer[79]=' ';
//pos=79;
pos=80;
render_realloc();
return;
}
int charsleft = 80-pos;//calculate the ammount of chars that still fit in the buffer
for(posa = pos, strpos=0; strpos<=charsleft;posa++,strpos++) {//put the rest of the characters into the buffer
buffer[posa]= str[strpos];
}
int remainder = overrun % 20;
int extralines = 1+(overrun - remainder)/20; //divide by 20, removing remainder (adding 1 because at least one line of overrun)
for (line=0;line<extralines;line++) {
//scroll the display up by one line
for(pos2=20;pos2<40;pos2++) buffer[pos2-20]=buffer[pos2];//put line 2 on line 1
for(pos2=40;pos2<60;pos2++) buffer[pos2-20]=buffer[pos2];//put line 3 on line 2
for(pos2=60;pos2<80;pos2++) buffer[pos2-20]=buffer[pos2];//put line 4 on line 4
for(pos2=60,pos3=0;pos2<80;pos2++,pos3++) {
int strp = charsleft+pos3+line*20;
char ch;
if (strp>=len) {
ch = ' ';
} else {
ch = str[strp];
}
buffer[pos2]=ch;
}
pos-=20;
}
} else {//if there is no overrun, just copu the string to the buffer
for(spos2=0, pos2=pos;spos2<len;spos2++,pos2++) {
buffer[pos2]=str[spos2];
}
}
pos+=len;
render_realloc();
}
void newline() {
char spaces[21] = " ";// 20 spaces
int remainder = pos % 20;//remember the 0-19 clock story
int charsleft = 20-remainder;
spaces[charsleft]= '\0';
print2(spaces);
}
void print2ln(char str[]) {
print2(str);
newline();
}
void setup() {
lcd.begin(20, 4);
}
void cls() {
lcd.clear();
strcpy(buffer," ");//20*4 spaces
pos=0;
}
void loop() {
char tmp[100];
cls();
for (int i=47; i<127; i++) {
char tmp[2];
sprintf(tmp,"%c",i);
print2(tmp);
}
delay(5000);
//char tmp[500];
strcpy(tmp,"hello world!");
print2(tmp);
delay(5000);
newline();
newline();
strcpy(tmp,"test");
print2ln(tmp);
delay(5000);
strcpy(tmp,"1234567890abcdefghijklmnopqrstuvwxy");
print2(tmp);
delay(5000);
strcpy(tmp,"x");
print2(tmp);
delay(5000);
strcpy(tmp,"10 PRINT \"NO BEER FOR YOU!\"");
print2(tmp);
delay(5000);
}