Esempio n. 1
0
EXPORT void CALL DllTest ( HWND hParent )
{
    // Defining flags for tests
    BOOL init_audio = FALSE;
    BOOL init_timer = FALSE;
    BOOL open_audio_device = FALSE;
    BOOL format_match = FALSE;
    BOOL freq_match = FALSE;

    // Storage for SDL_Errors.
    char *sdl_error[3];

    // Clear the pointers (Should not be truly necessary unless something horrible goes wrong)
    memset(sdl_error, 0, sizeof(char*[3]));

    // Print out inital message
    printf("[JttL's SDL Audio plugin] Starting Audio Test.\n");

    // Make Sure SDL Audio is disabled so we can restart fresh
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the subsystems before attempting to reinitalize them, if either are initalized already
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    // Attempt to initialize SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) < 0 )
    {
        sdl_error[0] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize audio subsystem: %s\n", sdl_error[0]);
        init_audio = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Audio subsystem initialized.\n");
        init_audio = TRUE;
    }

    // Attempt to initialize SDL Timer
    if(SDL_InitSubSystem(SDL_INIT_TIMER) < 0 )
    {
        sdl_error[1] = SDL_GetError();
        printf("[JttL's SDL Audio plugin] Error: Couldn't initialize timer subsystem: %s\n", sdl_error[1]);
        init_timer = FALSE;
    }
    else
    {
        printf("[JttL's SDL Audio plugin] Timer subsystem initialized.\n");
        init_timer = TRUE;
    }

    // Close the audio device
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Prototype of our callback function
    void my_audio_callback(void *userdata, Uint8 *stream, int len);

    // Open the audio device
    SDL_AudioSpec *desired, *obtained;

    // Allocate a desired SDL_AudioSpec
    desired = malloc(sizeof(SDL_AudioSpec));

    // Allocate space for the obtained SDL_AudioSpec
    obtained = malloc(sizeof(SDL_AudioSpec));

    // 22050Hz - FM Radio quality
    desired->freq=GameFreq;

    // Print out message for frequency
    printf("[JttL's SDL Audio plugin] Requesting frequency: %iHz.\n", desired->freq);

    // 16-bit signed audio
    desired->format=AUDIO_S16SYS;

    // Print out message for format
    printf("[JttL's SDL Audio plugin] Requesting format: %i.\n", desired->format);

    // Enable two hardware channels (for Stereo output)
    desired->channels=2;

    // Large audio buffer reduces risk of dropouts but increases response time
    desired->samples=SecondaryBufferSize;

    // Our callback function
    desired->callback=my_audio_callback;
    desired->userdata=NULL;

    // Open the audio device
    if ( SDL_OpenAudio(desired, obtained) < 0 )
    {
        sdl_error[2] = SDL_GetError();
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Couldn't open audio device: %s\n", sdl_error[2]);
        open_audio_device = FALSE;
    }
    else 
    {
        open_audio_device = TRUE;
    }

    // Check to see if we have the audio format we requested.
    if(desired->format != obtained->format)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained audio format differs from requested.\n");
        format_match = FALSE;
    }
    else
    {
        format_match = TRUE;
    }

    // Check to see if we have the frequency we requested.
    if(desired->freq != obtained->freq)
    {
        fprintf(stderr, "[JttL's SDL Audio plugin] Error: Obtained frequency differs from requested.\n");
        freq_match = FALSE;
    }
    else 
    {
        freq_match = TRUE;
    }

    // Free no longer needed objects used for testing the specifications.
    free(desired);
    free(obtained);

    // Uninitialize SDL audio, as it is no longer needed.
    SDL_PauseAudio(1);
    SDL_CloseAudio();

    // Quit the Audio and Timer subsystems if they are enabled. (They should be, unless something went horribly wrong.)
    if(SDL_WasInit(SDL_INIT_AUDIO) != 0) SDL_QuitSubSystem(SDL_INIT_AUDIO);
    if(SDL_WasInit(SDL_INIT_TIMER) != 0) SDL_QuitSubSystem(SDL_INIT_TIMER);

    char tMsg[1024];

    if((init_audio == TRUE) && ( init_timer == TRUE ) && ( open_audio_device == TRUE ) && (format_match == TRUE) && (freq_match == TRUE)) 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Audio test successful.");
        critical_failure = 0;
    }
    else 
    {
        sprintf(tMsg,"[JttL's SDL Audio plugin] Test Results\n--\n");
        if(init_audio != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Audio:\n - %s\n", tMsg,sdl_error[0]);
        }
        if(init_timer != TRUE)
        {
            sprintf(tMsg, "%sError initalizing SDL Timer:\n - %s\n", tMsg,sdl_error[1]);
        }
        if(open_audio_device != TRUE)
        {
            sprintf(tMsg, "%sError opening audio device:\n - %s\n", tMsg,sdl_error[2]);
        }
        if(format_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output audio format.\n", tMsg);
        }
        if(freq_match != TRUE)
        {
            sprintf(tMsg, "%sUnable to get the requested output frequency.\n", tMsg);
        }
        critical_failure = 1;
    }

    display_test(tMsg);
}
Esempio n. 2
0
void serial_process_command(char *line) {

  if(in_displayparams) {
    serial_displayparams_run(line);
    in_displayparams = false;
  }

  if(in_setdevicetag) {
    serial_setdevicetag_run(line);
    in_setdevicetag = false;
  }

  if(in_setrtc) {
    serial_setrtc_run(line);
    in_setrtc = false;
  }

  if(in_setkeyval) {
    serial_setkeyval_run(line);
    in_setkeyval = false;
  }

  serial_write_string("\r\n");
  if(strcmp(line,"HELLO") == 0) {
   serial_write_string("GREETINGS PROFESSOR FALKEN.\r\n");
  } else 
  if(strcmp(line,"LIST GAMES") == 0) {
    serial_write_string("I'M KIND OF BORED OF GAMES, TURNS OUT THE ONLY WAY TO WIN IS NOT TO PLAY...\r\n");
  } else 
  if(strcmp(line,"LOGXFER") == 0) {
    serial_sendlog();
  } else 
  if(strcmp(line,"DISPLAYPARAMS") == 0) {
    serial_displayparams();
  } else
  if(strcmp(line,"HELP") == 0) {
    serial_write_string("Available commands: HELP, LOGXFER, DISPLAYTEST, HELLO");
  } else 
  if(strcmp(line,"DISPLAYTEST") == 0) {
    display_test();
  } else
  if(strcmp(line,"LOGTEST") == 0) {
    char stemp[100];

    sprintf(stemp,"Raw log data\r\n");
    serial_write_string(stemp);

    uint8_t *flash_log = flashstorage_log_get();
    for(int n=0;n<1024;n++) {
      sprintf(stemp,"%u ",flash_log[n]);
      serial_write_string(stemp);
      if(n%64 == 0) serial_write_string("\r\n");
    }
    serial_write_string("\r\n");

    log_data_t data;
    data.time = 0;
    data.cpm  = 1;
    data.accel_x_start = 2;
    data.accel_y_start = 3;
    data.accel_z_start = 4;
    data.accel_x_end   = 5;
    data.accel_y_end   = 6;
    data.accel_z_end   = 7;
    data.log_type      = UINT_MAX;
    sprintf(stemp,"Log size: %u\r\n",flashstorage_log_size());
    serial_write_string(stemp);

    sprintf(stemp,"Writing test log entry of size: %u\r\n",sizeof(log_data_t));
    serial_write_string(stemp);

    flashstorage_log_pushback((uint8 *) &data,sizeof(log_data_t));

    sprintf(stemp,"Log size: %u\r\n",flashstorage_log_size());
    serial_write_string(stemp);
  } else 
  if(strcmp(line,"VERSION") == 0) {
    char stemp[50];
    sprintf(stemp,"Version: %s\r\n",OS100VERSION);
    serial_write_string(stemp);
  } else 
  if(strcmp(line,"GETDEVICETAG") == 0) {
    const char *devicetag = flashstorage_keyval_get("DEVICETAG");
    if(devicetag != 0) {
      char stemp[100];
      sprintf(stemp,"Devicetag: %s\r\n",devicetag);
      serial_write_string(stemp);
    } else {
      serial_write_string("No device tag set");
    }
  } else
  if(strcmp(line,"SETDEVICETAG") == 0) {
    serial_setdevicetag();
  } else 
  if(strcmp(line,"READPRIVATEKEY") == 0) {
   // serial_readprivatekey();  // removed for production
  } else
  if(strcmp(line,"WRITEPRIVATEKEY") == 0) {
   // serial_writeprivatekey(); // maybe this should be removed for production?
  } else 
  if(strcmp(line,"MAGREAD") == 0) {
    gpio_set_mode (PIN_MAP[41].gpio_device,PIN_MAP[41].gpio_bit, GPIO_OUTPUT_PP); // MAGPOWER
    gpio_set_mode (PIN_MAP[29].gpio_device,PIN_MAP[29].gpio_bit, GPIO_INPUT_PU);  // MAGSENSE

    // Power up magsense
    gpio_write_bit(PIN_MAP[41].gpio_device,PIN_MAP[41].gpio_bit,1);

    // wait...
    delay_us(1000);
    
    // Read magsense
    int magsense = gpio_read_bit(PIN_MAP[29].gpio_device,PIN_MAP[29].gpio_bit);

    char magsenses[50];
    sprintf(magsenses,"%u\r\n",magsense);
    serial_write_string(magsenses);
  } else
  if(strcmp(line,"WRITEDAC") == 0) {
    dac_init(DAC,DAC_CH2);

    int8_t idelta=1;
    uint8_t i=0;
    for(int n=0;n<1000000;n++) {
      
      if(i == 254) idelta = -1;
      if(i == 0  ) idelta =  1;

      i += idelta;

      dac_write_channel(DAC,2,i);
    }
    serial_write_string("WRITEDACFIN");
  } else
  if(strcmp(line,"TESTHP") == 0) {
    gpio_set_mode (PIN_MAP[12].gpio_device,PIN_MAP[12].gpio_bit, GPIO_OUTPUT_PP);  // HP_COMBINED
    for(int n=0;n<100000;n++) {
      gpio_write_bit(PIN_MAP[12].gpio_device,PIN_MAP[12].gpio_bit,1);
      delay_us(100);
      gpio_write_bit(PIN_MAP[12].gpio_device,PIN_MAP[12].gpio_bit,0);
      delay_us(100);
    }
  } else 
  if(strcmp(line,"READADC") == 0) {

    adc_init(PIN_MAP[12].adc_device); // all on ADC1

    adc_set_extsel(PIN_MAP[12].adc_device, ADC_SWSTART);
    adc_set_exttrig(PIN_MAP[12].adc_device, true);

    adc_enable(PIN_MAP[12].adc_device);
    adc_calibrate(PIN_MAP[12].adc_device);
    adc_set_sample_rate(PIN_MAP[12].adc_device, ADC_SMPR_55_5);

    gpio_set_mode (PIN_MAP[12].gpio_device,PIN_MAP[12].gpio_bit, GPIO_INPUT_ANALOG);
    gpio_set_mode (PIN_MAP[19].gpio_device,PIN_MAP[19].gpio_bit, GPIO_INPUT_ANALOG);
    gpio_set_mode (PIN_MAP[20].gpio_device,PIN_MAP[20].gpio_bit, GPIO_INPUT_ANALOG);

    int n=0;
    uint16 value1 = adc_read(PIN_MAP[12].adc_device,PIN_MAP[12].adc_channel);
    uint16 value2 = adc_read(PIN_MAP[19].adc_device,PIN_MAP[19].adc_channel);
    uint16 value3 = adc_read(PIN_MAP[20].adc_device,PIN_MAP[20].adc_channel);
    char values[50];
    sprintf(values,"PA6 ADC Read: %u\r\n",value1);
    serial_write_string(values);
    sprintf(values,"PC4 ADC Read: %u\r\n",value2);
    serial_write_string(values);
    sprintf(values,"PC5 ADC Read: %u\r\n",value3);
    serial_write_string(values);
  } else
  if(strcmp(line,"SETMICREVERSE") == 0) {
    gpio_set_mode (PIN_MAP[36].gpio_device,PIN_MAP[36].gpio_bit, GPIO_OUTPUT_PP);  // MICREVERSE
    gpio_set_mode (PIN_MAP[35].gpio_device,PIN_MAP[35].gpio_bit, GPIO_OUTPUT_PP);  // MICIPHONE
    gpio_write_bit(PIN_MAP[36].gpio_device,PIN_MAP[36].gpio_bit,1); // MICREVERSE
    gpio_write_bit(PIN_MAP[35].gpio_device,PIN_MAP[35].gpio_bit,0); // MICIPHONE
    serial_write_string("Set MICREVERSE to 1, MICIPHONE to 0\r\n");
  } else 
  if(strcmp(line,"SETMICIPHONE") == 0) {
    gpio_set_mode (PIN_MAP[36].gpio_device,PIN_MAP[36].gpio_bit, GPIO_OUTPUT_PP);  // MICREVERSE
    gpio_set_mode (PIN_MAP[35].gpio_device,PIN_MAP[35].gpio_bit, GPIO_OUTPUT_PP);  // MICIPHONE
    gpio_write_bit(PIN_MAP[36].gpio_device,PIN_MAP[36].gpio_bit,0); // MICREVERSE
    gpio_write_bit(PIN_MAP[35].gpio_device,PIN_MAP[35].gpio_bit,1); // MICIPHONE
    serial_write_string("Set MICREVERSE to 0, MICIPHONE to 1\r\n");
  } else
  if(strcmp(line,"TESTSIGN") == 0) {
    serial_signing_test();
  } else 
  if(strcmp(line,"PUBKEY") == 0) {
    signing_printPubKey();
    serial_write_string("\n\r");
  } else 
  if(strcmp(line,"GUID") == 0) {
    signing_printGUID();
    serial_write_string("\n\r");
  } else 
  if(strcmp(line,"KEYVALID") == 0) {
    if( signing_isKeyValid() == 1 )
      serial_write_string("uu_valid VALID KEY\r\n");
    else
      serial_write_string("uu_valid IMPROPER OR UNINITIALIZED KEY\r\n");
  } else 
  if(strcmp(line,"LOGSIG") == 0) {
    signing_hashLog();
    serial_write_string("\n\r");
  } else
  if(strcmp(line,"LOGPAUSE") == 0) {
    flashstorage_log_pause();
  } else 
  if(strcmp(line,"LOGRESUME") == 0) {
    flashstorage_log_resume();
  } else
  if(strcmp(line,"LOGCLEAR") == 0) {
    serial_write_string("Clearing flash log\r\n");
    flashstorage_log_clear();
    serial_write_string("Cleared\r\n");
  } else
  if(strcmp(line,"KEYVALDUMP") == 0) {
    serial_keyvaldump();
  } else
  if(strcmp(line,"KEYVALSET") == 0) {
    serial_setkeyval();
  } else
  if(strcmp(line,"SETRTC") == 0) {
    serial_setrtc();
  } else
  if(strcmp(line,"RTCALARM") == 0) {
    serial_write_string("Alarm triggered for 10s\r\n");
    rtc_set_alarm(RTC,rtc_get_time(RTC)+10);
  }

  serial_write_string("\r\n>");
}
//********************************
//********************************
//********** INITIALISE **********
//********************************
//********************************
void initialise (void)
{
	BYTE data;
	
	//##### GENERAL NOTE ABOUT PIC32'S #####
	//Try and use the peripheral libraries instead of special function registers for everything (literally everything!) to avoid
	//bugs that can be caused by the pipeline and interrupts.
	

	//---------------------------------
	//----- CONFIGURE PERFORMANCE -----
	//---------------------------------
	
	//----- SETUP EVERYTHING FOR OPTIMUM PERFORMANCE -----
	SYSTEMConfigPerformance(80000000ul);		//Note this sets peripheral bus to '1' max speed (regardless of configuration bit setting)
												//Use PBCLK divider of 1:1 to calculate UART baud, timer tick etc


	//----- SET PERIPHERAL BUS DIVISOR -----
	//To minimize dynamic power the PB divisor should be chosen to run the peripherals at the lowest frequency that provides acceptable system performance
	mOSCSetPBDIV(OSC_PB_DIV_2);			//OSC_PB_DIV_1, OSC_PB_DIV_2, OSC_PB_DIV_4, OSC_PB_DIV_8, 

	//----- SETUP INTERRUPTS -----
	INTEnableSystemMultiVectoredInt();

	//-------------------------
	//----- SETUP IO PINS -----
	//-------------------------
	//(Device will powerup with all IO pins as inputs)

	//----- TURN OFF THE JTAG PORT -----
	//(JTAG is on by default)
	//mJTAGPortEnable(0);		//Must be on for Microchip Multimedia Development board

	#define	PORTA_IO	0xc2ff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTAWrite(0xc033);					//Set initial ouput pin states
	mPORTASetPinsDigitalIn(PORTA_IO);		//(Sets high bits as input)
	mPORTASetPinsDigitalOut(~PORTA_IO);		//(Sets high bits as output)
	
	#define	PORTB_IO	0xfbff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTBWrite(0x6d13);					//Set initial ouput pin states
	mPORTBSetPinsDigitalIn(PORTB_IO);		//(Sets high bits as input)
	mPORTBSetPinsDigitalOut(~PORTB_IO);		//(Sets high bits as output)

	mPORTBSetPinsDigitalIn(BIT_0 | BIT_1 | BIT_3 | BIT_4 | BIT_15);			//Joystick inputs

	#define	PORTC_IO	0xf01e				//Setup the IO pin type (0 = output, 1 = input)
	mPORTCWrite(0x3018);					//Set initial ouput pin states
	mPORTCSetPinsDigitalIn(PORTC_IO);		//(Sets high bits as input)
	mPORTCSetPinsDigitalOut(~PORTC_IO);		//(Sets high bits as output)

	#define	PORTD_IO	0x7bfe				//Setup the IO pin type (0 = output, 1 = input)
	mPORTDWrite(0xbdaf);					//Set initial ouput pin states
	mPORTDSetPinsDigitalIn(PORTD_IO);		//(Sets high bits as input)
	mPORTDSetPinsDigitalOut(~PORTD_IO);		//(Sets high bits as output)

	mPORTDSetPinsDigitalOut(BIT_2 | BIT_1);		//LED's 2 and 3
	mPORTDSetPinsDigitalIn(BIT_9);

	#define	PORTE_IO	0x03ff				//Setup the IO pin type (0 = output, 1 = input)
	mPORTEWrite(0x02a2);					//Set initial ouput pin states
	mPORTESetPinsDigitalIn(PORTE_IO);		//(Sets high bits as input)
	mPORTESetPinsDigitalOut(~PORTE_IO);		//(Sets high bits as output)

	#define	PORTF_IO	0x111f				//Setup the IO pin type (0 = output, 1 = input)
	mPORTFWrite(0x0039);					//Set initial ouput pin states
	mPORTFSetPinsDigitalIn(PORTF_IO);		//(Sets high bits as input)
	mPORTFSetPinsDigitalOut(~PORTF_IO);		//(Sets high bits as output)

	#define	PORTG_IO	0xd3cf				//Setup the IO pin type (0 = output, 1 = input)
	mPORTGWrite(0xf203);					//Set initial ouput pin states
	mPORTGSetPinsDigitalIn(PORTG_IO);		//(Sets high bits as input)
	mPORTGSetPinsDigitalOut(~PORTG_IO);		//(Sets high bits as output)



	//Read pins using:
	// mPORTAReadBits(BIT_0);
	//Write pins using:
	// mPORTAClearBits(BIT_0);
	// mPORTASetBits(BIT_0);
	// mPORTAToggleBits(BIT_0);



	//----- INPUT CHANGE NOTIFICATION CONFIGURATION -----
	//EnableCN0();
	ConfigCNPullups(CN2_PULLUP_ENABLE | CN3_PULLUP_ENABLE | CN5_PULLUP_ENABLE | CN6_PULLUP_ENABLE | CN12_PULLUP_ENABLE);		//Joystick pins



	//----- SETUP THE A TO D PINS -----
	ENABLE_ALL_DIG;


	//---------------------
	//----- SETUP USB -----
	//---------------------
	//The USB specifications require that USB peripheral devices must never source current onto the Vbus pin.  Additionally, USB peripherals should not source
	//current on D+ or D- when the host/hub is not actively powering the Vbus line.  When designing a self powered (as opposed to bus powered) USB peripheral
	//device, the firmware should make sure not to turn on the USB module and D+ or D- pull up resistor unless Vbus is actively powered.  Therefore, the
	//firmware needs some means to detect when Vbus is being powered by the host. A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and
	//can be used to detect when Vbus is high (host actively powering), or low (host is shut down or otherwise not supplying power).  The USB firmware
	//can then periodically poll this I/O pin to know when it is okay to turn on the USB module/D+/D- pull up resistor.  When designing a purely bus powered
	//peripheral device, it is not possible to source current on D+ or D- when the host is not actively providing power on Vbus. Therefore, implementing this
	//bus sense feature is optional.  This firmware can be made to use this bus sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the
	//HardwareProfile.h file.    
    //	#if defined(USE_USB_BUS_SENSE_IO)
    //	tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h
    //	#endif
    
	//If the host PC sends a GetStatus (device) request, the firmware must respond	and let the host know if the USB peripheral device is currently bus powered
	//or self powered.  See chapter 9 in the official USB specifications for details regarding this request.  If the peripheral device is capable of being both
	//self and bus powered, it should not return a hard coded value for this request.  Instead, firmware should check if it is currently self or bus powered, and
	//respond accordingly.  If the hardware has been configured like demonstrated on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the
	//currently selected power source.  On the PICDEM FS USB Demo Board, "RA2" is used for	this purpose.  If using this feature, make sure "USE_SELF_POWER_SENSE_IO"
	//has been defined in HardwareProfile.h, and that an appropriate I/O pin has been mapped to it in HardwareProfile.h.
    //	#if defined(USE_SELF_POWER_SENSE_IO)
    //	tris_self_power = INPUT_PIN;	// See HardwareProfile.h
    //	#endif
    
    
    //Enable the USB port now - we will check to see if Vbus is  powered at the end of init and disable it if not.
    //USBDeviceInit();	//usb_device.c.  Initializes USB module SFRs and firmware variables to known states.

	

	//------------------------
	//----- SETUP TIMERS -----
	//------------------------
	//(INCLUDE THE USAGE OF ALL TIMERS HERE EVEN IF NOT SETUP HERE SO THIS IS THE ONE POINT OF
	//REFERENCE TO KNOW WHICH TIMERS ARE IN USE AND FOR WHAT).

	//----- SETUP TIMER 1 -----
	//Used for: Available
	//OpenTimer1((T1_ON | T1_IDLE_CON | T1_GATE_OFF | T1_PS_1_4 | T1_SOURCE_INT), 20000);

	//----- SETUP TIMER 2 -----
	//Used for: 
	//OpenTimer2((T2_ON | T2_IDLE_CON | T2_GATE_OFF | T2_PS_1_1 | T2_SOURCE_INT), 0xffff);		//0xffff = 305Hz

	//----- SETUP TIMER 3 -----
	//Used for: 
	//OpenTimer3((T3_ON | T3_IDLE_CON | T3_GATE_OFF | T3_PS_1_1 | T3_SOURCE_INT), PIEZO_TIMER_PERIOD);

	//----- SETUP TIMER 4 -----
	//Used for: 
	//OpenTimer4((T4_ON | T4_IDLE_CON | T4_GATE_OFF | T4_PS_1_1 | T4_SOURCE_INT), 20000);

	//----- SETUP TIMER 5 -----
	//Used for: Heartbeat
	OpenTimer5((T5_ON | T5_IDLE_CON | T5_GATE_OFF | T5_PS_1_1 | T5_SOURCE_INT), 40000);		//1mS with 80MHz osc and PB_DIV_2
	ConfigIntTimer5(T5_INT_ON | T5_INT_PRIOR_7);											//1=lowest priority to 7=highest priority.  ISR function must specify same value



	//---------------------------------
	//----- SETUP EVAL BOARD CPLD -----
	//---------------------------------
	//Graphics bus width = 16
	mPORTGSetPinsDigitalOut(BIT_14);
	mPORTGSetBits(BIT_14);

	//SPI source select = SPI3 (not used)
	mPORTGSetPinsDigitalOut(BIT_12);
	mPORTGClearBits(BIT_12);
	
	//SPI peripheral destination select = Expansion Slot (not used)
	mPORTASetPinsDigitalOut(BIT_7 | BIT_6);
	mPORTASetBits(BIT_7);
	mPORTAClearBits(BIT_6);


	//--------------------------------------
    //----- PARALLEL MASTER PORT SETUP -----
	//--------------------------------------
    PMMODE = 0;
    PMAEN = 0;
    PMCON = 0;
    PMMODE = 0x0610;
    PMCONbits.PTRDEN = 1;                   //Enable RD line
    PMCONbits.PTWREN = 1;                   //Enable WR line
    PMCONbits.PMPEN = 1;                    //Enable PMP


	//------------------------------
	//----- INITIALISE DISPLAY -----
	//------------------------------
	display_initialise();


	display_test();

	//LOAD OUR GLOBAL HTML STYLES FILE READY FOR DISPLAY HTML PAGES
	BYTE dummy_styles_count;
	DWORD file_size;
	if (display_html_setup_read_file(global_css, 0, &file_size))
	{
		dummy_styles_count = 0;
		display_html_read_styles(&file_size, &dummy_styles_count, 1);			//1 = this is global styles file
	}

}
Esempio n. 4
0
/*-------------------------------------------------------------------------------------------------------------------------------------------
 * main function
 *-------------------------------------------------------------------------------------------------------------------------------------------
 */
int
main ()
{
    static uint_fast8_t     last_ldr_value = 0xFF;
    struct tm               tm;
    LISTENER_DATA           lis;
    ESP8266_INFO *          esp8266_infop;
    uint_fast8_t            esp8266_is_up = 0;
    uint_fast8_t            code;

#if SAVE_RAM == 0
    IRMP_DATA               irmp_data;
    uint32_t                stop_time;
    uint_fast8_t            cmd;
#endif
    uint_fast8_t            status_led_cnt              = 0;
    uint_fast8_t            display_flag                = DISPLAY_FLAG_UPDATE_ALL;
    uint_fast8_t            show_temperature            = 0;
    uint_fast8_t            time_changed                = 0;
    uint_fast8_t            power_is_on                 = 1;
    uint_fast8_t            night_power_is_on           = 1;
    uint_fast8_t            ldr_value;
    uint_fast8_t            ap_mode = 0;

    SystemInit ();
    SystemCoreClockUpdate();                                                // needed for Nucleo board

#if defined (STM32F103)                                                     // disable JTAG to get back PB3, PB4, PA13, PA14, PA15
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);                    // turn on clock for the alternate function register
    GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);                // disable the JTAG, enable the SWJ interface
#endif

    log_init ();                                                            // initilize logger on uart

#if SAVE_RAM == 0
    irmp_init ();                                                           // initialize IRMP
#endif
    timer2_init ();                                                         // initialize timer2 for IRMP, DCF77, EEPROM etc.
    delay_init (DELAY_RESOLUTION_1_US);                                     // initialize delay functions with granularity of 1 us
    board_led_init ();                                                      // initialize GPIO for green LED on disco or nucleo board
    button_init ();                                                         // initialize GPIO for user button on disco or nucleo board
    rtc_init ();                                                            // initialize I2C RTC
    eeprom_init ();                                                         // initialize I2C EEPROM

    if (button_pressed ())                                                  // set ESP8266 into flash mode
    {
        board_led_on ();
        esp8266_flash ();
    }

    log_msg ("\r\nWelcome to WordClock Logger!");
    log_msg ("----------------------------");
    log_str ("Version: ");
    log_msg (VERSION);

    if (rtc_is_up)
    {
        log_msg ("rtc is online");
    }
    else
    {
        log_msg ("rtc is offline");
    }

    if (eeprom_is_up)
    {
        log_msg ("eeprom is online");
        read_version_from_eeprom ();
        log_printf ("current eeprom version: 0x%08x\r\n", eeprom_version);

        if ((eeprom_version & 0xFF0000FF) == 0x00000000)
        {                                                               // Upper and Lower Byte must be 0x00
            if (eeprom_version >= EEPROM_VERSION_1_5_0)
            {
#if SAVE_RAM == 0
                log_msg ("reading ir codes from eeprom");
                remote_ir_read_codes_from_eeprom ();
#endif
                log_msg ("reading display configuration from eeprom");
                display_read_config_from_eeprom ();

                log_msg ("reading timeserver data from eeprom");
                timeserver_read_data_from_eeprom ();
            }

            if (eeprom_version >= EEPROM_VERSION_1_7_0)
            {
                log_msg ("reading night timers from eeprom");
                night_read_data_from_eeprom ();
            }
        }
    }
    else
    {
        log_msg ("eeprom is offline");
    }

    ldr_init ();                                                            // initialize LDR (ADC)
    display_init ();                                                        // initialize display

    dcf77_init ();                                                          // initialize DCF77

    night_init ();                                                          // initialize night time routines

    short_isr = 1;
    temp_init ();                                                           // initialize DS18xx
    short_isr = 0;

    display_reset_led_states ();
    display_mode                = display_get_display_mode ();
    animation_mode              = display_get_animation_mode ();
    auto_brightness             = display_get_automatic_brightness_control ();

    if (eeprom_is_up)
    {
        if (eeprom_version != EEPROM_VERSION)
        {
            log_printf ("updating EEPROM to version 0x%08x\r\n", EEPROM_VERSION);

            eeprom_version = EEPROM_VERSION;
            write_version_to_eeprom ();
#if SAVE_RAM == 0
            remote_ir_write_codes_to_eeprom ();
#endif
            display_write_config_to_eeprom ();
            timeserver_write_data_to_eeprom ();
            night_write_data_to_eeprom ();
            eeprom_version = EEPROM_VERSION;
        }
    }

    ds3231_flag = 1;

#if SAVE_RAM == 0
    stop_time = uptime + 3;                                                 // wait 3 seconds for IR signal...
    display_set_status_led (1, 1, 1);                                       // show white status LED

    while (uptime < stop_time)
    {
        if (irmp_get_data (&irmp_data))                                     // got IR signal?
        {
            display_set_status_led (1, 0, 0);                               // yes, show red status LED
            delay_sec (1);                                                  // and wait 1 second
            (void) irmp_get_data (&irmp_data);                              // flush input of IRMP now
            display_set_status_led (0, 0, 0);                               // and switch status LED off

            log_msg ("calling IR learn function");
            if (remote_ir_learn ())                                         // learn IR commands
            {
                remote_ir_write_codes_to_eeprom ();                         // if successful, save them in EEPROM
            }
            break;                                                          // and break the loop
        }
    }
#endif

    display_set_status_led (0, 0, 0);                                       // switch off status LED

    esp8266_init ();
    esp8266_infop = esp8266_get_info ();

    while (1)
    {
        if (! ap_mode && esp8266_is_up && button_pressed ())                // if user pressed user button, set ESP8266 to AP mode
        {
            ap_mode = 1;
            log_msg ("user button pressed: configuring esp8266 as access point");
            esp8266_is_online = 0;
            esp8266_infop->is_online = 0;
            esp8266_infop->ipaddress[0] = '\0';
            esp8266_accesspoint ("wordclock", "1234567890");
        }


        if (status_led_cnt)
        {
            status_led_cnt--;

            if (! status_led_cnt)
            {
                display_set_status_led (0, 0, 0);
            }
        }

        if ((code = listener (&lis)) != 0)
        {
            display_set_status_led (1, 0, 0);                               // got net command, light red status LED
            status_led_cnt = STATUS_LED_FLASH_TIME;

            switch (code)
            {
                case LISTENER_SET_COLOR_CODE:                               // set color
                {
                    display_set_colors (&(lis.rgb));
                    log_printf ("command: set colors to %d %d %d\r\n", lis.rgb.red, lis.rgb.green, lis.rgb.blue);
                    break;
                }

                case LISTENER_POWER_CODE:                                   // power on/off
                {
                    if (power_is_on != lis.power)
                    {
                        power_is_on = lis.power;
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_msg ("command: set power");
                    }
                    break;
                }

                case LISTENER_DISPLAY_MODE_CODE:                            // set display mode
                {
                    if (display_mode != lis.mode)
                    {
                        display_mode = display_set_display_mode (lis.mode);
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_printf ("command: set display mode to %d\r\n", display_mode);
                    }
                    break;
                }

                case LISTENER_ANIMATION_MODE_CODE:                          // set animation mode
                {
                    if (animation_mode != lis.mode)
                    {
                        animation_mode = display_set_animation_mode (lis.mode);
                        animation_flag = 0;
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_printf ("command: set animation mode to %d\r\n", animation_flag);
                    }
                    break;
                }

                case LISTENER_DISPLAY_TEMPERATURE_CODE:                     // set animation mode
                {
                    show_temperature = 1;
                    log_msg ("command: show temperature");
                    break;
                }

                case LISTENER_SET_BRIGHTNESS_CODE:                          // set brightness
                {
                    if (auto_brightness)
                    {
                        auto_brightness = 0;
                        last_ldr_value = 0xFF;
                        display_set_automatic_brightness_control (auto_brightness);
                    }
                    display_set_brightness (lis.brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                    log_printf ("command: set brightness to %d, disable autmomatic brightness control per LDR\r\n", lis.brightness);
                    break;
                }

                case LISTENER_SET_AUTOMATIC_BRIHGHTNESS_CODE:               // automatic brightness control on/off
                {
                    if (lis.automatic_brightness_control)
                    {
                        auto_brightness = 1;
                        log_msg ("command: enable automatic brightness control");
                    }
                    else
                    {
                        auto_brightness = 0;
                        log_msg ("command: disable automatic brightness control");
                    }

                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    break;
                }

                case LISTENER_TEST_DISPLAY_CODE:                            // test display
                {
                    log_msg ("command: start display test");
                    display_test ();
                    break;
                }

                case LISTENER_SET_DATE_TIME_CODE:                           // set date/time
                {
                    if (rtc_is_up)
                    {
                        rtc_set_date_time (&(lis.tm));
                    }

                    if (hour != (uint_fast8_t) lis.tm.tm_hour || minute != (uint_fast8_t) lis.tm.tm_min)
                    {
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                    }

                    wday   = lis.tm.tm_wday;
                    hour   = lis.tm.tm_hour;
                    minute = lis.tm.tm_min;
                    second = lis.tm.tm_sec;

                    log_printf ("command: set time to %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                                wdays_en[lis.tm.tm_wday], lis.tm.tm_year + 1900, lis.tm.tm_mon + 1, lis.tm.tm_mday,
                                lis.tm.tm_hour, lis.tm.tm_min, lis.tm.tm_sec);
                    break;
                }

                case LISTENER_GET_NET_TIME_CODE:                            // get net time
                {
                    net_time_flag = 1;
                    log_msg ("command: start net time request");
                    break;
                }

                case LISTENER_IR_LEARN_CODE:                                // IR learn
                {
#if SAVE_RAM == 0
                    log_msg ("command: learn IR codes");

                    if (remote_ir_learn ())
                    {
                        remote_ir_write_codes_to_eeprom ();
                    }
#endif
                    break;
                }

                case LISTENER_SAVE_DISPLAY_CONFIGURATION:                   // save display configuration
                {
                    display_write_config_to_eeprom ();
                    log_msg ("command: save display settings");
                    break;
                }
            }
        }

        if (auto_brightness && ldr_poll_brightness (&ldr_value))
        {
            if (ldr_value + 1 < last_ldr_value || ldr_value > last_ldr_value + 1)           // difference greater than 2
            {
                log_printf ("ldr: old brightnes: %d new brightness: %d\r\n", last_ldr_value, ldr_value);
                last_ldr_value = ldr_value;
                display_set_brightness (ldr_value);
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
            }
        }

        if (!esp8266_is_up)                                                 // esp8266 up yet?
        {
            if (esp8266_infop->is_up)
            {
                esp8266_is_up = 1;
                log_msg ("esp8266 now up");
            }
        }
        else
        {                                                                   // esp8266 is up...
            if (! esp8266_is_online)                                        // but not online yet...
            {
                if (esp8266_infop->is_online)                               // now online?
                {
                    char buf[32];
                    esp8266_is_online = 1;

                    log_msg ("esp8266 now online");
                    sprintf (buf, "  IP %s", esp8266_infop->ipaddress);
                    display_banner (buf);
                    display_flag = DISPLAY_FLAG_UPDATE_ALL;

                    net_time_flag = 1;
                }
            }
        }

        if (dcf77_time(&tm))
        {
            display_set_status_led (1, 1, 0);                       // got DCF77 time, light yellow = green + red LED

            status_led_cnt = 50;

            if (rtc_is_up)
            {
                rtc_set_date_time (&tm);
            }

            if (hour != (uint_fast8_t) tm.tm_hour || minute != (uint_fast8_t) tm.tm_min)
            {
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
            }

            wday        = tm.tm_wday;
            hour        = tm.tm_hour;
            minute      = tm.tm_min;
            second      = tm.tm_sec;

            log_printf ("dcf77: %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                         wdays_en[tm.tm_wday], tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
        }

        if (ds3231_flag)
        {
            if (rtc_is_up && rtc_get_date_time (&tm))
            {
                if (hour != (uint_fast8_t) tm.tm_hour || minute != (uint_fast8_t) tm.tm_min)
                {
                    display_flag = DISPLAY_FLAG_UPDATE_ALL;
                }

                wday        = tm.tm_wday;
                hour        = tm.tm_hour;
                minute      = tm.tm_min;
                second      = tm.tm_sec;

                log_printf ("read rtc: %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                             wdays_en[tm.tm_wday], tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
            }

            ds3231_flag = 0;
        }

        if (auto_brightness && ldr_conversion_flag)
        {
            ldr_start_conversion ();
            ldr_conversion_flag = 0;
        }

        if (net_time_flag)
        {
            if (esp8266_infop->is_online)
            {
                display_set_status_led (0, 0, 1);                       // light blue status LED
                status_led_cnt = STATUS_LED_FLASH_TIME;
                timeserver_start_timeserver_request ();                 // start a timeserver request, answer follows...
            }

            net_time_flag = 0;
            net_time_countdown = 3800;                                  // next net time after 3800 sec
        }

        if (show_time_flag)                                             // set every full minute
        {
#if WCLOCK24H == 1
            display_flag = DISPLAY_FLAG_UPDATE_ALL;
#else
            if (minute % 5)
            {
                display_flag = DISPLAY_FLAG_UPDATE_MINUTES;             // only update minute LEDs
            }
            else
            {
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
            }
#endif
            show_time_flag = 0;
        }

        if (power_is_on == night_power_is_on && night_check_night_times (power_is_on, wday, hour * 60 + minute))
        {
            power_is_on         = ! power_is_on;
            night_power_is_on   = ! night_power_is_on;
            display_flag        = DISPLAY_FLAG_UPDATE_ALL;
            log_printf ("Found Timer: %s at %02d:%02d\r\n", power_is_on ? "on" : "off", hour, minute);
        }

        if (show_temperature)
        {
            uint_fast8_t temperature_index;

            show_temperature = 0;

            if (ds18xx_is_up)
            {
                short_isr = 1;
                temperature_index = temp_read_temp_index ();
                short_isr = 0;
                log_printf ("got temperature from DS18xxx: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
            }
            else if (rtc_is_up)
            {
                temperature_index = rtc_get_temperature_index ();
                log_printf ("got temperature from RTC: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
            }
            else
            {
                temperature_index = 0xFF;
                log_msg ("no temperature available");
            }

            if (temperature_index != 0xFF)
            {
                display_temperature (power_is_on, temperature_index);

#if WCLOCK24H == 1                                                          // WC24H shows temperature with animation, WC12H rolls itself
                uint32_t    stop_time;

                stop_time = uptime + 5;

                while (uptime < stop_time)
                {
                    if (animation_flag)
                    {
                        animation_flag = 0;
                        display_animation ();
                    }
                }
#endif
                display_flag = DISPLAY_FLAG_UPDATE_ALL;                     // force update
            }
        }

        if (display_flag)                                                   // refresh display (time/mode changed)
        {
            log_msg ("update display");

#if WCLOCK24H == 1
            if (display_mode == MODES_COUNT - 1)                            // temperature
            {
                uint_fast8_t temperature_index;

                if (ds18xx_is_up)
                {
                    short_isr = 1;
                    temperature_index = temp_read_temp_index ();
                    short_isr = 0;
                    log_printf ("got temperature from DS18xxx: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
                }
                else if (rtc_is_up)
                {
                    temperature_index = rtc_get_temperature_index ();
                    log_printf ("got temperature from RTC: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
                }
                else
                {
                    temperature_index = 0x00;
                    log_msg ("no temperature available");
                }

                display_clock (power_is_on, 0, temperature_index - 20, display_flag);    // show new time
            }
            else
            {
                display_clock (power_is_on, hour, minute, display_flag);    // show new time
            }
#else
            display_clock (power_is_on, hour, minute, display_flag);        // show new time
#endif
            display_flag = DISPLAY_FLAG_NONE;
        }

        if (animation_flag)
        {
            animation_flag = 0;
            display_animation ();
        }

        if (dcf77_flag)
        {
            dcf77_flag = 0;
            dcf77_tick ();
        }

#if SAVE_RAM == 0
        cmd = remote_ir_get_cmd ();                                         // get IR command

        if (cmd != REMOTE_IR_CMD_INVALID)                                   // got IR command, light green LED
        {
            display_set_status_led (1, 0, 0);
            status_led_cnt = STATUS_LED_FLASH_TIME;
        }

        if (cmd != REMOTE_IR_CMD_INVALID)                                   // if command valid, log command code
        {
            switch (cmd)
            {
                case REMOTE_IR_CMD_POWER:                         log_msg ("IRMP: POWER key");                  break;
                case REMOTE_IR_CMD_OK:                            log_msg ("IRMP: OK key");                     break;
                case REMOTE_IR_CMD_DECREMENT_DISPLAY_MODE:        log_msg ("IRMP: decrement display mode");     break;
                case REMOTE_IR_CMD_INCREMENT_DISPLAY_MODE:        log_msg ("IRMP: increment display mode");     break;
                case REMOTE_IR_CMD_DECREMENT_ANIMATION_MODE:      log_msg ("IRMP: decrement animation mode");   break;
                case REMOTE_IR_CMD_INCREMENT_ANIMATION_MODE:      log_msg ("IRMP: increment animation mode");   break;
                case REMOTE_IR_CMD_DECREMENT_HOUR:                log_msg ("IRMP: decrement hour");             break;
                case REMOTE_IR_CMD_INCREMENT_HOUR:                log_msg ("IRMP: increment hour");             break;
                case REMOTE_IR_CMD_DECREMENT_MINUTE:              log_msg ("IRMP: decrement minute");           break;
                case REMOTE_IR_CMD_INCREMENT_MINUTE:              log_msg ("IRMP: increment minute");           break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_RED:      log_msg ("IRMP: decrement red brightness");   break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_RED:      log_msg ("IRMP: increment red brightness");   break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_GREEN:    log_msg ("IRMP: decrement green brightness"); break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_GREEN:    log_msg ("IRMP: increment green brightness"); break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_BLUE:     log_msg ("IRMP: decrement blue brightness");  break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_BLUE:     log_msg ("IRMP: increment blue brightness");  break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS:          log_msg ("IRMP: decrement brightness");       break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS:          log_msg ("IRMP: increment brightness");       break;
                case REMOTE_IR_CMD_GET_TEMPERATURE:               log_msg ("IRMP: get temperature");            break;
            }
        }

        switch (cmd)
        {
            case REMOTE_IR_CMD_POWER:
            {
                power_is_on = ! power_is_on;

                display_flag        = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_OK:
            {
                display_write_config_to_eeprom ();
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_DISPLAY_MODE:                      // decrement display mode
            {
                display_mode = display_decrement_display_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_DISPLAY_MODE:                      // increment display mode
            {
                display_mode = display_increment_display_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_ANIMATION_MODE:                    // decrement display mode
            {
                animation_mode = display_decrement_animation_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_ANIMATION_MODE:                    // increment display mode
            {
                animation_mode = display_increment_animation_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_HOUR:                              // decrement hour
            {
                if (hour > 0)
                {
                    hour--;
                }
                else
                {
                    hour = 23;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_HOUR:                              // increment hour
            {
                if (hour < 23)
                {
                     hour++;
                }
                else
                {
                    hour =  0;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_MINUTE:                            // decrement minute
            {
                if (minute > 0)
                {
                    minute--;
                }
                else
                {
                    minute = 59;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_MINUTE:                            // increment minute
            {
                if (minute < 59)
                {
                    minute++;
                }
                else
                {
                    minute = 0;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_RED:                    // decrement red brightness
            {
                display_decrement_color_red ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_RED:                    // increment red brightness
            {
                display_increment_color_red ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_GREEN:                  // decrement green brightness
            {
                display_decrement_color_green ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_GREEN:                  // increment green brightness
            {
                display_increment_color_green ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_BLUE:                   // decrement blue brightness
            {
                display_decrement_color_blue ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_BLUE:                   // increment blue brightness
            {
                display_increment_color_blue ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_AUTO_BRIGHTNESS_CONTROL:                     // toggle auto brightness
            {
                auto_brightness = ! auto_brightness;
                last_ldr_value = 0xFF;
                display_set_automatic_brightness_control (auto_brightness);
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS:                        // decrement brightness
            {
                if (auto_brightness)
                {
                    auto_brightness = 0;
                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                }

                display_decrement_brightness ();
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS:                        // increment brightness
            {
                if (auto_brightness)
                {
                    auto_brightness = 0;
                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                }

                display_increment_brightness ();
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_GET_TEMPERATURE:                             // get temperature
            {
                show_temperature    = 1;
                break;
            }

            default:
            {
                break;
            }
        }
#endif // SAVE_RAM == 0

        if (time_changed)
        {
            if (rtc_is_up)
            {
                tm.tm_hour = hour;
                tm.tm_min  = minute;
                tm.tm_sec  = second;
                rtc_set_date_time (&tm);
            }

            time_changed = 0;
        }
    }

    return 0;
}
/**
 * Launches a test of the OLED screen
 */
void cmd_displaytest(char *line) {
  display_test();
}
Esempio n. 6
0
int main (void)
{	
	int tmp,i,res;
	CLKPR = 0x80;  CLKPR = 0x00;  // Clock prescaler Reset

/*-----------------------------------------------------------------*
 *------------------------- Gear buttoms setup---------------------*
 *-----------------------------------------------------------------*/
	DDRC&=~(1<<PC7); // Neutral
	PORTC |= (1<<PC7); // Neutral pull-up
	DDRE&=~(1<<PE6); // Knap1 
	DDRE&=~(1<<PE7); // Knap2

	/* Buttoms interrupt */
	EICRB |= (1<<ISC71|1<<ISC70|1<<ISC61|1<<ISC60); /* Rising edge */
	EIMSK |= (1<<INT7 | 1<<INT6);


	uint8_t test_rx[8];

	int8_t data;
	char streng[10];

	// Recieve buffer
	st_cmd_t msg;

//  Init CAN, UART, I/O
	init();
	uartinit();
	sendtekst("UART initialized\n\r");
	TWI_init();
	sendtekst("TWI initialized\n\r");

	sei();		/* Interrupt enable */
	sendtekst("Interrupt enabled\n\r");
/*-----------------------------------------------------------------*
 *----------------------------Display setup -----------------------*
 *-----------------------------------------------------------------*/

	/* Set blink rates */
	set_blink_rate(LED0_7_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(LED0_7_ADDR, LED_BLINK2, 0, RPM_LED_DUTYCYCLE*2.56);

	set_blink_rate(LED8_15_ADDR, LED_BLINK1, (1.0/RPM16_RATE)*252, RPM16_DUTYCYCLE*2.56);
	set_blink_rate(LED8_15_ADDR, LED_BLINK2, 0, RPM_LED_DUTYCYCLE*2.56);

	set_blink_rate(SEG_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(SEG_ADDR, LED_BLINK2, 0, SEG_DUTYCYCLE*2.56);

	set_blink_rate(LED_BUTTONS_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(LED_BUTTONS_ADDR, LED_BLINK2, 0, SEG_DUTYCYCLE*2.56);


/*-----------------------------------------------------------------*
 *----------------------------CAN interrupt setup -----------------*
 *-----------------------------------------------------------------*/
	Can_sei();		/* Enable general can interrupt */
	Can_set_tx_int();	/* Enable can tx interrupt */
	Can_set_rx_int();	/* Enable can rx interrupt */

	/*
	 *	Kode til hurtig test af can 
	 */
	sendtekst("Config 3 mailboxes for rpm_msgid...\n\r");
	msg.id.std = rpm_msgid;
	msg.dlc = 8;
	res = can_config_rx_mailbox(&msg, 3);
	if (res == CAN_CMD_ACCEPTED) {
		sendtekst("SUCCESS\n\r");
	} else {
		sendtekst("FAIL\n\r");
	}	
    	// --- Init variables

	/* Init user led 0 & 1 */
	DDRB |= (1<<PB6 | 1<<PB5);
	PORTB |= (1<<PB6 | 1<<PB5);

	sendtekst("Beep\n\r");
	display_test();
    
    params.GearEst = 0;

	char dataout[] = {gear,0};

	while (1) {
		_delay_ms(20);

		/* Display selected parameter */
		if (mode == RPM_MODE) {		
			set_rpm(params.rpm, LED_ON);
		} else if (mode == VOLTAGE_MODE) {
			set_voltage(params.batteryV, LED_ON);
		} else if (mode == WATER_TEMP_MODE) {
			set_water_temp(params.waterTemp, LED_ON);
		}

		// Geat buttons to CAN
		dataout[1] = 0;
		/* Format buttom states for sending */ 
		dataout[1] |= (params.GearButDown*GEARDOWNBUT | 
					GEARUPBUT*params.GearButUp | 
					params.GearButNeutral*GEARNEUBUT);

		/* Send buttom states */
		if(dataout[1] != 0) {
			// Hack, sender gearskiftesignal et par gange, sådan at det går igennem
			// Symptombehandling, sygdommen skal kureres...
			if (dataout[1] & (GEARDOWNBUT) == GEARDOWNBUT)
				indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
			if (dataout[1] & (GEARUPBUT) == GEARUPBUT)
				indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
		

			set_leds(LED_BUTTONS_ADDR, indi_leds_state);
			for(j=0;j<1;j++){
				can_send_non_blocking(gear_msgid, dataout, 2);
				_delay_ms(5);
			}
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_2);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1);
			set_leds(LED_BUTTONS_ADDR, indi_leds_state);

		}
		/* Clear buttom states */
		params.GearButDown = 0;
		params.GearButUp = 0;
		params.GearButNeutral = 0;

		/* Display bottons code */
		buttons_state = get_buttons(LED_BUTTONS_ADDR) & (BUTTON1 | BUTTON2);
		if (buttons_state == 2) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_2);
			mode = VOLTAGE_MODE;
		} else if (buttons_state == 1) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_2);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1);
			mode = WATER_TEMP_MODE;
		} else if (buttons_state == 0) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1 | LED_BLINK2<<LED_BUTTON_2);
		} else {
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1 | LED_BLINK2<<LED_BUTTON_2);
			mode = RPM_MODE;
		}

		/* Indicator for water temp */
		if (params.waterTemp <= WATER_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI1);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI4);
		} else if (params.waterTemp > WATER_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI4);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI1);
		}

		/* Indicator for batt ok */
		if (params.batteryV <= VOLTAGE_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI2);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI5);
		} else if (params.batteryV > VOLTAGE_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI5);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI2);
		}
		
		/* Indicator for oil pressure ok */
		if (params.oilPressure <= OILPRESS_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI3);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI6);
		} else if (params.oilPressure > OILPRESS_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI6);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI3);
		}

		/* Indicator for Gear */
		if (params.GearNeutral < 0) {
			SEG_N(LED_ON);
		} else {
			if (params.GearEst > 6) {
				SEG_OFF();
			} else {
				switch (params.GearEst) {
                    case 0:
						SEG_N(LED_ON);
						break;
					case 1:
						SEG_1(LED_ON);
						break;
					case 2:
						SEG_2(LED_ON);
						break;
					case 3:
						SEG_3(LED_ON);
						break;
					case 4:
						SEG_4(LED_ON);
						break;
					case 5:
						SEG_5(LED_ON);
						break;
					case 6:
						SEG_6(LED_ON);
						break;
					default:
						break;

				}
			}
		}


/*		if (params.GearNeutral == 0) {
			SEG_OFF();
		} else if (params.GearNeutral > 0) {
			SEG_N(LED_BLINK2);
		}
*/

		/* Set indicator leds */
		set_leds(LED_BUTTONS_ADDR, indi_leds_state);
			
/*		itoa(params.batteryV, streng, 10);*/
/*		sendtekst(streng);*/
/*		sendtekst("\n\r");		*/
		PORTB ^= (1<<PB6);
	}
	return 0;
}