void calibrate(void) { mrf.SetChannel(15); int i; while (!status) { sprintf(txBuffer, "Switch\r\n"); rf_send(txBuffer, strlen(txBuffer) + 1); printf("Sent:%s\r\n", txBuffer); wait_ms(30); for (i=0; i<1; i++) { rxLen = rf_receive(rxBuffer, 128); printf("Received Length:%d\r\n", rxLen); while (rxLen <= 0) { printf("Listening\r\n"); rxLen = rf_receive(rxBuffer, 128); } active = rxBuffer[8] - 48; } if (active == 1) { printf("Switch Done!\r\n"); status = 1; //break; } } //mrf.SetChannel(com_channel); }
int main(void) { __disable_interrupt(); sys_init(); __delay_cycles(8000000);//Защита от коротких нажатий P1OUT |= BIT6; //защелкиваем питание led(1); ADC10_Init(); AFE_Init(); rf_init(); TACCR0 = 0xFFFF;// запуск таймера __enable_interrupt(); while (1) { if(rf_rx_data_ready_fg) { onRF_MessageReceived(); rf_rx_data_ready_fg = 0; } if (packetDataReady){ uchar packetSize = assemblePacket(); rf_send((uchar*)&packet_buf[0], packetSize); packetDataReady = 0; } if(rf_rx_data_ready_fg || packetDataReady){ // идем по циклу снова }else{ __bis_SR_register(CPUOFF + GIE); // Уходим в спящий режим } } }
__interrupt void USCI0TX_ISR(void) { UCA0TXBUF = rf_tx_buf[rf_tx_cntr++]; if (rf_tx_cntr > (rf_tx_buf_size - 1)) { // TX over? rf_tx_buf_size = 0; if(rf_tx_buf_1_size){ rf_send(rf_tx_buf_1,rf_tx_buf_1_size); //start sending packet from the queue rf_tx_buf_1_size = 0; }else{ //nothing to send in rf_tx_buf_1 IE2 &= ~UCA0TXIE; // Disable USCI_A0 TX interrupt } } }
/*-----------------Обработка полученного с компьютера сообщения--------------*/ void onRF_MessageReceived(){ switch(rf_rx_buf[0]){ case 0xFF: //stop recording command stopRecording(); rf_send(stopRecordingResponceMessage,5); break; case 0xFE: //start recording command startRecording(); break; case 0xFD: //hello command rf_send(helloMsg,5); break; case 0xFC: //версия прошивки rf_send(firmwareVersion,7); break; case 0xFB: //ping command pingCntr = 0; break; case 0xFA: //hardware config request rf_send(hardwareConfigMessage,7); break; default: if((rf_rx_buf_size < rf_rx_buf[0]) && (rf_rx_buf[0] < 0xFA)){//проверяем длину однобайтовой команды rf_send(unknownOneByteCmdError,7); } //проверяем два последних байта == маркер конца пакета if(((rf_rx_buf[rf_rx_buf[0]-1] == 0x55) && (rf_rx_buf[rf_rx_buf[0]-2] == 0x55))){ onRF_MultiByteMessage(); }else{ rf_send(noStopMarkerError,7); } break; } }
int main (void) { uint8_t channel = 2; //The wheels do not spin at same speed so calibration is required calibrate_right = 4/3; //Set the Channel. 0 is default, 15 is max mrf.SetChannel(channel); //Start the timer timer.start(); while(true) { //Try to receive some data rxLen = rf_receive(rxBuffer, 128); if(rxLen > 0) { pc.printf("Received: %s\r\n", rxBuffer); } //Send some data every .1 second if(timer.read_ms() >= 100) { //Reset the timer to 0 timer.reset(); //Calibration to get the full range of joystick if(LeftV.read() <= 0.35 || LeftV.read() >= 0.65) { L = (0.5 - LeftV.read()) * 300; S = 300; } //If close to middle (.5+error) then do nothing else { L = 0; S = 0; } //More calibration if((1.0 - RightV.read()) <= 0.35 || (1.0 - RightV.read()) >= 0.65) { R = (0.5 - (1.0 - RightV.read())) * 300 * calibrate_right; S = 300; } else { R = 0; } //Add the setmotor command to the buffer sprintf(txBuffer, "setmotor %d %d %d", L, R, S); //Send the buffer rf_send(txBuffer, strlen(txBuffer) + 1); pc.printf("Sent: %s\r\n", txBuffer); } } }
//!< Функция вызывается, когда принят по uart байт. void uart_rx_cb(uint8_t ch) { rf_TX_buffer[uart_rx_ptr++] = ch; if(uart_rx_ptr == RF_BUFFER_SIZE) uart_rx_ptr = 0; if ((ch == '\n') || (ch == '\r')) { uart_putchar('\r', NULL); uart_putchar('\n', NULL); rf_send(rf_TX_buffer, uart_rx_ptr); uart_rx_ptr = 0; } else { uart_putchar(ch, NULL); } }
int main() { unsigned char idx; unsigned int i = 0; store_cpu_rate(16); P0_DIR &= ~0x28; P0_ALT &= ~0x28; rf_init(); rf_configure(cfg); serial_init(19200); eco_page_init(); //long_function(4,6,8,4); msg[0] = 0x0A; msg[1] = 0x00; /* ADDR */ msg[2] = 0x02; msg[3] = 0xA0; /* LEN */ msg[4] = 0x02; msg[5] = 0xDD; msg[6] = 0xCC; for(idx = 4; idx > 0; idx--) { blink_led(); mdelay(300); } mdelay(1000); while(1) { blink4(); rf_send(dst_addr, 3, msg, 7); blink2(); mdelay(200); blink6(); } return 0; }
//MEthod to unpack the OSC message and send it using the zigbee modules. It retrieves the values in all the fields of the OSC object and creates an //appropriate OSC message. void OSCclass::sendOSCmsg(OSCmsg *sendmsg){ if(sendmsg->getType() == 0) ttype = 'n'; else ttype = sendmsg->getType(); strncpy(addr,sendmsg->getAddr(),5); strncpy(packet,sendmsg->getAddr(),5); packet[5] = ','; packet[6]= ttype; packet[7] = sendmsg->getArgs(); packet[8] = 0; printf("OSc mesage %s\r\n",packet); //Send this message on the zigbee rf_send(packet,8); printf("sent %s %d \r\n",packet,strlen(packet)); }
void udp_transpond_demo(void* parameter) { int sock; //int n, off; struct sockaddr_in server_addr; struct sockaddr_in remote_addr; socklen_t addr_len = sizeof(remote_addr); rt_uint8_t run_flag = 1; if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1){ rt_kprintf("Socket error\n"); goto __exit; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(6000); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (void *)&server_addr, sizeof(server_addr)) == -1) { rt_kprintf("Bind error\n"); lwip_close(sock); run_flag = 0; } rt_kprintf("udp_recv_demo start.\n"); while (run_flag) { //基站发包流速控制在1.8ms,丢包率在0.1% recvfrom(sock, &data, sizeof(data), 0, (void *)&remote_addr, &addr_len); rf_send((void *)&data.id, (void *)&data.data, data.data_len); //如果需要检查ACK,则打开接收 if (data.rcv_len > 0 && rf_recv((void *)&data.data, data.rcv_len) == 0) sendto(sock, data.data, data.rcv_len, 0, (void *)&remote_addr, addr_len); } lwip_close(sock); __exit: rt_kprintf("udp_recv_demo end.\n"); }
status_t msg_send(const msgType* txMsg) { uint16_t rfAddress = RF_PARENT_ADDRESS; #ifdef MSG_GATEWAY_NODE if (txMsg->type == MSG_TYPE_SENSORDATA) { putchar(0x02); /* STX */ putchar(txMsg->length); putchar(HIGH_BYTE(txMsg->address)); putchar(LOW_BYTE(txMsg->address)); for (uint8_t i = 0; i < txMsg->length; i++) { putchar(txMsg->data[i]); } putchar(0x03); /* ETX */ return STATUS_OK; } #endif #ifndef MSG_LEAF_NODE if (txMsg->type != MSG_TYPE_SENSORDATA) { /* Search through parents of the end destination node, until the current * node is found. The actual address this node should send to will then * be one level below this. */ rfAddress = txMsg->address; while (RF_LOCAL_ADDRESS != getParent(rfAddress)) { rfAddress = getParent(rfAddress); if (rfAddress == 0) { return STATUS_INVALID_ARG; /* Something's gone wrong... */ } } } #endif rf_send(rfAddress, (uint8_t const*)txMsg, txMsg->length + MSG_OVERHEAD_SIZE); return STATUS_OK; }
void onRF_MultiByteMessage(){ uchar msgOffset = 1; while (msgOffset < (rf_rx_buf[0]-2)){ if(rf_rx_buf[msgOffset] == 0xF0){//команда для ads1292 AFE_Cmd(rf_rx_buf[msgOffset+1]); msgOffset+=2; }else if(rf_rx_buf[msgOffset] == 0xF1){//Запись регистров ads1298 AFE_Write_Reg(rf_rx_buf[msgOffset+1], rf_rx_buf[msgOffset+2], &rf_rx_buf[msgOffset+3]); msgOffset+=rf_rx_buf[msgOffset+2]+3; }else if(rf_rx_buf[msgOffset] == 0xF2){//делители частоты для ads1298 8 значений for(int i = 0; i<8; i++){ if((rf_rx_buf[msgOffset+1+i] == 0) || (rf_rx_buf[msgOffset+1+i] == 1) || (rf_rx_buf[msgOffset+1+i] == 2) || (rf_rx_buf[msgOffset+1+i] == 5) || (rf_rx_buf[msgOffset+1+i] == 10)){ div[i] = rf_rx_buf[msgOffset+1+i]; } } msgOffset+=9; }else if(rf_rx_buf[msgOffset] == 0xF3){//Режим работы акселерометра setAccelerometerMode(rf_rx_buf[msgOffset+1]); msgOffset+=2; }else if(rf_rx_buf[msgOffset] == 0xF4){//Передача данных батарейки measureBatteryVoltage(rf_rx_buf[msgOffset+1]); msgOffset+=2; }else if(rf_rx_buf[msgOffset] == 0xF5){//передача данных loff статуса loffStatEnable = rf_rx_buf[msgOffset+1]; msgOffset+=2; }else if(rf_rx_buf[msgOffset] == 0xF6){//RF reset timeout при отсутствии Ping команды с компьютера. resetTimeout = rf_rx_buf[msgOffset+1] * 4; msgOffset+=2; }else if(rf_rx_buf[msgOffset] == 0xFE){//start recording command startRecording(); msgOffset+=1; }else{ rf_send(unknownMultiByteCmdError,7); return; } } }
int main(void) { __disable_interrupt(); sys_init(); led(1); ADC10_Init(); AFE_Init(); rf_init(); TACCR0 = 0xFFFF; // запуск таймера __enable_interrupt(); while (1) { if (rf_rx_data_ready_fg) { onRF_MessageReceived(); rf_rx_data_ready_fg = 0; } if (packetDataReady) { uchar packetSize = assemblePacket(); rf_send((uchar*) &packet_buf[0], packetSize); packetDataReady = 0; } if (rf_rx_data_ready_fg || packetDataReady) { ; // идем по циклу снова } else { __bis_SR_register(CPUOFF + GIE); // Уходим в спящий режим } } }
void sendNumber(int n) { sprintf(txbuffer,"%d",n); rf_send(txbuffer, strlen(txbuffer)+1); }
__interrupt void TimerA_ISR(void) { TACTL &= ~TAIFG; if(rfResetCntr == 0x01){ P3OUT |= BIT7;//BT reset pin hi rfResetCntr = 0; } if(isRecording){ if(resetTimeout){ pingCntr++; if(pingCntr > resetTimeout){//no signal from host for ~ resetTimeout * 4 seconds P3OUT &= ~BIT7; //BT reset pin lo if (rfResetCntr == 0)rfResetCntr = 1; pingCntr = 0; } } }else{//if not recording long new_data[4]; ADC10_Read_Data(&new_data[0]); addBatteryData(new_data[3]); ADC10_Measure(); } if(!(BIT5 & P2IN)){// if power button pressed btnCntr++; }else{ btnCntr = 0; } if(BIT0 & P1IN){// if rf connected rfConStat = 1; }else{ rfConStat = 0; } if(!(BIT4 & P2IN)){// if charge plug connected if(shutDownCntr == 0){ shutDownCntr = 1; rf_send(chargeShutDownMessage,5); } } if(btnCntr >= (4)){ //1 сек задержка перед выключением led(1); P1OUT &= ~BIT6; //power hold pin while(1){} //ждем отпускания кнопки } if(!lowBatteryMessageAlreadySent){ if(sumBatteryVoltage < BATT_LOW_TH){ lowBatteryMessageAlreadySent = 1; rf_send(lowBatteryMessage,7); if (shutDownCntr == 0) shutDownCntr = 1; } } if(shutDownCntr){ shutDownCntr++; if(shutDownCntr > 4){//wait 1 second before shut down P1OUT &= ~BIT6; //power hold pin } } if(powerUpCntr){ powerUpCntr++; if(powerUpCntr >= 2400){//забыли выключить питание (не стартует запись в теечение ~10 минут) P1OUT &= ~BIT6; //отключаем питание } if(powerUpCntr%2){ led(1); }else{ led(0); } } if(rf_delete_unfinished_incoming_messages()){ rf_send(unfinishedIncomingMsgError,7); } if(rf_tx_fail_flag){//debug information maybe delete rf_tx_fail_flag = 0; rf_send(txFailError,7); } }
__interrupt void TimerA_ISR(void) { TACTL &= ~TAIFG; if (rfResetCntr == 0x01) { P3OUT |= BIT7; // BT reset pin hi rfResetCntr = 0; } if (isRecording && rfConStat) { if (resetTimeout) { pingCntr++; if (pingCntr > resetTimeout) { // no signal from host for ~ resetTimeout * 4 seconds P3OUT &= ~BIT7; // BT reset pin lo if (rfResetCntr == 0) rfResetCntr = 1; pingCntr = 0; } } } else { // if not recording long new_data[4]; ADC10_Read_Data(&new_data[0]); addBatteryData(new_data[3]); ADC10_Measure(); } if (BIT0 & P1IN) // if rf connected rfConStat = 1; else rfConStat = 0; if (!lowBatteryMessageAlreadySent) { if (sumBatteryVoltage < BATT_LOW_TH) { lowBatteryMessageAlreadySent = 1; rf_send(lowBatteryMessage, 7); if(shutDownCntr == 0) shutDownCntr = 1; } } if (powerUpCntr) { powerUpCntr++; if (powerUpCntr >= 2400) // забыли выключить питание (не стартует запись в теечение ~10 минут) { if (shutDownCntr == 0) shutDownCntr = 1; } if (powerUpCntr % 2) led(1); else led(0); } if (shutDownCntr) { shutDownCntr++; if (shutDownCntr > 4) { // wait 1 second before shut down AFE_StopRecording(); P3OUT &= ~BIT7; // BT reset pin low TACCR0 = 0x00; led(0); } } if (rf_delete_unfinished_incoming_messages()) rf_send(unfinishedIncomingMsgError, 7); if(rf_tx_fail_flag) { // debug information maybe delete rf_tx_fail_flag = 0; rf_send(txFailError, 7); } }
int main (void) { pc.baud(115200); RoboState1 = Charging; RoboState2 = Charging; State = Picking; int xpos = x_min; int ypos = x_max; float xre = 0; float yre = 0; while(true){ switch(State){ default: State = Picking; break; case 1: //Done State = Done; break; case 2: //Picking mrf.SetChannel(channel1); rxLen = rf_receive(rxBuffer, 128); State = Picking; if (rxLen>0 && rxBuffer[0] == 'R'){ //if robot1 is ready wait(0.5); RoboState1 = Working; sprintf(txBuffer, "%d %d %d %d %d\r\n",xpos,ypos,y_max,y_min,x_max); rf_send(txBuffer, strlen(txBuffer) + 1); State = Waiting; }else{ mrf.SetChannel(channel2); rxLen = rf_receive(rxBuffer, 128); if (rxLen>0 && rxBuffer[0] == 'R'){ //else if robot2 is ready wait(0.5); sprintf(txBuffer, "%d %d %d %d %d\r\n",xpos,ypos,y_max,y_min,x_max); RoboState2 = Working; rf_send(txBuffer, strlen(txBuffer) + 1); State = Waiting; } } break; case 3: //Waiting rxLen = rf_receive(rxBuffer, 128); State = Waiting; if(rxLen > 0) { led1 = led1^1; pc.printf("%s", rxBuffer); if(rxBuffer[0] == 'D'){ sscanf(rxBuffer, "Died: %f,%f\r\n", &xre, &yre); xpos = int(xre); ypos = int(yre); State = Waiting; } if(rxBuffer[0] == 'F'){ State = Done; } if(rxBuffer[0] == 'C'){ if (RoboState1 == Working){ RoboState1 = Charging; } if (RoboState2 == Working){ RoboState2 == Charging; } State = Picking; } } break; } } }
int main(){ Buzzer.write(0); mrf.SetChannel(com_channel); clock_init(); cam_init(); pc.baud(115200); State = WAITING; Battery_Level = Battery_Time; t_battery.reset(); int start_x, start_y, y_min, y_max, dest_x; active = 1; mrf.SetChannel(15); for (int i=0; i<3; i++){ //load the tile it is under; rxLen = rf_receive(rxBuffer, 128); while (rxLen <= 0){ rxLen = rf_receive(rxBuffer, 128); } sscanf(rxBuffer,"active: %d\r\n", &active); } pc.printf("the active value is: %d\r\n", active); mrf.SetChannel(com_channel); while(1){ switch(State){ //use a state machine to control the behavior or a slave default: State = WAITING; break; case 1: //Waiting sprintf(txBuffer, "Ready\r\n"); rf_send(txBuffer, strlen(txBuffer) + 1); robot.stop(); rxLen = rf_receive(rxBuffer, 128); if (rxLen > 0){ int res = sscanf(rxBuffer, "%d %d %d %d %d\r\n", &start_x, &start_y, &y_min, &y_max, &dest_x); if (res){ sprintf(txBuffer, "Yes\r\n"); rf_send(txBuffer, strlen(txBuffer) + 1); State = WORKING; } }else{ State = WAITING; } break; case 2: //Working Buzzer.write(1); wait(0.2); Buzzer.write(0); go_to(start_x, start_y); Buzzer.write(1); wait(0.6); Buzzer.write(0); if (zig_zag(y_max, y_min, dest_x) > 0){ robot.stop(); sprintf(txBuffer, "Finished\r\n"); rf_send(txBuffer, strlen(txBuffer) + 1); State = WAITING; }else{ robot.stop(); rotate(90); Locate(position); sprintf(txBuffer, "Died: %3.2f,%3.2f\r\n",position[0],position[1]); rf_send(txBuffer, strlen(txBuffer) + 1); for (int b=0; b<3; b++){ Buzzer.write(1); wait(0.2); Buzzer.write(0); wait(0.2); } go_to(Charging_X, Charging_Y); State = CHARGING; } break; case 3: //charging sprintf(txBuffer, "Charging: %d\r\n",Battery_Level); rf_send(txBuffer, strlen(txBuffer) + 1); rxLen = rf_receive(rxBuffer, 128); if (rxLen > 0){ int res = sscanf(rxBuffer, "%d %d %d %d %d\r\n", &start_x, &start_y, &y_min, &y_max, &dest_x); if (res){ State = WORKING; } }else{ State = CHARGING; } wait(1); Battery_Level += 3; if (Battery_Level >= Battery_Time){ Battery_Level = Battery_Time; State = WAITING; } break; } } }