Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created February 21, 2015 15:07
Show Gist options
  • Save tuttlem/0b413109c8d5592b9065 to your computer and use it in GitHub Desktop.
Save tuttlem/0b413109c8d5592b9065 to your computer and use it in GitHub Desktop.
Double buffer arduino sketch
#include <Wire.h>
#include <LiquidCrystal.h>
#define LCD_WIDTH 16
#define LCD_HEIGHT 2
#define LCD_SIZE (LCD_WIDTH * LCD_HEIGHT)
class LCDDoubleBuffer {
public:
LCDDoubleBuffer(LiquidCrystal *lcd, const int width, const int height) {
this->_width = width;
this->_height = height;
this->_size = width * height;
this->_lcd = lcd;
this->_win_x = 0;
this->_win_y = 0;
this->_buffer = new char[this->_size];
}
~LCDDoubleBuffer() {
delete[] this->_buffer;
}
const int width() const { return this->_width; }
const int height() const { return this->_height; }
const int win_x() const { return this->_win_x; }
const int win_y() const { return this->_win_y; }
char* buffer() { return _buffer; }
void clear() {
memset(this->_buffer, ' ', sizeof(char) * this->_size);
}
void render() {
int buf_y = this->_win_y;
for (int y = 0; y < LCD_HEIGHT; y ++) {
int buf_x = this->_win_x;
for (int x = 0; x < LCD_WIDTH; x ++) {
this->_lcd->setCursor(x, y);
if (buf_y >= 0 && buf_y < this->_height &&
buf_x >= 0 && buf_x < this->_width) {
int ofs = buf_x + (buf_y * this->_width);
this->_lcd->print(this->_buffer[ofs]);
} else {
this->_lcd->print(" ");
}
buf_x ++;
}
buf_y ++;
}
}
void moveTo(const int x, const int y) {
this->_win_x = x;
this->_win_y = y;
}
void moveBy(const int x, const int y) {
this->_win_x += x;
this->_win_y += y;
}
void print(const int x, const int y, const char *s) {
char *o = this->_buffer + (x + (y * this->_width));
memcpy(o, s, strlen(s));
}
private:
int _width, _height, _size;
char *_buffer;
LiquidCrystal *_lcd;
int _win_x, _win_y;
};
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );
LCDDoubleBuffer dbuf(&lcd, 32, 32);
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0));
lcd.begin(16, 2);
dbuf.clear();
dbuf.print(0, 0, "Hello, world!");
}
float degs = 0.0f;
void loop()
{
float a = -3 + (cos(degs) * 5);
int x = (int)a;
dbuf.render();
dbuf.moveTo(x, 0);
delay(50);
degs += 0.1f;
if (degs > 360.0f) {
degs = 0.0f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment