Issue with creating bmp file on SD card

Hello together !
For my newest project, I want to create a bmp file on an SD card to store measured temperatures from an IR sensor converted to RGB colors inside (thermal image).
For unknown reason, it does not work as I do expect. The arduino creates the bmp file, but instead of the Red Color I want to write in for test purposes, the whole image is black.
So I think the RGB conversion from RGB888 to RGB565 and then from RGB 565 to RGB555 seems to have an issue.

#include <SD.h>

//Refer to http://www.fastgraph.com/help/bmp_header_format.html
const char bmp_header[54]=
{
      0x42, 0x4D, 0x36, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, 
      0x00, 0x00, 0x40, 0x01, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x00, 
      0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0xC4, 0x0E, 0x00, 0x00, 0x00, 0x00, 
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
  
#define SD_CS 10

void setup()
{
  Serial.begin(9600);
  //Initialize SD Card
  if (!SD.begin(SD_CS)) 
  {
    while (1);		//If failed, stop here
  }
  char str[] = "TEST.BMP";
  GrabImage(str);
}

void GrabImage(char* str)
{
  File outFile;
  byte VH,VL;
  int i,j = 0;
  
  //Create the File
  outFile = SD.open(str,FILE_WRITE);
  if (! outFile) return;

  //Write the BMP header
  for( i = 0; i < 54; i++)
  {
    char ch = bmp_header[i];
    outFile.write((uint8_t*)&ch,1);
  }
  
  //Test color, Red in RGB888
  byte r = 255;
  byte g = 0;
  byte b = 0;
  //Convert RGB888 to RGB565
  unsigned short rgb =  ((((r>>3)<<11) | ((g>>2)<<5) | (b>>3))) ;
	
  //Write 320x240x2 byte to the File
  for(i = 0; i < 240; i++){
    for(j = 0; j < 320; j++){
      VH = rgb & 0xFF00; //Mask the High Byte
      VL = rgb & 0x00FF; //Mask the Low Byte
      //RGB565 to RGB555 Conversion
      VL = (VH << 7) | ((VL & 0xC0) >> 1) | (VL & 0x1f);
      VH = VH >> 1;
      //Write image data to file, low byte first
      outFile.write(VL); 
      outFile.write(VH);
  }
  }
  //Close the file  
  outFile.close(); 
  return;
}

void loop()
{
}

I would be very happy about any kind of help !
Thanks,
Max

Found the solution :) I forgot to shift the High Byte right by 8-bit ^^ Now it works and I can even create bmp image with 640x480 on the sd card. They can than be viewed later on a LCD Display with the bmp print function of the UTFT lib. Awesome !

I compiled your sketch with IDE v. 1.6.3. I found I needed to add “#include <SPI.h>” for it to work. However, I do not know how to apply the correction you describe as " I forgot to shift the High Byte right by 8-bit ". Could you please give me that correction?

Thanks for the help and the programming!

Kindest Regards,
mjm

That was from 2 years ago. I believe he means do this,

VH = (rgb & 0xFF00) >> 8; //Mask the High Byte