Ejemplo n.º 1
0
/* C128-specific initialization.  */
int machine_specific_init(void)
{
    int delay;

    c128_log = log_open("C128");

    if (mem_load() < 0) {
        return -1;
    }

    event_init();

    if (z80mem_load() < 0) {
        return -1;
    }

    /* Setup trap handling.  */
    traps_init();

    /* Initialize serial traps.  */
    if (serial_init(c128_serial_traps) < 0) {
        return -1;
    }

    serial_trap_init(0xa4);
    serial_iec_bus_init();

    if (!video_disabled_mode) {
        joystick_init();
    }

    gfxoutput_init();

    /* initialize RS232 handler */
    rs232drv_init();
    c64_rsuser_init();

    /* initialize print devices */
    printer_init();

    /* Initialize the tape emulation.  */
    machine_tape_init_c128();

    /* Initialize the datasette emulation.  */
    datasette_init();

    /* Fire up the hardware-level drive emulation.  */
    drive_init();

    disk_image_init();

    /* Initialize autostart. FIXME: at least 0xa26 is only for 40 cols */
    resources_get_int("AutostartDelay", &delay);
    if (delay == 0) {
        delay = 3; /* default */
    }
    autostart_init((CLOCK)(delay * C128_PAL_RFSH_PER_SEC * C128_PAL_CYCLES_PER_RFSH), 1, 0xa27, 0xe0, 0xec, 0xee);

#ifdef USE_BEOS_UI
    /* Pre-init C128-specific parts of the menus before vdc_init() and
       vicii_init() create canvas windows with menubars at the top. This
       could also be used by other ports, e.g. GTK+...  */
    c128ui_init_early();
#endif

    if (vdc_init() == NULL) {
        return -1;
    }

    if (vicii_init(VICII_EXTENDED) == NULL) {
        return -1;
    }

    cia1_init(machine_context.cia1);
    cia2_init(machine_context.cia2);

#ifndef COMMON_KBD
    /* Initialize the keyboard.  */
    if (c128_kbd_init() < 0) {
        return -1;
    }
#endif

    c64keyboard_init();

    c128_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec, machine_timing.cycles_per_sec);

    /* Initialize native sound chip */
    sid_sound_chip_init();

    /* Initialize cartridge based sound chips */
    cartridge_sound_chip_init();

    drive_sound_init();
    video_sound_init();

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    /* Initialize keyboard buffer.  */
    kbdbuf_init(842, 208, 10, (CLOCK)(machine_timing.rfsh_per_sec * machine_timing.cycles_per_rfsh));

    /* Initialize the C128-specific I/O */
    c128io_init();

    /* Initialize the C128-specific part of the UI.  */
    c128ui_init();

#ifdef HAVE_MOUSE
    /* Initialize mouse support (if present).  */
    mouse_init();

#ifdef HAVE_LIGHTPEN
    /* Initialize lightpen support and register VICII/VDC callbacks */
    lightpen_init();
    lightpen_register_timing_callback(vicii_lightpen_timing, 1);
    lightpen_register_timing_callback(vdc_lightpen_timing, 0);
    lightpen_register_trigger_callback(c128_trigger_light_pen);
#endif
#endif

    c64iec_init();
    c128fastiec_init();

    cartridge_init();

    mmu_init();

    machine_drive_stub();

#if defined (USE_XF86_EXTENSIONS) && (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline
           use VICII as default */
        int fs;

        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_get_int("40/80ColumnKey", &fs);
            if (fs == 1) {
                resources_set_int("VICIIFullscreen", 1);
            } else {
                resources_set_int("VDCFullscreen", 1);
            }
        }
    }
#endif

    return 0;
}
Ejemplo n.º 2
0
Archivo: main.c Proyecto: MrSurly/grbl
int main(void)
{
  // Initialize system upon power-up.
  serial_init();   // Setup serial baud rate and interrupts
  settings_init(); // Load Grbl settings from EEPROM
  stepper_init();  // Configure stepper pins and interrupt timers
  system_init();   // Configure pinout pins and pin-change interrupt

  memset(sys_position,0,sizeof(sys_position)); // Clear machine position.
  sei(); // Enable interrupts

  // Initialize system state.
  #ifdef FORCE_INITIALIZATION_ALARM
    // Force Grbl into an ALARM state upon a power-cycle or hard reset.
    sys.state = STATE_ALARM;
  #else
    sys.state = STATE_IDLE;
  #endif
  
  // Check for power-up and set system alarm if homing is enabled to force homing cycle
  // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
  // startup scripts, but allows access to settings and internal commands. Only a homing
  // cycle '$H' or kill alarm locks '$X' will disable the alarm.
  // NOTE: The startup script will run after successful completion of the homing cycle, but
  // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
  // things uncontrollably. Very bad.
  #ifdef HOMING_INIT_LOCK
    if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
  #endif

  // Grbl initialization loop upon power-up or a system abort. For the latter, all processes
  // will return to this loop to be cleanly re-initialized.
  for(;;) {

    // Reset system variables.
    uint8_t prior_state = sys.state;
    memset(&sys, 0, sizeof(system_t)); // Clear system struct variable.
    sys.state = prior_state;
    sys.f_override = DEFAULT_FEED_OVERRIDE;  // Set to 100%
    sys.r_override = DEFAULT_RAPID_OVERRIDE; // Set to 100%
    sys.spindle_speed_ovr = DEFAULT_SPINDLE_SPEED_OVERRIDE; // Set to 100%
		memset(sys_probe_position,0,sizeof(sys_probe_position)); // Clear probe position.
    sys_probe_state = 0;
    sys_rt_exec_state = 0;
    sys_rt_exec_alarm = 0;
    sys_rt_exec_motion_override = 0;
    sys_rt_exec_accessory_override = 0;

    // Reset Grbl primary systems.
    serial_reset_read_buffer(); // Clear serial read buffer
    gc_init(); // Set g-code parser to default state
    spindle_init();
    coolant_init();
    limits_init();
    probe_init();
    plan_reset(); // Clear block buffer and planner variables
    st_reset(); // Clear stepper subsystem variables.

    // Sync cleared gcode and planner positions to current system position.
    plan_sync_position();
    gc_sync_position();

    // Print welcome message. Indicates an initialization has occured at power-up or with a reset.
    report_init_message();

    // Start Grbl main loop. Processes program inputs and executes them.
    protocol_main_loop();

  }
  return 0;   /* Never reached */
}
Ejemplo n.º 3
0
Archivo: main.c Proyecto: pienk/SiK
static void
hardware_init(void)
{
	__pdata uint16_t	i;

	// Disable the watchdog timer
	PCA0MD	&= ~0x40;

	// Select the internal oscillator, prescale by 1
	FLSCL	 =  0x40;
	OSCICN	 =  0x8F;
	CLKSEL	 =  0x00;

	// Configure the VDD brown out detector
	VDM0CN	 =  0x80;
	for (i = 0; i < 350; i++);	// Wait 100us for initialization
	RSTSRC	 =  0x06;		// enable brown out and missing clock reset sources

#ifdef _BOARD_RFD900A			// Redefine port skips to override bootloader defs
	P0SKIP  =  0xCF;                // P0 UART avail on XBAR
	P1SKIP  =  0xF8;                // P1 SPI1, CEX0 avail on XBAR 
	P2SKIP  =  0x01;                // P2 CEX3 avail on XBAR, rest GPIO
#endif

	// Configure crossbar for UART
	P0MDOUT	 =  0x10;		// UART Tx push-pull
	SFRPAGE	 =  CONFIG_PAGE;
	P0DRV	 =  0x10;		// UART TX
	SFRPAGE	 =  LEGACY_PAGE;
	XBR0	 =  0x01;		// UART enable

	// SPI1
#ifdef _BOARD_RFD900A
	XBR1	|= 0x44;	// enable SPI in 3-wire mode
	P1MDOUT	|= 0xF5;	// SCK1, MOSI1, MISO1 push-pull
	P2MDOUT	|= 0xFF;	// SCK1, MOSI1, MISO1 push-pull
#else
	XBR1	|= 0x40;	// enable SPI in 3-wire mode
	P1MDOUT	|= 0xF5;	// SCK1, MOSI1, MISO1 push-pull
#endif	
	SFRPAGE	 = CONFIG_PAGE;
	P1DRV	|= 0xF5;	// SPI signals use high-current mode, LEDs and PAEN High current drive
	P2DRV	|= 0xFF;	
	SFRPAGE	 = LEGACY_PAGE;
	SPI1CFG	 = 0x40;	// master mode
	SPI1CN	 = 0x00;	// 3 wire master mode
	SPI1CKR	 = 0x00;	// Initialise SPI prescaler to divide-by-2 (12.25MHz, technically out of spec)
	SPI1CN	|= 0x01;	// enable SPI
	NSS1	 = 1;		// set NSS high

	// Clear the radio interrupt state
	IE0	 = 0;

	// initialise timers
	timer_init();

	// UART - set the configured speed
	serial_init(param_get(PARAM_SERIAL_SPEED));

	// set all interrupts to the same priority level
	IP = 0;

	// global interrupt enable
	EA = 1;

	// Turn on the 'radio running' LED and turn off the bootloader LED
	LED_RADIO = LED_ON;
	LED_BOOTLOADER = LED_OFF;

	// ADC system initialise for temp sensor
	AD0EN = 1;	// Enable ADC0
	ADC0CF = 0xF9;  // Set amp0gn=1 (1:1)
	ADC0AC = 0x00;
	ADC0MX = 0x1B;	// Set ADC0MX to temp sensor
	REF0CN = 0x07;	// Define reference and enable temp sensor

#ifdef _BOARD_RFD900A
	// PCA0, CEX0 setup and enable.
	PCA0MD = 0x88;
	PCA0PWM = 0x00;
	PCA0CPH3 = 0x80;
	PCA0CPM3 = 0x42;
	PCA0CN = 0x40;
#endif
	XBR2	 =  0x40;		// Crossbar (GPIO) enable
}
Ejemplo n.º 4
0
int board_early_init_f (void)
{
	int index, len, i;
	int status;

#ifdef FPGA_DEBUG
	/* set up serial port with default baudrate */
	(void) get_clocks ();
	gd->baudrate = CONFIG_BAUDRATE;
	serial_init ();
	console_init_f ();
#endif

	/*
	 * Boot onboard FPGA
	 */
	status = fpga_boot ((unsigned char *) fpgadata, sizeof (fpgadata));
	if (status != 0) {
		/* booting FPGA failed */
#ifndef FPGA_DEBUG
		/* set up serial port with default baudrate */
		(void) get_clocks ();
		gd->baudrate = CONFIG_BAUDRATE;
		serial_init ();
		console_init_f ();
#endif
		printf ("\nFPGA: Booting failed ");
		switch (status) {
		case ERROR_FPGA_PRG_INIT_LOW:
			printf ("(Timeout: INIT not low after asserting PROGRAM*)\n ");
			break;
		case ERROR_FPGA_PRG_INIT_HIGH:
			printf ("(Timeout: INIT not high after deasserting PROGRAM*)\n ");
			break;
		case ERROR_FPGA_PRG_DONE:
			printf ("(Timeout: DONE not high after programming FPGA)\n ");
			break;
		}

		/* display infos on fpgaimage */
		index = 15;
		for (i = 0; i < 4; i++) {
			len = fpgadata[index];
			printf ("FPGA: %s\n", &(fpgadata[index + 1]));
			index += len + 3;
		}
		putc ('\n');
		/* delayed reboot */
		for (i = 20; i > 0; i--) {
			printf ("Rebooting in %2d seconds \r", i);
			for (index = 0; index < 1000; index++)
				udelay (1000);
		}
		putc ('\n');
		do_reset (NULL, 0, 0, NULL);
	}

	/*
	 * IRQ 0-15  405GP internally generated; active high; level sensitive
	 * IRQ 16    405GP internally generated; active low; level sensitive
	 * IRQ 17-24 RESERVED
	 * IRQ 25 (EXT IRQ 0) CAN0; active low; level sensitive
	 * IRQ 26 (EXT IRQ 1) DUART_A; active high; level sensitive
	 * IRQ 27 (EXT IRQ 2) DUART_B; active high; level sensitive
	 * IRQ 28 (EXT IRQ 3) unused; active low; level sensitive
	 * IRQ 29 (EXT IRQ 4) unused; active low; level sensitive
	 * IRQ 30 (EXT IRQ 5) unused; active low; level sensitive
	 * IRQ 31 (EXT IRQ 6) COMPACT FLASH; active high; level sensitive
	 */
	mtdcr (uicsr, 0xFFFFFFFF);	/* clear all ints */
	mtdcr (uicer, 0x00000000);	/* disable all ints */
	mtdcr (uiccr, 0x00000000);	/* set all to be non-critical */
	mtdcr (uicpr, 0xFFFFFFB1);	/* set int polarities */
	mtdcr (uictr, 0x10000000);	/* set int trigger levels */
	mtdcr (uicvcr, 0x00000001);	/* set vect base=0,INT0 highest priority */
	mtdcr (uicsr, 0xFFFFFFFF);	/* clear all ints */

	/*
	 * EBC Configuration Register: set ready timeout to 100 us
	 */
	mtebc (epcr, 0xb8400000);

	return 0;
}
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{
    pthread_t shooting_threads[MAX_PROCESSING_THREADS];
    char c;
    int i;

    // Initialization
    printf("CATIA:\tStarting Camera Application Triggering Image Analysis\n");
    chdk_pipe_init();
    int ret = serial_init("/dev/ttySAC0");
    if (ret < 0) {
        printf("CATIA:\tfailed to open /dev/ttySAC0\n");
        return -1;
    }
    pthread_mutex_init(&mut, NULL);
    socket_init(1);

    // Initial settings
    is_shooting = 0;
    mora_protocol.status = 0;
    image_idx = 0;
    image_count = 0;
    shooting_idx = 0;
    shooting_count = 0;
    shooting_thread_count = 0;

    // MAIN loop
    while (1) {

        // Read the serial
        if (read(fd, &c, 1) > 0) {
            parse_mora(&mora_protocol, c);
        } else if (errno != 11) {
            printf("CATIA:\nSerial error: %d\n" , errno);
        }

        // Parse serial commands
        if (mora_protocol.msg_received) {
            // Process Only Once
            mora_protocol.msg_received = FALSE;

            // Shoot an image if not busy
            if (mora_protocol.msg_id == MORA_SHOOT) {
                // Parse the shoot message
                union dc_shot_union* shoot = (union dc_shot_union*) malloc(sizeof(union dc_shot_union));
                for (i = 0; i < MORA_SHOOT_MSG_SIZE; i++) {
                    shoot->bin[i] = mora_protocol.payload[i];
                }
                printf("CATIA:\tSHOT %d,%d\n", shoot->data.nr, shoot->data.phi);

                pthread_create(&shooting_threads[(shooting_idx++ % MAX_PROCESSING_THREADS)], NULL, handle_msg_shoot, (void*)shoot);
                send_msg_status();
            }

            // Fill the image buffer (happens busy because needs fd anyway)
            if (mora_protocol.msg_id == MORA_BUFFER_EMPTY) {
                send_msg_image_buffer();
            }
        }

        // Read the socket
        if (socket_recv(image_buffer[image_idx], IMAGE_SIZE) == IMAGE_SIZE) {
            image_idx = (image_idx + 1) % MAX_IMAGE_BUFFERS;

            if (image_count < MAX_IMAGE_BUFFERS) {
                image_count++;
            }
        }

    }

    // Close
    close(fd);
    chdk_pipe_deinit();

    printf("CATIA:\tShutdown\n");
    return 0;
}
Ejemplo n.º 6
0
/*
************************************************************************************************************
*
*                                             function
*
*    name          :	modify_uboot_uart
*
*    parmeters     :
*
*    return        :
*
*    note          :	[email protected]
*
*
************************************************************************************************************
*/
int modify_uboot_uart(void)
{
    script_gpio_set_t fetch_cfg_gpio[2];
    u32  reg = 0;
    int uart_port_id = 0;
//disable uart0
    if(script_parser_fetch("uart_para","uart_debug_rx",(int *)(&fetch_cfg_gpio[0]),sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error: can't find card0_rx \n");
        return -1;
    }
	fetch_cfg_gpio[0].mul_sel = 0;
    if(script_parser_patch("uart_para","uart_debug_rx",(void*)&fetch_cfg_gpio[0],sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error : can't patch uart_debug_rx\n");
        return -1;
    }
    //config uart_tx
    if(script_parser_fetch("uart_para","uart_debug_tx",(int *)(&fetch_cfg_gpio[1]),sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error: can't find card0_tx \n");
        return -1;
    }
	fetch_cfg_gpio[1].mul_sel = 0;
    if(script_parser_patch("uart_para","uart_debug_tx",(void*)&fetch_cfg_gpio[1],sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error : can't patch uart_debug_tx\n");
        return -1;
    }
	//disable uart0
	gpio_request_simple("uart_para",NULL);
    //port_id
    if(script_parser_fetch("force_uart_para","force_uart_port",(int *)(&uart_port_id),sizeof(int)/4))
    {
        printf("debug_mode_error: can't find card0_tx \n");
        return -1;
    }
	if(script_parser_patch("uart_para","uart_debug_port",(int *)(&uart_port_id),sizeof(int)/4))
    {
        printf("debug_mode_error: can't find card0_tx \n");
        return -1;
    }
	if(script_parser_fetch("force_uart_para","force_uart_tx",(int *)(&fetch_cfg_gpio[0]),sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error: can't find card0_tx \n");
        return -1;
    }
    if(script_parser_patch("uart_para","uart_debug_tx",(void*)&fetch_cfg_gpio[0],sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error : can't patch uart_debug_tx\n");
        return -1;
    }
	if(script_parser_fetch("force_uart_para","force_uart_rx",(int *)(&fetch_cfg_gpio[1]),sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error: can't find card0_tx \n");
        return -1;
    }
    if(script_parser_patch("uart_para","uart_debug_rx",(void*)&fetch_cfg_gpio[1],sizeof(script_gpio_set_t)/4))
    {
        printf("debug_mode_error : can't patch uart_debug_tx\n");
        return -1;
    }

    printf("uart_port_id = %d\n",uart_port_id);
    uboot_spare_head.boot_data.uart_port = uart_port_id;
    //reset
#ifdef UART_RST_CTRL
	reg = readl(UART_RST_CTRL);
	reg &= ~(1 << (16 + uart_port_id));
	reg |=  (1 << (16 + uart_port_id));
        writel(reg,UART_RST_CTRL);
#endif
    //gate
	reg = readl(UART_GATE_CTRL);
    reg &= ~(1 << (16 + uart_port_id));
	reg |=  (1 << (16 + uart_port_id));
    writel(reg,UART_GATE_CTRL);
	//enable card0
	gpio_request_simple("uart_para",NULL);
    serial_init();
	return 0;
}
Ejemplo n.º 7
0
/* C64-specific initialization.  */
int machine_specific_init(void)
{
    int delay;

    scpu64_log = log_open("SCPU64");

    if (mem_load() < 0) {
        return -1;
    }

    event_init();

    /* Setup trap handling.  */
    traps_init();

    if (!video_disabled_mode) {
        joystick_init();
    }

    gfxoutput_init();

    /* Initialize serial traps.  */
    if (serial_init(scpu64_serial_traps) < 0) {
        return -1;
    }

    serial_trap_init(0xa4);
    serial_iec_bus_init();

    /* Initialize RS232 handler.  */
    rs232drv_init();
    c64_rsuser_init();

    /* Initialize print devices.  */
    printer_init();

    /* Fire up the hardware-level drive emulation.  */
    drive_init();

    disk_image_init();

    resources_get_int("AutostartDelay", &delay);
    if (delay == 0) {
        delay = 3; /* default */
    }

    /* Initialize autostart.  */
    autostart_init((CLOCK)(delay * SCPU64_PAL_RFSH_PER_SEC * SCPU64_PAL_CYCLES_PER_RFSH), 1, 0xcc, 0xd1, 0xd3, 0xd5);

#ifdef USE_BEOS_UI
    /* Pre-init C64-specific parts of the menus before vicii_init()
       creates a canvas window with a menubar at the top. This could
       also be used by other ports, e.g. GTK+...  */
    if (!console_mode) {
        scpu64ui_init_early();
    }
#endif

    if (vicii_init(VICII_STANDARD) == NULL && !video_disabled_mode) {
        return -1;
    }

    scpu64_mem_init();

    cia1_init(machine_context.cia1);
    cia2_init(machine_context.cia2);

#ifndef COMMON_KBD
    /* Initialize the keyboard.  */
    if (c64_kbd_init() < 0) {
        return -1;
    }
#endif
    c64keyboard_init();

    scpu64_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec, machine_timing.cycles_per_sec);

    /* Initialize native sound chip */
    sid_sound_chip_init();

    /* Initialize cartridge based sound chips */
    cartridge_sound_chip_init();

    /* Initialize userport based sound chips */
    userport_dac_sound_chip_init();

    drive_sound_init();
    video_sound_init();

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    /* Initialize keyboard buffer.  */
    kbdbuf_init(631, 198, 10, (CLOCK)(machine_timing.rfsh_per_sec * machine_timing.cycles_per_rfsh));

    /* Initialize the C64-specific I/O */
    c64io_init();

    /* Initialize the C64-specific part of the UI.  */
    if (!console_mode) {
        scpu64ui_init();
    }

    /* Initialize glue logic.  */
    scpu64_glue_init();

#ifdef HAVE_MOUSE
    /* Initialize mouse support (if present).  */
    mouse_init();

#ifdef HAVE_LIGHTPEN
    /* Initialize lightpen support and register VICII callbacks */
    lightpen_init();
    lightpen_register_timing_callback(vicii_lightpen_timing, 0);
    lightpen_register_trigger_callback(vicii_trigger_light_pen);
#endif
#endif
    c64iec_init();
    c64fastiec_init();

    cartridge_init();

    machine_drive_stub();
#if defined (USE_XF86_EXTENSIONS) && (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline */
        int fs;
        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_set_int("VICIIFullscreen", 1);
        }
    }
#endif

    return 0;
}
Ejemplo n.º 8
0
Serial::Serial(PinName tx, PinName rx, const char *name) : Stream(name) {
    serial_init(&_serial, tx, rx);
    _baud = 9600;
    serial_irq_handler(&_serial, Serial::_irq_handler, (uint32_t)this);
}
Ejemplo n.º 9
0
extern "C" int
start_raw(int argc, const char **argv)
{
	stage2_args args;

	clear_bss();
		// call C++ constructors before doing anything else
	call_ctors();
	args.heap_size = HEAP_SIZE;
	args.arguments = NULL;
	args.platform.boot_tgz_data = NULL;
	args.platform.boot_tgz_size = 0;
	args.platform.fdt_data = NULL;
	args.platform.fdt_size = 0;

	// if we get passed a uimage, try to find the third blob only if we do not have FDT data yet
	if (gUImage != NULL
		&& !gFDT
		&& image_multi_getimg(gUImage, 2,
			(uint32*)&args.platform.fdt_data,
			&args.platform.fdt_size)) {
		// found a blob, assume it is FDT data, when working on a platform
		// which does not have an FDT enabled U-Boot
		gFDT = args.platform.fdt_data;
	}

	serial_init(gFDT);
	console_init();
	cpu_init();

	if (args.platform.fdt_data) {
		dprintf("Found FDT from uimage @ %p, %" B_PRIu32 " bytes\n",
			args.platform.fdt_data, args.platform.fdt_size);
	} else if (gFDT) {
		/* Fixup args so we can pass the gFDT on to the kernel */
		args.platform.fdt_data = gFDT;
		args.platform.fdt_size = fdt_totalsize(gFDT);
	}

	// if we get passed an FDT, check /chosen for initrd
	if (gFDT != NULL) {
		int node = fdt_path_offset(gFDT, "/chosen");
		const void *prop;
		int len;
		phys_addr_t initrd_start = 0, initrd_end = 0;

		if (node >= 0) {
			prop = fdt_getprop(gFDT, node, "linux,initrd-start", &len);
			if (prop && len == 4)
				initrd_start = fdt32_to_cpu(*(uint32_t *)prop);
			prop = fdt_getprop(gFDT, node, "linux,initrd-end", &len);
			if (prop && len == 4)
				initrd_end = fdt32_to_cpu(*(uint32_t *)prop);
			if (initrd_end > initrd_start) {
				args.platform.boot_tgz_data = (void *)initrd_start;
				args.platform.boot_tgz_size = initrd_end - initrd_start;
		dprintf("Found boot tgz from FDT @ %p, %" B_PRIu32 " bytes\n",
			args.platform.boot_tgz_data, args.platform.boot_tgz_size);
			}
		}
	}

	// if we get passed a uimage, try to find the second blob
	if (gUImage != NULL
		&& image_multi_getimg(gUImage, 1,
			(uint32*)&args.platform.boot_tgz_data,
			&args.platform.boot_tgz_size)) {
		dprintf("Found boot tgz from uimage @ %p, %" B_PRIu32 " bytes\n",
			args.platform.boot_tgz_data, args.platform.boot_tgz_size);
	}

	{ //DEBUG:
		int i;
		dprintf("argc = %d\n", argc);
		for (i = 0; i < argc; i++)
			dprintf("argv[%d] @%lx = '%s'\n", i, (uint32)argv[i], argv[i]);
		dprintf("os: %d\n", (int)gUBootOS);
		dprintf("gd @ %p\n", gUBootGlobalData);
		if (gUBootGlobalData)
			dprintf("gd->bd @ %p\n", gUBootGlobalData->bd);
		//dprintf("fb_base %p\n", (void*)gUBootGlobalData->fb_base);
		if (gUImage)
			dump_uimage(gUImage);
		if (gFDT)
			dump_fdt(gFDT);
	}
	
	mmu_init();

	// wait a bit to give the user the opportunity to press a key
//	spin(750000);

	// reading the keyboard doesn't seem to work in graphics mode
	// (maybe a bochs problem)
//	sBootOptions = check_for_boot_keys();
	//if (sBootOptions & BOOT_OPTION_DEBUG_OUTPUT)
		serial_enable();

	main(&args);
	return 0;
}
Ejemplo n.º 10
0
// MAIN
int main(int argc, char ** argv){
	printf("Lancement du programme Main...\n");
	// CHOIX PERIPHERIQUE POUR LE ZIGBEE

	if(argc < 1){
		printf("Please provide a dev name.\n");
		return 0;
	} 

	char * devname = argv[1];
	printf("Lancement du programme DUMMYFPGA...\n");
	int xbeeRNE = serial_init(devname,9600);
	int * xbeeRNEPointer = &xbeeRNE;
	// POUR POUVOIR FACILEMENT ENVOYER VERS LE COORDINATEUR
    uint8_t destRequest[8];  
    destRequest[0] = 0x00;
	destRequest[1] = 0x00;
	destRequest[2] = 0x00;
	destRequest[3] = 0x00;
	destRequest[4] = 0x00;
	destRequest[5] = 0x00;
	destRequest[6] = 0x00;
	destRequest[7] = 0x00;

	//CREATION D'UNE LISTE DE CAPTEUR
	listeCapteurs = initCaptorsList();
	uint8_t question = 0x3F; // Pour pouvoir repondre a la demande '?'
	uint8_t numberCaptors = 0x01; // Nombre de capteurs (A mettre a jour)

	// INITIALISATION D'UN UNIQUE CAPTEUR (A FAIRE POUR TOUS LES CAPTEURS)
	uint8_t id = ID_TEMPERATURE; // Type de capteur
	uint8_t unitData = 0x0C; // unite (ici en degre celsius)
	uint8_t dataSize = 0x02; // le nombre d'octets qui composent la donnee (ici 2)
	uint8_t minTemp[2]; // Valeurs min et max et leur affectation (on suppose dataSize = 0x02)
	uint8_t maxTemp[2];
	minTemp[0] = 0x00; // A METTRE A JOUR EN FONCTION DES DONNEES
	minTemp[1] = 0x00;
	maxTemp[0] = 0x00;
	maxTemp[1] = 0x40;
	uint8_t fpgaName[2]; 	// Nom du FPGA (ici "#1")
	fpgaName[0] = 0x23;
	fpgaName[1] = 0x31;
	addCaptor(listeCapteurs,id,dataSize,unitData,minTemp,maxTemp);
	//showCaptor(listeCapteurs->premier); // Pour afficher les differents champs du capteur

	// A FAIRE POUR TOUS LES AUTRES CAPTEURS

	


	int count = 0;
	int finish = 0;
	while(!finish){
		printf("Count Value : %d", count);
		count++;
		struct TrameXbee * trameRetour = getTrame(xbeeRNEPointer);
		if(trameRetour){
				afficherTrame(trameRetour);
				// // FIN DU PROGRAMME
				uint8_t idRetour = trameRetour->header.frameID;
				switch(idRetour){
				    case ID_NI :{
				    // ARRIVEE D'UN NOUVEAU FPGA DANS LE RESEAU, ON VA METTRE A JOUR LA TABLE
				    // ICI ON NE SERA PAS DANS CE CAS LA
				       	break;
				       }
				    case ID_TX_STATUS :{
				    	if (trameRetour->trameData[4] == 0x00){
				    		printf("La trame a bien ete tranmise");
				    	} 			    	
				    	break;
				    }

				    case ID_RX :{

				    	uint8_t askCode = trameRetour->trameData[11];
				    	switch(askCode){
							case 0x3F :{
								// REQUETE INFO CAPTEUR
								printf("On a reçu une requete de demande d'infos sur les capteurs !\n");
								sendInfoCaptorValueFrameWithList(xbeeRNEPointer,name,listeCapteurs);
								break;
							}

							case 0x2A :{
							// REQUETE VALEUR CAPTEUR
							uint8_t capteurCode = trameRetour->trameData[12];
				    		fprintf(stderr, "Voici le code reçu : %02x\n", capteurCode);
				    		switch(capteurCode){
								case ID_TEMPERATURE :{
							    printf("On a recu une requête du maitre qui veut connaitre la temperature\n");
							    uint8_t valeur[2];
							    valeur[0] = 0x00;
							    valeur[1] = 0x3F;
							    uint8_t destRequest[8];
							    destRequest[0] = 0x00;
								destRequest[1] = 0x00;
								destRequest[2] = 0x00;
								destRequest[3] = 0x00;
								destRequest[4] = 0x00;
								destRequest[5] = 0x00;
								destRequest[6] = 0x00;
								destRequest[7] = 0x00;
								uint8_t testString [4*2 +1];
								sprintf(&testString[0],"%02x",0x2A);
								sprintf(&testString[2],"%02x",capteurCode);
								sprintf(&testString[4],"%02x",valeur[0]);
								sprintf(&testString[6],"%02x",valeur[1]);
								uint8_t bufferInfo[4];
		   						convertZeroPadedHexIntoByte(testString,bufferInfo);
							    struct TrameXbee * atToSend = computeATTrame(0x12, destRequest ,bufferInfo);
							    sendTrame(xbeeRNEPointer, atToSend);
							    break;
							    }
							    case ID_LIGHT :{
							 	printf("On a recu une requête du maitre qui veut connaitre la luminosite\n");
							    break;
							    }
							    case ID_GYRO :{
								printf("On a recu une requête du maitre qui veut connaitre l'orientation\n");
							    break;
							    }
							    case ID_ANALOG :{
							   	printf("On a recu une requête du maitre qui veut connaitre la valeur analogique\n");
							    break;
							    }
							    default :  
							    printf("ERREUR PAS DE CAPTEUR ICI...\n");
					       		break;
				    		}
								break;
							}
							default:
								break;
							}
				    	break;
				    }

				    default :  
				       break;
				}
			}
			else {
				printf("Pas de trame reçu on recommence !\n");
			}

	}


    printf("Fin Du Programme. Merci d'avoir participe au test!\n");
    close(xbeeRNE);
	
}
Ejemplo n.º 11
0
int main(void)
{
	serial_init(E_BAUD_4800);	
	serial_install_interrupts(E_FLAGS_SERIAL_RX_INTERRUPT);
	serial_flush();

	while(1) {
		char str[32] = {0x00};
		memset(str, 0x00, sizeof(str));

#if TEST_TYPE == TEST_SIMPLE
#warning Building Test Simple

		strcpy(buffer, "123456789");
	   	snprintf(str, sizeof(str), "CRC: %04x\n", 
				checkcrc((unsigned char *)buffer, strlen(buffer)));
		serial_poll_send(str, strlen(str));

#elif TEST_TYPE == TEST_RECEIVE
#warning Building Test Receive

		unsigned char size = 0x00;
		uint16_t crc = 0x0000;

		if (0 >= (size = slip_recv((unsigned char *)buffer, 128)))
			continue;

		memcpy(&crc, &buffer[size - 2], 2);
		memset(&buffer[size - 2], 0x00, 2);

	   	snprintf(str, sizeof(str), "RECV [%04x], CRC: %04x\r\n", 
				crc,
				checkcrc((unsigned char *)buffer, size));
		serial_poll_send(str, strlen(str));

#elif TEST_TYPE == TEST_VERIFY
#warning Building Test Verify

		unsigned char size = 0x00;

		if (0 >= (size = slip_recv((unsigned char *)buffer, 128)))
			continue;

	   	snprintf(str, sizeof(str), "Verification: [%s]\r\n", 
				slip_verify_crc16(buffer, size, size - 2) ?
				"positive" : "negative");

		serial_poll_send(str, strlen(str));

#elif TEST_TYPE == TEST_SEND
#warning Building Test Send

		strcpy(buffer, "123456789");
		slip_append_crc16((unsigned char *)buffer, strlen(buffer));
		serial_poll_send(buffer, 11);
		serial_poll_send("\n",1);

#else
#error Uknown test type
#endif
		_delay_ms(200);
	}

	return 0;
}
Ejemplo n.º 12
0
int main(void)
{
  // Initialize system upon power-up.
  serial_init();   // Setup serial baud rate and interrupts
  settings_init(); // Load Grbl settings from EEPROM
  stepper_init();  // Configure stepper pins and interrupt timers
  system_init();   // Configure pinout pins and pin-change interrupt
  
  memset(&sys, 0, sizeof(sys));  // Clear all system variables
  sys.abort = true;   // Set abort to complete initialization
  sei(); // Enable interrupts

  // Check for power-up and set system alarm if homing is enabled to force homing cycle
  // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
  // startup scripts, but allows access to settings and internal commands. Only a homing
  // cycle '$H' or kill alarm locks '$X' will disable the alarm.
  // NOTE: The startup script will run after successful completion of the homing cycle, but
  // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
  // things uncontrollably. Very bad.
  #ifdef HOMING_INIT_LOCK
    if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
  #endif
  
  // Force Grbl into an ALARM state upon a power-cycle or hard reset.
  #ifdef FORCE_INITIALIZATION_ALARM
    sys.state = STATE_ALARM;
  #endif
  
  // Grbl initialization loop upon power-up or a system abort. For the latter, all processes
  // will return to this loop to be cleanly re-initialized.
  for(;;) {

    // TODO: Separate configure task that require interrupts to be disabled, especially upon
    // a system abort and ensuring any active interrupts are cleanly reset.
  
    // Reset Grbl primary systems.
    serial_reset_read_buffer(); // Clear serial read buffer
    gc_init(); // Set g-code parser to default state
    spindle_init();
    coolant_init();
    limits_init(); 
    jog_init(); // by cm
    probe_init();
    plan_reset(); // Clear block buffer and planner variables
    st_reset(); // Clear stepper subsystem variables.

    // Sync cleared gcode and planner positions to current system position.
    plan_sync_position();
    gc_sync_position();

    // Reset system variables.
    sys.abort = false;
    sys.rt_exec_state = 0;
    sys.rt_exec_alarm = 0;
    sys.suspend = false;
          
    // Start Grbl main loop. Processes program inputs and executes them.
    protocol_main_loop();
    
  }
  return 0;   /* Never reached */
}
Ejemplo n.º 13
0
extern "C" int main() {
	turn_on_crystal_oscillator();
	start_system_pll();
	start_usb_pll();
	set_main_clock_to_system_pll();
	enable_peripheral_clocks();
	serial_init();

	configure_pins();
	delay(1000000);
	
	//enable_clock_output();
	
	NVIC.enable_interrupts();

	//serial_write_string("main():loop");
	//serial_write_line();
	
	// Power for FPGA
	v1p2_enable();	// FPGA VCCINT
	v2p5_enable();	// FPGA PLLs?
	v1p8_enable();	// FPGA VCCIOs, DDR2.
	v1p1_enable();	// USB internal voltage
	delay(1000000);

	// Power for the clock generator.
	// V3P3A must be turned on *after* V1P8 to satisfy
	// Si5351C requirement.
	v3p3a_enable();
	delay(1000000);
	
	// I2C configuration
	i2c0_init(500);
	
	// Give Si5351C time to power up?
	delay(100000);
	si5351c_disable_all_outputs();
	//si5351c_disable_oeb_pin_control();
	si5351c_power_down_all_clocks();
	si5351c_set_crystal_configuration();
	si5351c_enable_xo_and_ms_fanout();
	si5351c_configure_pll_sources_for_xtal();
	si5351c_configure_pll1_multisynth();
	
	si5351c_configure_multisynth(4, 1536, 0, 1, 0); // 50MHz
	si5351c_configure_multisynth(5, 1536, 0, 1, 0); // 50MHz
	si5351c_configure_multisynths_6_and_7();
	
	si5351c_configure_clock_control();
	si5351c_enable_clock_outputs();
	clockgen_output_enable();

	fe_enable();

	while(true) {
		//write_led_status(read_fpga_conf_done());
		write_led_status(1);
		delay(1000000);
		write_led_status(0);
		delay(1000000);
	}
	
	return 0;
}
Ejemplo n.º 14
0
int main(void)
{
    uint8_t  id, rec, i, cs;
    color_t  c;
    packet_t p;

    setup();
    stop_motor();
    sei();
    for(i = 0; i < 5; i++)
    {
        set_led_rgb(255, 0, 255);
        _delay_ms(50);
        set_led_rgb(255, 255, 0);
        _delay_ms(50);
    }

    // get the current liquid level 
    update_liquid_level();

    for(;;)
    {
        cli();
        g_reset = 0;
        g_current_sense_detected = 0;
        g_current_sense_num_cycles = 0;
        setup();
        serial_init();
        stop_motor();
        set_led_rgb(0, 0, 255);

        sei();
        id = address_exchange();

        for(; !check_reset();)
        {
            rec = receive_packet(&p);
            if (rec == COMM_CRC_FAIL)
                continue;

            if (rec == COMM_RESET)
                break;

            if (rec == COMM_OK && (p.dest == DEST_BROADCAST || p.dest == id))
            {
                // If we've detected a over current sitatuion, ignore all comamnds until reset
                cli();
                cs = g_current_sense_detected;
                sei();

                switch(p.type)
                {
                    case PACKET_PING:
                        break;

                    case PACKET_SET_MOTOR_SPEED:
                        if (!cs)
                            set_motor_speed(p.p.uint8[0], p.p.uint8[1]);

                        if (p.p.uint8[0] == 0)
                            flush_saved_tick_count(0);
                        break;

                    case PACKET_TICK_DISPENSE:
                        if (!cs)
                        {
                            dispense_ticks((uint16_t)p.p.uint32, 255);
                            flush_saved_tick_count(0);
                        }
                        break;

                    case PACKET_TIME_DISPENSE:
                        if (!cs)
                        {
                            run_motor_timed(p.p.uint32);
                            flush_saved_tick_count(0);
                        }
                        break;

                    case PACKET_IS_DISPENSING:
                        is_dispensing();
                        break;

                    case PACKET_LIQUID_LEVEL:
                        get_liquid_level();
                        break;

                    case PACKET_UPDATE_LIQUID_LEVEL:
                        update_liquid_level();
                        break;

                    case PACKET_LED_OFF:
                        set_led_pattern(LED_PATTERN_OFF);
                        break;

                    case PACKET_LED_IDLE:
                        if (!cs)
                            set_led_pattern(LED_PATTERN_IDLE);
                        break;

                    case PACKET_LED_DISPENSE:
                        if (!cs)
                            set_led_pattern(LED_PATTERN_DISPENSE);
                        break;

                    case PACKET_LED_DRINK_DONE:
                        if (!cs)
                            set_led_pattern(LED_PATTERN_DRINK_DONE);
                        break;

                    case PACKET_LED_CLEAN:
                        if (!cs)
                            set_led_pattern(LED_PATTERN_CLEAN);
                        break;

                    case PACKET_COMM_TEST:
                        comm_test();
                        break;

                    case PACKET_ID_CONFLICT:
                        id_conflict();
                        break;

                    case PACKET_SET_CS_THRESHOLD:
                        g_current_sense_threshold = p.p.uint16[0];
                        break;

                    case PACKET_SAVED_TICK_COUNT:
                        get_saved_tick_count();
                        break;

                    case PACKET_RESET_SAVED_TICK_COUNT:
                        reset_saved_tick_count();
                        break;

                    case PACKET_FLUSH_SAVED_TICK_COUNT:
                        flush_saved_tick_count(1);
                        break;

                    case PACKET_GET_LIQUID_THRESHOLDS:
                        get_liquid_thresholds();
                        break;

                    case PACKET_SET_LIQUID_THRESHOLDS:
                        set_liquid_thresholds(p.p.uint16[0], p.p.uint16[1]);
                        break;

                    case PACKET_TICK_SPEED_DISPENSE:
                        if (!cs)
                        {
                            dispense_ticks(p.p.uint16[0], (uint8_t)p.p.uint16[1]);
                            flush_saved_tick_count(0);
                        }
                        break;
                    case PACKET_PATTERN_DEFINE:
                        pattern_define(p.p.uint8[0]);
                        break;

                    case PACKET_PATTERN_ADD_SEGMENT:
                        c.red = p.p.uint8[0];
                        c.green = p.p.uint8[1];
                        c.blue = p.p.uint8[2];
                        pattern_add_segment(&c, p.p.uint8[3]);
                        break;

                    case PACKET_PATTERN_FINISH:
                        pattern_finish();
                        break;
                }
            }
        }
    }
    return 0;
}
Ejemplo n.º 15
0
unsigned long
load_kernel(unsigned long load_addr, int num_words, unsigned long cksum, bd_t *bp)
{
	char *cp, ch;
	int timer = 0, zimage_size;
	unsigned long initrd_size;

	/* First, capture the embedded board information.  Then
	 * initialize the serial console port.
	 */
	embed_config(&bp);
#if defined(CONFIG_SERIAL_CPM_CONSOLE) || defined(CONFIG_SERIAL_8250_CONSOLE)
	com_port = serial_init(0, bp);
#endif

	/* Grab some space for the command line and board info.  Since
	 * we no longer use the ELF header, but it was loaded, grab
	 * that space.
	 */
#ifdef CONFIG_MBX
	/* Because of the way the MBX loads the ELF image, we can't
	 * tell where we started.  We read a magic variable from the NVRAM
	 * that gives us the intermediate buffer load address.
	 */
	load_addr = *(uint *)0xfa000020;
	load_addr += 0x10000;		/* Skip ELF header */
#endif
	/* copy board data */
	if (bp)
		memcpy(hold_residual,bp,sizeof(bd_t));

	/* Set end of memory available to us.  It is always the highest
	 * memory address provided by the board information.
	 */
	end_avail = (char *)(bp->bi_memsize);

	puts("\nloaded at:     "); puthex(load_addr);
	puts(" "); puthex((unsigned long)(load_addr + (4*num_words))); puts("\n");
	if ( (unsigned long)load_addr != (unsigned long)&start ) {
		puts("relocated to:  "); puthex((unsigned long)&start);
		puts(" ");
		puthex((unsigned long)((unsigned long)&start + (4*num_words)));
		puts("\n");
	}

	if ( bp ) {
		puts("board data at: "); puthex((unsigned long)bp);
		puts(" ");
		puthex((unsigned long)((unsigned long)bp + sizeof(bd_t)));
		puts("\nrelocated to:  ");
		puthex((unsigned long)hold_residual);
		puts(" ");
		puthex((unsigned long)((unsigned long)hold_residual + sizeof(bd_t)));
		puts("\n");
	}

	/*
	 * We link ourself to an arbitrary low address.  When we run, we
	 * relocate outself to that address.  __image_being points to
	 * the part of the image where the zImage is. -- Tom
	 */
	zimage_start = (char *)(unsigned long)(&__image_begin);
	zimage_size = (unsigned long)(&__image_end) -
			(unsigned long)(&__image_begin);

	initrd_size = (unsigned long)(&__ramdisk_end) -
		(unsigned long)(&__ramdisk_begin);

	/*
	 * The zImage and initrd will be between start and _end, so they've
	 * already been moved once.  We're good to go now. -- Tom
	 */
	puts("zimage at:     "); puthex((unsigned long)zimage_start);
	puts(" "); puthex((unsigned long)(zimage_size+zimage_start));
	puts("\n");

	if ( initrd_size ) {
		puts("initrd at:     ");
		puthex((unsigned long)(&__ramdisk_begin));
		puts(" "); puthex((unsigned long)(&__ramdisk_end));puts("\n");
	}

	/*
	 * setup avail_ram - this is the first part of ram usable
	 * by the uncompress code.  Anything after this program in RAM
	 * is now fair game. -- Tom
	 */
	avail_ram = (char *)PAGE_ALIGN((unsigned long)_end);

	puts("avail ram:     "); puthex((unsigned long)avail_ram); puts(" ");
	puthex((unsigned long)end_avail); puts("\n");
	puts("\nLinux/PPC load: ");
	cp = cmd_line;
	/* This is where we try and pick the right command line for booting.
	 * If we were given one at compile time, use it.  It Is Right.
	 * If we weren't, see if we have a ramdisk.  If so, thats root.
	 * When in doubt, give them the netroot (root=/dev/nfs rw) -- Tom
	 */
#ifdef CONFIG_CMDLINE_BOOL
	memcpy (cmd_line, compiled_string, sizeof(compiled_string));
#else
	if ( initrd_size )
		memcpy (cmd_line, ramroot_string, sizeof(ramroot_string));
	else
		memcpy (cmd_line, netroot_string, sizeof(netroot_string));
#endif
	while ( *cp )
		putc(*cp++);
	while (timer++ < 5*1000) {
		if (tstc()) {
			while ((ch = getc()) != '\n' && ch != '\r') {
				if (ch == '\b' || ch == '\177') {
					if (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				} else if (ch == '\030'		/* ^x */
					   || ch == '\025') {	/* ^u */
					while (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				} else {
					*cp++ = ch;
					putc(ch);
				}
			}
			break;  /* Exit 'timer' loop */
		}
		udelay(1000);  /* 1 msec */
	}
	*cp = 0;
	puts("\nUncompressing Linux...");

	gunzip(0, 0x400000, zimage_start, &zimage_size);
	flush_instruction_cache();
	puts("done.\n");
	{
		struct bi_record *rec;
		unsigned long initrd_loc;
		unsigned long rec_loc = _ALIGN((unsigned long)(zimage_size) +
				(1 << 20) - 1, (1 << 20));
		rec = (struct bi_record *)rec_loc;

		/* We need to make sure that the initrd and bi_recs do not
		 * overlap. */
		if ( initrd_size ) {
			initrd_loc = (unsigned long)(&__ramdisk_begin);
			/* If the bi_recs are in the middle of the current
			 * initrd, move the initrd to the next MB
			 * boundary. */
			if ((rec_loc > initrd_loc) &&
					((initrd_loc + initrd_size)
					 > rec_loc)) {
				initrd_loc = _ALIGN((unsigned long)(zimage_size)
						+ (2 << 20) - 1, (2 << 20));
			 	memmove((void *)initrd_loc, &__ramdisk_begin,
					 initrd_size);
		         	puts("initrd moved:  "); puthex(initrd_loc);
			 	puts(" "); puthex(initrd_loc + initrd_size);
			 	puts("\n");
			}
		}

		rec->tag = BI_FIRST;
		rec->size = sizeof(struct bi_record);
		rec = (struct bi_record *)((unsigned long)rec + rec->size);

		rec->tag = BI_CMD_LINE;
		memcpy( (char *)rec->data, cmd_line, strlen(cmd_line)+1);
		rec->size = sizeof(struct bi_record) + strlen(cmd_line) + 1;
		rec = (struct bi_record *)((unsigned long)rec + rec->size);

		if ( initrd_size ) {
			rec->tag = BI_INITRD;
			rec->data[0] = initrd_loc;
			rec->data[1] = initrd_size;
			rec->size = sizeof(struct bi_record) + 2 *
				sizeof(unsigned long);
			rec = (struct bi_record *)((unsigned long)rec +
					rec->size);
		}

		rec->tag = BI_LAST;
		rec->size = sizeof(struct bi_record);
		rec = (struct bi_record *)((unsigned long)rec + rec->size);
	}
	puts("Now booting the kernel\n");
#if defined(CONFIG_SERIAL_CPM_CONSOLE) || defined(CONFIG_SERIAL_8250_CONSOLE)
	serial_close(com_port);
#endif

	return (unsigned long)hold_residual;
}
Ejemplo n.º 16
0
int main(void)
{
  // Initialize system
  serial_init(BAUD_RATE); // Setup serial baud rate and interrupts
  st_init(); // Setup stepper pins and interrupt timers
  sei(); // Enable interrupts

  memset(&sys, 0, sizeof(sys));  // Clear all system variables
  sys.abort = true;   // Set abort to complete initialization

  for(;;) {

    // Execute system reset upon a system abort, where the main program will return to this loop.
    // Once here, it is safe to re-initialize the system. At startup, the system will automatically
    // reset to finish the initialization process.
    if (sys.abort) {

      // Retain last known machine position and work coordinate offset(s). If the system abort
      // occurred while in motion, machine position is not guaranteed, since a hard stop can cause
      // the steppers to lose steps. Always perform a feedhold before an abort, if maintaining
      // accurate machine position is required.
      // TODO: Report last position and coordinate offset to users to help relocate origins. Future
      // releases will auto-reset the machine position back to [0,0,0] if an abort is used while
      // grbl is moving the machine.
/// by LETARTARE 3-> 4
      int32_t last_position[4];
      double last_coord_system[N_COORDINATE_SYSTEM][3];
      memcpy(last_position, sys.position, sizeof(sys.position)); // last_position[] = sys.position[]
      memcpy(last_coord_system, sys.coord_system, sizeof(sys.coord_system)); // last_coord_system[] = sys.coord_system[]

      // Reset system.
      memset(&sys, 0, sizeof(sys)); // Clear all system variables
      serial_reset_read_buffer(); // Clear serial read buffer
      settings_init(); // Load grbl settings from EEPROM
      protocol_init(); // Clear incoming line data
      plan_init(); // Clear block buffer and planner variables
      gc_init(); // Set g-code parser to default state
      spindle_init();
      limits_init();
      coolant_init();
      st_reset(); // Clear stepper subsystem variables.

      // Reload last known machine position and work systems. G92 coordinate offsets are reset.
      memcpy(sys.position, last_position, sizeof(last_position)); // sys.position[] = last_position[]
      memcpy(sys.coord_system, last_coord_system, sizeof(last_coord_system)); // sys.coord_system[] = last_coord_system[]
      gc_set_current_position(last_position[X_AXIS],last_position[Y_AXIS],last_position[Z_AXIS],last_position[C_AXIS]);
      plan_set_current_position(last_position[X_AXIS],last_position[Y_AXIS],last_position[Z_AXIS],last_position[C_AXIS]);

      // Set system runtime defaults
      // TODO: Eventual move to EEPROM from config.h when all of the new settings are worked out.
      // Mainly to avoid having to maintain several different versions.
      #ifdef CYCLE_AUTO_START
        sys.auto_start = true;
      #endif
      // TODO: Install G20/G21 unit default into settings and load appropriate settings.
    }

    protocol_execute_runtime();
    protocol_process(); // ... process the serial protocol

  }
  return 0;   /* never reached */
}
Ejemplo n.º 17
0
/* Plus4-specific initialization.  */
int machine_specific_init(void)
{
    int delay;

    plus4_log = log_open("Plus4");

    if (mem_load() < 0)
        return -1;

    /* Setup trap handling.  */
    traps_init();

    /* Initialize serial traps.  */
    if (serial_init(plus4_serial_traps) < 0)
        return -1;

    serial_trap_init(0xa8);
    serial_iec_bus_init();

    rs232drv_init();

    /* Initialize print devices.  */
    printer_init();

    /* Initialize the tape emulation.  */
    tape_init(&tapeinit);

    /* Initialize the datasette emulation.  */
    datasette_init();

    /* Fire up the hardware-level drive emulation.  */
    drive_init();

    /* Initialize autostart.  */
    resources_get_int("AutostartDelay", &delay);
    if (delay == 0) {
        delay = 2; /* default */
    }
    autostart_init((CLOCK)(delay * PLUS4_PAL_RFSH_PER_SEC
                   * PLUS4_PAL_CYCLES_PER_RFSH), 0, 0, 0xc8, 0xca, -40);

    /* Initialize the sidcart first */
    sidcart_sound_chip_init();

    /* Initialize native sound chip */
    ted_sound_chip_init();

    /* Initialize cartridge based sound chips */
    digiblaster_sound_chip_init();
    speech_sound_chip_init();

    drive_sound_init();
    video_sound_init();

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    if (ted_init() == NULL) {
        return -1;
    }

    acia_init();

#ifndef COMMON_KBD
    if (plus4_kbd_init() < 0) {
        return -1;
    }
#endif

    plus4_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec,
                                machine_timing.cycles_per_sec);

    /* Initialize keyboard buffer.  */
    kbdbuf_init(1319, 239, 8, (CLOCK)(machine_timing.rfsh_per_sec
                * machine_timing.cycles_per_rfsh));

    plus4ui_init();

    cs256k_init();

    h256k_init();

    plus4iec_init();

    machine_drive_stub();

#if defined (USE_XF86_EXTENSIONS) && \
    (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline */
        int fs;
        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_set_int("TEDFullscreen", 1);
        }
    }
#endif
    return 0;
}
Ejemplo n.º 18
0
void main() {
  unsigned char i,tmp;

  CMCON=0x07; 
  TRISA=0x30;
  TRISB=0xE7;
  
  PORTA=0xFE;
  PORTB=0x00;

  lcd_init();

  i2c_init();
  
  serial_init();

//teste lcd
  lcd_cmd(L_CLR); 
  lcd_cmd(L_L1);
  for(i=0;i<16;i++)
  {
    lcd_dat('A'+i);
  }
  lcd_cmd(L_L2);
  for(i=0;i<16;i++)
  {
    lcd_dat('a'+i);
  }

  atraso_ms(200);
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1+3);
  lcd_str("Teste LCD");
  
  for(i=32;i<128;i++)
  {
    if((i%16) == 0)lcd_cmd(L_L2);
    lcd_dat(i);
    atraso_ms(50);
  }

  atraso_ms(100);
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1+3);
  lcd_str("Teste LCD");
  lcd_cmd(L_L2+7);
  lcd_str("Ok");
  atraso_ms(500);

//teste LEDS
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1+1);
  lcd_str("Teste LEDs");
 
for(i=0;i<4;i++)
  {
    atraso_ms(100);
    RA1^=1;
    atraso_ms(100);
    RA2^=1;
    atraso_ms(100);
    PORTA^=0x40; //RA6=1;
    atraso_ms(100);
    PORTA^=0x80; //RA7=1;
    atraso_ms(100);
  }


//teste Teclado
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1+2);
  lcd_str("Teste Teclado");

  lcd_cmd(L_L2+1);

  i=0;
  while(i<14)
  {
    lcd_dat(tc_tecla(3000)+0x30);
    i++;
  }

//teste EEPROM EXT
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste EEPROM EXT");
// testar ? 
  lcd_cmd(L_L2);
  lcd_str("Testar (1/0) ?");
 
  if(tc_tecla(0) == 1)
  {
    tmp=e2pext_r(10);
    lcd_dat(tmp);

    e2pext_w(10,0xA5);
    e2pext_w(10,0x5A);
    i=e2pext_r(10);

    e2pext_w(10,tmp);

    lcd_cmd(L_CLR);
    lcd_cmd(L_L1);
    lcd_str("Teste EEPROM EXT");
    lcd_cmd(L_L2);
    if(i == 0x5A) 
      lcd_str("     OK");
    else
      lcd_str("     ERRO");

    atraso_ms(1000);
  }


//teste RTC
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste RTC");
  
//ajuste  rtc_w();

//  rtc_w();
 
  rtc_r();
  lcd_cmd(L_L2);
  lcd_str((char *)date);
   atraso_ms(1500);
  for(i=0;i<16;i++)
  {
    rtc_r();
    lcd_cmd(L_L2);;
    lcd_str((char *)time);
    atraso_ms(500); 
  }

   
   //teste serial
   
 //teste EEPROM EXT
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste Serial");
// testar ? 
  lcd_cmd(L_L2);
  lcd_str("Testar (1/0) ?");
  if(tc_tecla(0) == 1)
  {  
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste Serial TX");
  lcd_cmd(L_L2+2);
  lcd_str("9600 8N1");

  serial_tx_str("\r\n Picsimlab\r\n Teste Serial TX\r\n");

  for(i=0;i<4;i++)
  {
    serial_tx(i+0x30);
    serial_tx_str(" PicsimLab\r\n");
  }
  atraso_ms(1000);

  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste Serial RX");
  serial_tx_str(" Digite!\r\n");
  for(i=0;i<32;i++)
  {
    if(!(i%16))
    {
       lcd_cmd(L_L2);
       serial_tx_str("\r\n");
    }
    tmp=serial_rx(3000);
    lcd_dat(tmp);
    serial_tx(tmp);
  }
  atraso_ms(100);
  
  
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1);
  lcd_str("Teste Teclado TX");
  serial_tx_str("\r\n Aguarde!\r\n");
  for(i=0;i<32;i++)
  {
    if(!(i%16))
    {
      lcd_cmd(L_L2);
      serial_tx_str("\r\n");
    }
    tmp=tc_tecla(2000)+0x30;
    lcd_dat(tmp);
    serial_tx(tmp);
  }
  atraso_ms(100);
  }

//fim teste 
  lcd_cmd(L_CLR);
  lcd_cmd(L_L1+4);
  lcd_str("Fim");
  lcd_cmd(L_L2+1);
  lcd_str("Pressione RST");

  serial_tx_str("\r\n FIM!\r\n");  

  while(1);


}
Ejemplo n.º 19
0
int main(int argc, char* argv[]) {

    DDRC = 0x0f;
    DDRD = 0xf0;
    DDRB = 0xC3;
    PORTB = 0;
    PORTC = 0;
    PORTD = 0;
    serial_init();
    send_string_serial("Starting up...\n");
    _delay_ms(500);

    speed1 = 4000;
    speed2 = 4000;
    speed3 = 4000;
    speed4 = 1250;
    counter1 = 1;
    counter2 = 1;
    counter3 = 1;
    counter4 = 1;

    needState1 = FALSE;
    needState2 = FALSE;
    needState3 = FALSE;

    movingForward1 = FALSE;
    movingForward2 = FALSE;
    movingForward3 = FALSE;

    currentState1 = 0;
    currentState2 = 0;
    currentState3 = 0;

    motorState1 = getMotorState(currentState1);
    motorState2 = getMotorState(currentState2) << 4;
    unsigned char state = getMotorState(currentState3);
    motorState3 = ((state & 0x0C) << 4) | (state & 0x03);

    setupTimers();

	char index = 0;
	int speeds[3];
	char* buffer = (char*) speeds;

    while (1) {
		if  (UCSRA & (1<<RXC)) {
			buffer[index++] = UDR;
			
			if (index == 6) {
				// do something with the buffer
				setSpeed1(speeds[0]);
				setSpeed2(speeds[1]);
				setSpeed3(speeds[2]);
				index = 0;
				send_string_serial("Received full message\n\r");
			}
		}

        checkSerialSend();
        if (needState1) {
            currentState1 = getNextState(currentState1, movingForward1);
            motorState1 = getMotorState(currentState1);
            needState1 = FALSE;
        }
        if (needState2) {
            currentState2 = getNextState(currentState2, movingForward2);
            motorState2 = getMotorState(currentState2) << 4;
            needState2 = FALSE;
        }
        if (needState3) {
            currentState3 = getNextState(currentState3, movingForward3);
            state = getMotorState(currentState3);
            motorState3 = ((state & 0x0C) << 4) | (state & 0x03);
            needState3 = FALSE;
        }
/*
        if (needsNewSpeed) {
            currentSpeedIndex = (currentSpeedIndex + 1);
            if (currentSpeedIndex == 0x40) {
                currentSpeedIndex = 0;
                send_string_serial("Loop...\n");
            }
            setSpeed1(speed[0][currentSpeedIndex]);
            setSpeed2(speed[1][currentSpeedIndex]);
            setSpeed3(speed[2][currentSpeedIndex]);
            needsNewSpeed = FALSE;
        }
*/
    }

	return 0;
}
Ejemplo n.º 20
0
static void
mips_mipssim_init (ram_addr_t ram_size,
                   const char *boot_device,
                   const char *kernel_filename, const char *kernel_cmdline,
                   const char *initrd_filename, const char *cpu_model)
{
    char *filename;
    ram_addr_t ram_offset;
    ram_addr_t bios_offset;
    CPUState *env;
    ResetData *reset_info;
    int bios_size;

    /* Init CPUs. */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "5Kf";
#else
        cpu_model = "24Kf";
#endif
    }
    env = cpu_init(cpu_model);
    if (!env) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    reset_info = qemu_mallocz(sizeof(ResetData));
    reset_info->env = env;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* Allocate RAM. */
    ram_offset = qemu_ram_alloc(NULL, "mips_mipssim.ram", ram_size);
    bios_offset = qemu_ram_alloc(NULL, "mips_mipssim.bios", BIOS_SIZE);

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    /* Map the BIOS / boot exception handler. */
    cpu_register_physical_memory(0x1fc00000LL,
                                 BIOS_SIZE, bios_offset | IO_MEM_ROM);
    /* Load a BIOS / boot exception handler image. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = load_image_targphys(filename, 0x1fc00000LL, BIOS_SIZE);
        qemu_free(filename);
    } else {
        bios_size = -1;
    }
    if ((bios_size < 0 || bios_size > BIOS_SIZE) && !kernel_filename) {
        /* Bail out if we have neither a kernel image nor boot vector code. */
        fprintf(stderr,
                "qemu: Could not load MIPS bios '%s', and no -kernel argument was specified\n",
                filename);
        exit(1);
    } else {
        /* We have a boot vector start address. */
        env->active_tc.PC = (target_long)(int32_t)0xbfc00000;
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices. */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* Register 64 KB of ISA IO space at 0x1fd00000. */
    isa_mmio_init(0x1fd00000, 0x00010000);

    /* A single 16450 sits at offset 0x3f8. It is attached to
       MIPS CPU INT2, which is interrupt 4. */
    if (serial_hds[0])
        serial_init(0x3f8, env->irq[4], 115200, serial_hds[0]);

    if (nd_table[0].vlan)
        /* MIPSnet uses the MIPS CPU INT0, which is interrupt 2. */
        mipsnet_init(0x4200, env->irq[2], &nd_table[0]);
}
Ejemplo n.º 21
0
/* Mark weak until post/cpu/.../uart.c migrate over */
__weak
int uart_post_test(int flags)
{
	unsigned char c;
	int ret, saved_baud, b;
	struct serial_device *saved_dev, *s;

	/* Save current serial state */
	ret = 0;
	saved_dev = serial_current;
	saved_baud = gd->baudrate;

	for (s = serial_devices; s; s = s->next) {
		/* If this driver doesn't support loop back, skip it */
		if (!s->loop)
			continue;

		/* Test the next device */
		serial_current = s;

		ret = serial_init();
		if (ret)
			goto done;

		/* Consume anything that happens to be queued */
		while (serial_tstc())
			serial_getc();

		/* Enable loop back */
		s->loop(1);

		/* Test every available baud rate */
		for (b = 0; b < ARRAY_SIZE(bauds); ++b) {
			gd->baudrate = bauds[b];
			serial_setbrg();

			/*
			 * Stick to printable chars to avoid issues:
			 *  - terminal corruption
			 *  - serial program reacting to sequences and sending
			 *    back random extra data
			 *  - most serial drivers add in extra chars (like \r\n)
			 */
			for (c = 0x20; c < 0x7f; ++c) {
				/* Send it out */
				serial_putc(c);

				/* Make sure it's the same one */
				ret = (c != serial_getc());
				if (ret) {
					s->loop(0);
					goto done;
				}

				/* Clean up the output in case it was sent */
				serial_putc('\b');
				ret = ('\b' != serial_getc());
				if (ret) {
					s->loop(0);
					goto done;
				}
			}
		}

		/* Disable loop back */
		s->loop(0);

		/* XXX: There is no serial_stop() !? */
		if (s->stop)
			s->stop();
	}

 done:
	/* Restore previous serial state */
	serial_current = saved_dev;
	gd->baudrate = saved_baud;
	serial_reinit_all();
	serial_setbrg();

	return ret;
}
Ejemplo n.º 22
0
void get_ini_parm(void) {
   u32t  size = 0;
   void*  ini = 0;
   u32t btype = hlp_boottype();
   if (btype==QSBT_FAT || btype==QSBT_SINGLE) ini = hlp_freadfull("QSINIT.INI",&size,0);
   if (!ini) ini = hlp_freadfull("OS2LDR.INI",&size,0);
   
   if (ini) {
      char* cfgp = (char*)hlp_memrealloc(ini, size+1);
      char skipeol = 0, lstart = 1, backch = 0,
             error = 0, // error in string
            reason = 0, // collecting now: 1 - section name, 2 - key name, 3 - key
           section = 0; // 1 - config
      int    value = 0,
           errline = 1,
             strln =-1;
      if (!cfgp) return; else ini=cfgp;
      cfgp[size++]=0;
      sto_save(STOKEY_INIDATA,cfgp,size,0);

      while (size--) {
         char cc=*cfgp++;
         if (!size) cc='\n';
         if (skipeol && cc=='\n') skipeol=0;

         if (!skipeol)
         switch (cc) {
            case ' ' :
            case '\t':
               if (strln>0) strln++;
               break;
            case '\n':
               if (strln>0 && reason<3) { backch=1; error=1; break; }
               errline++;
            case '\r': {
               if (strln > 0 || value) {
                  long rc = str2long(cfgp-1-strln);
                  switch (value) {
                     // "DBPORT"
                     case 1:
                        if (rc>0 && !safeMode) hlp_seroutset(rc,0);
                        break;
                     // "BAUDRATE"
                     case 2: 
                        hlp_seroutset(0,rc);
                        break;
                     // "RESETMODE"
                     case 3:
                        if (rc) {
                           if (rc!=43 && rc!=50) rc=25;
                           vio_setmode(rc);
                        }
                        break;
                     // "NOAF"
                     case 4: useAFio=0; break;
                     // "MFSPRINT"
                     case 5: if (rc>0) mfs_rmcmode=0; break;
                  }
                  strln=0; value=0;
               }
               lstart=1; reason=0;
               break;
             }
            case '=' :
               if (reason==2 && strln>0) {
                  value=0;
                  if (section==1) {     // "config"
                     int ii=0;
                     while (strList[ii])
                        if (!cmpname(strList[ii++], cfgp-1, strln)) {
                           value=ii;
                           break;
                        }
                  }
                  if (!value) skipeol=1; else reason=3;
                  strln=0;
               } else error=1;
               break;
            case ';' : if (lstart) skipeol=1; else
                  if ( strln> 0 ) strln++;
               break;
            case '[' : if (lstart) { strln=0; reason=1; section=0; } 
                  else error=1;
               break;
            case ']' :
               if (reason==1 && !lstart) {
                  if (!cmpname("CONFIG", cfgp-1, strln)) section=1; else
                     section=0;
                  strln=0; skipeol=1;
               } else
                  error=1;
               reason=0;
               break;
            default:
               if (lstart==1 && section) { reason=2; strln=0; }
               lstart=0;
               if (strln>=0) strln++;
         }

         if (backch) { *--cfgp=cc; size++; backch=0; }
         if (error) { skipeol=1; error=0; reason=0; strln=0; }
      }
      //hlp_memfree(ini);
   } else {
#ifdef INITDEBUG
      serial_init(ComPortAddr = 0x2F8);
#endif
   }
   log_printf("hi!\n");
   log_printf("%s\n",aboutstr);
}
Ejemplo n.º 23
0
int main(){

    // signal mask
    sigset_t sigmask;
    sigset_t empty_mask;
    

    /* struct sigaction{
        void (*sa_handler)(int);
        void (*sa_sigaction)(int, siginfo_t *, void*);
        sigset_t    sa_mask;
        int     sa_flags;
        void (*sa_restorer)(void);
    }
    */
    struct sigaction saterm;            // SIGTERM raised by this program or another
    struct sigaction saint;             // SIGINT caused by ctrl + c

   
    // serial
    int fd = -1;                        // file descriptor
    int baudrate = 9600;
    const char* serial_device_path = "/dev/ttyACM0";
    
    ssize_t bytes_read;                 
    uint8_t buf[16];                    // temporarily stores bytes read from serial port


    // file descriptor sets
    fd_set readfds;                     // read file descriptor set
    fd_set writefds;                    // write file descriptor set

    int max_fd;                         // largest file descriptor value
    int selectrfds;                     // number read file descriptors pending
    int selectwfds;                     // number write file descriptors pending
   

    struct timespec timeout;            // timeout for pselect
    
    
    // received message data that is transferred here from buf
    uint8_t responseData[MESSAGE_LENGTH_BYTES + 1];  // plus 1 for null terminator

    // data received from the sensor
    uint8_t sensorId = 1;
    uint16_t sensorData; 


     // state variable declaration
    MessageState  receive_message_state = AWAITING_START_MARKER;

    // read and write states
    CommReadState commReadState = WAIT_FOR_CONNECTION;
    CommWriteState commWriteState = NO_WRITE;

    // select and serial error conditions
    ErrorCondition errorCondition;

    // debug variables 
    int read_select_zero_count = 0;
    int write_select_zero_count = 0;
    int sensor_id_mismatch_count = 0;
    int default_comm_read_state_count = 0;
    int default_comm_write_state_count = 0;

    // initialize logging levels
    // console level, file level, color on
    log_init(LOG_TRACE, LOG_INFO, 1);
            
    // initialize serial port connection
	fd = serial_init(serial_device_path, baudrate);

	if(fd == -1){
		log_fatal("serial port did not open");
		return -1;
	}

    log_info("serial port opened, %s, baud rate: %d, fd: %d", 
                serial_device_path, baudrate, fd);


    // pselect requires an argument that is 1 more than
    // the largest file descriptor value
    max_fd = fd + 1;
         

    // register the SIGTERM signal handler function
    memset(&saterm, 0, sizeof(saterm));
    saterm.sa_handler = signal_handler_term;

    /*  The sigaction() system call is used to change the action 
        taken by a process on receipt of a specific signal.
    */
    if(sigaction(SIGTERM, &saterm, NULL) < 0){
        log_fatal("sigaction saterm, errno: %s", strerror(errno));
        return 1;
    }
    

    // register the SIGINT signal handler function
    memset(&saint, 0, sizeof(saint));
    saint.sa_handler = signal_handler_term;
    if(sigaction(SIGINT, &saint, NULL) < 0){
        log_fatal("sigaction saint, errno: %s", strerror(errno));
        return 1;
    }

    // signal mask initialization
    sigemptyset(&sigmask);
    sigemptyset(&empty_mask);

    sigaddset(&sigmask, SIGTERM);
    sigaddset(&sigmask, SIGINT);

    // set as blocking so that pselect can receive event
    if(sigprocmask(SIG_BLOCK, &sigmask, NULL) < 0){
        log_fatal("sigprocmask, errno: %s", strerror(errno));
        return 1;
    }



    // main processing loop
    while(!exit_request){

        /*  can get SIGTERM at this point, but it will be delivered while
            in pselect, because SIGTERM is blocked.
        */

        /*
        int pselect(int nfds, fd_set *readfds, fd_set *writefds,
            fd_set *exceptfds, const struct timespec *timeout,
            const sigset_t *sigmask);

                nfds nfds is the highest-numbered file descriptor in any of the 
                    three sets, plus 1.

                timeout argument specifies maximum time select should wait 
                before returning. Will return sooner if fd is available

            pselect returns the number of file descriptors that have a pending condition
            or -1 if there was an error
        */
        

        /*  must call FD_ZERO and FD_SET every time through loop.
        *
        *   When select returns, it has updated the sets to show which file
        *   descriptors are ready for read/write/exception. All other flags
        *   have been cleared. Must call FD_SET to re-enable the file 
        *   descriptors that were cleared.
        */
        
        if(commReadState != NO_READ){

            FD_ZERO(&readfds);
            FD_SET(fd, &readfds);
            // re-initialize the timeout structure or it will eventually become zero
            // as time is deducted from the data members. timeval struct represents
            // an elapsed time
            timeout.tv_sec = 2;                     // seconds
            timeout.tv_nsec = 0;                    // nanoseconds

            selectrfds = pselect(max_fd, &readfds, NULL, NULL, &timeout, &empty_mask);
            fprintf(stderr, "\nnumber of read pending, selectrfds: %d\n", selectrfds);

            if(exit_request){
                log_info("received exit request");
                break;
            }

            errorCondition = check_select_return_value(selectrfds, errno, &read_select_zero_count);

            // debug 
            log_debug("commReadState: %d, %s", commReadState, 
                    debug_comm_read_state_string[commReadState]);

            if(errorCondition == SUCCESS){

                bytes_read = read_message(fd, readfds, buf);

                if(bytes_read > 0){

                    ssize_t bytes_not_processed = bytes_read;

                    while(bytes_not_processed > 0){

                        bytes_not_processed = 
                            process_received_message_bytes(&receive_message_state, 
                                            buf, bytes_not_processed, responseData);

                        if(receive_message_state == MESSAGE_COMPLETE){

                            // reset message state for next read
                            receive_message_state = AWAITING_START_MARKER;

                            switch(commReadState){
                                case WAIT_FOR_CONNECTION:
                                    // received hello?
                                    if(strcmp((const char*)responseData, helloMessage) == 0){
                                        log_info("received ready Signal\n");
                                        commReadState = NO_READ;
                                        commWriteState = SEND_READY_SIGNAL;
                                    }
                                    else{
                                        process_read_state_error_message(commReadState,
                                            responseData, (ssize_t)strlen((const char*)responseData));
                                    }
                                break;

                                case READ_ACK:
                                    // received <ACK>?
                                    if(strcmp((const char*)responseData, ackResponse) == 0){
                                        log_info("received ACK\n");
                                        commWriteState = NO_WRITE;     // redundant
                                        commReadState = READ_SENSOR;
                                    }
                                    else{
                                        // writing message here to indicate source of
                                        // warning
                                        log_warn("generated message below");
                                        // to avoid repeating the same code, this function
                                        // was created. However, when it logs the message,
                                        // it will refer to that function and not the source
                                        // here.
                                        process_read_state_error_message(commReadState,
                                            responseData, (ssize_t)strlen((const char*)responseData));
                                    }
                                break;

                                case READ_SENSOR:
                                    // response data should contain sensor data
                                    // verify sensor id
                                    if(responseData[1] == sensorId){
                                         // extract sensor data
                                        // responseData[2] is msb
                                        sensorData = (uint16_t)( 
                                            (((uint16_t)responseData[2]) << 8U) |
                                            ((uint16_t)responseData[3] & 0xFF) );
                                        
                                        process_sensor_data_received(sensorData);
                                    }
                                    else{
                                        log_warn("generated message below");
                                        process_read_state_error_message(commReadState,
                                            responseData, (ssize_t)strlen((const char*)responseData));

                                        ++sensor_id_mismatch_count;
                                    }
                                   
                                break;

                            default:
                                log_warn("generated message below");
                                process_read_state_error_message(commReadState,
                                            responseData, (ssize_t)strlen((const char*)responseData));

                                ++default_comm_read_state_count;
                                        
                            } // end switch
                        } // end if receive message state == message complete
                    } // end while(bytes_not_processed)
                } // end if bytes_read > 0
            }
            else{

                log_error("select return value indicates error condition: %s",
                            debug_error_condition_string[errorCondition]);
                
                if(errorCondition == SELECT_FAILURE){
                    log_fatal("breaking out of while(exit_request) loop");
                    break;
                }

                if(errorCondition == SELECT_ZERO_COUNT){
                    ++read_select_zero_count;
                }
            }
        } // end if read state

        
        if(commWriteState != NO_WRITE){

            FD_ZERO(&writefds);
            FD_SET(fd, &writefds);
            timeout.tv_sec = 2;                     // seconds
            timeout.tv_nsec = 0;                    // nanoseconds

            selectwfds = pselect(max_fd, NULL, &writefds, NULL, &timeout, &empty_mask);

            // debug
            log_trace("\nnumber of write pending, selectwfds: %d", selectwfds);

            // debug 
            log_trace("commWriteState: %d, %s\n", commWriteState,
                                debug_comm_write_state_string[commWriteState]);

            if(exit_request){
                log_info("received exit request");
                break;
            }

            errorCondition = check_select_return_value(selectwfds, errno, &write_select_zero_count);

            if(errorCondition == SUCCESS){

                ErrorCondition writeError;
                writeError = write_message(fd, writefds, commWriteState);

                if(writeError != SUCCESS){
                    log_error("writeError: %s\n",
                                debug_error_condition_string[writeError] );
                }
                else{

                    switch (commWriteState){
                    case SEND_READY_SIGNAL:
                        // The connected program does not rely on receiving the ready
                        // signal to transition to its next state of sending sensor data
                        // No need to resend this signal.
                        // Basically, this is just an example of how to write, and testing
                        // the writing ability. 
                        commReadState = READ_ACK;
                        commWriteState = NO_WRITE;  // message successfully sent
                    break;

                    case SEND_RESET:
                    case SEND_STOP: 
                        // Note: SEND_RESET, SEND_STOP have not yet been programmed
                        log_error("SEND_STOP, SEND_RESET not yet programmed");
                    break;

                    case NO_WRITE: 
                        
                        // not changing state
                    break;
                    
                    default:
                        log_warn("entered default case, commWriteState: %d",
                                    commWriteState );

                        ++default_comm_write_state_count;
                    }
                } 
            }
            else
            {
                log_error("select return value indicates error condition: %s",
                            debug_error_condition_string[errorCondition]);

                if(errorCondition == SELECT_FAILURE){
                    log_fatal("breaking out of while(exit_request) loop");
                    break;

                if(errorCondition == SELECT_ZERO_COUNT){
                    ++write_select_zero_count;
                }
            }

            
        }

        }   // end if(commWriteState)
        
    } // end while( !exit_request)

    // write debug values
    fprintf(stderr, "\n\n=====     End of Run     =====\n\n");

    fprintf(stderr, "How many times did select return 0? Relates to timing issues\n");
    fprintf(stderr, "read select_zero_count:  %d\n"
                    "write_select_zero_count: %d\n", 
                        read_select_zero_count, write_select_zero_count);

    fprintf(stderr, "\nWere there any sensor id mismactches? If so, data was lost. Needs correction\n");
    fprintf(stderr, "sensor id mismatch count: %d\n", sensor_id_mismatch_count);

    // Display number of times a switch default case occurred
    fprintf(stderr, "\nDefault state counts should all be zero\n");
    fprintf(stderr, "default_comm_read_state_count: %d\n", default_comm_read_state_count);
    fprintf(stderr, "default_comm_write_state_count: %d\n", default_comm_write_state_count);



    // properly close serial connection
    serial_close(fd);
    fd = -1;


	return 0;
}
Ejemplo n.º 24
0
void board_init_f(ulong board_type)
{
	gd_t gd_data;
	gd_t *new_gd;
	bd_t *bd;
	unsigned long *new_sp;
	unsigned long monitor_len;
	unsigned long monitor_addr;
	unsigned long addr;
	long sdram_size;

	/* Initialize the global data pointer */
	memset(&gd_data, 0, sizeof(gd_data));
	gd = &gd_data;

	/* Perform initialization sequence */
	board_early_init_f();
	cpu_init();
	board_postclk_init();
	env_init();
	init_baudrate();
	serial_init();
	console_init_f();
	display_banner();
	sdram_size = initdram(board_type);

	/* If we have no SDRAM, we can't go on */
	if (sdram_size <= 0)
		panic("No working SDRAM available\n");

	/*
	 * Now that we have DRAM mapped and working, we can
	 * relocate the code and continue running from DRAM.
	 *
	 * Reserve memory at end of RAM for (top down in that order):
	 *  - u-boot image
	 *  - heap for malloc()
	 *  - board info struct
	 *  - global data struct
	 *  - stack
	 */
	addr = CONFIG_SYS_SDRAM_BASE + sdram_size;
	monitor_len = __bss_end__ - _text;

	/*
	 * Reserve memory for u-boot code, data and bss.
	 * Round down to next 4 kB limit.
	 */
	addr -= monitor_len;
	addr &= ~(4096UL - 1);
	monitor_addr = addr;

	/* Reserve memory for malloc() */
	addr -= CONFIG_SYS_MALLOC_LEN;

#ifdef CONFIG_SYS_DMA_ALLOC_LEN
	/* Reserve DMA memory (must be cache aligned) */
	addr &= ~(CONFIG_SYS_DCACHE_LINESZ - 1);
	addr -= CONFIG_SYS_DMA_ALLOC_LEN;
#endif

#ifdef CONFIG_LCD
#ifdef CONFIG_FB_ADDR
	printf("LCD: Frame buffer allocated at preset 0x%08x\n",
	       CONFIG_FB_ADDR);
	gd->fb_base = (void *)CONFIG_FB_ADDR;
#else
	addr = lcd_setmem(addr);
	printf("LCD: Frame buffer allocated at 0x%08lx\n", addr);
	gd->fb_base = (void *)addr;
#endif /* CONFIG_FB_ADDR */
#endif /* CONFIG_LCD */

	/* Allocate a Board Info struct on a word boundary */
	addr -= sizeof(bd_t);
	addr &= ~3UL;
	gd->bd = bd = (bd_t *)addr;

	/* Allocate a new global data copy on a 8-byte boundary. */
	addr -= sizeof(gd_t);
	addr &= ~7UL;
	new_gd = (gd_t *)addr;

	/* And finally, a new, bigger stack. */
	new_sp = (unsigned long *)addr;
	gd->stack_end = addr;
	*(--new_sp) = 0;
	*(--new_sp) = 0;

	/*
	 * Initialize the board information struct with the
	 * information we have.
	 */
	bd->bi_dram[0].start = CONFIG_SYS_SDRAM_BASE;
	bd->bi_dram[0].size = sdram_size;
	bd->bi_baudrate = gd->baudrate;

	memcpy(new_gd, gd, sizeof(gd_t));

	relocate_code((unsigned long)new_sp, new_gd, monitor_addr);
}
Ejemplo n.º 25
0
int main(int argc, char* argv[]) {

	unsigned char ret;
	char c;
	char len;
	char i;
	char* annoyname = "Annoy_Light";
	char* stairname = "Stair_Light";

	DDRC = 0;
	PORTC = 0x7;
	unsigned char did = 1;

	// define direction of inputs and outputs
	// 1 for output, 0 for input
	// | for output, & for input
	DDRD = (1<<RELAY_STAIRS);
	DDRD |= (1<<RELAY_ANNOY);


	did = PINC & 0x7;

	serial_init();

	buf_index = 0;	
	transmit_flag = 0;	

//	FILE s=FDEV_SETUP_STREAM(send_char_serial,NULL,_FDEV_SETUP_WRITE);
//	stdout=&s;

//	sei();

	Device* annoydevice = createDevice(annoyname, 1, buffered_send_char);
	Device* stairdevice = createDevice(stairname, 1, buffered_send_char);
	
	setDeviceCName("Annoying Light", annoydevice);
	setDeviceCName("Stairs Light", stairdevice);
	setDeviceLocation(0, 0, 0, 0, annoydevice);
	setDeviceLocation(0, 0, 0, 0, stairdevice);
	
	addField(BOOL, "Light Status", 0, 1, 0, annoydevice);
	addField(BOOL, "Light Status", 0, 1, 0, stairdevice);

	while (1) {
		c = receive_char_serial();
		if (c == '\0') {
			if (receive_char_serial() == did) {
				serial_tx_enable();
				if (transmit_flag) {
					len = buf[0] + 1;
//					printf("sending packet %d\n", buf[3]);
					for (i = 0; i < len; i++) {
						send_char_serial(buf[i]);
					}
//					printf("bi:%d %d %d\n", buf_index, len, buf[3]);
					for (i = len; i < buf_index; i++) {
						buf[i-len] = buf[i];
					}
					buf_index -= len;
					if (buf_index == 0) {
						transmit_flag = 0;
					}
				} else {
					send_char_serial('\0');
				}
				serial_tx_disable();
			}
		} else {
			len = c;
			recvChar(len, annoydevice);
			recvChar(len, stairdevice);
			for (i = 0; i < len; i++) {
				c = receive_char_serial();
				recvChar(c, annoydevice);
				recvChar(c, stairdevice);
				if (shouldBreak(annoydevice)) break;
				if (shouldBreak(stairdevice)) break;
			}
		}
/*
		if (((r_front + 1) % MAX_LEN) != r_back) {
			r_front++;
			if (r_front == MAX_LEN) {
				r_front = 0;
			}
			recvChar(r_buf[r_front], device);
		}
*/

		if (hasChanged(0, annoydevice)) {
			ret = getBoolVal(0, annoydevice);
			if (ret) {
				RELAY_ANNOY_ON();
			} else {
				RELAY_ANNOY_OFF();
			}
		}
		if (hasChanged(0, stairdevice)) {
			ret = getBoolVal(0, stairdevice);
			if (ret) {
				RELAY_STAIRS_ON();
			} else {
				RELAY_STAIRS_OFF();
			}
		}
	}

	return 0;
}
Ejemplo n.º 26
0
/* C128-specific initialization.  */
int machine_specific_init(void)
{
    c128_log = log_open("C128");

    if (mem_load() < 0) {
        return -1;
    }

    if (z80mem_load() < 0) {
        return -1;
    }

    /* Setup trap handling.  */
    traps_init();

    /* Initialize serial traps.  */
    if (serial_init(c128_serial_traps) < 0) {
        return -1;
    }

    serial_trap_init(0xa4);
    serial_iec_bus_init();

    /* initialize RS232 handler */
    rs232drv_init();
    c64_rsuser_init();

    /* initialize print devices */
    printer_init();

    /* Initialize the tape emulation.  */
    machine_tape_init_c128();

    /* Initialize the datasette emulation.  */
    datasette_init();

    /* Fire up the hardware-level drive emulation.  */
    drive_init();

    /* Initialize autostart. FIXME: at least 0xa26 is only for 40 cols */
    autostart_init((CLOCK)(3 * C128_PAL_RFSH_PER_SEC * C128_PAL_CYCLES_PER_RFSH), 1, 0xa27, 0xe0, 0xec, 0xee);

    if (vdc_init() == NULL) {
        return -1;
    }

    if (vicii_init(VICII_EXTENDED) == NULL) {
        return -1;
    }

    cia1_init(machine_context.cia1);
    cia2_init(machine_context.cia2);

#ifndef COMMON_KBD
    /* Initialize the keyboard.  */
    if (c128_kbd_init() < 0) {
        return -1;
    }
#endif

    c64keyboard_init();

    c128_monitor_init();

    /* Initialize vsync and register our hook function.  */
    vsync_init(machine_vsync_hook);
    vsync_set_machine_parameter(machine_timing.rfsh_per_sec, machine_timing.cycles_per_sec);

    /* Initialize sound.  Notice that this does not really open the audio
       device yet.  */
    sound_init(machine_timing.cycles_per_sec, machine_timing.cycles_per_rfsh);

    /* Initialize keyboard buffer.  */
    kbdbuf_init(842, 208, 10, (CLOCK)(machine_timing.rfsh_per_sec * machine_timing.cycles_per_rfsh));

    /* Initialize the C128-specific part of the UI.  */
    c128ui_init();

#ifdef HAVE_MOUSE
    /* Initialize mouse support (if present).  */
    mouse_init();

    /* Initialize lightpen support and register VICII/VDC callbacks */
    lightpen_init();
    lightpen_register_timing_callback(vicii_lightpen_timing, 1);
    lightpen_register_timing_callback(vdc_lightpen_timing, 0);
    lightpen_register_trigger_callback(c128_trigger_light_pen);
#endif

    c64iec_init();
    c128fastiec_init();

    cartridge_init();

    mmu_init();

    machine_drive_stub();

#if defined (USE_XF86_EXTENSIONS) && (defined(USE_XF86_VIDMODE_EXT) || defined (HAVE_XRANDR))
    {
        /* set fullscreen if user used `-fullscreen' on cmdline 
           use VICII as default */
        int fs;

        resources_get_int("UseFullscreen", &fs);
        if (fs) {
            resources_get_int("40/80ColumnKey", &fs);
            if (fs == 1) {
                resources_set_int("VICIIFullscreen", 1);
            } else {
                resources_set_int("VDCFullscreen", 1);
            }
        }
    }
#endif

    return 0;
}
Ejemplo n.º 27
0
/*
 * Bootstrap-CPU start; we came from head.S
 */
void __no_return kernel_start(void)
{
	/* Before anything else, zero the bss section. As said by C99:
	 * “All objects with static storage duration shall be inited
	 * before program startup”, and that the implicit init is done
	 * with zero. Kernel assembly code also assumes a zeroed BSS
	 * space */
	clear_bss();

	/*
	 * Very-early setup: Do not call any code that will use
	 * printk(), `current', per-CPU vars, or a spin lock.
	 */

	setup_idt();

	schedulify_this_code_path(BOOTSTRAP);

	/*
	 * Memory Management init
	 */

	print_info();

	/* First, don't override the ramdisk area (if any) */
	ramdisk_init();

	/* Then discover our physical memory map .. */
	e820_init();

	/* and tokenize the available memory into allocatable pages */
	pagealloc_init();

	/* With the page allocator in place, git rid of our temporary
	 * early-boot page tables and setup dynamic permanent ones */
	vm_init();

	/* MM basics done, enable dynamic heap memory to kernel code
	 * early on .. */
	kmalloc_init();

	/*
	 * Secondary-CPUs startup
	 */

	/* Discover our secondary-CPUs and system IRQs layout before
	 * initializing the local APICs */
	mptables_init();

	/* Remap and mask the PIC; it's just a disturbance */
	serial_init();
	pic_init();

	/* Initialize the APICs (and map their MMIO regs) before enabling
	 * IRQs, and before firing other cores using Inter-CPU Interrupts */
	apic_init();
	ioapic_init();

	/* SMP infrastructure ready, fire the CPUs! */
	smpboot_init();

	keyboard_init();

	/* Startup finished, roll-in the scheduler! */
	sched_init();
	local_irq_enable();

	/*
	 * Second part of kernel initialization (Scheduler is now on!)
	 */

	ext2_init();

	// Signal the secondary cores to run their own test-cases code.
	// They've been waiting for us (thread 0) till all of kernel
	// subsystems has been properly initialized.  Wait No More!
	smpboot_trigger_secondary_cores_testcases();

	run_test_cases();
	halt();
}
Ejemplo n.º 28
0
static void real_main2 (int argc, char **argv)
{
#if defined (NATMEM_OFFSET) && defined( _WIN32 ) && !defined( NO_WIN32_EXCEPTION_HANDLER )
    extern int EvalException ( LPEXCEPTION_POINTERS blah, int n_except );
    __try
#endif
    {

    if (! graphics_setup ()) {
	exit (1);
    }

    if (restart_config[0]) {
#ifdef FILESYS
	free_mountinfo (currprefs.mountinfo);
        currprefs.mountinfo = alloc_mountinfo ();
#endif
	default_prefs (&currprefs, 0);
	fix_options ();
    }

#ifdef NATMEM_OFFSET
    init_shm ();
#endif

#ifdef FILESYS
    rtarea_init ();
    hardfile_install ();
#endif

    if (restart_config[0])
        parse_cmdline_and_init_file (argc, argv);
    else
	currprefs = changed_prefs;

    uae_inithrtimer ();
    sleep_test ();

    machdep_init ();

    if (! setup_sound ()) {
	write_log ("Sound driver unavailable: Sound output disabled\n");
	currprefs.produce_sound = 0;
    }
    inputdevice_init ();

    changed_prefs = currprefs;
    no_gui = ! currprefs.start_gui;

    if (restart_program == 2)
	no_gui = 1;
    else if (restart_program == 3)
	no_gui = 0;

    if (! no_gui) {
	int err = gui_init ();
	struct uaedev_mount_info *mi = currprefs.mountinfo;
	currprefs = changed_prefs;
	currprefs.mountinfo = mi;
	if (err == -1) {
	    write_log ("Failed to initialize the GUI\n");
	    if (restart_program == 3) {
	       restart_program = 0;
	       return;
	    }
	} else if (err == -2) {
	    restart_program = 0;
	    return;
	}
    }

    restart_program = 0;

#ifdef JIT
    if (!(( currprefs.cpu_level >= 2 ) && ( currprefs.address_space_24 == 0 ) && ( currprefs.cachesize )))
	canbang = 0;
#endif

#ifdef _WIN32
    logging_init(); /* Yes, we call this twice - the first case handles when the user has loaded
		       a config using the cmd-line.  This case handles loads through the GUI. */
#endif
    fix_options ();
    changed_prefs = currprefs;

#ifdef SAVESTATE
    savestate_init ();
#endif
#ifdef SCSIEMU
    scsidev_install ();
#endif
#ifdef AUTOCONFIG
    /* Install resident module to get 8MB chipmem, if requested */
    rtarea_setup ();
#endif

    keybuf_init (); /* Must come after init_joystick */

#ifdef AUTOCONFIG
    expansion_init ();
#endif
    memory_init ();
    memory_reset ();

#ifdef FILESYS
    filesys_install ();
#endif
#ifdef AUTOCONFIG
    bsdlib_install ();
    emulib_install ();
    uaeexe_install ();
    native2amiga_install ();
#endif

    if (custom_init ()) { /* Must come after memory_init */
#ifdef SERIAL_PORT
	serial_init ();
#endif
	DISK_init ();

	reset_frame_rate_hack ();
	init_m68k(); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init ()) {

#ifdef DEBUGGER
	    setup_brkhandler ();

	    if (currprefs.start_debugger && debuggable ())
		activate_debugger ();
#endif

#ifdef WIN32
#ifdef FILESYS
	    filesys_init (); /* New function, to do 'add_filesys_unit()' calls at start-up */
#endif
#endif
	    if (sound_available && currprefs.produce_sound > 1 && ! init_audio ()) {
		write_log ("Sound driver unavailable: Sound output disabled\n");
		currprefs.produce_sound = 0;
	    }

	    start_program ();
	}
    }

    }
#if defined (NATMEM_OFFSET) && defined( _WIN32 ) && !defined( NO_WIN32_EXCEPTION_HANDLER )
    __except( EvalException( GetExceptionInformation(), GetExceptionCode() ) )
    {
	// EvalException does the good stuff...
    }
#endif
}
Ejemplo n.º 29
0
int 
main(void){
	
	SCS |= 0x01;
	
	FIODIR0 = 0;	/* Just to make sure that all pins on Port0 are input. */
	
	/* The following pins are output: */
	FIODIR0 |= ((1<<21) | BACKLIGHT_PWM_PIN | SOUND_ENABLE_PIN | (1<<6));
	
	/* TODO what is this pin for ? */
	FIODIR0 |= (1<<12);
	FIOSET0 = (1<<12);

	setSpeed(SPEED_30);
		
	rand_seed(13); 				// initialize the random number generator
	
	/* Initialize the kernel. Kernel is not running yet */
	kernel_init();

	/* Initialize the display */
	lcd_init(0);
	
	/* Initialize the serial port */
	serial_init(38400);
	task_add(&serial_out);					// Task 0
	
	/* Enable IRQs. Now IRQ service routines start to run */
	enableIRQ();
	
	/* Enable radio communication */
	RF_init();								// Task 1 == produce_send_token)

	/* Initialize backlight task */
	inactivity_cnt = 0;		// consider power on to be a user activity
	task_add(&backl_proc);					// Task 2
	startPWMIRQ();

	/* Initialize keyboard handling */
	key_init();								// Task 3 == key_scan()

	/* Build an initial model of the internal and external state of the world */
	model_init();							// Task 4 == update_playtime()
	
	/* Show something to the user depending on model */
	mainscreen_init();						// Task 5 == win_scroll_all()
	
	dbg("RESET");
	
	/* Start the controller task 
		- keeps model up to date
		- starts actions according to model
		- shows relevant information on the screen
	*/
	task_add(&controller);					// Task 6
											// Task 7 == assemble_line()
	
	/* Start the kernel scheduler */
	while(1){
		schedule();
	};

	return 0;
}
Ejemplo n.º 30
0
void main(uint32_t magic, struct multiboot_info *mbi, 
          uintptr_t esp, uintptr_t stack_end)
{
    stack_start = esp;
    stack_size = stack_end - stack_start;

    vga_driver = vga_init();
    com_driver = serial_init();
    logging_init(vga_driver, com_driver);
        
    assert(magic == MULTIBOOT_MAGIC);
    assert(mbi->flags & MULTIBOOT_LOADER);
    kprintf(INFO, "\033\012Toutatis kernel booting from %s\033\017\n", 
            (char *)(mbi->boot_loader_name + (uint32_t)&kernel_voffset));

    arch_init();

    initrd_init(mbi); 

    assert(mbi->flags & MULTIBOOT_MEMINFO);
    paging_init((mbi->mem_lower + mbi->mem_upper) * 1024);
    paging_mark_reserved((uint32_t)mbi - (uint32_t)&kernel_voffset);

    assert(mbi->flags & MULTIBOOT_MMAP);
    for (mmap_entry_t *mmap = (mmap_entry_t *)(mbi->mmap_addr + (uint32_t)&kernel_voffset);
        (uint32_t)mmap < mbi->mmap_addr + (uint32_t)&kernel_voffset + mbi->mmap_length;
        mmap = (mmap_entry_t *)((uint32_t)mmap + mmap->size + sizeof(mmap->size))) {
        if (mmap->type == 2) {
            for (uint64_t i = 0; i < mmap->length; i += FRAME_SIZE) {
                paging_mark_reserved((mmap->addr + i) & 0xfffff000);
            }
        }
    }
    paging_finalize();

    void *p1 = kmalloc(8);
    void *p2 = kmalloc(8);
    *((char *)p1) = 'a';
    kprintf(INFO, "p1 @ 0x%x\n", (uint32_t)p1);
    kprintf(INFO, "p2 @ 0x%x\n", (uint32_t)p2);
    kfree(p2);
    kfree(p1);
    void *p3 = kmalloc(16);
    kprintf(INFO, "p3 @ 0x%x\n", (uint32_t)p3);
    uintptr_t phys;
    void *p4 = kmalloc_ap(0x1a0000, &phys);
    memset(p4, 0, 0x1a0000);
    *((char *)p4) = 'z';
    kprintf(INFO, "p4 @ 0x%x phys = %x\n", (uint32_t)p4, phys);
    void *p5 = kmalloc(0x02);
    kprintf(INFO, "p5 @ 0x%x\n", (uint32_t)p5);
    kfree(p5);
    kfree(p4);
    kfree(p3);

    print_mmap(mbi);

    syscall_init();

    scheduling_init();

    keyboard_init();

    process_t *proc1 = create_process("Process 1", 1);
    process_t *proc2 = create_process("Process 2", 1);
    process_t *proc3 = create_process("Process 3", 1);

    process_t *procs[] = { proc1, proc2, proc3 };
            
    unsigned int k = 0;
    unsigned int off = 0;
    for (k = 0; k < 10; ++k) {
        if (!create_thread(procs[k % 3], func2, (void *)(off + 80*2), 1, 0, 0)) {
            kprintf(INFO, "Oups\n");
            stop();
        }
        if (!create_thread(procs[k % 3], func1, (void *)k, 1, 1, 0)) {
            kprintf(INFO, "Oups\n");
            stop();
        }
        off += 2;
    }

    //create_thread(proc1, func3, (void *)0, 1, 1, 1);

    k = 0;
    unsigned int i = 0;
    off = 0;
    for (;;) {
        uint16_t *video = (uint16_t *)(0xc00b8000 + 80);
        *video = (uint16_t)alph[i++ % sizeof(alph)] | 0x0f00;
        
        if (k % 1 == 0) {
            //set_pos(0, 23);
            //vga_print_dec(k);
            //kprintf(INFO, "mem used: %6x num threads:%3d   \n", mem_used(kheap), get_num_threads());
        }
        /*
        if (!create_thread(proc1, func2, (void *)(off + 80*2), 1, 0, 0)) {
            kprintf(INFO, "Oups\n");
            break;
        }
        off += 2;
        off %= (60 * (25-2));
        */
        char c = keyboard_lastchar();
        if (c == 'u') {
            create_thread(proc1, func1, (void *)5, 1, 1, 0);
        } else if (c == 'k') {
            create_thread(proc1, func2, (void *)off, 1, 0, 0);
            off += 2;
        }
        ++k;
    }

    serial_terminate();
    stop();
}