Arduino Seek wrong position - colors

I have a file with colour values for my led strip. When I try to change some values it just appends them to the end of the file. After some trying and testing I found out that seek jumps to the end of the file instead of the position I tell it to jump to. It used to work a few month ago, but after picking up the project again it broke. I did try a few older Arduino versions, but that didn't fix it or raised different errors.
the code for changing values:
sdFile = SD.open(F("PIXELS1.BIN"), FILE_WRITE);
if (!sdFile) {
error(F("SD CAN'T OPEN FILE"));
}
sdFile.seek(ledArray[0]*3);
for(int i=ledArray[0];i<=ledArray[1];i++) {
sdFile.write(colorArray, sizeof(colorArray));
}
sdFile.close();

solved it by using an older SD lib version

Related

Arduino String.replace() not working after file name change

I have encountered a strange failure when this code runs on my NodeMCU 0.9 board. It is basically getting http code from an API in the following format:
<abbr title="klokken">kl</abbr> 11–12
In this case I want to isolate the 11 and 12 by first removing the first 42 characters which works perfectly fine and then replacing the – with --. When I open a sketch and paste this program in it it runs perfectly fine and returns 11--12 but when I save this program under a random name it is rebuilt and for some reason doesn't replace the characters properly it then returns 11–12.
I have tried to replace different parts of the string when it was rebuilt which worked fine but for some reason I can't seem to either find the index of nor replace the three strange characters.
http.begin(URL_time);
int httpCode = http.GET();
String timerange;
if(httpCode > 0){
timerange = http.getString();
timerange.remove(0,42);
timerange.replace("–", "--");
Serial.println(timerange);
Thus my question is if anyone knows how to work around this issue apart from not saving my code. Feel free to ask me to elaborate on my question when needed.
The string you're receiving is encoded in Windows Latin 1 (ISO 8859-1), and you're (probably) using UTF-8. What you need is to re-encode the string properly.

corona sdk crashes when attempting to open a file using io.open

I've never used corona sdk before and decided to create a key logger as a test to see if I liked corona.
I'm able to check input and specify the file path but once my code reaches io.open the simulater freezes and crashes and the input is not added to the text file.
I've looked just about every where I can think of for an answer and found none.
I'm sure this isn't the most efficient code out there. I'm a newbie to any type of programming outside of the ROBLOX engine.
function WriteToFile(String)
local path = system.pathForFile("R#T.txt", system.DocumentsDirectory)
print("Path") -- Just to try and determine the origin of the crash
local File, ErrorString = io.open(path, "W")
print("File")
if not File then
print('File error: ' .. ErrorString)
else
print("else")
File:write(String)
io.close(File)
end
File = nil
end
function ReturnInput( Key )
if Key.phase == 'down' then
print(Key.keyName)
WriteToFile(tostring(Key.keyName))
end
end
Runtime:addEventListener('key', ReturnInput)
Sorry to tell you this, but unfortunately you can not create keyloggers with Corona SDK. You can not create anything that runs on the background.
E.g. you can't make a floater widget and when you press it, you get screenshot.

How to check the available free space in Haxe?

I don't find a way to check the free space available in a device using Haxe, Openfl, Lime or another library.
I would like to avoid download data that will exceed the size recommended for an app in each device.
What do you do to check that?
Try creating a file of that size! Then either delete it or reopen and write (not append) over its contents.
I don't know whether all platforms Haxe supports will work fine with this trick, but this algorithm is reported to work in many places and languages (I personally tested it in Ruby and saw the same suggestion for C++/.NET). To check whether X bytes of disk space are available:
open a new file for writing
seek X-1 bytes from the beginning
write a byte of data (whatever you want, 0, 42...)
close the file (probably unrelated to the task at hand, but don't forget to do that anyway)
If there's insufficient disk space, you'll likely get an exception at some point in this algorithm. You'll have to find out what errors to expect and process them properly.
Using ihx I've found this is working and requires nothing but Haxe Standard Library:
haxe interactive shell v0.3.4
type "help" for help
>> import sys.io.*;
>> var f = File.write('loca', true)
sys.io.FileOutput : { __f => #abstract }
>> f.seek(39999, FileSeek.SeekBegin)
Void : null
>> f.writeByte(0)
Void : null
>> f.close()
Void : null
After these manipulations, I had a file named loca of exactly 40000 bytes in my working directory.
By the way, be careful when doing things like these in ihx since it re-runs the entire session with the last entered line appended each time.
Ongoing experimentation:
However, when there's insufficient disk space, it may not fail with errors. In this case you'll have to check the real size with sys.FileSystem.stat(path).size. And don't forget to delete the file if there's not enough space.

Java clipboard not working

I was trying to copy an image to the clipboard and paste it into gimp with this code snippet:
BufferedImage bi = new BufferedImage(board.getAmount()*16,16,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();
Color[] colors = board.getColors();
for (int loop = 0; loop < board.getAmount(); loop++) {
g2d.setColor(colors[loop]);
g2d.fill(new Rectangle(16*loop,0,16,16));
}
ImageSelection is = new ImageSelection(bi);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(is, null);
Anyways in theory everything should have worked out fine. It gave me no errors, but when I try to paste the image, nothing happens.
This was done on two different linux machines and neither worked. I then came to school and tried it out with the same code on Windows and it worked.
So I guess my real question is does it have something to do with open-jdk, or java 1.7, or is it linux's problem? And how can I fix it?
I think the next page could be useful: http://www.java2s.com/Code/Java/2D-Graphics-GUI/SendingImageObjectsthroughtheClipboard.htm.
Consider the following lines to copy the image to the clipboard.
final Clipboard clipboard = frame.getToolkit().getSystemClipboard();
label.setTransferHandler(new ImageSelection());
...
TransferHandler handler = label.getTransferHandler();
handler.exportToClipboard(label, clipboard, TransferHandler.COPY);
I had the same problem, and found this to work:
final Clipboard clipboard = frame.getToolkit().getSystemSelection();
...then continue using that as a regular clipboard. The "system selection" allows you to change what the window manager thinks is selected, and is therefore "on the clipboard".
I'm not sure what the best way to detect whether system selection or system clipboard should be used, but it looks like Windows will return null for getSystemSelection, so that can be used as a test.

How to print DIB backbuffer on printer - GDI, MFC

I'm using MFC's doc/view architecture to implement printing. I use double buffering, I draw everything onto my backbuffer which is DIB bitmap. Than I use StretchBlt to copy that DIB onto printer DC.
The strange thing is - print preview is working well! When I print on virtual PDF printer, it is working well! But when I print on actual printer (I'm testing on two different printers - same results) - it just prints "garbage". The "garbage" means sometimes it prints totally black page, sometimes it prints the first few pages repeatedly, i.e. it prints wrong part of DIB, just like if I messed up coordinates to StretchBlt, but I didn't mess anything up, I checked multiple times, plus why is print preview is working flawlessly then?
I tried many variations:
Using memory DC compatible to screen DC, when printing.
Using memory DC compatible to printer DC, and selecting my DIB into it.
Using memory DC compatible to printer DC, and using dedicated DIB onto which I copy my original backbuffer DIB.
etc.
But the results are same. Below is the code where i create the DIB. I think the DIB format might be the problem, so please advice if there is something wrong with it. I tried both 24 bits and 32 bits as values for bmiHeader.biBitCount.
// Setup proper backbuffer:
_CleanupBackBufferStuff();
_pMemDc = new CDC;
_pMemDc->CreateCompatibleDC(&aDC);
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = _sizeBackBuffer.cx;
bmi.bmiHeader.biHeight = -_sizeBackBuffer.cy; // top-down
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 24; // Tried 32 as well
bmi.bmiHeader.biCompression = BI_RGB;
unsigned char *pBitmapRawBits = 0;
HANDLE hMemBitmap = CreateDIBSection(aDC.GetSafeHdc(), &bmi, DIB_RGB_COLORS, (void**)&pBitmapRawBits, 0, 0);
_hOldSelBitmap = (HBITMAP)_pMemDc->SelectObject(hMemBitmap);
Also here is the code for StretchBlt (nothing special here):
pDC->SetStretchBltMode(HALFTONE);
SetBrushOrgEx(pDC->GetSafeHdc(), 0, 0, 0);
BOOL bSuccess = pDC->StretchBlt(rectClipBoxPlayground.left, rectClipBoxPlayground.top, rectClipBoxPlayground.Width(), rectClipBoxPlayground.Height(),
_pMemDc, rectClipBoxBackBuffer.left, rectClipBoxBackBuffer.top, rectClipBoxBackBuffer.Width(), rectClipBoxBackBuffer.Height(), SRCCOPY);
StretchBlt returns true, also (pDC->GetDeviceCaps(RASTERCAPS) & RC_STRETCHBLT) is true as well.
UPDATE: After Adrian's comment, I changed my code to use StretchDIBits. The problem is still the same! Below is the code I'm using currently:
// Copy back buffer to screen dc:
pDC->SetStretchBltMode(HALFTONE);
SetBrushOrgEx(pDC->GetSafeHdc(), 0, 0, 0);
HBITMAP hMemBitmap = (HBITMAP)_pMemDc->SelectObject(_hOldSelBitmap);
DWORD dwLines = StretchDIBits(pDC->GetSafeHdc(),
rectClipBoxPlayground.left, rectClipBoxPlayground.top, rectClipBoxPlayground.Width(), rectClipBoxPlayground.Height(),
rectClipBoxBackBuffer.left, _sizeBackBuffer.cy - rectClipBoxBackBuffer.top - rectClipBoxBackBuffer.Height(), rectClipBoxBackBuffer.Width(), rectClipBoxBackBuffer.Height(),
_pBitmapRawBits, &_bitmapInfo, DIB_RGB_COLORS, SRCCOPY);
_pMemDc->SelectObject(hMemBitmap);
It still behaives like the source coordinates are incorrect. It either prints one of first few pages (no matter what page I select), or prints almost-fully-black pages. The print preview is working perfectly, so this makes me think there should be no problems with my coordinate-calculation code. It works in preview, it works with virtual (pdf) printer, it fails when printing on actual printer. What the hell?....
Make sure you don't have the DIBSECTION selected into more than one DC at a time. That can cause all sorts of unpredictable behavior.
For printing, you can probably bypass the memory DC altogether if you keep your bmi and pBitmapRawBits handy. Make sure the DIBSECTION is not selected into any DC, and then call SetDIBitsToDevice or StretchDIBits to transfer the image to the printer DC.
If you're still having problems, you might want to check the capabilities of your printers. Not all the drivers support all the bitmap transfer methods. I believe the printing system is supposed to hide those differences from you, but perhaps not. Call GetDeviceCaps on your printer DC, and check the RASTERCAPS for RC_BITBLT and friends.

Resources