PQ
← Back to all articles
Astronomy & Space • • 8 min read

Decoding Starlight: From Diffraction Gratings to Astronomical FITS Files in C# .NET

Notes from developing the QNO SpeControl spectrometer software: how diffraction gratings separate spectral lines and how FITS headers are structured.

CONTENTS (2)

While developing spectrometer control software at ExploraScience Quy Nhon, one of the most interesting topics I studied was how a slit and diffraction grating turn incoming light into chemical fingerprints.

Figure 1 — Live camera spectral-line alignment and FITS export pipeline in QNO SpeControl.

1. The Diffraction Grating Equation

In an optical grating spectrometer, the diffraction angle θm\theta_m at order mm relates to wavelength λ\lambda and grating spacing dd:

d(sin⁡θi+sin⁡θm)=mλd(\sin\theta_i + \sin\theta_m) = m\lambda
Diffraction grating equation.

2. Writing 2880-Byte FITS Headers in C#

Unlike plain CSV files, FITS (Flexible Image Transport System) stores calibrated numeric arrays alongside 80-byte ASCII metadata cards padded to 2880-byte blocks:

Spectroscopy/FitsHeaderBuilder.cs C# / .NET
public static byte[] BuildMinimalFitsHeader(int sampleCount, double crval1Nm, double cdelt1Nm)
{
    var cards = new List<string>
    {
        FormatCard("SIMPLE", "T", "Standard FITS format"),
        FormatCard("BITPIX", "-64", "IEEE double precision floating point"),
        FormatCard("NAXIS", "1", "1D calibrated spectrum"),
        FormatCard("NAXIS1", sampleCount.ToString(), "Number of wavelength bins"),
        FormatCard("CRVAL1", crval1Nm.ToString("F4"), "Starting wavelength (nm)"),
        FormatCard("CDELT1", cdelt1Nm.ToString("F6"), "Wavelength dispersion per pixel (nm)"),
        "END".PadRight(80, ' ')
    };

    while ((cards.Count * 80) % 2880 != 0)
        cards.Add(new string(' ', 80));

    return Encoding.ASCII.GetBytes(string.Concat(cards));
}