void sysfs_power_meter::measure() { bool got_rate = false; bool got_capacity = false; rate = 0.0; capacity = 0.0; this->set_discharging(false); if (!is_present()) return; /** do not jump over. we may have discharging battery */ if (read_sysfs_string("/sys/class/power_supply/%s/status", name) == "Discharging") this->set_discharging(true); got_rate = set_rate_from_power(); got_capacity = set_capacity_from_energy(); if (!got_rate || !got_capacity) { double voltage = get_voltage(); if (voltage < 0.0) return; if (!got_rate) set_rate_from_current(voltage); if (!got_capacity) set_capacity_from_charge(voltage); } }
int main(void) { int result, done, op; result = SusiDllInit(); if (result == FALSE) { printf("SusiDllInit() failed\n"); return 1; } result = SusiHWMAvailable(); if (result == FALSE) { printf("SusiHWMAvailable() failed\n"); SusiDllUnInit(); return 1; } result = show_platform_info(); done = 0; while (! done) { show_menu(); if (scanf("%i", &op) <= 0) op = -1; switch (op) { case 0: done = 1; continue; case 1: result = get_voltage(); break; case 2: result = get_temperature(); break; case 3: result = get_fan_speed(); break; case 4: result = set_fan_speed(); break; default: printf("\nUnknown choice!\n\n"); continue; } if (result != 0) { printf("Library returns with error.\n"); SusiDllUnInit(); return 1; } } result = SusiDllUnInit(); if (result == FALSE) { printf("SusiDllUnInit() failed\n"); return 1; } return 0; }
int connect_to_robot() { int volts; printf("connecting..."); struct sockaddr_in s_addr; if (sock != -1) { close(sock); sock = -1; } if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { fprintf(stderr, "Failed to create socket\n"); exit(1); } while (1) { s_addr.sin_family = AF_INET; s_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); s_addr.sin_port = htons(55443); if (connect(sock, (struct sockaddr *) &s_addr, sizeof(s_addr)) >= 0) { /* connection succeeded */ printf("done\n"); sleep(1); volts = get_voltage(); printf("Battery state %2.1f volts\n", volts/10.0); re_initialize_robot(); return sock; } sleep(1); printf("."); fflush(stdout); } }
static int devfreq_cooling_get_requested_power(struct thermal_cooling_device *cdev, struct thermal_zone_device *tz, u32 *power) { struct devfreq_cooling_device *dfc = cdev->devdata; struct devfreq *df = dfc->devfreq; struct devfreq_dev_status *status = &df->last_status; unsigned long state; unsigned long freq = status->current_frequency; unsigned long voltage; u32 dyn_power = 0; u32 static_power = 0; int res; state = freq_get_state(dfc, freq); if (state == THERMAL_CSTATE_INVALID) { res = -EAGAIN; goto fail; } if (dfc->power_ops->get_real_power) { voltage = get_voltage(df, freq); if (voltage == 0) { res = -EINVAL; goto fail; } res = dfc->power_ops->get_real_power(df, power, freq, voltage); if (!res) { state = dfc->capped_state; dfc->res_util = dfc->power_table[state]; dfc->res_util *= SCALE_ERROR_MITIGATION; if (*power > 1) dfc->res_util /= *power; } else { goto fail; } } else { dyn_power = dfc->power_table[state]; /* Scale dynamic power for utilization */ dyn_power *= status->busy_time; dyn_power /= status->total_time; /* Get static power */ static_power = get_static_power(dfc, freq); *power = dyn_power + static_power; } trace_thermal_power_devfreq_get_power(cdev, status, freq, dyn_power, static_power, *power); return 0; fail: /* It is safe to set max in this case */ dfc->res_util = SCALE_ERROR_MITIGATION; return res; }
/* * remote configuration facility */ void fs20_configuration(void) { ccInitChip(); fs20_resetbuffer(); fs20_rxon(); fstelegram_t t; t.type = 'U'; // undefined uint16_t rxtimeout = 300; // wait 300*100ms= 30s for reception // wait for next telegram // exit if button pressed or timeout occured while(!fs20_readFS20Telegram(&t) && (rxtimeout--)>0) { _delay_ms(100); if(LED_PIN!=PA3) LED_TOGGLE(); // do not touch pin for CC1100 communication } fs20_idle(); // evaluate the result if(t.type=='F') { if((t.housecode==HOUSECODE) && (t.button==BUTTON_COMMAND)) { led_blink(3); // blink for confirmation switch(t.cmd) { case COMMAND_HCALIB1: xcalib1= get_voltage(); hcalib1= t.data[0]/100.0; recalibrate(); break; case COMMAND_HCALIB2: xcalib2= get_voltage(); hcalib2= t.data[0]/100.0; recalibrate(); break; case COMMAND_USFOFFSET: // we receive ufsoffset in centimeters set_usfconfig(t.data[0]/100.0, usfheight); break; case COMMAND_USFHEIGHT: // we receive usfheight in centimenters set_usfconfig(usfoffset, t.data[0]/100.0); break; } } } }
static int get_bo_voltage(struct mxs_regulator *sreg) { int uv; int offs; if (!sreg->parent) return -EINVAL; uv = get_voltage(sreg->parent); offs = (__raw_readl(sreg->parent->rdata->control_reg) & ~0x700) >> 8; return uv - 25000*offs; }
static uint8_t tick(uint32_t lap, uint32_t angle, struct segment_t *segment) { h = angle*150.0f+lap*10000; h = h % 0xffff; s=255; hsv_to_rgb(); char text[17]; sprintf(text,"%i",(int)get_voltage()); uint32_t length = strlen(text); uint32_t pos = (uint32_t)((angle)/10.0f); uint32_t charpos = (pos - (pos % 6))/6; uint32_t ascii = 0 ; if(charpos < length) { ascii = text[charpos]-32; } uint8_t line = font8x6[ascii][pos%6]; for(uint8_t x = 0; x < 8;x++) { if((line & (1<<(7-x)))== (1<<(7-x))) { segment->color[x].red = nr; segment->color[x].green = ng; segment->color[x].blue = nb; } else { segment->color[x].red = 0; segment->color[x].green = 0; segment->color[x].blue = 30; } } segment->color[8].red = 0; segment->color[8].green = 0; segment->color[8].blue = 30 ; segment->color[9].red = 0; segment->color[9].green = 0; segment->color[9].blue = 30 ; return 0; }
/** * get_static_power() - calculate the static power * @dfc: Pointer to devfreq cooling device * @freq: Frequency in Hz * * Calculate the static power in milliwatts using the supplied * get_static_power(). The current voltage is calculated using the * OPP library. If no get_static_power() was supplied, assume the * static power is negligible. */ static unsigned long get_static_power(struct devfreq_cooling_device *dfc, unsigned long freq) { struct devfreq *df = dfc->devfreq; unsigned long voltage; if (!dfc->power_ops->get_static_power) return 0; voltage = get_voltage(df, freq); if (voltage == 0) return 0; return dfc->power_ops->get_static_power(df, voltage); }
int cgiMain() { int sensor_num,sensor_idx; int i,j,k; char name[81]; light_sensor *p_sensor ; cgiFormInteger("sensor_num", &sensor_num, 0); if(sensor_num > 100) sensor_num = 100; cgiWriteEnvironment("/CHANGE/THIS/PATH/capcgi.dat"); cgiHeaderContentType("text/html"); OutHead(); OutBodyStart(); if(0 == check_password()) return 0; if(0 == sensor_num) { fprintf(cgiOut, "<p>数据出错,退出!!</p>\n"); OutBodyEnd(); return 0; } else { pwsw_h.sensor_num= sensor_num; for(i=0;i<sensor_num;i++) { p_sensor = &pwsw_h.sensor[i]; p_sensor->lux = get_lux(i+1); p_sensor->voltage = get_voltage(i+1); } } save_to_xml_file(); fprintf(cgiOut, "<p>保存成功,请返回!</p>\n"); fprintf(cgiOut, " <input type=\"button\" name=\"rest\" onclick=\"javascript:history.go(-1)\" value=\"重新载入\" />\n"); OutBodyEnd(); return 0; }
int balance_cal(void) { //UINT8 iMax = 0, UINT8 i = 0, j = 0; static int n = 0; TYPE_TEMP T_board = BMS_GetTemperatureValueAverage(); memset(validBalance, 0, TOTAL_VOLTAGES); if (n_open_balance == 5) { n_open_balance = 0; get_voltage((TYPE_VOLTAGE *) v_temp); n = 2; //(TOTAL_BALANCES - TOTAL_BALANCES * T_board / 75); if (n <= 0) goto end; select_nMaxFromArray(v_temp, TOTAL_VOLTAGES, validBalance, n); memset(&gb, 0, sizeof(gb)); for (i = 0; i < n; i++) { if (((getVoltageValueByCellIndex(validBalance[i]) - BMS_GetVoltageValueMin()) > THREASHOLD_V_BANLANCE) && (BMS_GetVoltageValueMin() >= VALUE_TH_BALANCE_VOL)) { gb.flags[validBalance[i]] = 1; } } for (i = 0; i < TOTAL_VOLTAGES; i++) { if (gb.flags[i]) { OPEN_BANLANCE_BY_LTC6804(i); } else { CLOSE_BANLANCE_BY_LTC6804(i); } } // battery_blance_sw_get(gb.Bytebalances); // mprintf("balance cal result:%02x%02x%02x\r\n", gb.Bytebalances[0], // gb.Bytebalances[1], gb.Bytebalances[2]); } end: n_open_balance++; }
void enter_sleep_mode(void) { get_voltage(); xprintf("sleeping\r\n"); cli(); PORTD = 0x73; // Select all rows PCMSK0 = 0xFF; // Enable all pin change interrupts PCIFR = (1 << PCIF0); PCICR = (1 << PCIE0); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sei(); // Enable interrupts sleep_mode(); check_voltage(); }
static uint8_t tick(uint32_t lap, uint32_t angle, struct segment_t *segment) { char text[17]; sprintf(text,"%i",(int)get_voltage()); uint32_t length = strlen(text); uint32_t pos = (uint32_t)((angle)/10.0f); uint32_t charpos = (pos - (pos % 4))/4; int ascii = -1 ; if(charpos < length) { ascii = text[charpos]-48; } uint8_t line = get_line(pos%4,ascii); for(uint8_t x = 0; x < 10;x++) { if(line & (1<<(4-x/2))) { segment->color[x].red = 255; segment->color[x].green = 255; segment->color[x].blue = 255; } else { segment->color[x].red = 0; segment->color[x].green = 0; segment->color[x].blue = 30; } } return 0; }
static int set_bo_voltage(struct mxs_regulator *sreg, int bo_uv) { int uv; int offs; u32 reg; int i; if (!sreg->parent) return -EINVAL; uv = get_voltage(sreg->parent); offs = (uv - bo_uv) / 25000; if (offs < 0 || offs > 7) return -EINVAL; reg = (__raw_readl(sreg->parent->rdata->control_reg) & ~0x700); pr_debug("%s: calculated offs %d\n", __func__, offs); __raw_writel((offs << 8) | reg, sreg->parent->rdata->control_reg); for (i = 10000; i; i--) { if (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & BM_POWER_STS_DC_OK) break; udelay(1); } if (i) goto out; for (i = 10000; i; i--) { if (__raw_readl(REGS_POWER_BASE + HW_POWER_STS) & BM_POWER_STS_DC_OK) break; udelay(1); } out: return !i; }
/** * \brief Example entry point. * * \return Unused (ANSI-C compatibility). */ int main(void) { uint8_t c_choice; int16_t s_adc_value; int16_t s_dac_value; int16_t s_threshold = 0; float f_dac_data; uint32_t ul_dac_data; /* Initialize the SAM system. */ sysclk_init(); board_init(); configure_console(); /* Output example information. */ puts(STRING_HEADER); /* Initialize threshold. */ gs_us_low_threshold = 500; gs_us_high_threshold = 2000; struct adc_config adc_cfg = { /* System clock division factor is 16 */ .prescal = ADC_PRESCAL_DIV16, /* The APB clock is used */ .clksel = ADC_CLKSEL_APBCLK, /* Max speed is 150K */ .speed = ADC_SPEED_150K, /* ADC Reference voltage is 0.625*VCC */ .refsel = ADC_REFSEL_1, /* Enables the Startup time */ .start_up = CONFIG_ADC_STARTUP }; struct adc_seq_config adc_seq_cfg = { /* Select Vref for shift cycle */ .zoomrange = ADC_ZOOMRANGE_0, /* Pad Ground */ .muxneg = ADC_MUXNEG_1, /* DAC Internal */ .muxpos = ADC_MUXPOS_3, /* Enables the internal voltage sources */ .internal = ADC_INTERNAL_3, /* Disables the ADC gain error reduction */ .gcomp = ADC_GCOMP_DIS, /* Disables the HWLA mode */ .hwla = ADC_HWLA_DIS, /* 12-bits resolution */ .res = ADC_RES_12_BIT, /* Enables the single-ended mode */ .bipolar = ADC_BIPOLAR_SINGLEENDED }; struct adc_ch_config adc_ch_cfg = { .seq_cfg = &adc_seq_cfg, /* Internal Timer Max Counter */ .internal_timer_max_count = 60, /* Window monitor mode is off */ .window_mode = ADC_WM_MODE_3, /* The equivalent voltage value is 500 * VOLT_REF / 4095 = 251mv. */ .low_threshold = gs_us_low_threshold, /* The equivalent voltage value is 2000 * VOLT_REF / 4095 = 1002mv. */ .high_threshold = gs_us_high_threshold, }; start_dac(); if(adc_init(&g_adc_inst, ADCIFE, &adc_cfg) != STATUS_OK) { puts("-F- ADC Init Fail!\n\r"); while(1); } if(adc_enable(&g_adc_inst) != STATUS_OK) { puts("-F- ADC Enable Fail!\n\r"); while(1); } adc_ch_set_config(&g_adc_inst, &adc_ch_cfg); adc_configure_trigger(&g_adc_inst, ADC_TRIG_CON); adc_configure_gain(&g_adc_inst, ADC_GAIN_1X); adc_set_callback(&g_adc_inst, ADC_WINDOW_MONITOR, adcife_wm_handler, ADCIFE_IRQn, 1); /* Display main menu. */ display_menu(); while (1) { scanf("%c", (char *)&c_choice); printf("%c\r\n", c_choice); switch (c_choice) { case '0': adc_disable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); printf("DAC output is set to(mv) from 0mv to %dmv: ", (int32_t)VOLT_REF); s_dac_value = get_voltage(); puts("\r"); f_dac_data = (float)s_dac_value * DACC_MAX_DATA / VDDANA; ul_dac_data = f_to_int(f_dac_data); if (s_dac_value >= 0) { dacc_write_conversion_data(DACC, ul_dac_data); } delay_ms(100); adc_clear_status(&g_adc_inst, ADCIFE_SCR_WM); adc_enable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); break; case '1': adc_disable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); printf("Low threshold is set to(mv) from 0mv to %dmv: ", (int32_t)VOLT_REF); s_threshold = get_voltage(); puts("\r"); if (s_threshold >= 0) { s_adc_value = s_threshold * MAX_DIGITAL / VOLT_REF; adc_configure_wm_threshold(&g_adc_inst, s_adc_value, gs_us_high_threshold); /* Renew low threshold. */ gs_us_low_threshold = s_adc_value; float f_low_threshold = (float)gs_us_low_threshold * VOLT_REF / MAX_DIGITAL; uint32_t ul_low_threshold = f_to_int(f_low_threshold); printf("Setting low threshold to %u mv (reg value to 0x%x ~%d%%)\n\r", ul_low_threshold, gs_us_low_threshold, gs_us_low_threshold * 100 / MAX_DIGITAL); } adc_clear_status(&g_adc_inst, ADCIFE_SCR_WM); adc_enable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); break; case '2': adc_disable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); printf("High threshold is set to(mv)from 0mv to %dmv:", (int32_t)VOLT_REF); s_threshold = get_voltage(); puts("\r"); if (s_threshold >= 0) { s_adc_value = s_threshold * MAX_DIGITAL / VOLT_REF; adc_configure_wm_threshold(&g_adc_inst, gs_us_low_threshold, s_adc_value); /* Renew high threshold. */ gs_us_high_threshold = s_adc_value; float f_high_threshold = (float)gs_us_high_threshold * VOLT_REF / MAX_DIGITAL; uint32_t ul_high_threshold = f_to_int(f_high_threshold); printf("Setting high threshold to %u mv (reg value to 0x%x ~%d%%)\n\r", ul_high_threshold, gs_us_high_threshold, gs_us_high_threshold * 100 / MAX_DIGITAL); } adc_clear_status(&g_adc_inst, ADCIFE_SCR_WM); adc_enable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); break; case '3': adc_disable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); puts("-a. Above low threshold.\n\r" "-b. Below high threshold.\n\r" "-c. In the comparison window.\n\r" "-d. Out of the comparison window.\n\r" "-q. Quit the setting.\r"); c_choice = get_wm_mode(); adc_configure_wm_mode(&g_adc_inst, c_choice); printf("Comparison mode is %c.\n\r", 'a' + c_choice - 1); adc_clear_status(&g_adc_inst, ADCIFE_SCR_WM); adc_enable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); break; case 'm': display_menu(); break; case 'i': display_info(); adc_clear_status(&g_adc_inst, ADCIFE_SCR_WM); adc_enable_interrupt(&g_adc_inst, ADC_WINDOW_MONITOR); break; } puts("Press \'m\' or \'M\' to display the main menu again!\r"); } }
// Control test // Feedback control test void ControlLogging(UINT8 node_id) { // Logging parameters UINT8 i2c_status; float curr_ang, curry_time = 0.0, curr_voltage = 0.0, log_time = 2.0; UINT32 start_millis, start_log_millis, log_Ts = 10; float reference = 1.5708; //#define PROGRAM_NEW_PARAMS #ifdef PROGRAM_NEW_PARAMS control_params_struct newControlParams = { .Fs = 625, .nd = 2, .d = {-0.6327,0.8222}, .nc = 2, .c = {-0.6327,0.8222}, .nf = 1, .f = {-0.9810} }; i2c_status = program_control_params(node_id,&newControlParams); UINT8 prog_status; if (i2c_status == I2C_STATUS_SUCCESFUL) { i2c_status = read_control_prog_status(1, &prog_status); if(i2c_status == I2C_STATUS_SUCCESFUL && prog_status == MOTOR_CONTROL_PROGRAMMING_STATUS_SUCCESS) { putsUART1("Control programming succesful!\n\r"); } else { putsUART1("Control programming failed, quitting...\n\r"); return; } } #else //set_default_control_params(node_id); #endif sprintf(buf,"\nreference: %0.2f rad, log time: %0.1f sec, Ts: %d ms\n\n\r", reference, log_time, log_Ts); putsUART1(buf); putsUART1("| Time | motor angle | motor voltage |\n\n\r"); delay_ms(100); putsUART1("starting logging:\n\r"); i2c_status = calibrate_encoder_zero(node_id); if (i2c_status != I2C_STATUS_SUCCESFUL) { sprintf(buf,"Motor with id %d not found on the bus, quitting\n\r",node_id); putsUART1(buf); return; } set_angle(node_id,0.0); start_millis = millis; unsigned char log_stage = 0; while(curry_time < (1.0 + 2.0*log_time)) { start_log_millis = millis; curry_time = ((float)(start_log_millis - start_millis))/1000.0; if ( (log_stage == 0) && (curry_time > 1.0) ){ i2c_status = set_angle(node_id,reference); if (i2c_status == I2C_STATUS_SUCCESFUL) { log_stage = 1; } } if ( (log_stage == 1) && curry_time > (1.0 + log_time)) { i2c_status = set_angle(node_id,0.0); if (i2c_status == I2C_STATUS_SUCCESFUL) { log_stage = 2; } } i2c_status = get_angle(node_id,&curr_ang); i2c_status |= get_voltage(node_id,&curr_voltage); if (i2c_status == I2C_STATUS_SUCCESFUL) { sprintf(buf,"%f, %f, %f\n\r", curry_time, curr_ang, curr_voltage); putsUART1(buf); } // Wait until Ts milliseconds has passed since start while( millis - start_log_millis < log_Ts); } putsUART1("logging completed!\n\r"); set_calibration_status_unknown(node_id); }
int get_percentage(void) { return (51.02*get_voltage() - 535.71); }
int main(void) { hardware_init(); luke_init(); #ifdef MULTI_CLASS_DEVICE hid_set_interface_list(hid_interfaces, sizeof (hid_interfaces)); #endif usb_init(); uint8_t regAddr = 0; while (1) { if (usb_is_configured() && usb_out_endpoint_has_data(1)) { // uint8_t len; const unsigned char *RxDataBuffer; unsigned char *TxDataBuffer = usb_get_in_buffer(1); /* Data received from host */ if (!usb_in_endpoint_halted(1)) { /* Wait for EP 1 IN to become free then send. This of * course only works using interrupts. */ while (usb_in_endpoint_busy(1)) ; usb_get_out_buffer(1, &RxDataBuffer); uint8_t pcktVer = RxDataBuffer[0] & 0xC0; uint8_t pcktLen = RxDataBuffer[0] & 0x2F; if (pcktVer == PROTOCOL_VERSION && pcktLen > 1) { uint8_t opcode = RxDataBuffer[1]; TxDataBuffer[1] = opcode; // echo back operation code ATTID id = (RxDataBuffer[2] << 8) + RxDataBuffer[3]; uint8_t len; switch (opcode) { case OP_ATT_VALUE_GET: TxDataBuffer[2] = RC_OK; // Return OK code TxDataBuffer[0] = PROTOCOL_VERSION; switch (id) { case ATT_PRODUCT_NAME: len = strlen(PRODUCT_NAME) + 1; // +1 for NULL TxDataBuffer[0] |= len + 3; // packet length memcpy(&TxDataBuffer[3], PRODUCT_NAME, len); break; case ATT_PRODUCT_REVISION: TxDataBuffer[0] |= 2 + 3; // packet length TxDataBuffer[3] = '0' + PORTCbits.RC2; TxDataBuffer[4] = NULL; break; case ATT_PRODUCT_SERIAL: /* TxDataBuffer[0] |= NVM_PRODUCT_SERIAL_SIZE + 3; // packet length for (uint8_t i=0; i<NVM_PRODUCT_SERIAL_SIZE; i++) { // Please note that 1 word of HEF is 14bits but lower 8bits is high-endurance TxDataBuffer[i+3] = (uint8_t) FLASH_ReadWord(NVM_PRODUCT_SERIAL_ADDR + i); } */ TxDataBuffer[0] |= NVM_PRODUCT_SERIAL_SIZE + 3; // packet length memcpy(&TxDataBuffer[3], NVM_PRODUCT_SERIAL_ADDR, NVM_PRODUCT_SERIAL_SIZE); break; case ATT_FIRM_VERSION: len = strlen(FIRM_VERSION) + 1; // +1 for NULL TxDataBuffer[0] |= len + 3; // packet length memcpy(&TxDataBuffer[3], FIRM_VERSION, len); break; case ATT_I2C0_RW_2BYTE: TxDataBuffer[0] |= 2 + 3; // packet length uint16_t dat = i2c_reg_read(regAddr); TxDataBuffer[4] = dat >> 8; TxDataBuffer[3] = dat; break; case ATT_VOLTAGE: TxDataBuffer[0] |= 4 + 3; // packet length float volt = get_voltage(); TxDataBuffer[3] = 0x00; memcpy(&TxDataBuffer[4], &volt, 3); break; case ATT_CURRENT: TxDataBuffer[0] |= 4 + 3; // packet length float curr = get_current(); TxDataBuffer[3] = 0x00; memcpy(&TxDataBuffer[4], &curr, 3); break; default: TxDataBuffer[0] |= 3; // packet length TxDataBuffer[2] = RC_FAIL; // Return error code break; } // end of switch (id) break; case OP_ATT_VALUE_SET: TxDataBuffer[0] = PROTOCOL_VERSION | 3; // packet length TxDataBuffer[2] = RC_OK; // Return OK code switch (id) { case ATT_I2C0_REG_ADDR: regAddr = RxDataBuffer[4]; break; case ATT_I2C0_RW_2BYTE: i2c_reg_write(regAddr, RxDataBuffer[5], RxDataBuffer[4]); break; default: TxDataBuffer[2] = RC_FAIL; // Return error code break; } // end of switch (id) break; default: TxDataBuffer[0] = PROTOCOL_VERSION | 3; // packet length TxDataBuffer[2] = RC_FAIL; // Return error code break; } // switch (opcode) // Send response memcpy(usb_get_in_buffer(1), TxDataBuffer, EP_1_IN_LEN); usb_send_in_buffer(1, EP_1_IN_LEN); } // end of if (pcktVer == PROTOCOL_VERSION && pcktLen > 1) } usb_arm_out_endpoint(1); } #ifndef USB_USE_INTERRUPTS usb_service(); #endif }
/** * \brief Example entry point. * * Initialize ADC to 12-bit, enable channel "ADC_CHANNEL_POTENTIOMETER", then * enable hardware trigger with TIOA0 every second. Finally, start conversion. * * \return Unused (ANSI-C compatibility). */ int main(void) { uint8_t c_choice; int16_t s_adc_value; int16_t s_threshold = 0; /* Initialize the SAM system. */ sysclk_init(); board_init(); configure_console(); /* Output example information. */ puts(STRING_HEADER); /* Initialize threshold. */ gs_us_low_threshold = 0x0; gs_us_high_threshold = MAX_DIGITAL; /* Enable peripheral clock. */ pmc_enable_periph_clk(ID_ADC); /* Initialize ADC. */ /* startup = 10: 640 periods of ADCClock * for prescale = 4 * prescale: ADCClock = MCK / ( (PRESCAL+1) * 2 ) => 64MHz / ((4+1)*2) = 6.4MHz * ADC clock = 6.4 MHz */ adc_init(ADC, sysclk_get_cpu_hz(), 6400000, 10); #if SAM3S || SAM3XA || SAM4S adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); #elif SAM3N adc_configure_timing(ADC, 0); #endif adc_check(ADC, sysclk_get_cpu_hz()); /* Hardware trigger TIOA0. */ adc_configure_trigger(ADC, ADC_TRIG_TIO_CH_0, 0); /* Enable channels for x,y and z. */ adc_enable_channel(ADC, ADC_CHANNEL_POTENTIOMETER); /* Configure TC. */ configure_tc0(); /* Channel 5 has to be compared. */ adc_set_comparison_channel(ADC, ADC_CHANNEL_POTENTIOMETER); /* Compare mode, in the window. */ adc_set_comparison_mode(ADC, ADC_EMR_CMPMODE_IN); /* Set up Threshold. */ adc_set_comparison_window(ADC, gs_us_high_threshold, gs_us_low_threshold); /* Enable ADC interrupt. */ NVIC_EnableIRQ(ADC_IRQn); /* Start TC0 and hardware trigger. */ tc_start(TC0, 0); /* Display main menu. */ display_menu(); while (1) { while (uart_read(CONSOLE_UART, &c_choice)) { } printf("%c\r\n", c_choice); switch (c_choice) { case '0': s_adc_value = adc_get_channel_value(ADC, ADC_CHANNEL_POTENTIOMETER); printf("-I- Current voltage is %d mv, %d%% of ADVREF\n\r", (s_adc_value * VOLT_REF / MAX_DIGITAL), (s_adc_value * 100 / MAX_DIGITAL)); break; case '1': puts("Low threshold is set to(mv):"); s_threshold = get_voltage(); puts("\r"); if (s_threshold >= 0) { s_adc_value = s_threshold * MAX_DIGITAL / VOLT_REF; adc_set_comparison_window(ADC, s_adc_value, gs_us_high_threshold); /* Renew low threshold. */ gs_us_low_threshold = s_adc_value; float f_low_threshold = (float)gs_us_low_threshold * VOLT_REF / MAX_DIGITAL; uint32_t ul_low_threshold = f_to_int(f_low_threshold); printf("Setting low threshold to %u mv (reg value to 0x%x ~%d%%)\n\r", ul_low_threshold, gs_us_low_threshold, gs_us_low_threshold * 100 / MAX_DIGITAL); } break; case '2': puts("High threshold is set to(mv):"); s_threshold = get_voltage(); puts("\r"); if (s_threshold >= 0) { s_adc_value = s_threshold * MAX_DIGITAL / VOLT_REF; adc_set_comparison_window(ADC, gs_us_low_threshold, s_adc_value); /* Renew high threshold. */ gs_us_high_threshold = s_adc_value; float f_high_threshold = (float)gs_us_high_threshold * VOLT_REF / MAX_DIGITAL; uint32_t ul_high_threshold = f_to_int(f_high_threshold); printf("Setting high threshold to %u mv (reg value to 0x%x ~%d%%)\n\r", ul_high_threshold, gs_us_high_threshold, gs_us_high_threshold * 100 / MAX_DIGITAL); } break; case '3': puts("-a. Below low threshold.\n\r" "-b. Above high threshold.\n\r" "-c. In the comparison window.\n\r" "-d. Out of the comparison window.\n\r" "-q. Quit the setting.\r"); c_choice = get_comparison_mode(); adc_set_comparison_mode(ADC, c_choice); printf("Comparison mode is %c.\n\r", 'a' + c_choice); break; case 'm': case 'M': display_menu(); break; case 'i': case 'I': display_info(); break; case 's': case 'S': enter_asleep(); break; } puts("Press \'m\' or \'M\' to display the main menu again!\r"); } }
int main(void) { float voltage; uint8_t skytraq_packet_id = 0; clock_setup(); gpio_setup(); usart_setup(); adc_setup(); delay_ms(100); gps_tx_queue.enqueue(binary_rate); usart_enable_tx_interrupt(USART2); // enable GPS TX interrupt while (1) { voltage = get_voltage(); if (voltage < 6.2) { // char buf[100]; // sprintf(buf, "%f\r\n", voltage); // for(int i = 0; i < strlen(buf); ++i){ // usart_send_blocking(USART1, buf[i]); // } usart_disable_tx_interrupt(USART2); usart_disable_rx_interrupt(USART2); gpio_clear(GPIOB, GPIO2 | GPIO12); // hold both GPS and XBEE in reset usart_disable_tx_interrupt(USART3); usart_disable_rx_interrupt(USART3); while(1); // and spin } xbee_packet_t xbee_pkt; if (!gps_rx_queue.isEmpty()) { gps_packet_t gps_pkt = gps_rx_queue.dequeue(); if (gps_pkt.payload[0] == GPS_ACK || gps_pkt.payload[0] == GPS_NACK) { // ignore ACK and NACK continue; } ++skytraq_packet_id; // length/max_length + 1 more if remainder is bigger than 0 uint8_t fragments_needed = (gps_pkt.length / MAX_FRAG_LENGTH) + (((gps_pkt.length % MAX_FRAG_LENGTH) > 0) ? 1 : 0); xbee_build_header(xbee_pkt); //xbee_set_dest_addr(xbee_pkt, 0x0013A20040AD1B15, 0xFFFE); xbee_set_dest_addr(xbee_pkt, 0x000000000000FFFF, 0xFFFE); uint8_t current_fragment = 1; char* src_ptr = &(gps_pkt.payload[0]); while (current_fragment <= fragments_needed) { xbee_pkt.payload[INDEX_TYPE] = TYPE_SKYTRAQ; xbee_pkt.payload[INDEX_ID] = skytraq_packet_id; xbee_pkt.payload[INDEX_X] = current_fragment; xbee_pkt.payload[INDEX_Y] = fragments_needed; size_t bytes_to_copy = ( (current_fragment == fragments_needed) ? (gps_pkt.length % MAX_FRAG_LENGTH) : MAX_FRAG_LENGTH); memcpy(&(xbee_pkt.payload[INDEX_SKYTRAQ_START]), src_ptr, bytes_to_copy); if (current_fragment == fragments_needed) { xbee_pkt.length = INDEX_SKYTRAQ_START + (gps_pkt.length % MAX_FRAG_LENGTH) + 1; } else { xbee_pkt.length = INDEX_SKYTRAQ_START + MAX_FRAG_LENGTH + 1; } xbee_tx_queue.enqueue(xbee_pkt); usart_enable_tx_interrupt(USART3); // enable XBEE TX interrupt ++current_fragment; src_ptr += bytes_to_copy; } } if (!xbee_rx_queue.isEmpty()) { xbee_rx_queue.dequeue(); } } // while(1) return 0; }
void dump_useful_info() { int i; rpi_mailbox_property_t *buf; clock_info_t *clk_info; rpi_mailbox_tag_t tags[] = { TAG_GET_FIRMWARE_VERSION , TAG_GET_BOARD_MODEL , TAG_GET_BOARD_REVISION , TAG_GET_BOARD_MAC_ADDRESS , TAG_GET_BOARD_SERIAL //, TAG_GET_ARM_MEMORY //, TAG_GET_VC_MEMORY //, TAG_GET_DMA_CHANNELS //, TAG_GET_CLOCKS //, TAG_GET_COMMAND_LINE }; char *tagnames[] = { "FIRMWARE_VERSION" , "BOARD_MODEL" , "BOARD_REVISION" , "BOARD_MAC_ADDRESS" , "BOARD_SERIAL" //, "ARM_MEMORY" //, "VC_MEMORY" //, "DMA_CHANNEL" //, "CLOCKS" //, "COMMAND_LINE" }; char *clock_names[] = { "RESERVED", "EMMC", "UART", "ARM", "CORE", "V3D", "H264", "ISP", "SDRAM", "PIXEL", "PWM" }; int n = sizeof(tags) / sizeof(rpi_mailbox_tag_t); RPI_PropertyInit(); for (i = 0; i < n ; i++) { RPI_PropertyAddTag(tags[i]); } RPI_PropertyProcess(); for (i = 0; i < n; i++) { buf = RPI_PropertyGet(tags[i]); print_tag_value(tagnames[i], buf, 1); } for (i = MIN_CLK_ID; i <= MAX_CLK_ID; i++) { clk_info = get_clock_rates(i); printf("%15s_FREQ : %10.3f MHz %10.3f MHz %10.3f MHz\r\n", clock_names[i], (double) (clk_info->rate) / 1.0e6, (double) (clk_info->min_rate) / 1.0e6, (double) (clk_info->max_rate) / 1.0e6 ); } printf(" CORE TEMP : %6.2f °C\r\n", get_temp()); printf(" CORE VOLTAGE : %6.2f V\r\n", get_voltage(COMPONENT_CORE)); printf(" SDRAM_C VOLTAGE : %6.2f V\r\n", get_voltage(COMPONENT_SDRAM_C)); printf(" SDRAM_P VOLTAGE : %6.2f V\r\n", get_voltage(COMPONENT_SDRAM_P)); printf(" SDRAM_I VOLTAGE : %6.2f V\r\n", get_voltage(COMPONENT_SDRAM_I)); printf(" CMD_LINE : %s\r\n", get_cmdline()); printf(" COPRO : %s\r\n", get_cmdline_prop("copro")); }
float voltage_reader::get_voltage() { return get_voltage(1); }
// Steps through a lot of random voltages void RandomLogging(UINT8 node_id, float max_voltage) { UINT8 i2c_status; float curr_ang, curry_time = 0.0, swap_time; UINT16 log_time = 2, log_Ts = 10; float curr_voltage, sent_voltage; UINT32 start_millis, start_log_millis, random_store = 0; i2c_status = disable_motor(node_id); if (i2c_status != I2C_STATUS_SUCCESFUL) { sprintf(buf,"Motor with id %d not found on the bus, quitting\n\r",node_id); putsUART1(buf); return; } sprintf(buf,"\nlog voltages: random, log time: %d sec, Ts: %d ms\n\n\r", log_time, log_Ts); putsUART1(buf); putsUART1("| Time | motor angle | motor voltage |\n\n\r"); delay_ms(100); putsUART1("starting logging:\n\r"); swap_time = ((float) log_time); calibrate_encoder_zero(node_id); set_voltage(node_id,0.0); sent_voltage = 0.0; start_millis = millis; while(curry_time < 30.0) { start_log_millis = millis; curry_time = ((float)(start_log_millis - start_millis))/1000.0; i2c_status = get_angle(node_id,&curr_ang); i2c_status |= get_voltage(node_id,&curr_voltage); if (i2c_status == I2C_STATUS_SUCCESFUL) { sprintf(buf,"%f, %f, %f\n\r", curry_time, curr_ang, curr_voltage); putsUART1(buf); } // To determine next random voltage // This should be random enough //random_store = (random_store << 1) | (ReadTimer45() & 1); random_store = (random_store << 1) | (read_adc(0) & 1); if (curry_time > swap_time) { sent_voltage = max_voltage*((float)random_store)/((float)0xFFFFFFFF); i2c_status = set_voltage(node_id,sent_voltage); if (i2c_status == I2C_STATUS_SUCCESFUL) { swap_time = swap_time + ((float) log_time); RED_LED_SWAP(); } } if (GET_BUT2() && curry_time > 2.0) { start_log_millis = millis; while( millis - start_log_millis < 1000.0); break; } // Wait until Ts milliseconds has passed since start while( millis - start_log_millis < log_Ts); } putsUART1("logging completed!\n\r"); set_calibration_status_unknown(node_id); }
void TransientLogging(UINT8 node_id, float log_voltage) { // Logging parameters UINT8 i2c_status; float curr_ang, curr_voltage, curry_time = 0.0, sent_voltage = 0.0, log_time = 1.0; UINT16 log_Ts = 10; UINT32 start_millis, start_log_millis; disable_motor(node_id); sprintf(buf,"\nlog voltage: %0.1f V, log time: %0.1f sec, Ts: %d ms\n\n\r", log_voltage, log_time, log_Ts); putsUART1(buf); putsUART1("| Time | motor angle | motor voltage |\n\n\r"); delay_ms(100); putsUART1("starting logging:\n\r"); i2c_status = calibrate_encoder_zero(node_id); if (i2c_status != I2C_STATUS_SUCCESFUL) { sprintf(buf,"Motor with id %d not found on the bus, quitting\n\r",node_id); putsUART1(buf); return; } start_millis = millis; //set_drive_voltage(1,log_voltage); unsigned char log_stage = 0; while( curry_time < (2.0 + log_time) ) { start_log_millis = millis; curry_time = ((float)(start_log_millis - start_millis))/1000.0; // Waits one second until activating motor if ( (log_stage == 0) && (curry_time > 1.0) ){ i2c_status = set_voltage(node_id,log_voltage); if (i2c_status == I2C_STATUS_SUCCESFUL) { log_stage = 1; sent_voltage = log_voltage; } } // After log_time set voltage to zero and continue recording if ( (log_stage == 1) && (curry_time > (log_time + 1.0)) ) { i2c_status = set_voltage(node_id,0.0); // TODO: LP filter if (i2c_status == I2C_STATUS_SUCCESFUL) { log_stage = 2; sent_voltage = 0.0; } } i2c_status = get_angle(node_id,&curr_ang); i2c_status |= get_voltage(node_id,&curr_voltage); if (i2c_status == I2C_STATUS_SUCCESFUL) { sprintf(buf,"%f, %f, %f\n\r", curry_time, curr_ang, curr_voltage); putsUART1(buf); } // Wait until Ts milliseconds has passed since start while( millis - start_log_millis < log_Ts); } putsUART1("logging completed!\n\r"); set_calibration_status_unknown(node_id); }
int main(void) { // All ports default to input, but turn pull-up resistors on for the stars // (not the ADC input! Made that mistake already) // (stars not used) //PORTB = (1 << STAR2_PIN) | (1 << STAR3_PIN) | (1 << STAR4_PIN); // Set PWM pin to output DDRB = (1 << PWM_PIN); // Turn features on or off as needed #ifdef VOLTAGE_MON ADC_on(); #else ADC_off(); #endif ACSR |= (1<<7); //AC off // Enable sleep mode set to Idle that will be triggered by the sleep_mode() command. // Will allow us to go idle between WDT interrupts (which we're not using anyway) set_sleep_mode(SLEEP_MODE_IDLE); // Determine what mode we should fire up // Read the last mode that was saved if (noinit_decay) // not short press, forget mode { noinit_mode = 0; mode_idx = 0; } else { // short press, advance to next mode mode_idx = noinit_mode; next_mode(); noinit_mode = mode_idx; } // set noinit data for next boot noinit_decay = 0; // set PWM mode if (modes[mode_idx] < FAST_PWM_START) { // Set timer to do PWM for correct output pin and set prescaler timing TCCR0A = 0x21; // phase corrected PWM is 0x21 for PB1, fast-PWM is 0x23 } else { // Set timer to do PWM for correct output pin and set prescaler timing TCCR0A = 0x23; // phase corrected PWM is 0x21 for PB1, fast-PWM is 0x23 } TCCR0B = 0x01; // pre-scaler for timer (1 => 1, 2 => 8, 3 => 64...) // Now just fire up the mode PWM_LVL = modes[mode_idx]; uint8_t i = 0; uint8_t j = 0; uint8_t strobe_len = 0; #ifdef VOLTAGE_MON uint8_t lowbatt_cnt = 0; uint8_t voltage; #endif while(1) { if(mode_idx < SOLID_MODES) { // Just stay on at a given brightness sleep_mode(); } else if (mode_idx < BATT_CHECK_MODE) { PWM_LVL = 0; get_voltage(); _delay_ms(200); // the first reading is junk #ifdef BATTCHECK_VpT uint8_t result = battcheck(); blink(result >> 5, BLINK_SPEED/8); _delay_ms(BLINK_SPEED); blink(1,5); _delay_ms(BLINK_SPEED*3/2); blink(result & 0b00011111, BLINK_SPEED/8); #else blink(battcheck()); #endif // BATTCHECK_VpT _delay_ms(2000); // wait at least 2 seconds between readouts } else if (mode_idx < SINGLE_BEACON_MODES) { // heartbeat flasher
int scpi_function (uint8_t keynr, char *s) { uint8_t retval; switch (keynr) { /* case 0: retval=scpi_dummy(s); break; case 1: retval=scpi_dummy(s); break; case 2: retval=scpi_dummy(s); break; case 3: retval=scpi_dummy(s); break; case 4: retval=scpi_dummy(s); break; case 5: retval=scpi_dummy(s); break; case 6: retval=scpi_dummy(s); break; case 7: retval=scpi_dummy(s); break; case 8: retval=scpi_dummy(s); break; case 9: retval=scpi_dummy(s); break; case 10: retval=scpi_dummy(s); break; case 11: retval=scpi_dummy(s); break; */ case 12: retval=get_voltage(s); break; case 13: retval=set_voltage(s); break; case 14: retval=get_current(s); break; case 15: retval=set_current(s); break; case 16: retval=get_sweep_start(s); break; case 17: retval=set_sweep_start(s); break; case 18: retval=get_sweep_stop(s); break; case 19: retval=set_sweep_stop(s); break; case 20: retval=get_sweep_step(s); break; case 21: retval=set_sweep_step(s); break; case 22: retval=get_sweep_time(s); break; case 23: retval=set_sweep_time(s); break; case 24: retval=do_sweep(s); break; case 25: retval=set_output(s); break; case 26: retval=set_instrument_nsel(s); break; case 27: retval=get_instrument_nsel(s); break; default: retval=-2; break; } return retval; }
/* * get height of water over ground in meters */ float get_height(void) { // for details see documentation float h= hscale*get_voltage()+hoffset; if(h<0.0) h= 0.0; return h; }
int main() { uint8_t i, change; uint8_t hand; uint32_t timeout = 0; uart_init(); xdev_out(uart_putchar); // Determine which hand this is from PE2 // Left is hand 0, right is hand 1 PORTE = (1 << 2); DDRE = 0; hand = (PINE & 0x04) ? 0 : 1; xprintf("\r\nHand %d\r\n", hand); // Initialise NRF24 // Set the last byte of the address to the hand ID rx_address[4] = hand; nrf24_init(); nrf24_config(CHANNEL, sizeof msg); nrf24_tx_address(tx_address); nrf24_rx_address(rx_address); matrix_init(); msg[0] = hand & 0x01; msg[1] = 0; msg[2] = 0; // Set up LED and flash it briefly DDRE |= 1<<6; PORTE = 1<<6; _delay_ms(500); PORTE = 0; get_voltage(); check_voltage(); // Scan the matrix and detect any changes. // Modified rows are sent to the receiver. while (1) { timeout++; matrix_scan(); for (i=0; i<ROWS; i++) { change = matrix_prev[i] ^ matrix[i]; // If this row has changed, send the row number and its current state if (change) { if (DEBUG) xprintf("%d %08b -> %08b %ld\r\n", i, matrix_prev[i], matrix[i], timeout); msg[1] = i; msg[2] = matrix[i]; nrf24_send(msg); while (nrf24_isSending()); timeout = 0; } matrix_prev[i] = matrix[i]; } // Sleep if there has been no activity for a while if (timeout > SLEEP_TIMEOUT) { timeout = 0; enter_sleep_mode(); } } }
void main() { // make sure we're not kicking/chipping right off the start PORTA &= ~(_BV(KICK_PIN) | _BV(CHIP_PIN)); // ensure KICK_PIN, CHIP_PIN, and CHARGE_PIN are outputs DDRA |= _BV(KICK_PIN) | _BV(CHIP_PIN) | _BV(CHARGE_PIN); // MISO is handled by CS interrupt // ensure N_KICK_CS & MISO are inputs /* DDRA &= ~(_BV(N_KICK_CS_PIN) | _BV(KCKR_MISO_PIN)); */ // when DDRB = 0 and PORTB = 1, these are configured as pull-up inputs, // when a button is pressed, these pins are driven towards ground // PORTB refers to pull-up or not /* PORTB |= _BV(DB_KICK_PIN) | _BV(DB_CHIP_PIN) | _BV(DB_CHG_PIN); */ // ensure debug buttons are inputs /* DDRB &= ~_BV(DB_KICK_PIN) & ~_BV(DB_CHIP_PIN) & ~_BV(DB_CHG_PIN); */ // enable interrupts for PCINT0-PCINT7 GIMSK |= _BV(PCIE0); // enable interrupts for PCINT8-PCINT11 GIMSK |= _BV(PCIE1); // only have the N_KICK_CS interrupt enabled PCMSK0 = _BV(INT_N_KICK_CS); // enable interrupts on debug buttons PCMSK1 = _BV(INT_DB_KICK) | _BV(INT_DB_CHIP) | _BV(INT_DB_CHG); // hard-coded for PA1, check datasheet before changing // Set lower three bits to value of pin we read from ADMUX |= V_MONITOR_PIN; // Interrupt on TIMER 0 TIMSK0 |= _BV(OCIE0A); // CTC - Clear Timer on Compare Match TCCR0A |= _BV(WGM01); // OCR0A is max val of timer before reset // we need 1000 clocks at 1 Mhz to get 1 millisecond // if we prescale by 8, then we need 125 on timer to get 1 ms exactly OCR0A = TIMING_CONSTANT; // reset every millisecond // ADC Initialization PRR &= ~_BV(PRADC); // disable power reduction - Pg. 133 ADCSRA |= _BV(ADEN); // enable the ADC - Pg. 133 ADCSRB |= _BV(ADLAR); // present left adjusted // because we left adjusted and only need 8 bit precision, // we can now read ADCH directly // enable global interrupts sei(); // needs to be int to force voltage_accum calculation to use ints const int kalpha = 32; // We handle voltage readings here while (true) { // get a voltage reading by weighing in a new reading, same concept as // TCP RTT estimates (exponentially weighted sum) last_voltage_ = get_voltage(); int voltage_accum = (255 - kalpha) * last_voltage_ + kalpha * get_voltage(); last_voltage_ = voltage_accum / 255; if (charge_allowed_ && last_voltage_ < VOLTAGE_CUTOFF) { PORTA |= _BV(CHARGE_PIN); } else { PORTA &= ~(_BV(CHARGE_PIN)); } _delay_ms(VOLTAGE_READ_DELAY_MS); } }