Subversion Repositories Projects

Rev

Rev 328 | Rev 330 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/****************************************************************************
 *   Copyright (C) 2009 by Claas Anders "CaScAdE" Rathje                    *
 *   admiralcascade@gmail.com                                               *
 *   Project-URL: http://www.mylifesucks.de/oss/c-osd/                      *
 *                                                                          *
 *   This program is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by   *
 *   the Free Software Foundation; either version 2 of the License.         *
 *                                                                          *
 *   This program is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *   GNU General Public License for more details.                           *
 *                                                                          *
 *   You should have received a copy of the GNU General Public License      *
 *   along with this program; if not, write to the                          *
 *   Free Software Foundation, Inc.,                                        *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.              *
 *                                                                          *
 *                                                                          *
 *   Credits to:                                                            *
 *   Holger Buss & Ingo Busker from mikrokopter.de for the MK project       *
 *   Gregor "killagreg" Stobrawa for making the MK code readable            *
 *   Klaus "akku" Buettner for the hardware                                 *
 *   Manuel "KeyOz" Schrape for explaining the MK protocol to me            *
 ****************************************************************************/


#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

/* TODO:
 * - verifiy correctness of values
 * - clean up code :)
 */


/* ##########################################################################
 * Debugging and general purpose definitions
 * ##########################################################################*/

#define ALLCHARSDEBUG 0         // set to 1 and flash firmware to see all chars

#ifndef WRITECHARS                      // if WRITECHARS not set via makefile
#define WRITECHARS -1           // set to 2XX and flash firmware to write new char
                                                        // enables the allchars as well to see results
#endif

#ifndef NTSC                            // if NTSC is not thet via makefile
#define NTSC 0                          // set to 1 for NTSC mode + lifts the bottom line
#endif

#define ARTHORIZON 0            // set to 1 to enable roll&nick artificial horizon
#define NOOSD 0                         // set to 1 to disable OSD completely
#define NOOSD_BUT_WRN 0         // set to 1 to disable OSD completely but show
                                                        // battery and receive signal warnings
#define UBAT_WRN 94                     // voltage for blinking warning, like FC settings
#define RCLVL_WRN 100           // make the RC level blink if below this number

// ### read datasheet before changing stuff below this line :)
#define BLINK   0b01001111      // attribute byte for blinking chars

/* ##########################################################################
 * FLAGS usable during runtime
 * ##########################################################################*/

#define COSD_FLAG_NTSC                   1
#define COSD_FLAG_ARTHORIZON     2
#define COSD_FLAG_NOOSD                  4
#define COSD_FLAG_NOOSD_BUT_WRN  8
#define COSD_ICONS_WRITTEN              16

/* ##########################################################################
 * Software SPI to communicate with MAX7456
 * ##########################################################################*/

#define MAX_CS_HIGH             PORTA |=  (1 << PA1);
#define MAX_CS_LOW              PORTA &= ~(1 << PA1);
#define MAX_SDIN_HIGH           PORTA |=  (1 << PA2);
#define MAX_SDIN_LOW            PORTA &= ~(1 << PA2);
#define MAX_SCLK_HIGH           PORTA |=  (1 << PA3);
#define MAX_SCLK_LOW            PORTA &= ~(1 << PA3);
#define MAX_RESET_HIGH          PORTA |=  (1 << PA5);
#define MAX_RESET_LOW           PORTA &= ~(1 << PA5);

/* ##########################################################################
 * LED controll
 * ##########################################################################*/

#define LED1_ON                 PORTC |=  (1 << PC0);
#define LED1_OFF                PORTC &= ~(1 << PC0);
#define LED2_ON                 PORTC |=  (1 << PC1);
#define LED2_OFF                PORTC &= ~(1 << PC1);
#define LED3_ON                 PORTC |=  (1 << PC2);
#define LED3_OFF                PORTC &= ~(1 << PC2);
#define LED4_ON                 PORTC |=  (1 << PC3);
#define LED4_OFF                PORTC &= ~(1 << PC3);

/* ##########################################################################
 * switch controll
 * ##########################################################################*/

#define S1_PRESSED              !(PINC & (1<<PC5))
#define S2_PRESSED              !(PINC & (1<<PC4))

/* ##########################################################################
 * gain some fake arm compat :)
 * ##########################################################################*/

#define u8 uint8_t
#define s8 int8_t
#define u16 uint16_t
#define s16 int16_t
#define u32 uint32_t
#define s32 int32_t

#if !(ALLCHARSDEBUG|(WRITECHARS != -1))
/* ##########################################################################
 * MK data strucs & flags
 * ##########################################################################*/

#define NC_FLAG_FREE                    1
#define NC_FLAG_PH                      2
#define NC_FLAG_CH                      4
#define NC_FLAG_RANGE_LIMIT             8
#define NC_SERIAL_LINK_OK               16
#define NC_FLAG_TARGET_REACHED          32

#define FLAG_MOTOR_RUN  1
#define FLAG_FLY        2
#define FLAG_CALIBRATE  4
#define FLAG_START      8

/*
 * FC Debug Struct
 * portions taken and adapted from
 * http://svn.mikrokopter.de/mikrowebsvn/filedetails.php?repname=FlightCtrl&path=%2Ftags%2FV0.72p%2Fuart.h
 */

typedef struct {
    uint8_t Digital[2];
    uint16_t Analog[32]; // Debugvalues
} __attribute__((packed)) DebugOut_t;

/*
 * NaviCtrl OSD Structs
 * portions taken and adapted from
 * http://svn.mikrokopter.de/mikrowebsvn/filedetails.php?repname=NaviCtrl&path=%2Ftags%2FV0.14e%2Fuart1.h
 */

typedef struct {
    s32 Longitude; // in 1E-7 deg
    s32 Latitude; // in 1E-7 deg
    s32 Altitude; // in mm
    u8 Status; // validity of data
} __attribute__((packed)) GPS_Pos_t;

typedef struct {
    s16 Distance; // distance to target in cm
    s16 Bearing; // course to target in deg
} __attribute__((packed)) GPS_PosDev_t;

typedef struct {
    GPS_Pos_t CurrentPosition; // see ubx.h for details
    GPS_Pos_t TargetPosition;
    GPS_PosDev_t TargetPositionDeviation;
    GPS_Pos_t HomePosition;
    GPS_PosDev_t HomePositionDeviation;
    u8 WaypointIndex; // index of current waypoints running from 0 to WaypointNumber-1
    u8 WaypointNumber; // number of stored waypoints
    u8 SatsInUse; // no of satellites used for position solution
    s16 Altimeter; // hight according to air pressure
    s16 Variometer; // climb(+) and sink(-) rate
    u16 FlyingTime; // in seconds
    u8 UBat; // Battery Voltage in 0.1 Volts
    u16 GroundSpeed; // speed over ground in cm/s (2D)
    s16 Heading; // current flight direction in deg as angle to north
    s16 CompassHeading; // current compass value
    s8 AngleNick; // current Nick angle in 1°
    s8 AngleRoll; // current Rick angle in 1°
    u8 RC_Quality; // RC_Quality
    u8 MKFlags; // Flags from FC
    u8 NCFlags; // Flags from NC
    u8 Errorcode; // 0 --> okay
    u8 OperatingRadius; // current operation radius around the Home Position in m
    u8 Reserve[7]; // for future use
} __attribute__((packed)) NaviData_t;


/* ##########################################################################
 * global definitions and global vars
 * ##########################################################################*/

#define baud 57600

#define RXD_BUFFER_LEN          150
#define TXD_BUFFER_LEN          150

volatile uint8_t rxd_buffer_locked = 0;
volatile uint8_t rxd_buffer[RXD_BUFFER_LEN];
volatile uint8_t txd_buffer[TXD_BUFFER_LEN];
volatile uint8_t ReceivedBytes = 0;
volatile uint8_t *pRxData = 0;
volatile uint8_t RxDataLen = 0;
volatile uint16_t setsReceived = 0;

volatile NaviData_t naviData;
volatile DebugOut_t debugData;

// cache old vars for blinking attribute, checkup is faster than full
// attribute write each time
volatile uint8_t last_UBat = 255;
volatile uint8_t last_RC_Quality = 255;

// 16bit should be enough, normal LiPos don't last that long
volatile uint16_t uptime = 0;
volatile uint16_t timer = 0;

#endif // ends !(ALLCHARSDEBUG|(WRITECHARS != -1))

// general PAL|NTSC distingiusch stuff
uint8_t top_line = 1;
uint8_t bottom_line = 14;

// Flags
uint8_t COSD_FLAGS = 0;

/* ##########################################################################
 * debounce buttons
 * ##########################################################################*/

int s1_pressed() {
        if (S1_PRESSED) {
                _delay_ms(25);
                if (S1_PRESSED) return 1;
        }
        return 0;
}

int s2_pressed() {
        if (S2_PRESSED) {
                _delay_ms(25);
                if (S2_PRESSED) return 1;
        }
        return 0;
}

/* ##########################################################################
 * MAX7456 SPI & Display stuff
 * ##########################################################################*/


/**
 * Send a byte through SPI
 */

void spi_send(uint8_t byte) {
    for (int8_t i = 7; i >= 0; i--) {
        if (((byte >> i) & 1)) {
            MAX_SDIN_HIGH
        } else {
            MAX_SDIN_LOW
        }
        MAX_SCLK_HIGH
        MAX_SCLK_LOW
    }
}

/**
 *  Send <byte> to <address> of MAX7456
 */

void spi_send_byte(uint8_t address, uint8_t byte) {
    // start sending
    MAX_CS_LOW

    spi_send(address);
    spi_send(byte);

    // end sending
    MAX_CS_HIGH
}

/**
 *  write a <character> to <address> of MAX7456 display memory
 */

void write_char(uint16_t address, char character) {
    spi_send_byte(0x05, (address & 0xFF00) >> 8); // DMAH
    spi_send_byte(0x06, (address & 0x00FF)); // DMAL
    spi_send_byte(0x07, character); // DMDI
}

/**
 *  write a character <attribute> to <address> of MAX7456 display memory
 */

void write_char_att(uint16_t address, char attribute) {
    // the only important part is that the DMAH[1] is set
    // so we add 2 which binary is the 2nd lowest byte
    spi_send_byte(0x05, ((address & 0xFF00) >> 8) | 2); // DMAH
    spi_send_byte(0x06, (address & 0x00FF)); // DMAL
    spi_send_byte(0x07, attribute); // DMDI
}

/**
 *  write a <character> at <x>/<y> to MAX7456 display memory
 */

void write_char_xy(uint8_t x, uint8_t y, char character) {
    uint16_t address = y * 30 + x;
    write_char(address, character);
}

/**
 *  write a  character <attribute> at <x>/<y> to MAX7456 display memory
 */

void write_char_att_xy(uint8_t x, uint8_t y, char attribute) {
    uint16_t address = y * 30 + x;
    write_char_att(address, attribute);
}

/**
 *  clear display by writing blank characters all over it
 */

void clear(void) {
    uint16_t memory_address = 0;
    for (unsigned int a = 0; a < 480; a++) {
        write_char(memory_address++, 0);
    }
}

/**
 *  write an ascii <character> to <address> of MAX7456 display memory
 */

void write_ascii_char(uint16_t address, char c) {
    if (c == 32) c = 0; // remap space
    else if (c > 48 && c <= 57) c -= 48; // remap numbers
    else if (c == '0') c = 10; // remap zero
    else if (c >= 65 && c <= 90) c -= 54; // remap big letters
    else if (c >= 97 && c <= 122) c -= 60; // remap small letters
    else if (c == '(') c = 63; // remap
    else if (c == ')') c = 64; // remap
    else if (c == '.') c = 65; // remap
    else if (c == '?') c = 66; // remap
    else if (c == ';') c = 67; // remap
    else if (c == ':') c = 68; // remap
    else if (c == ',') c = 69; // remap
    else if (c == '\'') c = 70; // remap
    else if (c == '/') c = 71; // remap
    else if (c == '"') c = 72; // remap
    else if (c == '-') c = 73; // remap minus
    else if (c == '<') c = 74; // remap
    else if (c == '>') c = 75; // remap
    else if (c == '@') c = 76; // remap
    write_char(address, c);
}

/**
 *  write an ascii <string> at <x>/<y> to MAX7456 display memory
 */

void write_ascii_string(uint8_t x, uint8_t y, char *string) {
    while (*string) {
        write_ascii_char(((x++)+(y * 30)), *string);
        string++;
    }
}

/**
 *  Write only the last three digits of a <number> at <x>/<y> to MAX7456
 *  display memory. takes full 16bit numbers as well for stuff
 *  like compass only taking three characters (values <= 999)
 */

void write_3digit_number_u(uint8_t x, uint8_t y, uint16_t number) {
    uint16_t num = 100;
    uint8_t started = 0;

    while (num > 0) {
        uint8_t b = number / num;
        if (b > 0 || started || num == 1) {
            write_ascii_char((x++)+(y * 30), '0' + b);
            started = 1;
        } else {
            write_ascii_char((x++)+(y * 30), 0);
        }
        number -= b * num;

        num /= 10;
    }
}

/**
 *  Write only the last two digits of a number at <x>/<y> to MAX7456
 *  display memory. takes full 16bit numbers as well for stuff
 *  like seconds only taking two characters (values <= 99)
 *  Since this is used for seconds only and it looks better, there
 *  is a trading 0 attached
 */

void write_2digit_number_u(uint8_t x, uint8_t y, uint16_t number) {
    uint16_t num = 10;
    uint8_t started = 0;

    while (num > 0) {
        uint8_t b = number / num;
        if (b > 0 || started || num == 1) {
            write_ascii_char((x++)+(y * 30), '0' + b);
            started = 1;
        } else {
            write_ascii_char((x++)+(y * 30), '0');
        }
        number -= b * num;

        num /= 10;
    }
}

/**
 *  write a unsigned number as /10th at <x>/<y> to MAX7456 display memory
 */

void write_number_u_10th(uint8_t x, uint8_t y, uint16_t number) {
    uint16_t num = 10000;
    uint8_t started = 0;

    while (num > 0) {
        uint8_t b = number / num;

        if (b > 0 || started || num == 1) {
            if ((num / 10) == 0) write_char((x++)+(y * 30), 65);
            write_ascii_char((x++)+(y * 30), '0' + b);
            started = 1;
        } else {
            write_ascii_char((x++)+(y * 30), 0);
        }
        number -= b * num;

        num /= 10;
    }
}

/**
 *  write a unsigned number at <x>/<y> to MAX7456 display memory
 */

void write_number_u(uint8_t x, uint8_t y, uint16_t number) {
    uint16_t num = 10000;
    uint8_t started = 0;

    while (num > 0) {
        uint8_t b = number / num;
        if (b > 0 || started || num == 1) {
            write_ascii_char((x++)+(y * 30), '0' + b);
            started = 1;
        } else {
            write_ascii_char((x++)+(y * 30), 0);
        }
        number -= b * num;

        num /= 10;
    }
}

/**
 *  write a signed number at <x>/<y> to MAX7456 display memory
 */

void write_number_s(uint8_t x, uint8_t y, int16_t w) {
    if (((uint16_t) w) > 32767) {
        w = w - 65536;

        int16_t num = -10000;
        uint8_t started = 0;

        while (num < 0) {
            uint8_t b = w / num;
            if (b > 0 || started || num == 1) {
                if (!started) write_char((x - 1)+(y * 30), 0x49);
                write_ascii_char((x++)+(y * 30), '0' + b);
                started = 1;
            } else {
                write_ascii_char((x++)+(y * 30), 0);
            }
            w -= b * num;

            num /= 10;
        }
    } else {
        write_char((x)+(y * 30), 0);
        write_number_u(x, y, w);
    }
}

/**
 *  write <seconds> as human readable time at <x>/<y> to MAX7456 display mem
 */

void write_time(uint8_t x, uint8_t y, uint16_t seconds) {
    uint16_t min = seconds / 60;
    seconds -= min * 60;
    write_3digit_number_u(x, y, min);
    write_char_xy(x + 3, y, 68);
    write_2digit_number_u(x + 4, y, seconds);
}

/**
 * for testing write all chars to screen
 */

void write_all_chars() {
    uint16_t x = 3, y = 2, t = 0;
    while (t < 256) {
        write_char_xy(x++, y, t++);
        if (x > 25) {
            y++;
            x = 3;
        }
    }
}

#if !(ALLCHARSDEBUG|(WRITECHARS != -1))
/* ##########################################################################
 * USART stuff
 * ##########################################################################*/


/**
 * init usart1
 */

void usart1_init() {
    UBRR1H = ((F_CPU / (16UL * baud)) - 1) >> 8;
    UBRR1L = (F_CPU / (16UL * baud)) - 1;

    // Enable receiver and transmitter; enable RX interrupt
    UCSR1B = (1 << RXEN1) | (1 << TXEN1) | (1 << RXCIE1);

    //asynchronous 8N1
    UCSR1C = (1 << URSEL1) | (3 << UCSZ10);
}

/**
 * send a single <character> through usart1
 */

void usart1_putc(unsigned char character) {
    // wait until UDR ready
    while (!(UCSR1A & (1 << UDRE1)));
    UDR1 = character;
}

/**
 * send a <string> throught usart1
 */

void usart1_puts(char *s) {
    while (*s) {
        usart1_putc(*s);
        s++;
    }
}

/**
 * receive data through usart1
 * portions taken and adapted from
 * http://svn.mikrokopter.de/mikrowebsvn/filedetails.php?repname=FlightCtrl&path=%2Fbranches%2FV0.72p+Code+Redesign+killagreg%2Fuart0.c
 */

ISR(SIG_USART1_RECV) {
    if (rxd_buffer_locked) return; // if rxd buffer is locked immediately return
    LED1_ON
            static uint16_t crc;
    static uint8_t ptr_rxd_buffer = 0;
    uint8_t crc1, crc2;
    uint8_t c;

    c = UDR1; // catch the received byte

    // the rxd buffer is unlocked
    if ((ptr_rxd_buffer == 0) && (c == '#')) // if rxd buffer is empty and syncronisation character is received
    {
                /*
                // skip other datasets
        if (ptr_rxd_buffer == 2 && rxd_buffer[ptr_rxd_buffer] != 'O') {
                        ptr_rxd_buffer = 0; // reset rxd buffer
                rxd_buffer_locked = 0; // unlock rxd buffer
                }*/

                rxd_buffer[ptr_rxd_buffer++] = c; // copy 1st byte to buffer
        crc = c; // init crc
    } else if (ptr_rxd_buffer < RXD_BUFFER_LEN) // collect incomming bytes
    {
        if (c != '\r') // no termination character
        {
            rxd_buffer[ptr_rxd_buffer++] = c; // copy byte to rxd buffer
            crc += c; // update crc
        } else // termination character was received
        {
            // the last 2 bytes are no subject for checksum calculation
            // they are the checksum itself
            crc -= rxd_buffer[ptr_rxd_buffer - 2];
            crc -= rxd_buffer[ptr_rxd_buffer - 1];
            // calculate checksum from transmitted data
            crc %= 4096;
            crc1 = '=' + crc / 64;
            crc2 = '=' + crc % 64;
            // compare checksum to transmitted checksum bytes
            if ((crc1 == rxd_buffer[ptr_rxd_buffer - 2]) && (crc2 == rxd_buffer[ptr_rxd_buffer - 1])) { // checksum valid
                rxd_buffer[ptr_rxd_buffer] = '\r'; // set termination character
                ReceivedBytes = ptr_rxd_buffer + 1; // store number of received bytes
                rxd_buffer_locked = 1; // lock the rxd buffer
            } else { // checksum invalid
                rxd_buffer_locked = 0; // unlock rxd buffer
            }
            ptr_rxd_buffer = 0; // reset rxd buffer pointer
        }
    } else // rxd buffer overrun
    {
        ptr_rxd_buffer = 0; // reset rxd buffer
        rxd_buffer_locked = 0; // unlock rxd buffer
    }
    LED1_OFF
}

/**
 * Decode the recevied Buffer
 * portions taken and adapted from
 * http://svn.mikrokopter.de/mikrowebsvn/filedetails.php?repname=FlightCtrl&path=%2Ftags%2FV0.72p%2Fuart.c
 */

void Decode64(void) {
    uint8_t a, b, c, d;
    uint8_t x, y, z;
    uint8_t ptrIn = 3;
    uint8_t ptrOut = 3;
    uint8_t len = ReceivedBytes - 6;

    while (len) {
        a = rxd_buffer[ptrIn++] - '=';
        b = rxd_buffer[ptrIn++] - '=';
        c = rxd_buffer[ptrIn++] - '=';
        d = rxd_buffer[ptrIn++] - '=';

        x = (a << 2) | (b >> 4);
        y = ((b & 0x0f) << 4) | (c >> 2);
        z = ((c & 0x03) << 6) | d;

        if (len--) rxd_buffer[ptrOut++] = x;
        else break;
        if (len--) rxd_buffer[ptrOut++] = y;
        else break;
        if (len--) rxd_buffer[ptrOut++] = z;
        else break;
    }
    pRxData = &rxd_buffer[3];
    RxDataLen = ptrOut - 3;
}

/**
 * request Data through USART in special MK format by adding checksum and
 * encode data in modified Base64
 * portions taken and adapted from
 * http://svn.mikrokopter.de/mikrowebsvn/filedetails.php?repname=FlightCtrl&path=%2Ftags%2FV0.72p%2Fuart.c
 */

void sendMKData(unsigned char cmd, unsigned char addr, unsigned char *snd, unsigned char len) {
    unsigned int pt = 0;
    unsigned char a, b, c;
    unsigned char ptr = 0;

    txd_buffer[pt++] = '#'; // Start-Byte
    txd_buffer[pt++] = 'a' + addr; // Adress
    txd_buffer[pt++] = cmd; // Command
    while (len) {
        if (len) {
            a = snd[ptr++];
            len--;
        } else a = 0;
        if (len) {
            b = snd[ptr++];
            len--;
        } else b = 0;
        if (len) {
            c = snd[ptr++];
            len--;
        } else c = 0;
        txd_buffer[pt++] = '=' + (a >> 2);
        txd_buffer[pt++] = '=' + (((a & 0x03) << 4) | ((b & 0xf0) >> 4));
        txd_buffer[pt++] = '=' + (((b & 0x0f) << 2) | ((c & 0xc0) >> 6));
        txd_buffer[pt++] = '=' + (c & 0x3f);
    }

    // add crc
    unsigned int tmpCRC = 0, i;
    for (i = 0; i < pt; i++) {
        tmpCRC += txd_buffer[i];
    }
    tmpCRC %= 4096;
    txd_buffer[i++] = '=' + tmpCRC / 64;
    txd_buffer[i++] = '=' + tmpCRC % 64;
    txd_buffer[i++] = '\r';

    usart1_puts((char*) txd_buffer);
}

/* ##########################################################################
 * timer stuff
 * ##########################################################################*/


/*
 * timer kicks in every 1000uS
 */

ISR(TIMER0_OVF_vect) {
    OCR0 = 6; // preload
    if (!timer--) {
        uptime++;
        timer = 999;
    }
}

/* ##########################################################################
 * compass stuff
 * ##########################################################################*/


/**
 * convert the <heading> gotton from NC into an index
 */

uint8_t heading_conv(uint16_t heading) {
    if (heading > 23 && heading < 68) {
        //direction = "NE";
        return 0;
    } else if (heading > 67 && heading < 113) {
        //direction = "E ";
        return 1;
    } else if (heading > 112 && heading < 158) {
        //direction = "SE";
        return 2;
    } else if (heading > 157 && heading < 203) {
        //direction = "S ";
        return 3;
    } else if (heading > 202 && heading < 248) {
        //direction = "SW";
        return 4;
    } else if (heading > 247 && heading < 293) {
        //direction = "W ";
        return 5;
    } else if (heading > 292 && heading < 338) {
        //direction = "NW";
        return 6;
    }
    //direction = "N ";
    return 7;
}

/**
 * draw a compass rose at <x>/<y> for <heading>
 */

void draw_compass(uint8_t x, uint8_t y, uint16_t heading) {
    //char* rose = "---N---O---S---W---N---O---S---W---N---O---S---W";
    char rose[48] = {216, 215, 216, 211, 216, 215, 216, 213, 216, 215, 216, 212,
                    216, 215, 216, 214, 216, 215, 216, 211, 216, 215, 216, 213,
                    216, 215, 216, 212, 216, 215, 216, 214, 216, 215, 216, 211,
                    216, 215, 216, 213, 216, 215, 216, 212, 216, 215, 216, 214};
        // the center is char 19 (north), we add the current heading in 8th
        // which would be 22.5 degrees, but float would bloat up the code
        // and *10 / 225 would take ages... so we take the uncorrect way
    uint8_t front = 19 + (heading / 22);
    for (uint8_t i = 0; i < 9; i++) {
                write_char_xy(x++, y, rose[front - 4 + i]);
    }
}

/* ##########################################################################
 * artificial horizon
 * ##########################################################################*/

// remember last time displayed values
int8_t old_af_x = -1, old_af_y = -1;

/**
 * draw roll und nick indicators (could be enhanced to full artificial horizon)
 * from line <firstline> to <listlines> for given <nick> and <roll> values
 */

void draw_artificial_horizon(uint8_t firstline, uint8_t lastline, int16_t nick, int16_t roll) {
        char noodle[5] = {225, 225, 226, 227, 227};
        uint8_t center_x = 15;
        uint8_t center_y = lastline - firstline;
        center_y = 7;
        write_char_xy(center_x,center_y,228);
        uint8_t cpos, nicky, rollx;
       
        // which line
        int8_t ypos =  nick / 20;
        // which character from the array?
        if (nick < 0) {
                cpos = -1*((nick - (ypos * 20))/4);
                ypos--;
        } else cpos = 4-((nick - (ypos * 20))/4);
        if (cpos > 4) cpos = 4;

        nicky = center_y - ypos;
        if (nicky > lastline) nicky = lastline;
        else if (nicky < firstline) nicky = firstline;

        // ensure roll-borders
        rollx = (roll / 8)+15;
        if (rollx < 2) rollx = 2;
        else if (rollx > 28) rollx = 28;


        // clear roll
        if (old_af_x != rollx && old_af_x >= 0) {
                write_char_xy(old_af_x,13,0);
        }

        // clear nick
        if (old_af_y != nicky && old_af_y >= 0) {
                write_char_xy(center_x-1,old_af_y,0);
                write_char_xy(center_x+1,old_af_y,0);
        }


        // draw nick
        write_char_xy(center_x-1,nicky,noodle[cpos]);
        write_char_xy(center_x+1,nicky,noodle[cpos]);

        // draw roll
        write_char_xy(rollx,lastline,229);

        // update old vars
        old_af_x = rollx;
        old_af_y = nicky;

        // debug numbers
        //write_3digit_number_u(20,6,cpos);
        //write_number_s(20,7,ypos);   
        //write_number_s(0,7,nick);            
        //write_number_s(18,11,roll);  
}

/* ##########################################################################
 * A simple config menu for the flags
 * ##########################################################################*/

void config_menu(void) {
        // disable interrupts (makes the menu more smoothely)
        cli();

        // clear screen
        clear();
       
        char* menu[4] = {"Normal OSD      ",
                                         "Art.Horizon     ",
                                         "NO OSD          ",
                                         "NO OSD but WRN  "};

        uint8_t inmenu = 1;
        uint8_t chosen = 0;
        write_ascii_string(10,  4, "Config Menu");
       
        // clear all mode flags
        COSD_FLAGS &= ~(COSD_FLAG_ARTHORIZON | COSD_FLAG_NOOSD | COSD_FLAG_NOOSD_BUT_WRN);

        // wait a bit before doing stuff so user has chance to release button
        _delay_ms(250);

        while (inmenu) {
                        write_ascii_string(2,  7, menu[chosen]);
                        if (s2_pressed()) {
                                chosen = (chosen + 1) % 4;
                                _delay_ms(500);
                        } else if (s1_pressed()) {
                                switch (chosen) {
                                        case 1:         // artificial horizon
                                                COSD_FLAGS |= COSD_FLAG_ARTHORIZON;
                                                break;
                                        case 2:         // everything off
                                                COSD_FLAGS |= COSD_FLAG_NOOSD;
                                                break;
                                        case 3:         // only warning
                                                COSD_FLAGS |= COSD_FLAG_NOOSD_BUT_WRN;
                                                break;
                                        //default:      // normal OSD, so let the flags cleared
                                }
                                // leave menu
                                inmenu = 0;
                                _delay_ms(500);
                        }
        }

        // clear screen up again
        clear();

        // update flags to paint display again if needed
        COSD_FLAGS &= ~COSD_ICONS_WRITTEN;

        // enable interrupts again
        sei();
}

#endif // ends !(ALLCHARSDEBUG|(WRITECHARS != -1))

/* ##########################################################################
 * MAIN
 * ##########################################################################*/

int main(void) {
        // set up FLAGS, compiler should flatten this one
        COSD_FLAGS = (NTSC << (COSD_FLAG_NTSC - 1));
        COSD_FLAGS |= (ARTHORIZON << (COSD_FLAG_ARTHORIZON - 1));
        COSD_FLAGS |= (NOOSD << (COSD_FLAG_NOOSD - 1));
        COSD_FLAGS |= (NOOSD_BUT_WRN << (COSD_FLAG_NOOSD_BUT_WRN - 1));

        // set up Atmega162 Ports
    DDRA |= (1 << PA1); // PA1 output (/CS)
    MAX_CS_HIGH
    DDRA |= (1 << PA2); // PA2 output (SDIN)
    MAX_SDIN_LOW
    DDRA |= (1 << PA3); // PA3 output (SCLK)
    MAX_SCLK_LOW
    DDRA |= (1 << PA5); // PA5 output (RESET)
    MAX_RESET_HIGH

    DDRC |= (1 << PC0); // PC0 output (LED1 gn)
    LED1_OFF
    DDRC |= (1 << PC1); // PC1 output (LED2 rt)
    LED2_OFF
    DDRC |= (1 << PC2); // PC2 output (LED3 gn)
    LED3_OFF
    DDRC |= (1 << PC3); // PC3 output (LED4 rt)
    LED4_OFF

    DDRC &= ~(1 << PC4); // PC4 input  (MODE)
    PORTC |= (1 << PC4); // pullup
    DDRC &= ~(1 << PC5); // PC5 input  (SET)
    PORTC |= (1 << PC5); // pullup

        // set up top and bottom lines
        if (COSD_FLAGS & COSD_FLAG_NTSC) {
                bottom_line = 12;
        } else {
                bottom_line = 14;
        }

        // reset the MAX7456 to be sure any undefined states do no harm
    MAX_RESET_LOW
    MAX_RESET_HIGH

        // check for keypress at startup
        if (s2_pressed()) { // togle COSD_FLAG_ARTHORIZON
                        COSD_FLAGS ^= (1 << (COSD_FLAG_ARTHORIZON - 1));
                        _delay_ms(100);
    }

    // give the FC/NC and the maxim time to come up
    LED4_ON
    _delay_ms(2000);

    LED4_OFF

    /* ##########################################################################
     * Pushing NEW chars to the MAX7456
     * ##########################################################################*/

#if (WRITECHARS != -1)
        void learn_char(uint8_t number, unsigned char* data) {
        // select character to write (CMAH)
        spi_send_byte(0x09, number);

        for (uint8_t i = 0; i < 54; i++) {
            // select 4pixel byte of char (CMAL)
            spi_send_byte(0x0A, i);

            // write 4pixel byte of char (CMDI)
            spi_send_byte(0x0B, data[i]);
        }

        // write to the NVM array from the shadow RAM (CMM)
        spi_send_byte(0x08, 0b10100000);

        // according to maxim writing to nvram takes about 12ms, lets wait longer
        _delay_ms(120);
    }

    // DISABLE display (VM0)
    spi_send_byte(0x00, 0b00000000);

    /**
     * easy char creation:
     * http://cascade.dyndns.org/~cascade/scripts/max7456/
     */

        // flashing more than 8 chars per time is not proven to be safe
        // so take care
#if WRITECHARS == 200
        // GPS
    unsigned char cc8[54] = {0x55, 0x50, 0x55, 0x55, 0x4a, 0x15, 0x55, 0x2a,
        0x85, 0x55, 0x2a, 0xa1, 0x55, 0x4a, 0xa8, 0x55,
        0x52, 0xa8, 0x55, 0x54, 0xaa, 0x55, 0x55, 0x09,
        0x55, 0x55, 0x52, 0x55, 0x55, 0x1a, 0x55, 0x51,
        0x96, 0x55, 0x18, 0x85, 0x54, 0x88, 0x28, 0x54,
        0x82, 0x05, 0x55, 0x20, 0xa1, 0x55, 0x48, 0x15,
        0x55, 0x52, 0x85, 0x55, 0x54, 0x15};

    unsigned char cc9[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x45,
        0x55, 0x55, 0x21, 0x55, 0x55, 0xa8, 0x55, 0x55,
        0xa1, 0x55, 0x55, 0x98, 0x15, 0x55, 0x2a, 0x85,
        0x55, 0x4a, 0xa1, 0x55, 0x4a, 0xa8, 0x55, 0x52,
        0xaa, 0x15, 0x54, 0xaa, 0x15, 0x55, 0x28, 0x55,
        0x55, 0x41, 0x55, 0x55, 0x55, 0x55};

    // RC
    unsigned char cca[54] = {0x54, 0xaa, 0x85, 0x52, 0x00, 0x21, 0x48, 0x2a,
        0x08, 0x60, 0x80, 0x82, 0x62, 0x08, 0x22, 0x62,
        0x2a, 0x22, 0x62, 0x08, 0x22, 0x60, 0x88, 0x82,
        0x48, 0x08, 0x08, 0x52, 0x08, 0x21, 0x54, 0x48,
        0x45, 0x55, 0x48, 0x55, 0x55, 0x48, 0x55, 0x55,
        0x48, 0x55, 0x55, 0x48, 0x55, 0x55, 0x48, 0x55,
        0x55, 0x2a, 0x15, 0x54, 0xaa, 0x85};

    // km/h
    unsigned char ccb[54] = {0x55, 0x55, 0x55, 0x01, 0x55, 0x55, 0x21, 0x55,
        0x55, 0x20, 0x15, 0x55, 0x22, 0x15, 0x55, 0x28,
        0x15, 0x55, 0x22, 0x15, 0x55, 0x00, 0x00, 0x15,
        0x52, 0xaa, 0x15, 0x52, 0x22, 0x15, 0x52, 0x22,
        0x15, 0x50, 0x00, 0x05, 0x55, 0x54, 0x85, 0x55,
        0x54, 0x80, 0x55, 0x54, 0xa8, 0x55, 0x54, 0x88,
        0x55, 0x54, 0x88, 0x55, 0x54, 0x00};


    // small meters m
    unsigned char ccc[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x15, 0x22,
        0x8a, 0x15, 0x28, 0xa2, 0x15, 0x20, 0x82, 0x15,
        0x20, 0x82, 0x15, 0x00, 0x00, 0x15};

    // vario down
    unsigned char ccd[54] = {0x55, 0x00, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28,
        0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55,
        0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55,
        0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28,
        0x55, 0x00, 0x28, 0x00, 0x2a, 0xaa, 0xa8, 0x0a,
        0xaa, 0xa0, 0x42, 0xaa, 0x81, 0x50, 0xaa, 0x05,
        0x54, 0x28, 0x15, 0x55, 0x00, 0x55};

    // vario hold
    unsigned char cce[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00,
        0x2a, 0xaa, 0xa8, 0x2a, 0xaa, 0xa8, 0x00, 0x00,
        0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // vario up
    unsigned char ccf[54] = {0x55, 0x00, 0x55, 0x54, 0x28, 0x15, 0x50, 0xaa,
        0x05, 0x42, 0xaa, 0x81, 0x0a, 0xaa, 0xa0, 0x2a,
        0xaa, 0xa8, 0x00, 0x28, 0x00, 0x55, 0x28, 0x55,
        0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28,
        0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55,
        0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55,
        0x55, 0x28, 0x55, 0x55, 0x00, 0x55};

    learn_char(200, cc8);
    learn_char(201, cc9);
    learn_char(202, cca);
    learn_char(203, ccb);
    learn_char(204, ccc);
    learn_char(205, ccd);
    learn_char(206, cce);
    learn_char(207, ccf);
#endif
#if WRITECHARS == 208
   // degree symbol
    unsigned char cd0[54] = {0x55, 0x55, 0x55, 0x54, 0x01, 0x55, 0x52, 0xa8,
        0x55, 0x48, 0x02, 0x15, 0x48, 0x52, 0x15, 0x48,
        0x52, 0x15, 0x48, 0x02, 0x15, 0x52, 0xa8, 0x55,
        0x54, 0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // clock on symbol
    unsigned char cd1[54] = {0x54, 0x14, 0x51, 0x52, 0x82, 0x08, 0x48, 0x22,
        0x88, 0x48, 0x22, 0x28, 0x48, 0x22, 0x28, 0x52,
        0x82, 0x08, 0x54, 0x14, 0x51, 0x55, 0x40, 0x55,
        0x55, 0x2a, 0x15, 0x54, 0x88, 0x85, 0x52, 0x08,
        0x21, 0x48, 0x48, 0x08, 0x48, 0x4a, 0x88, 0x48,
        0x50, 0x08, 0x52, 0x15, 0x21, 0x54, 0x80, 0x85,
        0x55, 0x2a, 0x15, 0x55, 0x40, 0x55};

    // clock fly symbol
    unsigned char cd2[54] = {0x40, 0x45, 0x11, 0x2a, 0x20, 0x88, 0x20, 0x20,
        0x88, 0x28, 0x21, 0x21, 0x21, 0x20, 0x21, 0x21,
        0x2a, 0x21, 0x45, 0x40, 0x45, 0x55, 0x40, 0x55,
        0x55, 0x2a, 0x15, 0x54, 0x88, 0x85, 0x52, 0x08,
        0x21, 0x48, 0x48, 0x08, 0x48, 0x4a, 0x88, 0x48,
        0x50, 0x08, 0x52, 0x15, 0x21, 0x54, 0x80, 0x85,
        0x55, 0x2a, 0x15, 0x55, 0x40, 0x55};

    // compass north
    unsigned char cd3[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54,
        0x54, 0x55, 0x52, 0x12, 0x15, 0x52, 0x82, 0x15,
        0x02, 0x82, 0x00, 0xa2, 0x22, 0x2a, 0x02, 0x0a,
        0x00, 0x52, 0x0a, 0x15, 0x52, 0x12, 0x15, 0x54,
        0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // compass south
    unsigned char cd4[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x01, 0x55, 0x54, 0xa8, 0x55, 0x52, 0x02, 0x15,
        0x04, 0x84, 0x40, 0xa1, 0x21, 0x2a, 0x04, 0x48,
        0x40, 0x52, 0x02, 0x15, 0x54, 0xa8, 0x55, 0x55,
        0x01, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // compass east
    unsigned char cd5[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54,
        0x00, 0x55, 0x52, 0xaa, 0x15, 0x52, 0x00, 0x55,
        0x02, 0x05, 0x40, 0xa2, 0xa1, 0x2a, 0x02, 0x05,
        0x40, 0x52, 0x00, 0x55, 0x52, 0xaa, 0x15, 0x54,
        0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // compass west
    unsigned char cd6[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54,
        0x54, 0x55, 0x52, 0x12, 0x15, 0x52, 0x12, 0x15,
        0x02, 0x02, 0x00, 0xa2, 0x22, 0x2a, 0x02, 0x8a,
        0x00, 0x52, 0x8a, 0x15, 0x52, 0x12, 0x15, 0x54,
        0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // compass between
    unsigned char cd7[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x45, 0x55, 0x55, 0x21, 0x55,
        0x01, 0x21, 0x00, 0xa8, 0x20, 0xaa, 0x01, 0x21,
        0x00, 0x55, 0x21, 0x55, 0x55, 0x45, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    learn_char(208, cd0);
    learn_char(209, cd1);
    learn_char(210, cd2);
    learn_char(211, cd3);
    learn_char(212, cd4);
    learn_char(213, cd5);
    learn_char(214, cd6);
    learn_char(215, cd7);
#endif
#if WRITECHARS == 216
    // compass line
    unsigned char cd8[54] = {0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x00, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0x00, 0x00,
        0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow right
    unsigned char cd9[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x15, 0x55, 0x54, 0x85, 0x40, 0x00, 0xa1,
        0x2a, 0xaa, 0xa8, 0x2a, 0xaa, 0xa8, 0x40, 0x00,
        0xa1, 0x55, 0x54, 0x85, 0x55, 0x55, 0x15, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow right-up
    unsigned char cda[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x40, 0x01, 0x55, 0x2a, 0xa8, 0x55,
        0x4a, 0xa8, 0x55, 0x52, 0xa8, 0x55, 0x4a, 0xa8,
        0x55, 0x2a, 0x28, 0x54, 0xa8, 0x48, 0x52, 0xa1,
        0x51, 0x4a, 0x85, 0x55, 0x52, 0x15, 0x55, 0x54,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow up
    unsigned char cdb[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x41, 0x55, 0x55, 0x28, 0x55, 0x54,
        0xaa, 0x15, 0x52, 0xaa, 0x85, 0x54, 0x28, 0x15,
        0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28,
        0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x55,
        0x28, 0x55, 0x55, 0x41, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow left-up
    unsigned char cdc[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x40, 0x01, 0x55, 0x2a, 0xa8, 0x55, 0x2a,
        0xa1, 0x55, 0x2a, 0x85, 0x55, 0x2a, 0xa1, 0x55,
        0x28, 0xa8, 0x55, 0x21, 0x2a, 0x15, 0x45, 0x4a,
        0x85, 0x55, 0x52, 0xa1, 0x55, 0x54, 0x85, 0x55,
        0x55, 0x15, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow left
    unsigned char cdd[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x54,
        0x55, 0x55, 0x52, 0x15, 0x55, 0x4a, 0x00, 0x01,
        0x2a, 0xaa, 0xa8, 0x2a, 0xaa, 0xa8, 0x4a, 0x00,
        0x01, 0x52, 0x15, 0x55, 0x54, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow left-down
    unsigned char cde[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x15, 0x55,
        0x54, 0x85, 0x55, 0x52, 0xa1, 0x45, 0x4a, 0x85,
        0x21, 0x2a, 0x15, 0x28, 0xa8, 0x55, 0x2a, 0xa1,
        0x55, 0x2a, 0x85, 0x55, 0x2a, 0xa1, 0x55, 0x2a,
        0xa8, 0x55, 0x40, 0x01, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    // arrow down
    unsigned char cdf[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x41, 0x55, 0x55, 0x28, 0x55, 0x55,
        0x28, 0x55, 0x55, 0x28, 0x55, 0x55, 0x28, 0x55,
        0x55, 0x28, 0x55, 0x55, 0x28, 0x55, 0x54, 0x28,
        0x15, 0x52, 0xaa, 0x85, 0x54, 0xaa, 0x15, 0x55,
        0x28, 0x55, 0x55, 0x41, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

    learn_char(216, cd8);
        learn_char(217, cd9);
    learn_char(218, cda);
    learn_char(219, cdb);
    learn_char(220, cdc);
    learn_char(221, cdd);
    learn_char(222, cde);
    learn_char(223, cdf);
#endif
#if WRITECHARS == 224
     // arrow right-down
    unsigned char ce0[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x54, 0x55, 0x55, 0x52,
        0x15, 0x55, 0x4a, 0x85, 0x55, 0x52, 0xa1, 0x51,
        0x54, 0xa8, 0x48, 0x55, 0x2a, 0x28, 0x55, 0x4a,
        0xa8, 0x55, 0x52, 0xa8, 0x55, 0x4a, 0xa8, 0x55,
        0x2a, 0xa8, 0x55, 0x40, 0x01, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

        // horizon up
    unsigned char ce1[54] ={0x55, 0x55, 0x55, 0x00, 0x00, 0x00, 0xaa, 0xaa,
        0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0x00, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

        // horizon middle
    unsigned char ce2[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x00, 0x00, 0x00,
        0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x00, 0x00,
        0x00, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55};

        // horizon down
    unsigned char ce3[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00,
        0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
        0x00, 0x00, 0x00, 0x55, 0x55, 0x55};

        // horizon center
    unsigned char ce4[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x00,
        0x14, 0x00, 0xaa, 0x14, 0xaa, 0xaa, 0x82, 0xaa,
        0x00, 0xaa, 0x00, 0x54, 0x00, 0x15};

        // horizon roll
    unsigned char ce5[54] ={0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
        0x55, 0x00, 0x55, 0x00, 0x2a, 0x14, 0xa8, 0x4a,
        0x82, 0xa1, 0x52, 0xaa, 0x85, 0x54, 0xaa, 0x15,
        0x55, 0x28, 0x55, 0x55, 0x41, 0x55};
       
        // gps PH
    unsigned char ce6[54] ={0x55, 0x05, 0x11, 0x54, 0xa0, 0x88, 0x54, 0x88,
        0x88, 0x54, 0xa0, 0xa8, 0x54, 0x84, 0x88, 0x44,
        0x84, 0x88, 0x21, 0x15, 0x11, 0xa8, 0x55, 0x55,
        0xa1, 0x55, 0x55, 0x98, 0x15, 0x55, 0x2a, 0x85,
        0x55, 0x4a, 0xa1, 0x55, 0x4a, 0xa8, 0x55, 0x52,
        0xaa, 0x15, 0x54, 0xaa, 0x15, 0x55, 0x28, 0x55,
        0x55, 0x41, 0x55, 0x55, 0x55, 0x55};
       
        // gps CH
    unsigned char ce7[54] ={0x55, 0x55, 0x41, 0x55, 0x55, 0x28, 0x55, 0x54,
        0x81, 0x55, 0x54, 0x85, 0x55, 0x54, 0x81, 0x45,
        0x55, 0x28, 0x21, 0x55, 0x01, 0xa8, 0x54, 0x88,
        0xa1, 0x54, 0x88, 0x98, 0x14, 0xa8, 0x2a, 0x84,
        0x88, 0x4a, 0xa0, 0x88, 0x4a, 0xa8, 0x11, 0x52,
        0xaa, 0x15, 0x54, 0xaa, 0x15, 0x55, 0x28, 0x55,
        0x55, 0x41, 0x55, 0x55, 0x55, 0x55};

    learn_char(224, ce0);
        learn_char(225, ce1);
        learn_char(226, ce2);
        learn_char(227, ce3);
        learn_char(228, ce4);
        learn_char(229, ce5);
        learn_char(230, ce6);
        learn_char(231, ce7);
#endif
#endif // write char general
    /* ##########################################################################
     * continue normal main
     * ##########################################################################*/

       
        // Setup Video Mode
        if (COSD_FLAGS & COSD_FLAG_NTSC) {
        // NTSC + enable display immediately (VM0)
        spi_send_byte(0x00, 0b00001000);
        } else {
        // PAL + enable display immediately (VM0)
        spi_send_byte(0x00, 0b01001000);
        }

    // clear all display-mem (DMM)
    spi_send_byte(0x04, 0b00000100);

    // clearing takes 12uS according to maxim so lets wait longer
    _delay_us(120);

    // 8bit mode
    spi_send_byte(0x04, 0b01000000);

    // write blank chars to whole screen
    clear();

#if !(ALLCHARSDEBUG|(WRITECHARS != -1))
    // init usart
    usart1_init();

    // set up timer
    TCCR0 |= (1 << CS00) | (1 << CS01); // timer0 prescaler 64
    OCR0 = 6; // preload
    TIMSK |= (1 << TOIE0); // enable overflow timer0

    // enable interrupts
    sei();
#endif

    //write_ascii_string(2,  7, "         CaScAdE          ");
    //write_ascii_string(2,  8, "is TESTING his open source");
    //write_ascii_string(2,  9, "    EPi OSD Firmware");

    // custom char preview
    /*write_char_xy( 2, 7, 200);
    write_char_xy( 3, 7, 201);
    write_char_xy( 4, 7, 202);
    write_char_xy( 5, 7, 203);
    write_char_xy( 6, 7, 204);
    write_char_xy( 7, 7, 205);
    write_char_xy( 8, 7, 206);
    write_char_xy( 9, 7, 207);
    write_char_xy(10, 7, 208);
    write_char_xy(11, 7, 209);
    write_char_xy(12, 7, 210);
    write_char_xy(13, 7, 211);
    write_char_xy(14, 7, 212);
    write_char_xy(15, 7, 213);
    write_char_xy(16, 7, 214);
    write_char_xy(17, 7, 215);*/


    // we are ready
    LED3_ON



#if ALLCHARSDEBUG | (WRITECHARS != -1)
        clear();
    write_all_chars();
#else
    // clear serial screen
    //usart1_puts("\x1B[2J\x1B[H");
    //usart1_puts("hello world!\r\n");

   
    // request data ever 100ms from FC
        //unsigned char ms = 10;
        //sendMKData('d', 0, &ms, 1);
     
    // request OSD Data from NC every 100ms
        unsigned char ms = 10;
    sendMKData('o', 1, &ms, 1);
        // and disable debug...
        //ms = 0;
        //sendMKData('d', 0, &ms, 1);

        // stats for after flight
        int16_t max_Altimeter = 0;
        uint16_t max_GroundSpeed = 0;
        int16_t max_Distance = 0;
        uint8_t min_UBat = 255;
        uint16_t max_FlyingTime = 0;

        // flags from last round to check for changes
        uint8_t old_MKFlags = 0;
       
    char* directions[8] = {"NE", "E ", "SE", "S ", "SW", "W ", "NW", "N "};
        char arrowdir[8] =   { 218,  217,  224,  223,  222,  221,  220, 219};

    while (1) {
                // write icons at init or after menu/mode-switch
                if (!(COSD_FLAGS & COSD_ICONS_WRITTEN)) {
                            write_char_xy(5, top_line, 203); // km/h
                            write_char_xy(10, top_line, 202); // RC-transmitter
                            write_char_xy(16, top_line, 208); // degree symbol
                            write_char_xy(27, top_line, 204); // small meters m
                            write_ascii_string(6, bottom_line, "V"); // voltage
                            write_char_xy(14, bottom_line, 209); // on clock
                            write_char_xy(22, bottom_line, 210); // fly clock
                            write_char_xy(26, bottom_line, 200); // sat1
                            write_char_xy(27, bottom_line, 201); // sat2
                                COSD_FLAGS |= COSD_ICONS_WRITTEN;
                }
        if (rxd_buffer_locked) {
            if (rxd_buffer[2] == 'D') { // FC Data
                /*Decode64();
                debugData = *((DebugOut_t*) pRxData);
                write_number_s(12, 2, RxDataLen);
                write_number_s(20, 2, setsReceived++);
                write_number_s(12, 3, debugData.Analog[0]);
                write_number_s(12, 4, debugData.Analog[2]);
                write_number_s(12, 5, debugData.Analog[1]);
                write_number_s(12, 6, debugData.Analog[3]);
                write_number_s(12, 7, debugData.Analog[9]);
                write_number_s(12, 8, debugData.Analog[10]);
                                write_number_s(12, 4, debugData.Analog[12]);
                                write_number_s(12, 5, debugData.Analog[13]);
                                write_number_s(12, 6, debugData.Analog[14]);
                                write_number_s(12, 7, debugData.Analog[15]);*/

            } else if (rxd_buffer[2] == 'O') { // NC OSD Data
                Decode64();
                naviData = *((NaviData_t*) pRxData);

                                // first line
                                write_3digit_number_u(2, top_line, (uint16_t)(((uint32_t)naviData.GroundSpeed*36)/1000));

                write_3digit_number_u(7, top_line, naviData.RC_Quality);
                if (naviData.RC_Quality <= RCLVL_WRN && last_RC_Quality > RCLVL_WRN) {
                    for (uint8_t x = 0; x < 4; x++)
                        write_char_att_xy(7 + x, top_line, BLINK);
                } else if (naviData.RC_Quality > RCLVL_WRN && last_RC_Quality <= RCLVL_WRN) {
                    for (uint8_t x = 0; x < 4; x++)
                        write_char_att_xy(7 + x, top_line, 0);
                }
                last_RC_Quality = naviData.RC_Quality;

                write_3digit_number_u(13, top_line, naviData.CompassHeading);

                write_ascii_string(17, top_line, directions[heading_conv(naviData.CompassHeading)]);

                if (naviData.Variometer == 0) {
                    write_char_xy(20, top_line, 206); // plain line
                } else if (naviData.Variometer > 0) {
                    write_char_xy(20, top_line, 207); // arrow up
                } else {
                    write_char_xy(20, top_line, 205); // arrow down
                }

                                // TODO: is this really dm?
                write_number_s(22, top_line, naviData.Altimeter/10);

                                // seccond line
                draw_compass(11, top_line + 1, naviData.CompassHeading);

                                // TODO: verify correctness
                                uint16_t heading_home = (naviData.HomePositionDeviation.Bearing + 360 - naviData.CompassHeading) % 360;
                                write_char_xy(27, top_line + 1, arrowdir[heading_conv(heading_home)]);

       
                                write_number_s(22, top_line + 1, naviData.HomePositionDeviation.Distance/100);

                                // center
                                if (naviData.MKFlags & FLAG_MOTOR_RUN) { // should be engines running
                                        if (!(old_MKFlags & FLAG_MOTOR_RUN)) { // motors just started, clear middle
                                                clear();
                                                // update flags to paint display again if needed
                                                COSD_FLAGS &= ~COSD_ICONS_WRITTEN;
                                        }
                                if (COSD_FLAGS & COSD_FLAG_ARTHORIZON) {
                                        draw_artificial_horizon(top_line + 2, bottom_line - 1, naviData.AngleNick, naviData.AngleRoll);
                                }
                                } else {
                                        // stats
                                        write_ascii_string(2, 5, "max Altitude:");
                                        write_number_s(17, 5, max_Altimeter/10);
                                        write_char_xy(22, 5, 204); // small meters m
                                        write_ascii_string(2, 6, "max Speed   :");
                                        write_3digit_number_u(19, 6, (uint16_t)(((uint32_t)max_GroundSpeed*36)/1000));
                                        write_char_xy(22, 6, 203); // km/h
                                        write_ascii_string(2, 7, "max Distance:");
                                        write_number_s(17, 7, max_Distance/100);
                                        write_char_xy(22, 7, 204); // small meters m
                                        write_ascii_string(2, 8, "min voltage :");
                                        //write_number_s(17, 8, min_UBat/10);
                                        write_number_u_10th(16, 8, min_UBat);
                                        write_ascii_string(22, 8, "V"); // voltage
                                        write_ascii_string(2, 9, "max time    :");
                                        write_time(16, 9, max_FlyingTime);
                                        write_char_xy(22, 9, 210); // fly clock
                                }

                                // bottom line
                write_number_u_10th(0, bottom_line, naviData.UBat);
                if (naviData.UBat <= UBAT_WRN && last_UBat > UBAT_WRN) {
                    for (uint8_t x = 0; x < 7; x++)
                        write_char_att_xy(x, bottom_line, BLINK);
                } else {
                    for (uint8_t x = 0; x < 7; x++)
                        write_char_att_xy(x, bottom_line, 0);
                }

                write_time(8, bottom_line, uptime);
                write_time(16, bottom_line, naviData.FlyingTime);

                write_3digit_number_u(23, bottom_line, naviData.SatsInUse);

                                if (naviData.NCFlags & NC_FLAG_CH) {
                                        write_char_xy(27, bottom_line, 231);    // gps ch
                                } else if (naviData.NCFlags & NC_FLAG_PH) {
                                        write_char_xy(27, bottom_line, 230);    // gps ph
                                } else { // (naviData.NCFlags & NC_FLAG_FREE)
                                        write_char_xy(27, bottom_line, 201);    // sat2 (free)
                                }

                //write_number_s(8, 5, RxDataLen);
                //write_number_s(16, 5, setsReceived++);

                                // remember statistics
                                if (naviData.Altimeter > max_Altimeter) max_Altimeter = naviData.Altimeter;
                                if (naviData.GroundSpeed > max_GroundSpeed) max_GroundSpeed = naviData.GroundSpeed;
                                if (naviData.HomePositionDeviation.Distance > max_Distance) {
                                        max_Distance = naviData.HomePositionDeviation.Distance;
                                }
                                if (naviData.UBat < min_UBat) min_UBat = naviData.UBat;
                                if (naviData.FlyingTime > max_FlyingTime) max_FlyingTime = naviData.FlyingTime;
                               
                                old_MKFlags = naviData.MKFlags;
            }
            rxd_buffer_locked = 0;
        }
        // handle keypress
        if (s1_pressed()) {
                        //sendMKData('d', 1, (unsigned char*) 0, 1);
            // request OSD Data from NC every 100ms
                        /*unsigned char ms = 10;
            sendMKData('o', 1, &ms, 1);
            _delay_ms(500);*/

                        config_menu();
        }
                if (s2_pressed()) {
            uptime = 0;
            _delay_ms(100);
        }
    }
#endif
    return 0;
}