Ed Nisley's Blog: Shop notes, electronics, firmware, machinery, 3D printing, laser cuttery, and curiosities. Contents: 100% human thinking, 0% AI slop.
The motor winding resistance limits the peak current to about 200 V / 40 Ω = 5 A, in the absence of the transistor current limiter, and, if it gets above that, things have gone very, very wrong. Mostly, I expect currents under 1 A and it may be useful to reduce the full scale appropriately.
The cheap eBay “SS49” Hall effect sensors I’m using produce anywhere between 0.9 and 1.8 mV/G; I’ll use 1.4 mV/G, which is at least close to the original Honeywell spec. That allows a bit over ±1000 G around the sensor’s VCC/2 bias within its output voltage range (the original datasheet says minimum ±650 G), so I’ll use B = 1000 G as the maximum magnetic flux density. The overall calibration will be output voltage / input current and I’m not above doing a one-off calibration run and baking the constant into the firmware.
The effective mean path length turns out to be a useful value for a slit toroid:
effective MPL = (toroid MPL - air gap length) + (µ · air gap length)
The SS49 style sensor spec says they’re 1.6 mm thick, and the saw-cut gaps run a bit more, but 1.5 mm will be close enough for now.
The relation between all those values:
B = 0.4 π µ NI / (effective MPL)
Solving for NI:
NI = B · (eff MPL) / (0.4 π µ)
Solving for N:
N = B · (eff MPL) / (0.4 π µ I)
You always round up the result for N, because fractional turns aren’t a thing you can do with a toroid.
The saturation flux density seems to be measured at H = 10 Oe, but that applies to the intact toroids. The air gap dramatically reduces the effective µ, so you must apply a higher H to get the same B in the ferrite at saturation. At least, I think that’s the way it should work.
H = 0.4 π NI / (geometric MPL)
Then:
FT50-61: H = 58 Oe
FT82-43: H = 30 Oe
I’m surely missing some second-order effect that invalidates all those numbers.
Figuring the wire size for the windings:
FT50:
ID = 0.281 inch
Circumference = 0.882 inch
28 turns → wire OD = 0.882/28 = 31 mil
20 AWG without insulation
FT82:
ID = 0.520 inch
Circumference = 1.63 inch
25 turns → wire OD = 1.63/25 = 65 mil
14 AWG without insulation
Of course, the wire needs insulation, but, even so, the FT82 allows a more rational wire size.
Page 4.12 of the writeup from Magnetics Inc has equations and a helpful chart. They suggest water cooling a diamond-bonded wheel during the slitting operation; my slapdash technique worked only because I took candy-ass cuts.
Mulling over how to add a 1/rev sensor to the sewing machine motor, it occurred to me that simply drilling a hole through the pulley would provide a clean optical path and a convenient 2/rev output signal.
However, the OEM pulley doesn’t extend beyond the end of the shaft:
Kenmore 158 – AC drive motor – overview
Rather than drill a hole in the shaft or (attempt to) affix something onto a pulley that spins at 10 kRPM, I figured I should make another pulley and mutilate that.
Because this will surely call for more than one new pulley before I get everything right, a lathe form tool seemed in order. Introducing a suitable blank from the Bin o’ 1/4 Inch Bits to Mr. Bench Grinder produced a likely looking candidate, with an included angle of about 35° (a skosh over 17° on each side) and sized just a wee bit narrower than the pulley groove.
From the top:
Pulley form tool – top
From the side:
Pulley form tool – side
Skim the surface of a 5/8 inch rod to match the pulley OD, plunge a cutoff tool to make most of the cut, insert bit in holder, align perpendicular to workpiece, line up to center of cut, slobber on more cutting lube:
Pulley form tool – prepared blank
Plunging the tool slowly into the cut produces … no chips … nothing … smoke?
Come to find out that the Bin o’ 1/4 Inch Bits contained not just lathe tool bits & blanks made from tool steel, but one length of 1/4 inch square key stock made from ordinary soft steel:
Pulley form tool – damage
I should have known that from the type of sparks flying off the grinding wheel, right?
You knew that just from looking at the first picture, because a real lathe bit blank wouldn’t be all beat to shit…
Mary recently learned that large spools of thread have a cross-wound lay that should feed over the end, not from the side as do ordinary stack-wound spools. So I built a right-angle adapter that fits over the not-quite-vertical spool pin on the sewing machine and aims directly at the thread tensioner:
Large spool adapter – on sewing machine
The solid model shows off the fluted rod that passes through the spool:
Large Spool Adapter – solid model – mount
It’s more impressive from the other end:
Large Spool Adapter – solid model – spool end
The first pass at the rod had six flutes, but that seemed unreasonably fine; now it has four. The round base on the rod provides more griptivity to the platform while building and has enough space for the two alignment pins that position it in the middle of the dome:
Large Spool Adapter – solid model – alignment holes
The dome gets glued to the rod base plate:
Large spool adapter – clamped
The spool pin hole is a snug fit around the pin on the sewing machine, because otherwise it would tend to rotate until the spool pointed to the rear of the machine. The fluted rod is a snug friction fit inside the (cardboard) spool. Some useful dimensions:
Spool pin (on Model 158): 5 mm OD, 40 mm tall
Large spool cores: 16 mm ID, 27 mm OD, 70 mm long
I had all manner of elaborate plans to make an expanding fluted rod, but came to my senses and built the simple version first. If that rod isn’t quite big enough, I can build another adapter, just like this one, only slightly larger. The source code includes a 0.5 mm taper, which may suffice.
Back in the day, shortly after the Thing-O-Matic started producing dependable results, one of the very first things I made was a simple adapter to mount large spools on the pin in the most obvious way:
Large spool adapter – old TOM version
Now we all know better than that, my OpenSCAD-fu has grown stronger, and the M2 produces precise results. Life is good!
The OpenSCAD source code:
// Large thread spool adapter
// Ed Nisley - KE4ZNU - August 2014
Layout = "Show"; // Build Show Spindle Spool
Gap = 10.0; // between pieces in Show
//- Extrusion parameters must match reality!
// Print with 4 shells and 3 solid layers
ThreadThick = 0.20;
ThreadWidth = 0.40;
HoleWindage = 0.2; // extra clearance
Protrusion = 0.1; // make holes end cleanly
AlignPinOD = 1.70; // assembly alignment pins: filament dia
function IntegerMultiple(Size,Unit) = Unit * ceil(Size / Unit);
//----------------------
// Dimensions
LEN = 0; // subscripts for cylindrical objects
ID = 1;
OD = 2;
Spindle = [40.0,5.0,14.0]; // spool spindle on sewing machine
Spool = [70.0,16.0,27.0]; // spool core
Taper = 0.50; // spool diameter increase at base
CottonRoll = [65.0,Spool[OD],45.0]; // thread on spool
Mount = [Spindle[LEN],(Spindle[ID] + 4*ThreadWidth),1.0*Spool[ID]];
Flutes = 4;
Flange = [2.0,Spool[OD],Spool[OD]];
ScrewHole = [10.0,4.0 - 0.7,5.0]; // retaining screw
PinOC = Spool[ID]/4; // alignment pin spacing
//----------------------
// Useful routines
module PolyCyl(Dia,Height,ForceSides=0) { // based on nophead's polyholes
Sides = (ForceSides != 0) ? ForceSides : (ceil(Dia) + 2);
FixDia = Dia / cos(180/Sides);
cylinder(r=(FixDia + HoleWindage)/2,
h=Height,
$fn=Sides);
}
module ShowPegGrid(Space = 10.0,Size = 1.0) {
RangeX = floor(100 / Space);
RangeY = floor(125 / Space);
for (x=[-RangeX:RangeX])
for (y=[-RangeY:RangeY])
translate([x*Space,y*Space,Size/2])
%cube(Size,center=true);
}
//- Locating pin hole with glue recess
// Default length is two pin diameters on each side of the split
module LocatingPin(Dia=AlignPinOD,Len=0.0) {
PinLen = (Len != 0.0) ? Len : (4*Dia);
translate([0,0,-ThreadThick])
PolyCyl((Dia + 2*ThreadWidth),2*ThreadThick,4);
translate([0,0,-2*ThreadThick])
PolyCyl((Dia + 1*ThreadWidth),4*ThreadThick,4);
translate([0,0,-(Len/2 + ThreadThick)])
PolyCyl(Dia,(Len + 2*ThreadThick),4);
}
//----------------------
// Spindle
module SpindleMount() {
render(convexity=4)
difference() {
union() {
resize([0,0,Mount[OD]]) // spool backing plate
translate([0,CottonRoll[OD]/2,0])
sphere(d=CottonRoll[OD],center=true);
translate([0,CottonRoll[OD]/4,0]) // mounting post
rotate([90,0,0])
cylinder(d=Mount[OD],h=CottonRoll[OD]/2,center=true);
}
translate([0,(2*Mount[LEN] - Protrusion),Mount[OD]/4]) // punch spindle hole
rotate([90,0,0])
// PolyCyl(Spindle[ID],2*Mount[LEN],6);
cylinder(d=Spindle[ID],h=2*Mount[LEN],$fn=6);
for (i=[-1,1]) { // punch alignment pin holes
translate([i*PinOC,CottonRoll[OD]/2,0])
LocatingPin(Len=Mount[OD]/3);
}
translate([0,0,-CottonRoll[OD]]) // remove half toward spool
cube(2*CottonRoll[OD],center=true);
}
}
//----------------------
// Spool holder
module SpoolMount() {
difference() {
union() {
translate([0,0,(Flange[LEN] - Protrusion)])
difference() {
cylinder(d1=(Spool[ID] + Taper),d2=Spool[ID],h=Spool[LEN],$fn=2*Flutes); // fit spool ID
for (a=[0 : 360/Flutes : 360-1]) // create flutes
rotate(a + 180/Flutes)
translate([Spool[ID]/2,0,-Protrusion])
rotate(180/16)
cylinder(r=Spool[ID]/4,h=(Spool[LEN] + 2*Protrusion),$fn=16);
translate([0,0,(Spool[LEN] - ScrewHole[LEN])]) // punch screw hole
PolyCyl(ScrewHole[ID],(ScrewHole[LEN] + Protrusion),6);
}
cylinder(d=Flange[OD],h=Flange[LEN]); // base flange
}
for (i=[-1,1]) // punch alignment pin holes
translate([0,i*PinOC,0]) // ... orients solid flange up
LocatingPin(Len=Flange[LEN]);
}
}
ShowPegGrid();
if (Layout == "Spindle") {
SpindleMount();
}
if (Layout == "Spool") {
SpoolMount();
}
if (Layout == "Show") {
translate([0,Mount[OD]/4,2.0]) {
rotate([90,0,0])
SpindleMount();
translate([0,Gap,CottonRoll[OD]/2])
rotate([-90,0,0]) rotate(90)
SpoolMount();
}
color("Orange") {
translate([0,0,2])
cylinder(d=Spindle[ID],h=Spindle[LEN],$fn=6);
cylinder(d=Spindle[OD],h=2.0,$fn=18);
}
}
if (Layout == "Build") {
translate([-5,0,0])
rotate(90)
SpindleMount();
translate([Flange[OD]/2,0,0])
SpoolMount();
}
The motor current (200 mA/div) never goes to zero, but the ET227 collector voltage hits zero as the transistor saturates: the motor winding soaks up all the available line voltage and the transistor dissipation drops close to zero. The datasheet suggests VCE(sat) < 0.1 V for IC < 5 A, albeit with IB = 30 A (!).
The ET227 base drive was 77 mA, measured on a better meter than the low-resolution one in the power supply, and the transistor gain works out to 8 = 620 mA / 77 mA along those flat tops.
Eyeballometrically speaking, the dissipation averages 50 W = 90 V x 620 mA during those spiky sections where the transistor must absorb the difference between the line voltage and the motor voltage. The cursors say that takes 5 ms of the 8.3 ms period of the 120 Hz full wave rectified power, so the duty cycle is 42% and the average average dissipation works out to 20 W. That’s still enough to warm up that big heatsink; the motor driver will need a thermal sensor and a quiet fan.
That commutation noise looks pretty scary, doesn’t it?
The test setup:
Kenmore 158 – AC motor FW ET227 drive – test setup
The bridge rectifier doesn’t really need a heatsink, but it looked better for a Circuit Cellar picture…
Took a picture of the sewing machine setup with the Sony DSC-F717, transferred it into DigiKam, got the “done transferring, you can disconnect the camera” message, believed it, disconnected the camera, deleted the image file, and then discovered that DigiKam mislaid the image file.
Rather than re-set-up and re-take the shot, I followed my own directions and recovered the image from the Memory Stick:
dmesg | tail
[43176.079853] usb 2-1.6.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[43176.079855] usb 2-1.6.3: Product: Sony PTP
[43176.079856] usb 2-1.6.3: Manufacturer: Sony
[43198.073652] usb 2-1.6.3: USB disconnect, device number 22
[43333.788533] sd 9:0:0:0: [sdc] 1947648 512-byte logical blocks: (997 MB/951 MiB)
[43333.803292] sd 9:0:0:0: [sdc] No Caching mode page found
[43333.803299] sd 9:0:0:0: [sdc] Assuming drive cache: write through
[43333.824681] sd 9:0:0:0: [sdc] No Caching mode page found
[43333.824688] sd 9:0:0:0: [sdc] Assuming drive cache: write through
[43333.825491] sdc: sdc1
sudo dd if=/dev/sdc of=/tmp/pix.bin bs=1M
^C615+0 records in
614+0 records out
643825664 bytes (644 MB) copied, 38.5841 s, 16.7 MB/s
strings -t x pix.bin | grep Exif | head
68006 Exif
208006 Exif
3f8005 _Exif
7b8006 Exif
13d8006 Exif
15b0005 wExif
1798005 CExif
19c0006 Exif
1b90006 Exif
1f98005 %Exif
dd if=pix.bin of=image03.jpg bs=$((16#1000)) count=1K skip=$((16#3f8))
1024+0 records in
1024+0 records out
4194304 bytes (4.2 MB) copied, 0.0121431 s, 345 MB/s
display image03.jpg
convert image03.jpg dsc00656.jpg
Obviously, there was a bit more flailing around than you see here, but that’s the gist of the adventure. For what it’s worth, image01 was a random blurred shot and image02 is the ID picture I keep on all my cameras.
The convert step discards all the junk after the end of the image, so the dsc00656.jpg file doesn’t include anything unexpected.
The picture isn’t all that much to look at, even after cropping out the background, but …
Kenmore 158 – stepper drive test
The advantage of the manual method: renewing one’s acquaintance with tools that come in handy for other tasks.
For some reason, WordPress chokes when uploading the starting shape as a PNG file, so here it is as a JPG with a black border replacing the original transparency:
gel_shape
With the gel highlight:
gel_highlight
Adding a border:
gel_border
Adding text, shadow, and background:
gel_button
Adding the drop shadow may increase the image size ever so slightly, so the -repage 0x0+7+7 operation may require resetting the exact image size.
The smaller buttons came directly from The GIMP, with full-frontal manual control over everything. Obviously, that doesn’t scale well for many buttons that should all look pretty much the same, because you want to get your fingers out of the loop.
But, obviously, when you do this on a mass scale, you want better control over the colors and text and suchlike; that’s in the nature of fine tuning when it’s needed.
I’m not entirely convinced I want gel-flavored buttons, but it was a fun exercise.
The Adafruit 2.8 inch TFT Touch Shield for Arduino v2 seems just about ideal for a small control panel, such as one might use with a modified sewing machine. All you need is a few on-screen buttons, a few status display, and a bit of Arduino love: what more could one ask?
So I gimmicked up some small buttons with GIMP, made two large buttons with ImageMagick, and lashed together some Arduino code based on the Adafruit demo:
Adafruit TFT display – timing demo
The picture doesn’t do justice to the display: it’s a nice piece of hardware that produces a crisp image. The moire patterns come from the interaction of TFT display pixels / camera pixels / image resizing.
It’s not obvious from the Adafruit description, but the display is inherently portrait-mode as shown. The (0,0) origin lies in the upper left corner, just over the DC power jack, and screen buffer updates proceed left-to-right, top-to-bottom from there.
The gotcha: even with the Arduino Mega’s hardware SPI, writing the full display requires nearly 4 seconds. Yeah, slow-scan TV in action. Writing the screen with a solid color requires several seconds.
After commenting out the serial tracing instructions from the Adafruit demo and tweaking a few other things, these timings apply:
-------------
Writing background
Elapsed: 3687
Writing six buttons
Elapsed: 529
Overwriting six buttons
Elapsed: 531
Rewriting buttons 10 times
Elapsed: 1767
Overwriting 2 large buttons
Elapsed: 1718
The button images come from BMP files on a MicroSD card and 8 KB of RAM won’t suffice for even a small button. Instead, the transfer loop buffers 20 pixels = 60 bytes from the card, writes them to the display, and iterates until it’s done.
Trust me on this: watching the buttons gradually change is depressing.
Yes, it could work as a control panel for the sewing machine, but it doesn’t have nearly the pep we’ve come to expect from touch-screen gadgetry. On the other paw, Arduinos are 8-bit microcontrollers teleported from the mid-90s, when crappy 20×4 LCD panels were pretty much as good as it got.
The SPI hardware clock runs at half the oscillator frequency = 16 MHz/2 = 8 MHz = 125 ns/bit. Clocking a single byte thus requires 1 µs; even allowing that each pixel = 3 bytes = 6 SPI operations, there’s a lot of software overhead ripe for the chopping block. I’d be sorely tempted to write a pair of unrolled loops that read 20 pixels and write 20 pixels with little more than a pointer increment & status spin between successive SPI transfers.
It’ll make hotshot C++ programmers flinch, but splicing all that into a single routine, throwing out all the clipping and error checking, and just getting it done might push the times down around 20 µs/pixel. Admittedly, that’s barely twice as fast, but should be less depressing.
However, even with all that effort, the time required to update the screen will clobber the motor control. You can’t devote a big fraction of a second to rewriting a button at the same time you’re monitoring the pedal position, measuring the motor speed, and updating the control voltage. That’s the same problem that makes Arduino microcontrollers inadequate for contemporary 3D printers: beyond a certain point, the hardware is fighting your efforts, not helping you get things done.
A reasonable workaround: no screen updates while the motor turns, because you shouldn’t have any hands free while you’re sewing.
The Arduino source code, hacked from the Adafruit demo:
// 2.8 inch TFT display exercise
// Crudely hacked from Adafruit demo code: spitftbitmap.ino
// 2014-07-03 Ed Nisley KE4ZNU
/***************************************************
This is our Bitmap drawing example for the Adafruit ILI9341 Breakout and Shield
----> http://www.adafruit.com/products/1651
Check out the links above for our tutorials and wiring diagrams
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional)
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_GFX.h> // Core graphics library
#include "Adafruit_ILI9341.h" // Hardware-specific library
#include <SPI.h>
#include <SD.h>
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
#define SD_CS 4
unsigned long MillisNow, MillisThen;
void setup(void) {
Serial.begin(115200);
tft.begin();
tft.fillScreen(ILI9341_BLACK);
Serial.print(F("Initializing SD card..."));
if (!SD.begin(SD_CS)) {
Serial.println(F("failed!"));
}
Serial.println(F("OK!"));
}
void loop() {
Serial.println(F("--------------"));
Serial.println(F("Writing background"));
MillisThen = millis();
bmpDraw("Test1.bmp", 0, 0);
MillisNow = millis();
Serial.print(F("" Elapsed: ""));
Serial.println(MillisNow - MillisThen);
Serial.println(F("Writing 6 small buttons"));
MillisThen = millis();
bmpDraw("Red50x25.bmp",10,10);
bmpDraw("Red50x25.bmp",10,50);
bmpDraw("Red50x25.bmp",10,100);
bmpDraw("Grn50x25.bmp",80,25);
bmpDraw("Grn50x25.bmp",80,75);
bmpDraw("Grn50x25.bmp",80,125);
MillisNow = millis();
Serial.print(F("" Elapsed: ""));
Serial.println(MillisNow - MillisThen);
Serial.println(F("Overwriting 6 small buttons"));
MillisThen = millis();
bmpDraw("Grn50x25.bmp",10,10);
bmpDraw("Grn50x25.bmp",10,50);
bmpDraw("Grn50x25.bmp",10,100);
bmpDraw("Red50x25.bmp",80,25);
bmpDraw("Red50x25.bmp",80,75);
bmpDraw("Red50x25.bmp",80,125);
MillisNow = millis();
Serial.print(F("" Elapsed: ""));
Serial.println(MillisNow - MillisThen);
Serial.println(F("Writing small button 10x2 times"));
MillisThen = millis();
for (byte i=0; i<10; i++) {
bmpDraw("Grn50x25.bmp",10,175);
bmpDraw("Red50x25.bmp",10,175);
}
MillisNow = millis();
Serial.print(F("" Elapsed: ""));
Serial.println(MillisNow - MillisThen);
Serial.println(F("Overwriting 2 large buttons"));
MillisThen = millis();
bmpDraw("GelDn.bmp",0,250);
bmpDraw("GelUp.bmp",0,250);
bmpDraw("GelUp.bmp",120,250);
bmpDraw("GelDn.bmp",120,250);
MillisNow = millis();
Serial.print(F("" Elapsed: ""));
Serial.println(MillisNow - MillisThen);
}
// This function opens a Windows Bitmap (BMP) file and
// displays it at the given coordinates. It's sped up
// by reading many pixels worth of data at a time
// (rather than pixel by pixel). Increasing the buffer
// size takes more of the Arduino's precious RAM but
// makes loading a little faster. 20 pixels seems a
// good balance.
#define BUFFPIXEL 20
void bmpDraw(char *filename, uint8_t x, uint16_t y) {
File bmpFile;
int bmpWidth, bmpHeight; // W+H in pixels
uint8_t bmpDepth; // Bit depth (currently must be 24)
uint32_t bmpImageoffset; // Start of image data in file
uint32_t rowSize; // Not always = bmpWidth; may have padding
uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer
boolean goodBmp = false; // Set to true on valid header parse
boolean flip = true; // BMP is stored bottom-to-top
int w, h, row, col;
uint8_t r, g, b;
uint32_t pos = 0, startTime = millis();
if((x >= tft.width()) || (y >= tft.height())) return;
// Serial.println();
// Serial.print(F("Loading image '"));
// Serial.print(filename);
// Serial.println('\'');
// Open requested file on SD card
if ((bmpFile = SD.open(filename)) == NULL) {
// Serial.print(F("File not found"));
return;
}
// Parse BMP header
if(read16(bmpFile) == 0x4D42) { // BMP signature
// Serial.print(F("File size: "));
// Serial.println(read32(bmpFile));
read32(bmpFile);
(void)read32(bmpFile); // Read & ignore creator bytes
bmpImageoffset = read32(bmpFile); // Start of image data
// Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
// Read DIB header
// Serial.print(F("Header size: "));
// Serial.println(read32(bmpFile));
read32(bmpFile);
bmpWidth = read32(bmpFile);
bmpHeight = read32(bmpFile);
if(read16(bmpFile) == 1) { // # planes -- must be '1'
bmpDepth = read16(bmpFile); // bits per pixel
// Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth);
if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed
goodBmp = true; // Supported BMP format -- proceed!
// Serial.print(F("Image size: "));
// Serial.print(bmpWidth);
// Serial.print('x');
// Serial.println(bmpHeight);
// BMP rows are padded (if needed) to 4-byte boundary
rowSize = (bmpWidth * 3 + 3) & ~3;
// If bmpHeight is negative, image is in top-down order.
// This is not canon but has been observed in the wild.
if(bmpHeight < 0) {
bmpHeight = -bmpHeight;
flip = false;
}
// Crop area to be loaded
w = bmpWidth;
h = bmpHeight;
if((x+w-1) >= tft.width()) w = tft.width() - x;
if((y+h-1) >= tft.height()) h = tft.height() - y;
// Set TFT address window to clipped image bounds
tft.setAddrWindow(x, y, x+w-1, y+h-1);
for (row=0; row<h; row++) { // For each scanline...
// Seek to start of scan line. It might seem labor-
// intensive to be doing this on every line, but this
// method covers a lot of gritty details like cropping
// and scanline padding. Also, the seek only takes
// place if the file position actually needs to change
// (avoids a lot of cluster math in SD library).
if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
else // Bitmap is stored top-to-bottom
pos = bmpImageoffset + row * rowSize;
if(bmpFile.position() != pos) { // Need seek?
bmpFile.seek(pos);
buffidx = sizeof(sdbuffer); // Force buffer reload
}
for (col=0; col<w; col++) { // For each pixel...
// Time to read more pixel data?
if (buffidx >= sizeof(sdbuffer)) { // Indeed
bmpFile.read(sdbuffer, sizeof(sdbuffer));
buffidx = 0; // Set index to beginning
}
// Convert pixel from BMP to TFT format, push to display
b = sdbuffer[buffidx++];
g = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
tft.pushColor(tft.color565(r,g,b));
} // end pixel
} // end scanline
// Serial.print(F("Loaded in "));
// Serial.print(millis() - startTime);
// Serial.println("" ms"");
} // end goodBmp
}
}
bmpFile.close();
if(!goodBmp) Serial.println(F("BMP format not recognized."));
}
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(File &f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(File &f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}