Plot an array into bitmap in C/C++ for thermal printer

混江龙づ霸主 提交于 2019-12-02 08:36:36
Chris K

The algorithm for this took three main stages:
1) Translate the Y from top left to bottom left.
2) Break up the X into word:bit values.
3) Use Bresenham's algorithm to draw lines between the points. And then figure out how to make the line thicker.

For my exact case, the target bitmap is 384x384, so requires 19k of SRAM to store in memory. I had to ditch the "lame" Arduino Mega and upgrade to the ChipKIT uC32 to pull this off, 32k of RAM, 80 MHz cpu, & twice the I/O!

The way I figured out this was to base my logic on Adafruit's Thermal library for Arduino. In their examples, they include how to convert a 1-bit bitmap into a static array for printing. I used their GFX library to implement the setXY function as well as their GFX Bresenham's algorithm to draw lines between (X,Y)s using my setXY().

It all boiled down to the code in this function I wrote:

// *bitmap is global or class member pointer to byte array of size 384/8*384
// bytesPerRow is 384/8
void setXY(int x, int y) {
    //  integer divide by 8 (/8) because array size is byte or char
    int xByte = x/8;
    //  modulus 8 (%8) to get the bit to set
    uint8_t shifty = x%8;
    //  right shift because we start from the LEFT
    int xVal = 0x80 >> shifty;
    //  inverts Y from bottom to start of array
    int yRow = yMax - y;
    //  Get the actual byte in the array to manipulate
    int offset = yRow*bytesPerRow + xByte;
    //  Use logical OR in case there is other data in the bitmap,
    //  such as a frame or a grid
    *(bitmap+offset)|=xVal;
}

The big point is to remember with an array, we are starting at the top left of the bitmap, going right across the row, then down one Y row and repeating. The gotchya's are in translating the X into the word:bit combo. You've got to shift from the left (sort-of like translating the Y backwards). Another gotchya is one-off error in bookkeeping for the Y.

I put all of this in a class, which helped prevent me from making one big function to do it all and through better design made the implementation easier than I thought it would be.

Pic of the printout:


Write-up of the project is here.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!