int main(int argc, char* argv[]) { // ************ Déclarations ************ u16 text[4]={0xcdef,0x89ab,0x4567,0x0123}; u16 k128[8] = {0x0011, 0x2233, 0x4455, 0x6677, 0x8899, 0xaabb, 0xccdd, 0xeeff}; u16 wk[4]; u16 rk[2*NBROUND]; START_ENCRYPT(); // **************************************** // Test clé 128 bits // **************************************** wKS_128(k128,wk); rKS_128(k128,rk); // ************ Vérification chiffrement ************ Gr(text, wk, rk); #ifdef PRINT uart1_init(); printf("Verification avec la cle de 128 bits \n\nLe chiffrement donne : \n"); printf("5ec42cea 657b89ff\n"); ps(text); #endif // ************ Controle du déchiffrement ************ START_DECRYPT(); wKS_128(k128,wk); rKS_128(k128,rk); Gr_1(text, wk, rk); #ifdef PRINT printf("Controle du dechiffrement : \n\n"); ps(text); #endif END_EXPE(); return 0; }
/*---------------------------------------------------------------------------*/ #if WITH_TINYOS_AUTO_IDS uint16_t TOS_NODE_ID = 0x1234; /* non-zero */ uint16_t TOS_LOCAL_ADDRESS = 0x1234; /* non-zero */ #endif /* WITH_TINYOS_AUTO_IDS */ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_on(LEDS_RED); uart1_init(BAUD2UBR(115200)); /* Must come before first printf */ leds_on(LEDS_GREEN); ds2411_init(); /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible with an Ethernet MAC address - byte 0 (byte 2 in the DS ID) cannot be odd. */ ds2411_id[2] &= 0xfe; leds_on(LEDS_BLUE); xmem_init(); leds_off(LEDS_RED); rtimer_init(); /* * Hardware initialization done! */ /* Initialize energest first (but after rtimer) */ energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); #if WITH_TINYOS_AUTO_IDS node_id = TOS_NODE_ID; #else /* WITH_TINYOS_AUTO_IDS */ /* Restore node id if such has been stored in external mem */ node_id_restore(); #endif /* WITH_TINYOS_AUTO_IDS */ /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */ #ifdef IEEE_802154_MAC_ADDRESS { uint8_t ieee[] = IEEE_802154_MAC_ADDRESS; memcpy(ds2411_id, ieee, sizeof(uip_lladdr.addr)); ds2411_id[7] = node_id & 0xff; } #endif random_init(ds2411_id[0] + node_id); leds_off(LEDS_BLUE); /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); ctimer_init(); #if NETSTACK_CONF_WITH_IPV4 slip_arch_init(BAUD2UBR(115200)); #endif /* NETSTACK_CONF_WITH_IPV4 */ init_platform(); set_rime_addr(); cc2420_init(); { uint8_t longaddr[8]; uint16_t shortaddr; shortaddr = (linkaddr_node_addr.u8[0] << 8) + linkaddr_node_addr.u8[1]; memset(longaddr, 0, sizeof(longaddr)); linkaddr_copy((linkaddr_t *)&longaddr, &linkaddr_node_addr); PRINTF("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x ", longaddr[0], longaddr[1], longaddr[2], longaddr[3], longaddr[4], longaddr[5], longaddr[6], longaddr[7]); cc2420_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); } PRINTF(CONTIKI_VERSION_STRING " started. "); if(node_id > 0) { PRINTF("Node id is set to %u.\n", node_id); } else { PRINTF("Node id is not set.\n"); } /* PRINTF("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", ds2411_id[0], ds2411_id[1], ds2411_id[2], ds2411_id[3], ds2411_id[4], ds2411_id[5], ds2411_id[6], ds2411_id[7]);*/ #if NETSTACK_CONF_WITH_IPV6 memcpy(&uip_lladdr.addr, ds2411_id, sizeof(uip_lladdr.addr)); /* Setup nullmac-like MAC for 802.15.4 */ /* sicslowpan_init(sicslowmac_init(&cc2420_driver)); */ /* PRINTF(" %s channel %u\n", sicslowmac_driver.name, CC2420_CONF_CCA_THRESH); */ /* Setup X-MAC for 802.15.4 */ queuebuf_init(); NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_LLSEC.init(); NETSTACK_NETWORK.init(); PRINTF("%s %s %s, channel check rate %lu Hz, radio channel %u, CCA threshold %i\n", NETSTACK_LLSEC.name, NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval()), CC2420_CONF_CHANNEL, CC2420_CONF_CCA_THRESH); process_start(&tcpip_process, NULL); #if DEBUG PRINTF("Tentative link-local IPv6 address "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { PRINTF("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } PRINTF("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } #endif /* DEBUG */ if(!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, UIP_DS6_DEFAULT_PREFIX, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); PRINTF("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { PRINTF("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } PRINTF("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #else /* NETSTACK_CONF_WITH_IPV6 */ NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_LLSEC.init(); NETSTACK_NETWORK.init(); PRINTF("%s %s %s, channel check rate %lu Hz, radio channel %u\n", NETSTACK_LLSEC.name, NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1: NETSTACK_RDC.channel_check_interval()), CC2420_CONF_CHANNEL); #endif /* NETSTACK_CONF_WITH_IPV6 */ #if !NETSTACK_CONF_WITH_IPV4 && !NETSTACK_CONF_WITH_IPV6 uart1_set_input(serial_line_input_byte); serial_line_init(); #endif leds_off(LEDS_GREEN); #if TIMESYNCH_CONF_ENABLED timesynch_init(); timesynch_set_authority_level((linkaddr_node_addr.u8[0] << 4) + 16); #endif /* TIMESYNCH_CONF_ENABLED */ #if NETSTACK_CONF_WITH_IPV4 process_start(&tcpip_process, NULL); process_start(&uip_fw_process, NULL); /* Start IP output */ process_start(&slip_process, NULL); slip_set_input_callback(set_gateway); { uip_ipaddr_t hostaddr, netmask; uip_init(); uip_ipaddr(&hostaddr, 172,16, linkaddr_node_addr.u8[0],linkaddr_node_addr.u8[1]); uip_ipaddr(&netmask, 255,255,0,0); uip_ipaddr_copy(&meshif.ipaddr, &hostaddr); uip_sethostaddr(&hostaddr); uip_setnetmask(&netmask); uip_over_mesh_set_net(&hostaddr, &netmask); /* uip_fw_register(&slipif);*/ uip_over_mesh_set_gateway_netif(&slipif); uip_fw_default(&meshif); uip_over_mesh_init(UIP_OVER_MESH_CHANNEL); PRINTF("uIP started with IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&hostaddr)); } #endif /* NETSTACK_CONF_WITH_IPV4 */ watchdog_start(); #if !PROCESS_CONF_NO_PROCESS_NAMES print_processes(autostart_processes); #endif /* !PROCESS_CONF_NO_PROCESS_NAMES */ autostart_start(autostart_processes); /* * This is the scheduler loop. */ #if DCOSYNCH_CONF_ENABLED timer_set(&mgt_timer, DCOSYNCH_PERIOD * CLOCK_SECOND); #endif /* watchdog_stop();*/ while(1) { int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); /* * Idle processing. */ int s = splhigh(); /* Disable interrupts. */ /* uart1_active is for avoiding LPM3 when still sending or receiving */ if(process_nevents() != 0 || uart1_active()) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; #if DCOSYNCH_CONF_ENABLED /* before going down to sleep possibly do some management */ if(timer_expired(&mgt_timer)) { watchdog_periodic(); timer_reset(&mgt_timer); msp430_sync_dco(); #if CC2420_CONF_SFD_TIMESTAMPS cc2420_arch_sfd_init(); #endif /* CC2420_CONF_SFD_TIMESTAMPS */ } #endif /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_SWITCH(ENERGEST_TYPE_CPU, ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); watchdog_stop(); /* check if the DCO needs to be on - if so - only LPM 1 */ if (msp430_dco_required) { _BIS_SR(GIE | CPUOFF); /* LPM1 sleep for DMA to work!. */ } else { _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This statement will block until the CPU is woken up by an interrupt that sets the wake up flag. */ } /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); watchdog_start(); ENERGEST_SWITCH(ENERGEST_TYPE_LPM, ENERGEST_TYPE_CPU); } } return 0; }
///////////////// // main routine ///////////////// void main (void) { uint8_t Rx, loop; ///////////////// // init peripherals ///////////////// // disable interrupts DISABLE_INTERRUPTS; // switch to 16MHz (default is 2MHz) CLK.CKDIVR.byte = 0x00; // configure green LED pin (PH2) gpio_init(&PORT_H, PIN_2, OUTPUT_PUSHPULL_FAST); // init timer TIM4 for 1ms clock with interrupts tim4_init(); // init pins for UART1 Rx(=PA4) and Tx(=PA5) gpio_init(&PORT_A, PIN_4, INPUT_PULLUP_NOEXINT); gpio_init(&PORT_A, PIN_5, OUTPUT_PUSHPULL_FAST); // init UART1 (connected to PC on muBoard) uart1_init(115200L); // enable interrupts ENABLE_INTERRUPTS; ///////////////// // main loop ///////////////// loop = 0; while (1) { // if byte received via UART1, echo byte+1 while (uart1_check_Rx()) { Rx = uart1_receive(); // grab oldest byte putchar((char) (Rx+1)); } // every 1ms do if (g_flagClock) { g_flagClock = 0; // every 500ms toggle LED & print text if (g_clock > 500) { g_clock = 0; // toggle LED PORT_H.ODR.bit.b2 ^= 1; // print something to UART (blocking) printf("loop: %d\n", (int) (++loop)); } // loop 500ms } // loop 1ms } // main loop } // main
/*---------------------------------------------------------------------------*/ int main(void) { /* * Initalize hardware. */ halInit(); clock_init(); uart1_init(115200); /* Led initialization */ leds_init(); INTERRUPTS_ON(); PRINTF("\r\nStarting "); PRINTF(CONTIKI_VERSION_STRING); PRINTF(" on %s\r\n", boardDescription->name); boardPrintStringDescription(); PRINTF("\r\n"); /* * Initialize Contiki and our processes. */ process_init(); #if WITH_SERIAL_LINE_INPUT uart1_set_input(serial_line_input_byte); serial_line_init(); #endif /* rtimer and ctimer should be initialized before radio duty cycling layers */ rtimer_init(); /* etimer_process should be initialized before ctimer */ process_start(&etimer_process, NULL); ctimer_init(); netstack_init(); set_rime_addr(); printf("%s %s, channel check rate %lu Hz\n", NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval())); printf("802.15.4 PAN ID 0x%x, EUI-%d:", IEEE802154_CONF_PANID, UIP_CONF_LL_802154?64:16); uip_debug_lladdr_print(&linkaddr_node_addr); printf(", radio channel %u\n", RF_CHANNEL); procinit_init(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); /* Set the Clear Channel Assessment (CCA) threshold of the radio. The CCA threshold is used both for sending packets and for waking up ContikiMAC nodes. If the CCA threshold is too high, ContikiMAC will not wake up from neighbor transmissions. If the CCA threshold is too low, transmissions will be too restrictive and no packets will be sent. DEFAULT_RADIO_CCA_THRESHOLD is defined in this file. */ ST_RadioSetEdCcaThreshold(DEFAULT_RADIO_CCA_THRESHOLD); autostart_start(autostart_processes); #if UIP_CONF_IPV6 printf("Tentative link-local IPv6 address "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { printf("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } if(!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); printf("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { printf("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #endif /* UIP_CONF_IPV6 */ watchdog_start(); while(1) { int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); ENERGEST_OFF(ENERGEST_TYPE_CPU); /* watchdog_stop(); */ ENERGEST_ON(ENERGEST_TYPE_LPM); /* Go to idle mode. */ halSleepWithOptions(SLEEPMODE_IDLE,0); /* We are awake. */ /* watchdog_start(); */ ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } }
int main() { /* receive enable aktivieren, data deaktivieren */ DDRD = (1 << PD4) | (1 << PD5) | (1 << PD6) | (1 << PD7); PORTD = (1 << PD6); /* Ziffernfeld-pins (PA0-PA7) als Eingang schalten */ DDRA = 0; PORTA = 0xFF; /* LEDs und Summer als Ausgang schalten */ DDRB = (1 << PB0) | (1 << PB1) | (1 << PB2) | (1 << PB3) | (1 << PB4); /* Selbst-Test: Alle LEDs hintereinander für 250 ms aktivieren, ebenso den Summer */ PORTB = 0; _delay_ms(250); PORTB = (1 << PB0); _delay_ms(250); PORTB = (1 << PB1); _delay_ms(250); PORTB = (1 << PB2); _delay_ms(250); PORTB = (1 << PB3); _delay_ms(250); PORTB = (1 << PB4); _delay_ms(250); PORTB = 0; memset((void*)ibuffer, '\0', sizeof(ibuffer)); uart2_init(); uart2_puts("Initializing RS485\r\n"); uart1_init(); uart2_puts("Waiting for LCD...\r\n"); lcd_init(LCD_DISP_ON); uart2_puts("initialized LCD\r\n"); lcd_clrscr(); lcd_puts("pinpad ready\nself-test ok"); uart2_puts("done. now accepting cmds\r\n"); /* Timer aufsetzen: nach 1 ms soll der Interrupt ausgelöst werden. */ /* 8 bit counter (TIMER0) */ /* normal mode */ TCCR0A = 0; /* CLK/64 */ TCCR0B = (1 << CS01) | (1 << CS00); /* timer ticks: 250 */ TCNT0 = 5; TIMSK0 = (1 << TOIE0); TIFR0 = (1 << TOV0); sei(); int c; char keypress_buffer[COMMAND_BUFFER_SIZE + 2] = "^PAD c $\r\n"; char bufcopy[COMMAND_BUFFER_SIZE]; for (;;) { /* Handle commands received on the UART */ if (ibuffer[sizeof(ibuffer)-2] == '$') { strncpy(bufcopy, (const char *)ibuffer, sizeof(bufcopy)); /* change the end of packet marker in memory so that the next * packet will be accepted by the RX interrupt handler */ ibuffer[sizeof(ibuffer)-2] = '\0'; handle_command(bufcopy); } uint8_t sample = (PINA | (1 << 3)); bool button_debounced = true; for (c = 0; c < sizeof(lookup_table) / sizeof(struct lookup_entry); c++) { if (sample != lookup_table[c].state || lookup_table[c].debounce != DEBOUNCE_MS) { button_debounced = false; continue; } keypress_buffer[5] = lookup_table[c].key; uart_puts(keypress_buffer); lookup_table[c].debounce = DEBOUNCE_MS+1; } if (button_debounced) { _delay_ms(80); } } }
int main(int argc, char** argv) { int i,r; int rbuf[20]; int data; int format; processor_init(); uart1_init(); uart2_init(); TRISDbits.TRISD0 = 0; TRISBbits.TRISB12 = 0; TRISBbits.TRISB11 = 0; TRISBbits.TRISB0 = 1; TRISBbits.TRISB1 = 1; TRISBbits.TRISB2 = 1; ADPCFGbits.PCFG0 = 1; ADPCFGbits.PCFG1 = 1; ADPCFGbits.PCFG2 = 1; ledstatus = 0; cb = buffer_init(); while(1) { if ( buffer_full(cb) ) /* Signal buffer overflow */ PORTDbits.RD0 = 1; if ( !buffer_empty(cb) ) { int data; /* Get a 'char' from the buffer */ buffer_read(cb, &data); if ( data & 0x0100 ) { format = (~PORTB) & 0x3; /* Print the last sentence and begin reading the new one */ PORTBbits.RB12 = 1; //transmit_raw_buffer(rbuf, r); process_seatalk_string(rbuf, r, format); PORTBbits.RB12 = 0; r = 0; rbuf[r++] = data; } else { /* Accumulate data into the buffer */ //printf("rx: %x\n",data); rbuf[r++] = data; } } } return (EXIT_SUCCESS); }
/** * \brief The main application * * This application logs visible and infrared irradiance levels to an SD card * * * \note * */ int main(void) { uint8_t ct, swDnUp, swBbIr; uint8_t errSD, cnt, r; uint16_t cntout = 0; strJSON[0] = '\0'; // "erase" the string DDRD &= ~(1<<5); // make the Bluetooth connection monitor pin an input PORTD &= ~(1<<5); // disable internal pull-up resistor DDRD |= (1<<4); // make Bluetooth power control an output DDRD |= (1<<7); // make Bluetooth baud rate control an output DDRB |= (1<<1); // make GPS power control an output DDRB |= (1<<0); // make GPS on/off an output GPS_power_off; // default to power off GPS_On_Off_Low; // brief (~200ms) high pulse turns GPS on/off BT_power_off(); // BT_baud_9600(); BT_baud_115k(); // cli(); // setupDiagnostics(); // need heartbeat timer to correctly turn SD power off (may work around this) // // also may help with power control tracking while testing dead battery re-charge // sei(); // turnSDCardPowerOff(); // force SD card power off, and pins in lowest power modes if (!(PRR0 & (1<<PRSPI))) // is SPI power on (Pwr Save bit clear)? { if (SPCR & (1<<SPE)) // is SPI enabled? { SPCR &= ~(1<<SPE); // disable SPI } PRR0 |= (1<<PRSPI); // turn off power to SPI module, stop its clock } DESELECT(); DDR_SPI &= ~((1<<DD_MOSI)|(1<<DD_SCK)); // change SPI output lines MOSI and SCK into inputs // pins might source current momentarily // set port bits to 0, disable any internal pull-ups; tri-state the pins SPI_PORT &= ~((1<<SPI_MOSI_BIT)|(1<<SPI_SCK_BIT)|(1<<SPI_MISO_BIT)); // MISO was already an input SD_CS_DD &= ~(1<<SD_CS_BIT); // change SS to an input, momentarily sources current through internal pull-up SD_CS_PORT &= ~(1<<SD_CS_BIT); // set port bit to zero, tri-state the input SD_PWR_DD |= (1<<SD_PWR_BIT); // Turns on PWR pin as output SD_PWR_PORT |= (1<<SD_PWR_BIT); // Drive PWR pin high; this will turn FET off SD_PWR_DD &= ~(1<<SD_PWR_BIT); // change PWR pin to an input // internal pull-up momentarily pulls high, along with external pull-up SD_PWR_PORT &= ~(1<<SD_PWR_BIT); // tri-state the pin; external pull-up keeps FET off // Stat |= STA_NOINIT; // Set STA_NOINIT // try allowing the following on first power-up, even if cell is barely charged cli(); setupDiagnostics(); uart0_init(); initFlags |= (1<<initUART0); uart1_init(); initFlags |= (1<<initUART1); sei(); // main osc is not tuned yet, can't do that until I2C is working commandBuffer[0] = '\0'; // "empty" the command buffer commandBufferPtr = commandBuffer; stateFlags1 |= (1<<writeDataHeaders); // write column headers at least once on startup intTmp1 = readCellVoltage(&cellVoltageReading); I2C_Init(); // enable I2C initFlags |= (1<<initI2C); if (initFlags & (1<<initUART0)) outputStringToUART0("\r\n UART0 Initialized\r\n"); if (initFlags & (1<<initUART1)) outputStringToUART1("\r\n UART1 Initialized\r\n"); if (initFlags & (1<<initI2C)) outputStringToUART0("\r\n I2C_Init completed\r\n"); // test the I2C bus, if it doesn't work nothing much else will intTmp1 = I2C_Start(); if (intTmp1 == 0) { // I2C start timed out // we are hung, go into SOS mode PRR0 |= (1<<PRTWI); // disable I2C, turn module power off (set Power Reduction bit) DDRC &= 0b00111111; // make SCL and SDA pins inputs so we can read them PORTC &= 0b00111111; // disable internal pull-up resistors // uart0 is about all we've got to talk on UBRR0 = 207; // 0.2% error BAUD_4800_2X_OSC_8MHZ, assume main osc untuned 8MHz Timer2 = 0; while (1) { // mostly, fast-blink the pilot light for (Timer1 = 10; Timer1; ); // Wait for 100ms PORTA |= (0b00000100); // set pilot light on for (Timer1 = 10; Timer1; ); // Wait for 100ms PORTA &= ~(0b00000100); // turn off bit 2, pilot light blinkey if (!Timer2) { // about every 3 seconds, send diagnostics cli(); // temporarily disable interrupts to prevent Timer3 from // changing the count partway through stateFlags1 |= (1<<isRoused); // enable uart output rouseCountdown = 100; // hold the Rouse flag on long enough for output sei(); len = sprintf(str, "\n\r I2C bus start failure: SCL = %i, SDA = %i \n\r", (PINC & 1), ((PINC & 2) ? 1 : 0)); outputStringToUART0(str); Timer2 = 1000; // ~3 sec to next message } } } else { // I2C bus started OK intTmp1 = I2C_Write(0); // send the generic device address so devices release the bus I2C_Stop(); // release I2C bus and continue } intTmp1 = rtc_readTime(&dt_RTC); strcat(strJSON, "\r\n{\"timechange\":{\"from\":\""); datetime_getstring(datetime_string, &dt_RTC); strcat(strJSON, datetime_string); strcat(strJSON, "\",\"to\":\""); if (dt_RTC.year) { // 0 on power up, otherwise must already have been set rtcStatus = rtcTimeRetained; strcat(strJSON, datetime_string); strcat(strJSON, "\",\"by\":\"retained\"}}\r\n"); } else { // RTC year = 0 on power up, clock needs to be set rtc_setdefault(); if (!rtc_setTime(&dt_RTC)) { rtcStatus = rtcTimeSetToDefault; datetime_getstring(datetime_string, &dt_RTC); strcat(strJSON, datetime_string); strcat(strJSON, "\",\"by\":\"default\"}}\r\n"); } else { rtcStatus = rtcTimeSetFailed; strcat(strJSON, datetime_string); strcat(strJSON, "\",\"by\":\"failure\"}}\r\n"); } } stateFlags1 |= (1<<writeJSONMsg); // log JSON message on next SD card write timeFlags &= ~(1<<nextAlarmSet); // alarm not set yet irradFlags |= (1<<isDark); // set the Dark flag, default till full-power initializations passed // tune uC osc down to 7.3728 MHz, implement 115200 baud // need I2C to do this tuneMainOsc(); r = initializeADXL345(); if (r) { len = sprintf(str, "\n\r ADXL345 initialize failed: %d\n\r\n\r", r); outputStringToUART0(str); } else { initFlags |= (1<<initAccelerometer); outputStringToUART0("\r\n ADXL345 initialized\r\n"); } switch (rtcStatus) { case rtcTimeRetained: outputStringToBothUARTs("\n\r time retained through uC reset\n\r"); break; case rtcTimeSetToDefault: outputStringToBothUARTs("\n\r time set to default, now elapsed to "); datetime_getstring(datetime_string, &dt_RTC); outputStringToBothUARTs(datetime_string); outputStringToBothUARTs("\n\r\n\r"); break; case rtcTimeSetFailed: outputStringToBothUARTs("\n\r could not set Real Time Clock \n\r"); break; } // attempt to read/write the time zone; will retry later if e.g. power too low syncTimeZone(); stateFlags1 |= (1<<isRoused); // force on for testing, enable UART output // for (Timer1 = 3; Timer1; ); // Wait for 30ms outputStringToUART0("\r\n test\r\n"); // for (Timer1 = 3; Timer1; ); // Wait for 30ms outputStringToUART0("\r\n test\r\n"); // for (Timer1 = 3; Timer1; ); // Wait for 30ms outputStringToUART0("\r\n test\r\n"); // for (Timer1 = 3; Timer1; ); // Wait for 30ms outputStringToBothUARTs("\n\r Power good \n\r\n\r"); /* // try to adjust the uC clock frequency // first step, measure the uC clock, relative to the RTC, which latter should be very accurate // eventually put this in a more reasonable place, but for now right here before main loop // go into uC clock adjust mode outputStringToUART0("\r\n going into uC adjust mode\r\n"); timeFlags &= ~(1<<nextAlarmSet); // clear flag disableRTCInterrupt(); intTmp1 = rtc_enableSqWave(); // PRTIM1 make sure power reduction register bit if off so timers run // go back into normal timekeeping mode outputStringToUART0("\r\n returning to timekeeping mode\r\n"); if (!(timeFlags & (1<<nextAlarmSet))) { intTmp1 = rtc_setupNextAlarm(&dt_CurAlarm); timeFlags |= (1<<nextAlarmSet); } */ while (1) { // main program loop // code that will only run once when/if cell voltage first goes above threshold, // sufficient to run initializations and modules that take more power if (!(stateFlags1 & (1<<reachedFullPower))) { if (cellVoltageReading.adcWholeWord > CELL_VOLTAGE_GOOD_FOR_STARTUP) { stateFlags1 |= (1<<reachedFullPower); // flag, so this loop does not happen again till next reset if (cellVoltageReading.adcWholeWord > CELL_VOLTAGE_GOOD_FOR_ALL_FUNCTIONS) { // probably, somebody has just popped a fresh battery in, and wants to set up this device stayRoused(18000); // keep system roused for 3 minutes (180 sec) for diagnostic output } else { // probably, battery has slowly charged from dead, and nobody is here watching // long diagnostics would just waste power for no good reason stayRoused(300); // only briefly, 3 seconds, then go into low power mode } if (cellVoltageReading.adcWholeWord > CELL_VOLTAGE_GOOD_FOR_ALL_FUNCTIONS) { // it's likely someone is setting up this device with a fresh battery tuneMainOsc(); // re-tune, in case clock was slow on first low-power startup keepBluetoothPowered(180); // start with Bluetooth power on for 3 minutes } } // end test CELL_VOLTAGE_GOOD_FOR_STARTUP } // end test reachedFullPower flag // end of segment that runs only once, when Full Power first achieved // beginning of loop that runs repeatedly // tests of normal operation checkCriticalPower(); if (stateFlags1 & (1<<reachedFullPower)) { // only run this after cell has charged to full power and modules initialized if (motionFlags & (1<<tapDetected)) { outputStringToUART0("\n\r Tap detected \n\r\n\r"); if (stateFlags1 & (1<<isRoused)) { // if tap detected while already roused stayRoused(12000); // 2 minutes (120 seconds) tuneMainOsc(); // re-tune, in case clock was slow on first low-power startup keepBluetoothPowered(120); // try for two minutes to get a Bluetooth connection } motionFlags &= ~(1<<tapDetected); } if (stateFlags1 & (1<<isRoused)) { // if roused irradFlags &= ~(1<<isDark); // clear the Dark flag timeFlags &= ~(1<<nextAlarmSet); // flag that the next alarm might not be correctly set // if (irradFlags & (1<<isDark)) // timeFlags &= ~(1<<nextAlarmSet); // flag that the next alarm might not be correctly set } if (BT_connected()) { // keep resetting this, so BT power will stay on for 2 minutes after connection lost // to allow easy reconnection keepBluetoothPowered(120); } else { // not connected if (btFlags & (1<<btWasConnected)) { // connection lost ; // action(s) when connection lost } btFlags &= ~(1<<btWasConnected); // clear the flag } } // end of this full power segment machineState = Idle; // beginning, or done with everything; return to Idle state while (machineState == Idle) { // RTC interrupt will break out of this checkCriticalPower(); // if (stateFlags1 & (1<<reachedFullPower)) { // another full-power-only segment intTmp1 = clearAnyADXL345TapInterrupt(); if (intTmp1) { len = sprintf(str, "\r\n could not clear ADXL345 Tap Interrupt: %d\r\n", intTmp1); outputStringToUART0(str); } enableAccelInterrupt(); checkForBTCommands(); checkForCommands(); // } // end of this full-power segment if (!(timeFlags & (1<<nextAlarmSet))) { // outputStringToUART0("\n\r about to call setupNextAlarm \n\r\n\r"); intTmp1 = rtc_setupNextAlarm(&dt_CurAlarm); timeFlags |= (1<<nextAlarmSet); } if (!(stateFlags1 & (1<<isRoused))) { // may add other conditions later // go to sleep PORTA &= ~(0b00000100); // turn off bit 2, pilot light blinkey // SE bit in SMCR must be written to logic one and a SLEEP // instruction must be executed. // When the SM2..0 bits are written to 010, the SLEEP instruction makes the MCU enter // Power-down mode // SM2 = bit 3 // SM1 = bit 2 // SM0 = bit 1 // SE = bit 0 // don't set SE yet SMCR = 0b00000100; // set SE (sleep enable) SMCR |= (1<<SE); // go intoPower-down mode SLEEP asm("sleep"); } } // end of (machState == Idle) // when (machState != Idle) execution passes on from this point // when RTCC alarm or Accelerometer tap occurs, changes machineState to WakedFromSleep checkCriticalPower(); // Tap interrupt will not be active until first time initialization, so // following flag should not be settable till then anyway // but put internal check in case code rearranged if (motionFlags & (1<<tapDetected)) { // if it was a tap, go into Roused state if (stateFlags1 & (1<<reachedFullPower)) { // only if had achieved full power and initialized stayRoused(3000); // 30 seconds } else { stayRoused(300); // 3 seconds } motionFlags &= ~(1<<tapDetected); // clear the flag } timeFlags &= ~(1<<nextAlarmSet); // flag that current alarm is no longer valid while (timeFlags & (1<<alarmDetected)) { // interrupt that woke from sleep was RTC alarm // use 'while' loop to allow various tests to break out timeFlags &= ~(1<<alarmDetected); // clear flag so this will only happen once in any case // monitor cell voltage, to decide whether there is enough power to proceed // remember previous voltage; very first read on intialize, so should be meaningful previousADCCellVoltageReading = cellVoltageReading.adcWholeWord; intTmp1 = readCellVoltage(&cellVoltageReading); if (!(stateFlags1 & (1<<reachedFullPower))) { // if not achieved full power and initialized, skip this data acquisition loop // for testing, set to 10-second interval, so don't have to wait an hour to see if battery charging worked irradFlags &= ~(1<<isDark); // remove this line when done testing dead battery re-charging break; // will test reachedFullPower at top of main program loop } if (cellVoltageReading.adcWholeWord < CELL_VOLTAGE_THRESHOLD_UART) { // power too low for any output, no need to even read sensors // remove comment-out of following line when done testing dead battery re-charge // irradFlags |= (1<<isDark); // act as if dark, to save power break; } // see if it's time to log data if ((!((dt_CurAlarm.minute) & 0x01) && (dt_CurAlarm.second == 0)) || (irradFlags & (1<<isDark))) { // if an even number of minutes, and zero seconds // or the once-per-hour wakeup while dark timeFlags |= (1<<timeToLogData); if (irradFlags & (1<<isDark)) { // store the voltage reading at this point refDarkVoltage = cellVoltageReading.adcWholeWord; } // outputStringToUART0("\n\r Time to log data \n\r"); } else { timeFlags &= ~(1<<timeToLogData); // outputStringToUART0("\n\r Not time to log data \n\r"); } // if not time to log data, and not roused if ((!(timeFlags & (1<<timeToLogData))) && (!((stateFlags1 & (1<<isRoused))))) { // won't do anything with results anyway, don't bother reading sensors, save power stayRoused(5); // rouse for 0.05 second to flash the pilot light break; } datetime_getstring(datetime_string, &dt_CurAlarm); outputStringToBothUARTs(datetime_string); if (cellVoltageReading.adcWholeWord < CELL_VOLTAGE_THRESHOLD_READ_DATA) { len = sprintf(str, "\t power too low to read sensors, %lumV\r\n", (unsigned long)(2.5 * (unsigned long)(cellVoltageReading.adcWholeWord))); outputStringToBothUARTs(str); break; } // attempt to assure time zone is synchronized syncTimeZone(); // internally tests if work is already done // read sensors for (ct = 0; ct < 4; ct++) { switch (ct) { case 0: swDnUp = TSL2561_DnLooking; swBbIr = TSL2561_CHANNEL_BROADBAND; break; case 1: swDnUp = TSL2561_DnLooking; swBbIr = TSL2561_CHANNEL_INFRARED; break; case 2: swDnUp = TSL2561_UpLooking; swBbIr = TSL2561_CHANNEL_BROADBAND; break; case 3: swDnUp = TSL2561_UpLooking; swBbIr = TSL2561_CHANNEL_INFRARED; break; } intTmp1 = getIrrReading(swDnUp, swBbIr, &irrReadings[ct]); if (!intTmp1) { len = sprintf(str, "\t%lu", (unsigned long)((unsigned long)irrReadings[ct].irrWholeWord * (unsigned long)irrReadings[ct].irrMultiplier)); } else if (intTmp1 == errNoI2CAddressAck) { // not present or not responding len = sprintf(str, "\t-"); } else { len = sprintf(str, "\n\r Could not get reading, err code: %x \n\r", intTmp1); } outputStringToBothUARTs(str); } if (!temperature_GetReading(&temperatureReading)) { len = sprintf(str, "\t%d", (int8_t)(temperatureReading.tmprHiByte)); outputStringToBothUARTs(str); } else outputStringToBothUARTs("\t-"); // calc cell voltage from ADC reading earlier // formula from datasheet: V(measured) = adcResult * (1024 / Vref) // using internal reference, Vref = 2.56V = 2560mV // V(measured) = adcResult * 2.5 (units are millivolts, so as to get whole numbers) len = sprintf(str, "\t%lu", (unsigned long)(2.5 * (unsigned long)(cellVoltageReading.adcWholeWord))); outputStringToBothUARTs(str); outputStringToBothUARTs("\r\n"); // begin to build log string while testing, even if we end up not logging data strcpy(strLog, "\n\r"); strcat(strLog, datetime_string); irradFlags &= ~((1<<isDarkBBDn) | (1<<isDarkIRDn) | (1<<isDarkBBUp) | (1<<isDarkIRUp)); // default clear for (ct = 0; ct < 4; ct++) { // generate irradiance readings if (!(irrReadings[ct].validation)) { lngTmp1 = (unsigned long)((unsigned long)irrReadings[ct].irrWholeWord * (unsigned long)irrReadings[ct].irrMultiplier); // len = sprintf(str, "\t%lu", (unsigned long)((unsigned long)irrReadings[ct].irrWholeWord * (unsigned long)irrReadings[ct].irrMultiplier)); len = sprintf(str, "\t%lu", lngTmp1); if ((ct == 0) || (ct == 3)) { // broadband lngTmp2 = darkCutOffBB; } else { // infrared lngTmp2 = darkCutoffIR; } if (lngTmp1 < lngTmp2) { switch (ct) { case 0: irradFlags |= (1<<isDarkBBDn); break; case 1: irradFlags |= (1<<isDarkIRDn); break; case 2: irradFlags |= (1<<isDarkBBUp); break; case 3: irradFlags |= (1<<isDarkIRUp); break; } } } else { // no valid data for this reading len = sprintf(str, "\t"); // treat invalid readings as if dark switch (ct) { case 0: irradFlags |= (1<<isDarkBBDn); break; case 1: irradFlags |= (1<<isDarkIRDn); break; case 2: irradFlags |= (1<<isDarkBBUp); break; case 3: irradFlags |= (1<<isDarkIRUp); break; } } strcat(strLog, str); } // end of irradiance sensor validity testing if (timeFlags & (1<<timeToLogData)) { // outputStringToUART0("\n\r Entered log data routine \n\r"); // (previously built irradiance part of log string) // log temperature if (!temperatureReading.verification) len = sprintf(str, "\t%d", (int8_t)(temperatureReading.tmprHiByte)); else len = sprintf(str, "\t"); strcat(strLog, str); // log cell voltage len = sprintf(str, "\t%lu\n\r", (unsigned long)(2.5 * (unsigned long)(cellVoltageReading.adcWholeWord))); strcat(strLog, str); len = strlen(strLog); errSD = writeCharsToSDCard(strLog, len); if (errSD) { tellFileError (errSD); } else { outputStringToBothUARTs(" Data written to SD card \n\r\n\r"); } } // end of test if time to log data // test if dark or not dark // if all sensors are less than thresholds, or missing; and system not in Roused state if ((irradFlags & (1<<isDarkBBDn)) && (irradFlags & (1<<isDarkIRDn)) && (irradFlags & (1<<isDarkBBUp)) && (irradFlags & (1<<isDarkIRUp)) && (!(stateFlags1 & (1<<isRoused)))) { // flag that it is dark irradFlags |= (1<<isDark); } else { // or not // try new algorithm: if (cellVoltageReading.adcWholeWord > CELL_VOLTAGE_THRESHOLD_SD_CARD) { // if cell is high irradFlags &= ~(1<<isDark); // always leave the Dark state } else { // if cell voltage is low, only leave the Dark state // if cell has charged somewhat since last reading // this should eliminate early morning drain, when data will not be good anyway // require a small increase in cell voltage to ignore random jitter if (cellVoltageReading.adcWholeWord > (refDarkVoltage + 3)) { irradFlags &= ~(1<<isDark); } } } // end of testing for dark or not dark // let main loop restore Idle state, after assuring timer interrupts are re-established break; // if did everything, break here } // end of data acquisition segment turnSDCardPowerOff(); if (stateFlags1 & (1<<reachedFullPower)) { // another full-power-only segment if (!BT_connected()) { // timeout diagnostics if no Bluetooth connection if (stateFlags1 & (1<<isRoused)) { len = sprintf(str, "\r\n sleep in %u seconds\r\n", (rouseCountdown/100)); outputStringToUART0(str); } if (BT_powered()) { len = sprintf(str, "\r\n BT off in %u seconds\r\n", (btCountdown/100)); outputStringToUART0(str); } } } // end of this full-power-only segment } // end of main program loop } // end of fn main
///////////////// // main routine ///////////////// void main (void) { uint8_t Rx, loop; ///////////////// // init peripherals ///////////////// // disable interrupts DISABLE_INTERRUPTS; // switch to 16MHz (default is 2MHz) CLK.CKDIVR.byte = 0x00; // configure green LED pin (PH2) gpio_init(&PORT_H, PIN_2, OUTPUT_PUSHPULL_FAST); // init timer TIM4 for 1ms clock with interrupts tim4_init(); // init pins for UART1 Rx(=PA4) and Tx(=PA5) gpio_init(&PORT_A, PIN_4, INPUT_PULLUP_NOEXINT); gpio_init(&PORT_A, PIN_5, OUTPUT_PUSHPULL_FAST); // init UART1 (connected to PC on muBoard) uart1_init(115200L); // init pins for UART3 Rx(=PD6) and Tx(=PD5) gpio_init(&PORT_D, PIN_6, INPUT_PULLUP_NOEXINT); gpio_init(&PORT_D, PIN_5, OUTPUT_PUSHPULL_FAST); // init UART3 (available on io-plug on muBoard) uart3_init(115200L); // enable interrupts ENABLE_INTERRUPTS; ///////////////// // main loop ///////////////// loop = 0; while (1) { // if byte received via UART1 send via UART3 if (uart1_check_Rx()) uart3_send_byte(uart1_receive()); // if byte received via UART3 send via UART1 if (uart3_check_Rx()) uart1_send_byte(uart3_receive()); // every 1ms do if (g_flagClock) { g_flagClock = 0; // every 500ms toggle LED & print text if (g_clock > 500) { g_clock = 0; // toggle LED PORT_H.ODR.bit.b2 ^= 1; } // loop 500ms } // loop 1ms } // main loop } // main
///////////////// // main routine ///////////////// void main (void) { int8_t ret1, ret2; int16_t accX1, accY1, accZ1; int16_t accX2, accY2, accZ2; char buf[100]; uint8_t count=0, len=0; ///////////////// // init peripherals ///////////////// // disable interrupts DISABLE_INTERRUPTS; // switch to 16MHz (default is 2MHz) CLK.CKDIVR.byte = 0x00; // set default option bytes to assert bootloader is running flash_OPT_default(); // init timer TIM3 for sleep and timeout (required by I2C) tim3_init(); // init timer TIM4 for 1ms clock with interrupts tim4_init(); // init I2C bus i2c_init(); // init and reset LCD display lcd_init(); // init pins for UART1 Rx(=PA4) and Tx(=PA5) gpio_init(&PORT_A, PIN_4, INPUT_PULLUP_NOEXINT); gpio_init(&PORT_A, PIN_5, OUTPUT_PUSHPULL_FAST); // init UART1 to high speed (connected to PC on muBoard) uart1_init(230400L); // init LEDs on muBoard for visual feedback GPIO_SET(PORT_H,PIN_2|PIN_3, 1); gpio_init(&PORT_H, PIN_2|PIN_3, OUTPUT_PUSHPULL_FAST); // enable interrupts ENABLE_INTERRUPTS; // init I2C routine pointers I2C_routine(); // initialize sensors do { bno055.dev_addr = BNO055_I2C_ADDR1; ret1 = bno055_init(&bno055); ret1 |= bno055_set_power_mode(POWER_MODE_NORMAL); ret1 |= bno055_set_operation_mode(OPERATION_MODE_AMG); } while (ret1 && USE_I2C_ADDR1); do { bno055.dev_addr = BNO055_I2C_ADDR2; ret2 = bno055_init(&bno055); ret2 |= bno055_set_power_mode(POWER_MODE_NORMAL); ret2 |= bno055_set_operation_mode(OPERATION_MODE_AMG); } while (ret2 && USE_I2C_ADDR2); ///////////////// // main loop ///////////////// while (1) { // every 1ms do if (g_flagClock) { g_flagClock = 0; // every 10ms do if (g_clock > 10) { g_clock = 0; // just to be sure accX1 = accY1 = accZ1 = ret1 = 0; accX2 = accY2 = accZ2 = ret2 = 0; // read data from sensor 1 #if USE_I2C_ADDR1 bno055.dev_addr = BNO055_I2C_ADDR1; ret1 = bno055_read_accel_x(&accX1); ret1 |= bno055_read_accel_y(&accY1); ret1 |= bno055_read_accel_z(&accZ1); if (ret1 != 0) { accX1 = accY1 = accZ1 = 0; } #endif // USE_I2C_ADDR1 // read data from sensor 2 #if USE_I2C_ADDR2 bno055.dev_addr = BNO055_I2C_ADDR2; ret2 = bno055_read_accel_x(&accX2); ret2 |= bno055_read_accel_y(&accY2); ret2 |= bno055_read_accel_z(&accZ2); if (ret2 != 0) { accX2 = accY2 = accZ2 = 0; } #endif // USE_I2C_ADDR2 // send data to PC via UART1. Use SW FIFO for background operation len = 0; buf[len++] = (uint8_t)(accX1 >> 8); // x1-acc (MSB first) buf[len++] = (uint8_t) accX1; buf[len++] = (uint8_t)(accY1 >> 8); // y1-acc (MSB first) buf[len++] = (uint8_t) accY1; buf[len++] = (uint8_t)(accZ1 >> 8); // z1-acc (MSB first) buf[len++] = (uint8_t) accZ1; buf[len++] = (uint8_t)(accX2 >> 8); // x2-acc (MSB first) buf[len++] = (uint8_t) accX2; buf[len++] = (uint8_t)(accY2 >> 8); // y2-acc (MSB first) buf[len++] = (uint8_t) accY2; buf[len++] = (uint8_t)(accZ2 >> 8); // z2-acc (MSB first) buf[len++] = (uint8_t) accZ2; uart1_send_buf(len, buf); // indicate I2C status via red LED (on=ok) GPIO_SET(PORT_H,PIN_3, ret1|ret2); // show life beat via green LED if (++count > 20) { count = 0; GPIO_TOGGLE(PORT_H,PIN_2); // print to LCD sprintf(buf, "%02d %03d %03d %03d", (int) ret1, (int) accX1, (int) accY1, (int) accZ1); lcd_print(1, 1, buf); sprintf(buf, "%02d %03d %03d %03d", (int) ret2, (int) accX2, (int) accY2, (int) accZ2); lcd_print(2, 1, buf); } } // loop 10ms } // loop 1ms } // main loop
int main() { lcd_init(); uart1_init(); mems_init(); lcd_cmd(1); delay(1000); lcd_cmd(0x85); lcd_string("WELCOME"); while(1) { delay(500); ch=mems_start(); lcd_cmd(1); lcd_string("MEMS DATA"); delay(500); if(ch==1) { delay(1000); uart1_data('S'); lcd_cmd(1); lcd_cmd(0x80); lcd_data('S'); lcd_cmd(0xc0); lcd_num(ch); } else if(ch==5) { delay(1000); uart1_data('F'); lcd_cmd(1); lcd_cmd(0x80); lcd_data('F'); lcd_cmd(0xc0); lcd_num(ch); } else if((ch==8)||(ch==9)) { delay(1000); uart1_data('B'); lcd_cmd(1); lcd_cmd(0x80); lcd_data('B'); lcd_cmd(0xc0); lcd_num(ch); } else if((ch==21)||(ch==22)) { delay(1000); uart1_data('L'); lcd_cmd(1); lcd_cmd(0x80); lcd_data('L'); lcd_cmd(0xc0); lcd_num(ch); } else if((ch==24)||(ch==25)) { delay(1000); uart1_data('R'); lcd_cmd(1); lcd_cmd(0x80); lcd_data('R'); lcd_cmd(0xc0); lcd_num(ch); } mems_stop(); } }
void main() { char error,error2; uart1_init(9600); SPI1_Init(); buf[0]='E'; buf[1]='n'; buf[2]='g'; buf[3]='S'; buf[4]='h'; buf[5]='a'; buf[6]='d'; buf[7]='y'; trisd=255; error = MMC_init(); if(!error){ uart1_write_text("connected"); } else uart1_write_text("not connected"); while(1) { if(rd0_bit==0) { buf[0]='E'; buf[1]='n'; buf[2]='g'; buf[3]='S'; buf[4]='h'; buf[5]='a'; buf[6]='d'; buf[7]='y'; error2 = Mmc_write_Sector(1, buf); if(!error2) { uart1_write_text("write success"); } else uart1_write_text("write not success"); while(rd0_bit==0){} } if(rd1_bit==0) { error2 = Mmc_read_Sector(1, read); uart1_write_text(read); while(rd1_bit==0){} } if(rd2_bit==0) { buf[0]='E'; buf[1]='n'; buf[2]='g'; buf[3]='i'; buf[4]='s'; buf[5]='m'; buf[6]='a'; buf[7]='i'; buf[7]='l'; error2 = Mmc_write_Sector(1, buf); if(!error2) { uart1_write_text("write success"); } else uart1_write_text("write not success"); while(rd2_bit==0){} } } }
/*---------------------------------------------------------------------------*/ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_toggle(LEDS_RED | LEDS_GREEN | LEDS_BLUE); #if WITH_UIP slip_arch_init(BAUD2UBR(115200)); /* Must come before first printf */ #else /* WITH_UIP */ uart1_init(BAUD2UBR(115200)); /* Must come before first printf */ #endif /* WITH_UIP */ printf("Starting %s " "($Id: contiki-sky-main.c,v 1.9 2009/11/20 10:45:07 nifi Exp $)\n", __FILE__); ds2411_init(); xmem_init(); leds_toggle(LEDS_RED | LEDS_GREEN | LEDS_BLUE); rtimer_init(); /* * Hardware initialization done! */ /* Restore node id if such has been stored in external mem */ // node_id_burn(3); node_id_restore(); printf("node_id : %hu\n", node_id); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", ds2411_id[0], ds2411_id[1], ds2411_id[2], ds2411_id[3], ds2411_id[4], ds2411_id[5], ds2411_id[6], ds2411_id[7]); #if WITH_UIP uip_init(); uip_sethostaddr(&slipif.ipaddr); uip_setnetmask(&slipif.netmask); uip_fw_default(&slipif); /* Point2point, no default router. */ #endif /* WITH_UIP */ /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); process_start(&sensors_process, NULL); /* * Initialize light and humidity/temp sensors. */ SENSORS_ACTIVATE(light_sensor); SENSORS_ACTIVATE(sht11_sensor); ctimer_init(); set_rime_addr(); cc2420_init(); cc2420_set_pan_addr(panId, 0 /*XXX*/, ds2411_id); cc2420_set_channel(RF_CHANNEL); cc2420_set_txpower(31); nullmac_init(&cc2420_driver); rime_init(&nullmac_driver); // xmac_init(&cc2420_driver); // rime_init(&xmac_driver); /* rimeaddr_set_node_addr*/ #if WITH_UIP process_start(&tcpip_process, NULL); process_start(&uip_fw_process, NULL); /* Start IP output */ process_start(&slip_process, NULL); #endif /* WITH_UIP */ SENSORS_ACTIVATE(button_sensor); print_processes(autostart_processes); autostart_start(autostart_processes); energest_init(); /* * This is the scheduler loop. */ printf("process_run()...\n"); ENERGEST_ON(ENERGEST_TYPE_CPU); while (1) { do { /* Reset watchdog. */ } while(process_run() > 0); /* * Idle processing. */ if(lpm_en) { int s = splhigh(); /* Disable interrupts. */ if(process_nevents() != 0) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_OFF(ENERGEST_TYPE_CPU); ENERGEST_ON(ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); _BIS_SR(GIE | SCG0 | /*SCG1 |*/ CPUOFF); /* LPM3 sleep. */ /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } } } return 0; }
/*! \brief Main function. Execution starts here. */ int main(void) { sysclk_init(); irq_initialize_vectors(); cpu_irq_enable(); /* Initialize the sleep manager */ sleepmgr_init(); /* Initialize the SAM board */ board_init(); /* Serial line [UART] initialization */ uart1_init(CONF_UART_BAUDRATE); #if WITH_SERIAL_LINE_INPUT /* If SLIP-radio is enabled, the handler is overridden. */ uart1_set_input(serial_line_input_byte); #endif while(!uart_is_tx_ready(CONSOLE_UART)); /* PRINT Contiki Entry String */ PRINTF("Starting "); PRINTF(CONTIKI_VERSION_STRING); /* Configure sys-tick for 1 ms */ clock_init(); /* Initialize Contiki Process function */ process_init(); /* rtimer and ctimer should be initialized before radio duty cycling layers*/ rtimer_init(); /* etimer_process should be initialized before ctimer */ process_start(&etimer_process, NULL); /* Initialize the ctimer process */ ctimer_init(); #ifdef WITH_LED_DEBUGGING configure_led_debug_pins(); #ifdef WITH_AR9170_WIFI_SUPPORT configure_ar9170_disconnect_pins(); #endif #endif /* rtimer initialization */ rtimer_init(); /* Network protocol stack initialization */ netstack_init(); /* Process init initialization */ procinit_init(); /* Initialize energy estimation routines */ energest_init(); /* Initialize watch-dog process */ watchdog_start(); #ifdef WITH_AR9170_WIFI_SUPPORT #ifdef WITH_USB_SUPPORT /* Start network-related system processes. */ #if WITH_UIP6 #ifdef WITH_SLIP #warning SLIP_RADIO enabled! process_start(&slip_radio_process, NULL); #endif #endif #else #error USB support must be enabled. #endif #endif #ifdef WITH_USB_SUPPORT /* Start ARM Cortex-M3 USB Host Stack */ uhc_start(); configure_ar9170_disconnect_pins(); #endif /* Autostart all declared [not system] processes */ //autostart_start(autostart_processes); #if UIP_CONF_IPV6 printf("Tentative link-local IPv6 address: "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { printf("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } if(!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); printf("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { printf("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #endif /* UIP_CONF_IPV6 */ PRINTF("Starting Contiki OS main loop...\n"); while(true) { /* Contiki Polling System */ process_run(); } }
/*---------------------------------------------------------------------------*/ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_on(LEDS_RED); uart1_init(BAUD2UBR(115200)); /* Must come before first printf */ #if WITH_UIP slip_arch_init(BAUD2UBR(115200)); #endif /* WITH_UIP */ leds_on(LEDS_GREEN); ds2411_init(); /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible with an Ethernet MAC address - byte 0 (byte 2 in the DS ID) cannot be odd. */ ds2411_id[2] &= 0xfe; leds_on(LEDS_BLUE); xmem_init(); leds_off(LEDS_RED); rtimer_init(); /* * Hardware initialization done! */ /* Restore node id if such has been stored in external mem */ node_id_restore(); random_init(ds2411_id[0] + node_id); leds_off(LEDS_BLUE); /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); process_start(&sensors_process, NULL); /* * Initialize light and humidity/temp sensors. */ sensors_light_init(); battery_sensor.activate(); sht11_init(); ctimer_init(); cc2420_init(); cc2420_set_pan_addr(IEEE802154_PANID, 0 /*XXX*/, ds2411_id); cc2420_set_channel(RF_CHANNEL); printf(CONTIKI_VERSION_STRING " started. "); if(node_id > 0) { printf("Node id is set to %u.\n", node_id); } else { printf("Node id is not set.\n"); } set_rime_addr(); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", ds2411_id[0], ds2411_id[1], ds2411_id[2], ds2411_id[3], ds2411_id[4], ds2411_id[5], ds2411_id[6], ds2411_id[7]); #if WITH_UIP6 memcpy(&uip_lladdr.addr, ds2411_id, sizeof(uip_lladdr.addr)); sicslowpan_init(sicslowmac_init(&cc2420_driver)); process_start(&tcpip_process, NULL); printf(" %s channel %u\n", sicslowmac_driver.name, RF_CHANNEL); #if UIP_CONF_ROUTER rime_init(rime_udp_init(NULL)); uip_router_register(&rimeroute); #endif /* UIP_CONF_ROUTER */ #else /* WITH_UIP6 */ rime_init(MAC_DRIVER.init(&cc2420_driver)); printf(" %s channel %u\n", rime_mac->name, RF_CHANNEL); #endif /* WITH_UIP6 */ #if !WITH_UIP && !WITH_UIP6 uart1_set_input(serial_line_input_byte); serial_line_init(); #endif #if PROFILE_CONF_ON profile_init(); #endif /* PROFILE_CONF_ON */ leds_off(LEDS_GREEN); #if WITH_FTSP ftsp_init(); #endif /* WITH_FTSP */ #if TIMESYNCH_CONF_ENABLED timesynch_init(); timesynch_set_authority_level(rimeaddr_node_addr.u8[0]); #endif /* TIMESYNCH_CONF_ENABLED */ #if WITH_UIP process_start(&tcpip_process, NULL); process_start(&uip_fw_process, NULL); /* Start IP output */ process_start(&slip_process, NULL); slip_set_input_callback(set_gateway); { uip_ipaddr_t hostaddr, netmask; uip_init(); uip_ipaddr(&hostaddr, 172,16, rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1]); uip_ipaddr(&netmask, 255,255,0,0); uip_ipaddr_copy(&meshif.ipaddr, &hostaddr); uip_sethostaddr(&hostaddr); uip_setnetmask(&netmask); uip_over_mesh_set_net(&hostaddr, &netmask); /* uip_fw_register(&slipif);*/ uip_over_mesh_set_gateway_netif(&slipif); uip_fw_default(&meshif); uip_over_mesh_init(UIP_OVER_MESH_CHANNEL); printf("uIP started with IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&hostaddr)); } #endif /* WITH_UIP */ button_sensor.activate(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); print_processes(autostart_processes); autostart_start(autostart_processes); /* * This is the scheduler loop. */ #if DCOSYNCH_CONF_ENABLED timer_set(&mgt_timer, DCOSYNCH_PERIOD * CLOCK_SECOND); #endif watchdog_start(); /* watchdog_stop();*/ while(1) { int r; #if PROFILE_CONF_ON profile_episode_start(); #endif /* PROFILE_CONF_ON */ do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); #if PROFILE_CONF_ON profile_episode_end(); #endif /* PROFILE_CONF_ON */ /* * Idle processing. */ int s = splhigh(); /* Disable interrupts. */ /* uart1_active is for avoiding LPM3 when still sending or receiving */ if(process_nevents() != 0 || uart1_active()) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; #if DCOSYNCH_CONF_ENABLED /* before going down to sleep possibly do some management */ if (timer_expired(&mgt_timer)) { timer_reset(&mgt_timer); msp430_sync_dco(); } #endif /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_OFF(ENERGEST_TYPE_CPU); ENERGEST_ON(ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); watchdog_stop(); _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This statement will block until the CPU is woken up by an interrupt that sets the wake up flag. */ /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } } return 0; }
/*---------------------------------------------------------------------------*/ int main(void) { /* * Initialize hardware. */ halInit(); clock_init(); uart1_init(115200); // Led initialization leds_init(); INTERRUPTS_ON(); PRINTF("\r\nStarting "); PRINTF(CONTIKI_VERSION_STRING); PRINTF(" on %s\r\n",boardDescription->name); /* * Initialize Contiki and our processes. */ process_init(); #if WITH_SERIAL_LINE_INPUT uart1_set_input(serial_line_input_byte); serial_line_init(); #endif /* rtimer and ctimer should be initialized before radio duty cycling layers*/ rtimer_init(); /* etimer_process should be initialized before ctimer */ process_start(&etimer_process, NULL); ctimer_init(); rtimer_init(); netstack_init(); set_rime_addr(); printf("%s %s, channel check rate %lu Hz\n", NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval())); printf("802.15.4 PAN ID 0x%x, EUI-%d:", IEEE802154_CONF_PANID, UIP_CONF_LL_802154?64:16); uip_debug_lladdr_print(&rimeaddr_node_addr); printf(", radio channel %u\n", RF_CHANNEL); procinit_init(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); autostart_start(autostart_processes); watchdog_start(); while(1){ int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); ENERGEST_OFF(ENERGEST_TYPE_CPU); //watchdog_stop(); ENERGEST_ON(ENERGEST_TYPE_LPM); /* Go to idle mode. */ halSleepWithOptions(SLEEPMODE_IDLE,0); /* We are awake. */ //watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } }
/*---------------------------------------------------------------------------*/ int main(void) { /* Hardware initialization */ bus_init(); rtimer_init(); stack_poison(); /* model-specific h/w init. */ model_init(); /* Init LEDs here */ leds_init(); fade(LEDS_GREEN); /* initialize process manager. */ process_init(); /* Init UART1 */ uart1_init(); #if DMA_ON dma_init(); #endif #if SLIP_ARCH_CONF_ENABLE /* On cc2430, the argument is not used */ slip_arch_init(0); #else uart1_set_input(serial_line_input_byte); serial_line_init(); #endif PUTSTRING("##########################################\n"); putstring(CONTIKI_VERSION_STRING "\n"); putstring(SENSINODE_MODEL " (CC24"); puthex(((CHIPID >> 3) | 0x20)); putstring("-" FLASH_SIZE ")\n"); #if STARTUP_VERBOSE #ifdef HAVE_SDCC_BANKING PUTSTRING(" With Banking.\n"); #endif /* HAVE_SDCC_BANKING */ #ifdef SDCC_MODEL_LARGE PUTSTRING(" --model-large\n"); #endif /* SDCC_MODEL_LARGE */ #ifdef SDCC_MODEL_HUGE PUTSTRING(" --model-huge\n"); #endif /* SDCC_MODEL_HUGE */ #ifdef SDCC_STACK_AUTO PUTSTRING(" --stack-auto\n"); #endif /* SDCC_STACK_AUTO */ PUTCHAR('\n'); PUTSTRING(" Net: "); PUTSTRING(NETSTACK_NETWORK.name); PUTCHAR('\n'); PUTSTRING(" MAC: "); PUTSTRING(NETSTACK_MAC.name); PUTCHAR('\n'); PUTSTRING(" RDC: "); PUTSTRING(NETSTACK_RDC.name); PUTCHAR('\n'); PUTSTRING("##########################################\n"); #endif watchdog_init(); /* Initialise the cc2430 RNG engine. */ random_init(0); /* start services */ process_start(&etimer_process, NULL); ctimer_init(); /* initialize the netstack */ netstack_init(); set_rime_addr(); #if BUTTON_SENSOR_ON || ADC_SENSOR_ON process_start(&sensors_process, NULL); sensinode_sensors_activate(); #endif #if UIP_CONF_IPV6 memcpy(&uip_lladdr.addr, &rimeaddr_node_addr, sizeof(uip_lladdr.addr)); queuebuf_init(); process_start(&tcpip_process, NULL); #if DISCO_ENABLED process_start(&disco_process, NULL); #endif /* DISCO_ENABLED */ #if VIZTOOL_CONF_ON process_start(&viztool_process, NULL); #endif #if (!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; uip_ip6addr(&ipaddr, 0x2001, 0x630, 0x301, 0x6453, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); } #endif /* UIP_CONF_IPV6_RPL */ #endif /* UIP_CONF_IPV6 */ /* * Acknowledge the UART1 RX interrupt * now that we're sure we are ready to process it */ model_uart_intr_en(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); fade(LEDS_RED); #if BATMON_CONF_ON process_start(&batmon_process, NULL); #endif autostart_start(autostart_processes); watchdog_start(); while(1) { uint8_t r; do { /* Reset watchdog and handle polls and events */ watchdog_periodic(); #if CLOCK_CONF_STACK_FRIENDLY if(sleep_flag) { if(etimer_pending() && (etimer_next_expiration_time() - clock_time() - 1) > MAX_TICKS) { etimer_request_poll(); } sleep_flag = 0; } #endif r = process_run(); } while(r > 0); #if NETSTACK_CONF_SHORTCUTS len = NETSTACK_RADIO.pending_packet(); if(len) { packetbuf_clear(); len = NETSTACK_RADIO.read(packetbuf_dataptr(), PACKETBUF_SIZE); if(len > 0) { packetbuf_set_datalen(len); NETSTACK_RDC.input(); } } #endif #if LPM_MODE #if (LPM_MODE==LPM_MODE_PM2) SLEEP &= ~OSC_PD; /* Make sure both HS OSCs are on */ while(!(SLEEP & HFRC_STB)); /* Wait for RCOSC to be stable */ CLKCON |= OSC; /* Switch to the RCOSC */ while(!(CLKCON & OSC)); /* Wait till it's happened */ SLEEP |= OSC_PD; /* Turn the other one off */ #endif /* LPM_MODE==LPM_MODE_PM2 */ /* * Set MCU IDLE or Drop to PM1. Any interrupt will take us out of LPM * Sleep Timer will wake us up in no more than 7.8ms (max idle interval) */ SLEEP = (SLEEP & 0xFC) | (LPM_MODE - 1); #if (LPM_MODE==LPM_MODE_PM2) /* * Wait 3 NOPs. Either an interrupt occurred and SLEEP.MODE was cleared or * no interrupt occurred and we can safely power down */ __asm nop nop nop __endasm; if (SLEEP & SLEEP_MODE0) { #endif /* LPM_MODE==LPM_MODE_PM2 */ ENERGEST_OFF(ENERGEST_TYPE_CPU); ENERGEST_ON(ENERGEST_TYPE_LPM); /* We are only interested in IRQ energest while idle or in LPM */ ENERGEST_IRQ_RESTORE(irq_energest); /* Go IDLE or Enter PM1 */ PCON |= IDLE; /* First instruction upon exiting PM1 must be a NOP */ __asm nop __endasm; /* Remember energest IRQ for next pass */ ENERGEST_IRQ_SAVE(irq_energest); ENERGEST_ON(ENERGEST_TYPE_CPU); ENERGEST_OFF(ENERGEST_TYPE_LPM); #if (LPM_MODE==LPM_MODE_PM2) SLEEP &= ~OSC_PD; /* Make sure both HS OSCs are on */ while(!(SLEEP & XOSC_STB)); /* Wait for XOSC to be stable */ CLKCON &= ~OSC; /* Switch to the XOSC */ /* * On occasion the XOSC is reported stable when in reality it's not. * We need to wait for a safeguard of 64us or more before selecting it */ clock_delay_usec(65); while(CLKCON & OSC); /* Wait till it's happened */ } #endif /* LPM_MODE==LPM_MODE_PM2 */ #endif /* LPM_MODE */ } }
void main(void) { ////////////////////// TMUNUM_INFO xx; TMUNUM_INFO yy; /////////////////////////// unsigned char index; static unsigned char num_byte = 0; char y =0; EA = 0; Soft_WDT_Disnable(); mcu_f340_init(); delay_ms(10); var_init(); fmu_cmd_init(); uart1_init(); #ifdef ID_ONE_WIRE one_wire_init( ONE_WIRE_STANDARD_SPEED); #endif delay_ms(10); tmu_address_init(); EA = 1; WatchDog_Init(); index = 0; countnum = 0; port_num = 0; while(1) { xx.c[0] = 2; xx.c[1] = 2; xx.c[2] = 2; xx.c[3] = 2; xx.c[4] = 2; xx.c[5] = 2; write_tmunum_info(&xx); read_tmunum_info(&yy); } while(1) { char x[10]={1,2,3,4,5,6,7,8,9,10}; char temp[10]; int i; unsigned char code * data ptrCode; x[0] = y++; WatchDog(); earseCodeFlash(TMU_NUM_INFO_ADDR); WatchDog(); writeInnerFlash(TMU_NUM_INFO_ADDR, 10, x); ptrCode = (char code *)TMU_NUM_INFO_ADDR; for(i = 0;i<10;i++) { temp[i] = 0; } for (i = 0; i <10; i++) { temp[i] = *ptrCode++; } WatchDog(); } while(1) { WatchDog(); uart_process(); if(flag30ms) { /*sssssssssssssssss*/ flag30ms = 0; if(num_byte == 0) { num_byte = 1; read_id(0,0,(unsigned char*)localid_buf); WatchDog(); } else { num_byte = 0; read_id(0,1,(unsigned char*)localid_buf); WatchDog(); refresh_current_id(); memory_clear((unsigned char*)localid_buf,sizeof(localid_buf)); read_id_96(); } } if( flag60ms ) { flag60ms = 0; index ++; uart1_timeout(); port_state_process(); slot_aging_time(); if(index >= 20) { index = 0; fmu_cmd_update_file_timer_count(); } } } }
// ***************************************************************************** // Function: configure hardware. *********************************************** // ***************************************************************************** void setupHardware(void) { // Disable watchdog if enabled by bootloader/fuses. *********************** MCUSR &= ~(1 << WDRF); wdt_disable(); // Configure outputs. ***************************************************** // Configure LEDs. Active high. // Orange. LED1DDR |= (1 << LED1PIN); LED1PORT &= ~(1 << LED1PIN); //OFF // Green. LED2DDR |= (1 << LED2PIN); LED2PORT &= ~(1 << LED2PIN); //OFF // Configure camera trigger pin. Active high. CAMDDR |= (1 << CAMPIN); CAMPORT &= ~(1 << CAMPIN); //OFF // Stepper ports. Step on rising edge, enable active low. // Build stepper enable. BUILDENABLEDDR |= (1 << BUILDENABLEPIN); BUILDENABLEPORT &= ~(1 << BUILDENABLEPIN); // Disabled... // Build stepper direction. BUILDDIRDDR |= (1 << BUILDDIRPIN); BUILDDIRPORT |= (1 << BUILDDIRPIN); // Build stepper clock. BUILDCLOCKDDR |= (1 << BUILDCLOCKPIN); BUILDCLOCKPORT &= ~(1 << BUILDCLOCKPIN); // Tilt stepper enable. Active high. TILTENABLEDDR |= (1 << TILTENABLEPIN); TILTENABLEPORT &= ~(1 << TILTENABLEPIN); // Disabled... // Beamer stepper direction. TILTDIRDDR |= (1 << TILTDIRPIN); TILTDIRPORT |= (1 << TILTDIRPIN); // Beamer stepper clock. TILTCLOCKDDR |= (1 << TILTCLOCKPIN); TILTCLOCKPORT &= ~(1 << TILTCLOCKPIN); // Low... // Servo port. SERVOCLOCKDDR |= (1 << SERVOCLOCKPIN); SERVOCLOCKPORT |= (1 << SERVOCLOCKPIN); // Configure inputs. ****************************************************** // Limit switches using internal pull-ups. Configured as inputs by default. LIMITBUILDTOPPORT |= (1 << LIMITBUILDTOPPIN); // Build platform top. LIMITBUILDBOTTOMPORT |= (1 << LIMITBUILDBOTTOMPIN); // Build platform bottom. LIMITTILTPORT |= (1 << LIMITTILTPIN); // Tilt. // Configure INT1--3 to fire on falling edge. EICRA |= (1 << ISC11 | 1 << ISC10 | 1 << ISC01 | 1 << ISC00); // Fire on rising edge. Datasheed p. 86. EICRB |= (1 << ISC61 | 1 << ISC60); EIMSK |= (1 << INT6 | 1 << INT1 | 1 << INT0); // Configure PCINT4 for tilt. // PCICR |= (1 << PCIE0); // PCMSK0 |= (1 << PCINT4); // Configure timer0. Call ISR every 0,1 ms. ******************************* // Prescaler: 16.000.000 Hz / 8 = 2.000.000 Hz // 1 s / 2.000.000 = 0,0000005 s per clock cycle. // Clock cycles per millisecond: // 0,001 s / 0,0000005 s = 2.000 clock cycles per millisecond. // Overflow at 200 clock cycles comes every 0,1 ms. TCCR0A |= (1 << WGM01); // CTC mode. Data sheet page 104. TCCR0B |= (1<<CS01); // Set prescaler to 8. Data sheet page 106. OCR0A = 200; // Set channel A compare value. TIMSK0 |= (1<<OCIE0A); // Enable channel A compare interrupt. // Stepper PWM for beamer drive. ****************************************** // Configure timer1 for CTC with output toggle on OC1A and interrupt. Prescaler 1. TCCR1A |= (1 << COM1A0); // Toggle OC1A on compare match. TCCR1B |= (1 << WGM12); // CTC with OCR1AH/OCR1AL compare registers. Data sheet page 130. // TCCR1B |= (1 << CS10); // Set prescaler to 1. Datasheet page 133. Do this later... TIMSK1 |= (1 << OCIE1A); // Enable channel A CTC interrupt. Datasheet p. 136. // Stepper PWM for build platform drive. ********************************** // Configure timer3 for CTC with interrupt on compare match. Prescaler 1. TCCR3A |= (1 << COM3A0); // Toggle OC3A on compare match. TCCR3B |= (1 << WGM32); // CTC with OCR3AH/OCR3AL compare registers. Data sheet page 130. // TCCR3B |= (1 << CS30); // Set prescaler to 1. Datasheet page 133. DO NOT ENABLE BY DEFAULT! TIMSK3 |= (1 << OCIE3A); // Enable channel A CTC interrupt. Datasheet p. 136. // Stepper PWM for tilt. ************************************************** // TIMER 4 IS A BITCH! // SUPPOSEDLY ONLY OCR4C CAN SERVE AS TOP THAT RESETS ON COMPARE MATCH! Datasheet p 149 under Normal Mode. // Thus, make sure to set OCR4A and OCR4B to the same value to use OC4A output pin. // Configure timer4 in 8 bit mode for CTC with interrupt on compare match. Prescaler 64. // TCCR4A |= (1 << COM4A0); // Toggle OC4A on compare match. Datasheet p 162. // TCCR4B |= (1 << CS42 | 1 << CS41 | 1 << CS40); // Prescaler 64. Datasheet p 166. DISABLED! Enable in menu function. // TIMSK4 |= (1 << OCIE4A); // Initialise UART using uart.c function. // This calculates the baud interval and passes it to the init function. // Don't forget to enable interrupts later on... uart1_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) ); // Inititalise USB using LUFA function. *********************************** USB_Init(); // Initialise LCD. ******************************************************** // lcd_init(0x0C); // LCD on, cursor off: see lcd.h. // lcd_clrscr(); // Clear and set cursor to home. // Initialise button. ***************************************************** // buttonInit(); // Initialise rotary encoder. ********************************************* // rotaryEncoderInit(); }
/** main function */ int main(void) { // SPCR &= ~(1<<SPE); // TIMSK0 &= ~(1<<TOIE1); wdt_disable(); /* Clear WDRF in MCUSR */ MCUSR &= ~(1<<WDRF); /* Write logical one to WDCE and WDE */ /* Keep old prescaler setting to prevent unintentional time-out */ WDTCSR |= (1<<WDCE) | (1<<WDE); /* Turn off WDT */ WDTCSR = 0x00; //volatile long l; // for(l=0;l<1000000;l++); DDR_CONFIG_IN(CONFIG1); PIN_SET(CONFIG1); wdt_enable(WDTO_2S); wdt_reset(); volatile unsigned long l; for(l=0;l<10;l++); if( !PIN_HIGH(CONFIG1) ){ global.config = 30; }else{ global.config = 21; } leds_init(); wdt_reset(); if( global.config == 21 ){ DDR_CONFIG_IN(JUMPER1C1); PIN_SET(JUMPER1C1); }else if( global.config == 30 ){ DDR_CONFIG_IN(JUMPER1C2); PIN_SET(JUMPER1C2); adc_init(); uint16_t bat = adc_getChannel(6); if( bat < ADC_MINBATIDLE ){ //global.flags.lowbat = 1; } } wdt_reset(); init_pwm(); #if SERIAL_UART uart1_init( UART_BAUD_SELECT(UART_BAUDRATE,F_CPU)); stdout = &mystdout; #endif #if RC5_DECODER rc5_init(); #endif wdt_reset(); #if STATIC_SCRIPTS init_script_threads(); #endif settings_read(); //if((global.config == 21 && !PIN_HIGH(JUMPER1C1)) || (global.config== 30 && !PIN_HIGH(JUMPER1C2))) // interfaces_setEnabled(IFACE_RF,0); control_init(); wdt_reset(); #if RS485_CTRL rs485_init(); zbus_core_init(); #endif //rf_init(); packet_init(idbuf[0],0); wdt_reset(); srandom(random_seed); random_seed = random(); /* enable interrupts globally */ sei(); // global.state = STATE_RUNNING; // global.state = STATE_PAUSE; // global.flags.running = 0; while (1) { wdt_reset(); //leds_main(); #if 1 packet_tick(); #else if(packetbase ){//> 32){ packetbase = 0; packet_tick(); //if(main_reset++ > 16000) // jump_to_bootloader(); //uint16_t bat = adc_getChannel(6); /*if( bat < ADC_MINBATIDLE ){ global.flags.lowbat = 1; }*/ } #endif //if( global.flags.lowbat ){ // control_lowbat(); //} if( global.flags.timebase ){ //control_tick(); global.flags.timebase=0; } /* after the last pwm timeslot, rebuild the timeslot table */ //if (global.flags.last_pulse) { // global.flags.last_pulse = 0; //if(global.flags.running) //update_pwm_timeslots(); //} /* at the beginning of each pwm cycle, call the fading engine and * execute all script threads */ if (global.flags.new_cycle) { global.flags.new_cycle = 0; if(control_faderunning) update_brightness(); if(global.flags.running){ #if STATIC_SCRIPTS // execute_script_threads(); #endif } //continue; } #if RC5_DECODER #endif #if RS485_CTRL rs485_process(); #endif #if SERIAL_UART //serial_process(); #endif } }
/*---------------------------------------------------------------------------*/ int main(void) { /* * Initialize hardware. */ halInit(); clock_init(); uart1_init(115200); // Led initialization leds_init(); INTERRUPTS_ON(); PRINTF("\r\nStarting "); PRINTF(CONTIKI_VERSION_STRING); PRINTF(" on %s\r\n",boardDescription->name); /* * Initialize Contiki and our processes. */ process_init(); #if WITH_SERIAL_LINE_INPUT uart1_set_input(serial_line_input_byte); serial_line_init(); #endif process_start(&etimer_process, NULL); ctimer_init(); rtimer_init(); netstack_init(); set_rime_addr(); PRINTF("ACK enable=%u %s %s, channel check rate=%luHz, check interval %ums, clock second=%u, radio channel %u\r\n", ST_RadioAutoAckEnabled(), NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1: NETSTACK_RDC.channel_check_interval()), NETSTACK_RDC.channel_check_interval(), CLOCK_SECOND, RF_CHANNEL); #if !UIP_CONF_IPV6 ST_RadioEnableAutoAck(FALSE); // Because frames are not 802.15.4 compatible. ST_RadioEnableAddressFiltering(FALSE); #endif ST_RadioEnableAutoAck(TRUE); procinit_init(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); autostart_start(autostart_processes); watchdog_start(); while(1){ int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); ENERGEST_OFF(ENERGEST_TYPE_CPU); //watchdog_stop(); ENERGEST_ON(ENERGEST_TYPE_LPM); /* Go to idle mode. */ halSleepWithOptions(SLEEPMODE_IDLE,0); /* We are awake. */ //watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } }
void main() { bit i,j,k,m; int rc; int lc; int x; int y; i=1;j=1;m=1;k=1; uart1_init(9600); lcd_init(); for(;;) { rc=adc_read(1)*0.05; lc=adc_read(0)*0.05; x=adc_read(4)*0.05; y=adc_read(3)*0.05; if(x>=18) { lcd_out(1,1,"X+"); uart1_write_text("x+"); delay_ms(60); } if(x<=15) { lcd_out(1,1,"X-"); uart1_write_text("x-"); delay_ms(60); } if(y>=18) { lcd_out(1,1,"Y+"); uart1_write_text("y+"); delay_ms(60); } if(y<=15) { lcd_out(1,1,"Y-"); uart1_write_text("y-"); delay_ms(60); } if(lc<=7&&k==1) { lcd_out(2,1,"L1"); uart1_write_text("l1"); k=0; m=1; delay_ms(60); } if(lc>=9&&m==1) { lcd_out(2,1,"L2"); uart1_write_text("l2"); m=0; k=1; delay_ms(60); } if(rc<=12&&i==1) { lcd_out(2,1,"r1"); uart1_write_text("r1"); i=0; j=1; delay_ms(60); } if(rc>=14&&j==1) { lcd_out(2,1,"r2"); uart1_write_text("r2"); j=0; i=1; delay_ms(60); } } }
void main() { int i; int temp1; char test[32]; uart1_init(2400); CE_DIR=0; CSN_DIR=0; CSK_DIR=0; MOSI_DIR=0; MISO_DIR=1; delay_ms(500); nrf24_config(); CSN=1; CE=1; lcd_init(); Lcd_Cmd(_LCD_CURSOR_OFF); //lcd_out(2,1,"welcome"); trisb.f0=0; rb0_bit=0; trisd.f0=0; for(i=0;i<30;i++) { rd0_bit=1; delay_us(400); rd0_bit=0; delay_us(19600); } uart1_write_text("TEST"); uart1_write(13); //lcd_out(1,1,"S"); while(1) { temp1=read_add(0x07); if(((temp1&0b01000000)>>6)==1) { CE=0; delay_ms(50); //lcd_out(1,1,"data"); read_buff(0x61,test,32); uart1_write_text(test); lcd_out(1,1,test); reset(); CE=1; } if(uart1_data_ready()) { rfid[idx]=uart1_read(); ///////////////////////////////////////////////////////////03002e2838 if(rfid[idx]=='0'&&valid2<10) { valid2++; } else if(rfid[idx]=='3'&&valid2<10) { valid2++; } else if(rfid[idx]=='2'&&valid2<10) { valid2++; } else if(rfid[idx]=='E'&&valid2==5) { valid2++; } else if(rfid[idx]=='8'&&valid2<10) { valid2++; } else { valid2=0; } if(rfid[idx]=='0'&&valid1<10) //03002e90b0 { valid1++; } else if(rfid[idx]=='3'&&valid1==1) { valid1++; } else if(rfid[idx]=='2'&&valid1==4) { valid1++; } else if(rfid[idx]=='E'&&valid1==5) { valid1++; } else if(rfid[idx]=='9'&&valid1==6) { valid1++; } else if(rfid[idx]=='B'&&valid1==8) { valid1++; } else { valid1=0; } if(valid2>=10) { lcd_out(2,1,"User2 : 03002E2838"); delay_ms(1000); lcd_cmd(_lcd_clear); lcd_out(2,1,"UnValid"); valid2=0; for(i=0;i<30;i++) { rd0_bit=1; delay_us(400); rd0_bit=0; delay_us(19600); } delay_ms(1000); lcd_cmd(_lcd_clear); } if(valid1>=10) { lcd_out(2,1,"User1 : 03002E90B0"); delay_ms(1000); lcd_cmd(_lcd_clear); lcd_out(2,1,"Valid"); valid1=0; for(i=0;i<30;i++) { rd0_bit=1; delay_us(1500); rd0_bit=0; delay_us(18500); } delay_ms(1000); for(i=0;i<30;i++) { rd0_bit=1; delay_us(400); rd0_bit=0; delay_us(19600); } lcd_cmd(_lcd_clear); } } } }
void mcu_init(void) { mcu_arch_init(); #ifdef PERIPHERALS_AUTO_INIT sys_time_init(); #ifdef USE_LED led_init(); #endif /* for now this means using spektrum */ #if defined RADIO_CONTROL & defined RADIO_CONTROL_SPEKTRUM_PRIMARY_PORT & defined RADIO_CONTROL_BIND_IMPL_FUNC RADIO_CONTROL_BIND_IMPL_FUNC(); #endif #ifdef USE_UART0 uart0_init(); #endif #ifdef USE_UART1 uart1_init(); #endif #ifdef USE_UART2 uart2_init(); #endif #ifdef USE_UART3 uart3_init(); #endif #ifdef USE_UART4 uart4_init(); #endif #ifdef USE_UART5 uart5_init(); #endif #ifdef USE_I2C0 i2c0_init(); #endif #ifdef USE_I2C1 i2c1_init(); #endif #ifdef USE_I2C2 i2c2_init(); #endif #ifdef USE_ADC adc_init(); #endif #ifdef USE_USB_SERIAL VCOM_init(); #endif #if USE_SPI #if SPI_MASTER #if USE_SPI0 spi0_init(); #endif #if USE_SPI1 spi1_init(); #endif #if USE_SPI2 spi2_init(); #endif #if USE_SPI3 spi3_init(); #endif spi_init_slaves(); #endif // SPI_MASTER #if SPI_SLAVE #if USE_SPI0_SLAVE spi0_slave_init(); #endif #if USE_SPI1_SLAVE spi1_slave_init(); #endif #if USE_SPI2_SLAVE spi2_slave_init(); #endif #if USE_SPI3_SLAVE spi3_slave_init(); #endif #endif // SPI_SLAVE #endif // USE_SPI #ifdef USE_DAC dac_init(); #endif #else INFO("PERIPHERALS_AUTO_INIT not enabled! Peripherals (including sys_time) need explicit initialization.") #endif /* PERIPHERALS_AUTO_INIT */ }
void hw_init(void) { u08 t = md_InhibitPortPullUp; // see md.h #ifdef _AVR_IOM2561_H_ PRR0 = 0x00; // turn off power reduction registers on Mega2561 PRR1 = 0x00; #endif /* setup all ports as pulled up inputs */ DDRA = 0x00; // PortA if ((t&1)==0) PORTA = 0xFF; DDRB = 0x00; // PortB if ((t&2)==0) PORTB = 0xFF; DDRC = 0x00; // PortC if ((t&4)==0) PORTC = 0xFF; DDRD = 0x00; // PortD if ((t&8)==0) PORTD = 0xFF; DDRE = 0x00; // PortE if ((t&0x10)==0) PORTE = 0xFF; DDRF = 0x00; // PortF ADC Port all Input if ((t&0x20)==0) PORTF = 0xFF; DDRG = 0x00; // PortG if ((t&0x40)==0) PORTG = 0xFF; DDRA = 0x03; // PA0 PA1 output DDRB |= 0x10; // (1<<4); // PB4 output Speaker DDRC |= 0x04; // // Watchdog Enabled, Prescaler: OSC/16k // wdt_enable(WDTO_15MS); led_set(0, LED_OFF); // turn off all 4 leds #ifdef TIMER_CODE time_not_set = 1; timer0_init(); #endif #ifdef UART0 uart0_init(9600L, 8, 'N', 1, 0); #ifdef MDT_CODE if(MDT_COM_PORT == 0) uart0_init(MDT_BAUD_RATE, 8, 'N', 1, 0); #endif #endif #ifdef UART1 uart1_init(9600L, 8, 'N', 1, 0); #ifdef MDT_CODE if(MDT_COM_PORT == 1) uart1_init(MDT_BAUD_RATE, 8, 'N', 1, 0); #endif #endif #ifdef TWI_CODE // twi_init(); #endif #ifdef ADC_CODE ACSR = 0x80; // Analog Comparator Disabled adc_init(8); // start up continuous cycle of ADC capture, channels 0..7 #endif // including touch screen digitize } // now relies on timer0 call at 10 KHz
/*--------------------------------------------------------------------------*/ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_on(LEDS_RED); uart1_init(BAUD2UBR(115200)); /* Must come before first printf */ #if NETSTACK_CONF_WITH_IPV4 slip_arch_init(BAUD2UBR(115200)); #endif /* NETSTACK_CONF_WITH_IPV4 */ leds_on(LEDS_GREEN); /* xmem_init(); */ rtimer_init(); lcd_init(); PRINTF(CONTIKI_VERSION_STRING "\n"); /* * Hardware initialization done! */ leds_on(LEDS_RED); /* Restore node id if such has been stored in external mem */ // node_id_restore(); #ifdef NODEID node_id = NODEID; #ifdef BURN_NODEID flash_setup(); flash_clear(0x1800); flash_write(0x1800, node_id); flash_done(); #endif /* BURN_NODEID */ #endif /* NODE_ID */ if(node_id == 0) { node_id = *((unsigned short *)0x1800); } memset(node_mac, 0, sizeof(node_mac)); node_mac[6] = node_id >> 8; node_mac[7] = node_id & 0xff; /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */ #ifdef MAC_1 { uint8_t ieee[] = { MAC_1, MAC_2, MAC_3, MAC_4, MAC_5, MAC_6, MAC_7, MAC_8 }; memcpy(node_mac, ieee, sizeof(uip_lladdr.addr)); } #endif /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); ctimer_init(); set_rime_addr(); cc2420_init(); { uint8_t longaddr[8]; uint16_t shortaddr; shortaddr = (linkaddr_node_addr.u8[0] << 8) + linkaddr_node_addr.u8[1]; memset(longaddr, 0, sizeof(longaddr)); linkaddr_copy((linkaddr_t *)&longaddr, &linkaddr_node_addr); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", longaddr[0], longaddr[1], longaddr[2], longaddr[3], longaddr[4], longaddr[5], longaddr[6], longaddr[7]); cc2420_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); } leds_off(LEDS_ALL); if(node_id > 0) { PRINTF("Node id %u.\n", node_id); } else { PRINTF("Node id not set.\n"); } #if NETSTACK_CONF_WITH_IPV6 memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr)); /* Setup nullmac-like MAC for 802.15.4 */ queuebuf_init(); NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_NETWORK.init(); printf("%s %lu %u\n", NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval()), CC2420_CONF_CHANNEL); process_start(&tcpip_process, NULL); printf("IPv6 "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { printf("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } if(!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, UIP_DS6_DEFAULT_PREFIX, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); printf("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { printf("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #else /* NETSTACK_CONF_WITH_IPV6 */ NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_NETWORK.init(); printf("%s %lu %u\n", NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1: NETSTACK_RDC.channel_check_interval()), CC2420_CONF_CHANNEL); #endif /* NETSTACK_CONF_WITH_IPV6 */ #if !NETSTACK_CONF_WITH_IPV6 uart1_set_input(serial_line_input_byte); serial_line_init(); #endif #if TIMESYNCH_CONF_ENABLED timesynch_init(); timesynch_set_authority_level(linkaddr_node_addr.u8[0]); #endif /* TIMESYNCH_CONF_ENABLED */ /* process_start(&sensors_process, NULL); SENSORS_ACTIVATE(button_sensor);*/ energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); print_processes(autostart_processes); autostart_start(autostart_processes); duty_cycle_scroller_start(CLOCK_SECOND * 2); /* * This is the scheduler loop. */ watchdog_start(); watchdog_stop(); /* Stop the wdt... */ while(1) { int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); /* * Idle processing. */ int s = splhigh(); /* Disable interrupts. */ /* uart1_active is for avoiding LPM3 when still sending or receiving */ if(process_nevents() != 0 || uart1_active()) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_SWITCH(ENERGEST_TYPE_CPU, ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); watchdog_stop(); _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This statement will block until the CPU is woken up by an interrupt that sets the wake up flag. */ /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); watchdog_start(); ENERGEST_SWITCH(ENERGEST_TYPE_LPM, ENERGEST_TYPE_CPU); } } }
int main(void) { main_init(); rtca_init(); timer_a0_init(); uart0_init(); sim900_init_messagebus(); sim900.next_state = SIM900_OFF; settings_init(SEGMENT_B, VERSION_BASED); //settings_apply(); m.e = 0x0; m.seg[0] = 0x0; m.seg_num = 1; stat.http_post_version = POST_VERSION; stat.fix_id = 1; sim900.imei[0] = 0; sim900.flags = 0; gps_trigger_next = 0; gprs_trigger_next = s.gprs_loop_interval; rtca_set_next = 0; rtc_not_set = 1; gps_next_state = MAIN_GPS_IDLE; if (s.gps_invalidate_interval > s.gps_loop_interval) { s.gps_invalidate_interval = s.gps_loop_interval; } gprs_tx_trig = 0; gprs_tx_next = s.gprs_static_tx_interval; gprs_blackout_lift = 0; #ifdef DEBUG_GPS uart1_init(9600); uart1_tx_str("gps debug state\r\n", 17); #endif #ifdef DEBUG_GPRS uart0_tx_str("gprs debug state\r\n", 18); display_menu(); #endif #ifdef CALIBRATION sys_messagebus_register(&adc_calibration, SYS_MSG_RTC_SECOND); #else #ifndef DEBUG_GPRS sys_messagebus_register(&schedule, SYS_MSG_RTC_SECOND); sys_messagebus_register(&parse_gps, SYS_MSG_UART0_RX); #else sys_messagebus_register(&parse_UI, SYS_MSG_UART0_RX); #endif #ifndef DEBUG_GPS sys_messagebus_register(&parse_gprs, SYS_MSG_UART1_RX); #endif #endif #ifdef FM24_HAS_SLEEP_MODE fm24_sleep(); #endif // main loop while (1) { _BIS_SR(LPM3_bits + GIE); //wake_up(); #ifdef USE_WATCHDOG // reset watchdog counter WDTCTL = (WDTCTL & 0xff) | WDTPW | WDTCNTCL; #endif // new messages can be sent from within a check_events() call, so // parse the message linked list multiple times check_events(); check_events(); check_events(); #ifdef FM24_HAS_SLEEP_MODE // sleep if (fm24_status & FM24_AWAKE) { fm24_sleep(); } #endif // P4.0 and P4.1 //P4SEL &= ~0x3; /* PMMCTL0_H = 0xA5; SVSMHCTL &= ~SVMHE; SVSMLCTL &= ~(SVSLE+SVMLE); PMMCTL0_H = 0x00; */ } }
/*--------------------------------------------------------------------------*/ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_on(LEDS_RED); uart1_init(BAUD2UBR(115200)); /* Must come before first printf */ leds_on(LEDS_GREEN); /* xmem_init(); */ rtimer_init(); lcd_init(); watchdog_init(); PRINTF(CONTIKI_VERSION_STRING "\n"); /* PRINTF("Compiled at %s, %s\n", __TIME__, __DATE__);*/ /* * Hardware initialization done! */ leds_on(LEDS_RED); /* Restore node id if such has been stored in external mem */ #ifdef NODEID node_id = NODEID; #ifdef BURN_NODEID node_id_burn(node_id); node_id_restore(); /* also configures node_mac[] */ #endif /* BURN_NODEID */ #else node_id_restore(); /* also configures node_mac[] */ #endif /* NODE_ID */ /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */ #ifdef MAC_1 { uint8_t ieee[] = { MAC_1, MAC_2, MAC_3, MAC_4, MAC_5, MAC_6, MAC_7, MAC_8 }; memcpy(node_mac, ieee, sizeof(uip_lladdr.addr)); } #endif /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); ctimer_init(); set_rime_addr(); random_init(node_id); NETSTACK_RADIO.init(); #if CC11xx_CC1101 || CC11xx_CC1120 printf("Starting up cc11xx radio at channel %d\n", RF_CHANNEL); cc11xx_channel_set(RF_CHANNEL); #endif /* CC11xx_CC1101 || CC11xx_CC1120 */ #if CONFIGURE_CC2420 || CONFIGURE_CC2520 { uint8_t longaddr[8]; uint16_t shortaddr; shortaddr = (rimeaddr_node_addr.u8[0] << 8) + rimeaddr_node_addr.u8[1]; memset(longaddr, 0, sizeof(longaddr)); rimeaddr_copy((rimeaddr_t *)&longaddr, &rimeaddr_node_addr); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", longaddr[0], longaddr[1], longaddr[2], longaddr[3], longaddr[4], longaddr[5], longaddr[6], longaddr[7]); #if CONFIGURE_CC2420 cc2420_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); #endif /* CONFIGURE_CC2420 */ #if CONFIGURE_CC2520 cc2520_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); #endif /* CONFIGURE_CC2520 */ } #if CONFIGURE_CC2420 cc2420_set_channel(RF_CHANNEL); #endif /* CONFIGURE_CC2420 */ #if CONFIGURE_CC2520 cc2520_set_channel(RF_CHANNEL); #endif /* CONFIGURE_CC2520 */ #endif /* CONFIGURE_CC2420 || CONFIGURE_CC2520 */ NETSTACK_RADIO.on(); leds_off(LEDS_ALL); if(node_id > 0) { PRINTF("Node id %u.\n", node_id); } else { PRINTF("Node id not set.\n"); } #if WITH_UIP6 memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr)); /* Setup nullmac-like MAC for 802.15.4 */ queuebuf_init(); netstack_init(); printf("%s/%s %lu %u\n", NETSTACK_RDC.name, NETSTACK_MAC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval()), RF_CHANNEL); process_start(&tcpip_process, NULL); printf("IPv6 "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { printf("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } if(1) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, 0xfc00, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); printf("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { printf("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #else /* WITH_UIP6 */ netstack_init(); printf("%s %lu %u\n", NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1: NETSTACK_RDC.channel_check_interval()), RF_CHANNEL); #endif /* WITH_UIP6 */ #if !WITH_UIP6 uart1_set_input(serial_line_input_byte); serial_line_init(); #endif #ifdef NETSTACK_AES_H #ifndef NETSTACK_AES_KEY #error Please define NETSTACK_AES_KEY! #endif /* NETSTACK_AES_KEY */ { const uint8_t key[] = NETSTACK_AES_KEY; netstack_aes_set_key(key); } /*printf("AES encryption is enabled: '%s'\n", NETSTACK_AES_KEY);*/ printf("AES encryption is enabled\n"); #else /* NETSTACK_AES_H */ printf("Warning: AES encryption is disabled\n"); #endif /* NETSTACK_AES_H */ #if TIMESYNCH_CONF_ENABLED timesynch_init(); timesynch_set_authority_level(rimeaddr_node_addr.u8[0]); #endif /* TIMESYNCH_CONF_ENABLED */ #if CC11xx_CC1101 || CC11xx_CC1120 printf("cc11xx radio at channel %d\n", RF_CHANNEL); cc11xx_channel_set(RF_CHANNEL); #endif /* CC11xx_CC1101 || CC11xx_CC1120 */ #if CONFIGURE_CC2420 { uint8_t longaddr[8]; uint16_t shortaddr; shortaddr = (rimeaddr_node_addr.u8[0] << 8) + rimeaddr_node_addr.u8[1]; memset(longaddr, 0, sizeof(longaddr)); rimeaddr_copy((rimeaddr_t *)&longaddr, &rimeaddr_node_addr); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", longaddr[0], longaddr[1], longaddr[2], longaddr[3], longaddr[4], longaddr[5], longaddr[6], longaddr[7]); cc2420_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); } cc2420_set_channel(RF_CHANNEL); #endif /* CONFIGURE_CC2420 */ NETSTACK_RADIO.on(); /* process_start(&sensors_process, NULL); SENSORS_ACTIVATE(button_sensor);*/ energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); simple_rpl_init(); watchdog_start(); print_processes(autostart_processes); autostart_start(autostart_processes); duty_cycle_scroller_start(CLOCK_SECOND * 2); #if IP64_CONF_UIP_FALLBACK_INTERFACE_SLIP && WITH_SLIP /* Start the SLIP */ printf("Initiating SLIP: my IP is 172.16.0.2...\n"); slip_arch_init(0); { uip_ip4addr_t ipv4addr, netmask; uip_ipaddr(&ipv4addr, 172, 16, 0, 2); uip_ipaddr(&netmask, 255, 255, 255, 0); ip64_set_ipv4_address(&ipv4addr, &netmask); } uart1_set_input(slip_input_byte); #endif /* IP64_CONF_UIP_FALLBACK_INTERFACE_SLIP */ /* * This is the scheduler loop. */ while(1) { int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); /* * Idle processing. */ int s = splhigh(); /* Disable interrupts. */ /* uart1_active is for avoiding LPM3 when still sending or receiving */ if(process_nevents() != 0 || uart1_active()) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_OFF(ENERGEST_TYPE_CPU); ENERGEST_ON(ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); watchdog_stop(); _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This statement will block until the CPU is woken up by an interrupt that sets the wake up flag. */ /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } } }
/*---------------------------------------------------------------------------*/ int main(void) { /* * Initialize hardware. */ halInit(); clock_init(); uart1_init(115200); // Led initialization leds_init(); INTERRUPTS_ON(); PRINTF("\r\nStarting "); PRINTF(CONTIKI_VERSION_STRING); PRINTF(" on %s\r\n",boardDescription->name); /* * Initialize Contiki and our processes. */ process_init(); #if WITH_SERIAL_LINE_INPUT uart1_set_input(serial_line_input_byte); serial_line_init(); #endif //etimer_process should be started before ctimer init process_start(&etimer_process, NULL); //ctimer and rtimer should be initialized before netstack to enable RDC (cxmac, contikimac, lpp) ctimer_init(); rtimer_init(); netstack_init(); #if !UIP_CONF_IPV6 ST_RadioEnableAutoAck(FALSE); // Because frames are not 802.15.4 compatible. ST_RadioEnableAddressFiltering(FALSE); #endif set_rime_addr(); procinit_init(); energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); autostart_start(autostart_processes); watchdog_start(); while(1){ int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); ENERGEST_OFF(ENERGEST_TYPE_CPU); //watchdog_stop(); ENERGEST_ON(ENERGEST_TYPE_LPM); /* Go to idle mode. */ halSleepWithOptions(SLEEPMODE_IDLE,0); /* We are awake. */ //watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } }
/*---------------------------------------------------------------------------*/ int main(int argc, char **argv) { /* * Initalize hardware. */ msp430_cpu_init(); clock_init(); leds_init(); leds_on(LEDS_RED); clock_wait(2); uart1_init(115200); /* Must come before first printf */ #if WITH_UIP slip_arch_init(115200); #endif /* WITH_UIP */ clock_wait(1); leds_on(LEDS_GREEN); //ds2411_init(); /* XXX hack: Fix it so that the 802.15.4 MAC address is compatible with an Ethernet MAC address - byte 0 (byte 2 in the DS ID) cannot be odd. */ //ds2411_id[2] &= 0xfe; leds_on(LEDS_BLUE); //xmem_init(); leds_off(LEDS_RED); rtimer_init(); /* * Hardware initialization done! */ node_id = NODE_ID; /* Restore node id if such has been stored in external mem */ //node_id_restore(); /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */ #ifdef IEEE_802154_MAC_ADDRESS { uint8_t ieee[] = IEEE_802154_MAC_ADDRESS; //memcpy(ds2411_id, ieee, sizeof(uip_lladdr.addr)); //ds2411_id[7] = node_id & 0xff; } #endif //random_init(ds2411_id[0] + node_id); leds_off(LEDS_BLUE); /* * Initialize Contiki and our processes. */ process_init(); process_start(&etimer_process, NULL); ctimer_init(); init_platform(); set_rime_addr(); cc2520_init(); { uint8_t longaddr[8]; uint16_t shortaddr; shortaddr = (rimeaddr_node_addr.u8[0] << 8) + rimeaddr_node_addr.u8[1]; memset(longaddr, 0, sizeof(longaddr)); rimeaddr_copy((rimeaddr_t *)&longaddr, &rimeaddr_node_addr); printf("MAC %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x ", longaddr[0], longaddr[1], longaddr[2], longaddr[3], longaddr[4], longaddr[5], longaddr[6], longaddr[7]); cc2520_set_pan_addr(IEEE802154_PANID, shortaddr, longaddr); } cc2520_set_channel(RF_CHANNEL); printf(CONTIKI_VERSION_STRING " started. "); if(node_id > 0) { printf("Node id is set to %u.\n", node_id); } else { printf("Node id is not set.\n"); } #if WITH_UIP6 /* memcpy(&uip_lladdr.addr, ds2411_id, sizeof(uip_lladdr.addr)); */ memcpy(&uip_lladdr.addr, rimeaddr_node_addr.u8, UIP_LLADDR_LEN > RIMEADDR_SIZE ? RIMEADDR_SIZE : UIP_LLADDR_LEN); /* Setup nullmac-like MAC for 802.15.4 */ /* sicslowpan_init(sicslowmac_init(&cc2520_driver)); */ /* printf(" %s channel %u\n", sicslowmac_driver.name, RF_CHANNEL); */ /* Setup X-MAC for 802.15.4 */ queuebuf_init(); NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_NETWORK.init(); printf("%s %s, channel check rate %lu Hz, radio channel %u\n", NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1: NETSTACK_RDC.channel_check_interval()), RF_CHANNEL); process_start(&tcpip_process, NULL); printf("Tentative link-local IPv6 address "); { uip_ds6_addr_t *lladdr; int i; lladdr = uip_ds6_get_link_local(-1); for(i = 0; i < 7; ++i) { printf("%02x%02x:", lladdr->ipaddr.u8[i * 2], lladdr->ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); } if(!UIP_CONF_IPV6_RPL) { uip_ipaddr_t ipaddr; int i; uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); printf("Tentative global IPv6 address "); for(i = 0; i < 7; ++i) { printf("%02x%02x:", ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); } printf("%02x%02x\n", ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); } #else /* WITH_UIP6 */ NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_NETWORK.init(); printf("%s %s, channel check rate %lu Hz, radio channel %u\n", NETSTACK_MAC.name, NETSTACK_RDC.name, CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0? 1: NETSTACK_RDC.channel_check_interval()), RF_CHANNEL); #endif /* WITH_UIP6 */ #if !WITH_UIP && !WITH_UIP6 uart1_set_input(serial_line_input_byte); serial_line_init(); #endif leds_off(LEDS_GREEN); #if TIMESYNCH_CONF_ENABLED timesynch_init(); timesynch_set_authority_level((rimeaddr_node_addr.u8[0] << 4) + 16); #endif /* TIMESYNCH_CONF_ENABLED */ #if WITH_UIP process_start(&tcpip_process, NULL); process_start(&uip_fw_process, NULL); /* Start IP output */ process_start(&slip_process, NULL); slip_set_input_callback(set_gateway); { uip_ipaddr_t hostaddr, netmask; uip_init(); uip_ipaddr(&hostaddr, 172,16, rimeaddr_node_addr.u8[0],rimeaddr_node_addr.u8[1]); uip_ipaddr(&netmask, 255,255,0,0); uip_ipaddr_copy(&meshif.ipaddr, &hostaddr); uip_sethostaddr(&hostaddr); uip_setnetmask(&netmask); uip_over_mesh_set_net(&hostaddr, &netmask); /* uip_fw_register(&slipif);*/ uip_over_mesh_set_gateway_netif(&slipif); uip_fw_default(&meshif); uip_over_mesh_init(UIP_OVER_MESH_CHANNEL); printf("uIP started with IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&hostaddr)); } #endif /* WITH_UIP */ energest_init(); ENERGEST_ON(ENERGEST_TYPE_CPU); watchdog_start(); /* Stop the watchdog */ watchdog_stop(); #if !PROCESS_CONF_NO_PROCESS_NAMES print_processes(autostart_processes); #else /* !PROCESS_CONF_NO_PROCESS_NAMES */ putchar('\n'); /* include putchar() */ #endif /* !PROCESS_CONF_NO_PROCESS_NAMES */ autostart_start(autostart_processes); /* * This is the scheduler loop. */ while(1) { int r; do { /* Reset watchdog. */ watchdog_periodic(); r = process_run(); } while(r > 0); /* * Idle processing. */ int s = splhigh(); /* Disable interrupts. */ /* uart1_active is for avoiding LPM3 when still sending or receiving */ if(process_nevents() != 0 || uart1_active()) { splx(s); /* Re-enable interrupts. */ } else { static unsigned long irq_energest = 0; /* Re-enable interrupts and go to sleep atomically. */ ENERGEST_OFF(ENERGEST_TYPE_CPU); ENERGEST_ON(ENERGEST_TYPE_LPM); /* We only want to measure the processing done in IRQs when we are asleep, so we discard the processing time done when we were awake. */ energest_type_set(ENERGEST_TYPE_IRQ, irq_energest); watchdog_stop(); _BIS_SR(GIE | SCG0 | SCG1 | CPUOFF); /* LPM3 sleep. This statement will block until the CPU is woken up by an interrupt that sets the wake up flag. */ /* We get the current processing time for interrupts that was done during the LPM and store it for next time around. */ dint(); irq_energest = energest_type_time(ENERGEST_TYPE_IRQ); eint(); watchdog_start(); ENERGEST_OFF(ENERGEST_TYPE_LPM); ENERGEST_ON(ENERGEST_TYPE_CPU); } } }
void main() { char rec; int x,y; int f[5]; char send[7]; uart1_init(9600); trisc=0b10000000; DI=1; CLK=1; uart1_write_text("hello"); while(1) { if(uart1_data_ready()) { rec=uart1_read(); if(rec=='1') audio(1); if(rec=='2') audio(2); if(rec=='3') audio(3); if(rec=='4') audio(4); if(rec=='5') audio(5); } f[0]=adc_read(12); f[1]=adc_read(10); f[2]=adc_read(8); f[3]=adc_read(9); f[4]=adc_read(11); x=adc_read(0); y=adc_read(1); inttostr(f[0],send); uart1_write_text("f0="); uart1_write_text(send); uart1_write(13); IntToStr(f[1],send); uart1_write_text("f1="); uart1_write_text(send); uart1_write(13); IntToStr(f[2],send); uart1_write_text("f2="); uart1_write_text(send); uart1_write(13); IntToStr(f[3],send); uart1_write_text("f3="); uart1_write_text(send); uart1_write(13); IntToStr(f[4],send); uart1_write_text("f4="); uart1_write_text(send); uart1_write(13); IntToStr(x,send); uart1_write_text("x="); uart1_write_text(send); uart1_write(13); IntToStr(y,send); uart1_write_text("y="); uart1_write_text(send); uart1_write(13); delay_ms(1000); if(f[0]<170&&f[1]<180&&f[2]<180&&f[3]>250) { audio(2); delay_ms(5000); } else if(f[0]<170&&f[1]<180&&f[2]<180&&f[3]<170&&rec!='c') { audio(1); delay_ms(5000); } else if(f[0]>230&&f[1]>230&&f[2]>230&&f[3]>230&&x<280) { audio(3); delay_ms(5000); } else if(f[0]<170&&f[1]<180&&f[2]<180&&f[3]<170&&rec=='c') { audio(4); rec=0; delay_ms(5000); } else if(f[0]>230&&f[1]>230&&f[2]>230&&f[3]>230&&x>350&&rec=='b') { audio(5); rec=0; delay_ms(5000); } } }