int main( int argc, char *argv[] ) { uint8_t serial_buffer[BUFFER_SIZE]; uint8_t packet_buffer[BUFFER_SIZE]; uint8_t final_buffer[BUFFER_SIZE]; //uint8_t adc_sample_buffer[ADC_MAX_SAMPLES]; uint16_t buffer_offset = 0; uint8_t new_packet = 0; uint16_t bytes_read = 0; // Handle interrupt events to make sure files are closed before exiting (void) signal( SIGINT, sigint_handler ); tx_power = dbm_to_watt(1l); target_rssi = dbm_to_watt(-60l); // Make sure input is correct if( argc < 2 ) { printf("Usage: %s port baudrate\n", argv[0]); return 0; } printf("Power control test\r\n"); // Convert string serial number to integer serial_port_number = atoi( argv[1] ); // Use RS232 library to open serial port if ( OpenComport( serial_port_number, atoi(argv[2]) ) ) { printf("Error opening serial port.\n"); return 1; } // Flush the port while( PollComport( serial_port_number, serial_buffer, BUFFER_SIZE ) ); memset( serial_buffer, 0x00, sizeof(serial_buffer) ); // Run forever for(;;) { // Read a buffer full of data (if available) bytes_read = PollComport( serial_port_number, serial_buffer, BUFFER_SIZE ); if( bytes_read > 0 ) { if( bytes_read >= BUFFER_SIZE ) { printf("Uh oh!\n"); } else { memcpy( packet_buffer + buffer_offset, serial_buffer, bytes_read ); if ( packet_in_buffer( packet_buffer ) ) { buffer_offset = 0; new_packet = 1; bytes_read = find_and_escape_packet( packet_buffer, final_buffer ); } else { buffer_offset += bytes_read; if( buffer_offset > BUFFER_SIZE ) { printf("damn...\n"); memset( packet_buffer, 0x00, sizeof(packet_buffer) ); memset( serial_buffer, 0x00, sizeof(serial_buffer) ); buffer_offset = 0; } } if( new_packet == 1 ) { process_packet( final_buffer ); new_packet = 0; memset( packet_buffer, 0x00, sizeof(packet_buffer) ); } } } memset( serial_buffer, 0x00, sizeof(serial_buffer) ); // Don't take up all the processor time usleep(20000); if( 0 == send_message-- ) { SendByte( serial_port_number, next_power ); // Send initial packet send_message = 1; if(next_power == 0xff) { printf("*"); } // If no message is received before the next round, use full power next_power = 0xff; } } return 0; }
// --- функция отправки файла -------------------------------------------------- bool MainWindow::SendFile(QString FileName) { // отправка маркера начала передачи CHAR C_Write = S_MARK; DWORD write_counter; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); C_Write = NAME_MARK; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); //передача имени файла QFileInfo FInfo(FileName); QString FName = FInfo.fileName(); ui->progressBar->setMaximum(FInfo.size()); int progrProgress = 0; logstr = tr("] <font color=blue>отправка файла</font> <b>") + FName + tr("</b>"); string2log(logstr); logstr = tr("] передача имени файла..."); string2log(logstr); byte A; short errors = 0; CHAR C_Read; for(int i = 0; i < FName.size(); i++) { do { C_Read = NO_CHAR; A = FName[i].toAscii(); SendByte(A, workPort); ReadFile(workPort, &C_Read, 1, &write_counter, NULL); if(C_Read == NO_CHAR) errors++; else errors = 0; if(errors == MAX_ERRORS) { logstr = tr("] <font color=red>слишком много ошибок</font>"); string2log(logstr); return false; } if(C_Read == B_MARK) { logstr = tr("] <font color=red>прервано отправителем</font>"); string2log(logstr); C_Write = B_MARK; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); return false; } } while(C_Read != A_MARK); } logstr = tr("] имя файла передано"); string2log(logstr); logstr = tr("] передача самого файла..."); string2log(logstr); // передача файла C_Write = DATA_MARK; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); QFile FileToSend(FileName); if (FileToSend.open(QIODevice::ReadOnly)) { char A; short errors = 0; for(int i=0; i<(FileToSend.size()); i++) { do { C_Read = NO_CHAR; QByteArray AByte = ""; AByte = FileToSend.read(1); A = AByte[0]; SendByte(A, workPort); ReadFile(workPort, &C_Read, 1, &write_counter, NULL); if(C_Read == NO_CHAR) errors++; else errors = 0; if(errors == MAX_ERRORS) { logstr = tr("] <font color=red>слишком много ошибок при передаче</font>"); string2log(logstr); FileToSend.close(); return false; } if(C_Read == B_MARK) { logstr = tr("] <font color=red>передача прервана отправителем</font>"); string2log(logstr); C_Write = B_MARK; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); FileToSend.close(); return false; } } while(C_Read != A_MARK); progrProgress++; ui->progressBar->setValue(progrProgress); } FileToSend.close(); } C_Write = S_MARK; WriteFile(workPort, &C_Write, 1, &write_counter, NULL); logstr = tr("] <font color=green>файл передан</font>"); string2log(logstr); return true; }
void GrabAndSendCameraData(CvCapture* aCamHandle, int i2c_handle, int skippedFrame, int delayPixelSending, unsigned int idPayloadNum, GPS_DATA *last_data, unsigned char rf_buffer_len) { unsigned char frameBuff[645*200], buff_gps_data[40]; unsigned int i, idPixel; //capture camera, skip n frame IplImage *img = 0; uint8_t cntSkipFrame = 0; while (cntSkipFrame < skippedFrame) { //grab frame img = cvQueryFrame(aCamHandle); if (img) cntSkipFrame++; } //get picture and resize it //cvSaveImage("/dev/shm/capture.jpg", img, 0); //create image to store IplImage *dest = cvCreateImage(cvSize(200, 200), img->depth, img->nChannels); //resize it cvResize(img, dest, CV_INTER_LANCZOS4); //save the resized image //~ cvSaveImage("resized.jpg", dest, 0); //view pixel info int hcnt, wcnt; //method 1: //print header paket gambar snprintf((char*) frameBuff, 10, "\r%.3d\xff\r", idPayloadNum); SendBuf(COM_PORT, frameBuff, 7); usleep(RF_DELAY_LESS_PACKET_US); //print pixel idPixel = 0; for (hcnt = 0; hcnt < dest->height; hcnt++) { //loop height unsigned char* row = &CV_IMAGE_ELEM(dest, unsigned char, hcnt, 0); //row scanline //print header frame //~ uchar dataTX[4] = {0xff}; //header data //~ dataTX[1] = ((hcnt + 1) / 100) + 0x30; //counter height //~ dataTX[2] = (((hcnt + 1) % 100) / 10) + 0x30; //~ dataTX[3] = ((hcnt + 1) % 10) + 0x30; frameBuff[idPixel++] = 0xff; frameBuff[idPixel++] = ((hcnt + 1) / 100) + 0x30; //counter height frameBuff[idPixel++] = (((hcnt + 1) % 100) / 10) + 0x30; frameBuff[idPixel++] = ((hcnt + 1) % 10) + 0x30; #if VERBOSE==1 printf("Processing frame #%d\r\n", hcnt + 1); #endif //send header //~ SendBuf(COM_PORT, dataTX, 4); //~ usleep(RF_DELAY_LESS_PACKET_US); //loop per width for (wcnt = 0; wcnt < dest->width * dest->nChannels; wcnt += dest->nChannels) { // opencv rgb data sequence = BGR // row[x] = {R,G,B}; //~ frameBuff[wcnt + 4] = (row[wcnt + 2] == 0xff) ? 0xfe : row[wcnt + 2]; //~ frameBuff[wcnt + 1 + 4] = (row[wcnt + 1] == 0xff) ? 0xfe : row[wcnt + 1]; //~ frameBuff[wcnt + 2 + 4] = (row[wcnt + 0] == 0xff) ? 0xfe : row[wcnt + 0]; frameBuff[idPixel++] = (row[wcnt + 2] == 0xff) ? 0xfe : row[wcnt + 2]; frameBuff[idPixel++] = (row[wcnt + 1] == 0xff) ? 0xfe : row[wcnt + 1]; frameBuff[idPixel++] = (row[wcnt + 0] == 0xff) ? 0xfe : row[wcnt + 0]; //~ SendByte(COM_PORT, (row[wcnt + 2] == 0xff) ? 0xfe : row[wcnt + 2]); //usleep(5); //~ SendByte(COM_PORT, (row[wcnt + 1] == 0xff) ? 0xfe : row[wcnt + 1]); //usleep(5); //~ SendByte(COM_PORT, (row[wcnt + 0] == 0xff) ? 0xfe : row[wcnt + 0]); //usleep(5); //delay for buffer radio //~ if(wcnt%32==0) //~ usleep(delayPixelSending); } //send frame package //SendBuf(COM_PORT, frameBuff, 600); //delay for transceiver //usleep(delayPixelSending); //get gps data //~ GetAndFormatGPSData(i2c_handle, buff_gps_data, last_data); GetAndFormatGPSData(i2c_handle, &frameBuff[idPixel], last_data); //send the gps data //~ SendBuf(COM_PORT, buff_gps_data, 18); //~ usleep(2000); //~ SendBuf(COM_PORT, &buff_gps_data[18], 19); //~ usleep(RF_DELAY_US); //delay buffer radio //~ usleep(delayPixelSending+2000); //tail //~ snprintf(buff_gps_data, 5, " INA"); idPixel += 37; snprintf(&frameBuff[idPixel], 6, " %s", "GPS"); idPixel += 4; //send the data //~ SendBuf(COM_PORT, buff_gps_data, 4); //~ for(i=0;i<672;i+=32) //~ { //~ SendBuf(COM_PORT, &frameBuff[i], 32); //~ usleep(RF_DELAY_HALF_DUPLEX_US); //~ } //~ for(i=0;i<672;i++) //~ { //~ SendByte(COM_PORT, frameBuff[i]); //~ if(i%32==0) //~ usleep(RF_DELAY_HALF_DUPLEX_US); //~ } //~ usleep(50000); //~ printf("F#%.3d = %.3d\r\n", hcnt, idPixel); //~ if(hcnt==0) break; } //save to file //~ FILE *fp; //~ fp=fopen("raw_cam.log", "wb+"); //~ fwrite( //~ frameBuff, //~ sizeof(frameBuff[0]), //~ /* sizeof(frameBuff)/sizeof(frameBuff[0]) */ //~ idPixel, //~ fp); //~ fclose(fp); //send all data printf("Going to send %ld byte with delay %d us\r\n", idPixel, delayPixelSending); //trw433 #ifdef RADIO_TYPE_TRW433 for(i=0;i<(idPixel);i++) { SendByte(COM_PORT, frameBuff[i]); if(i%(rf_buffer_len-1)==0) //~ usleep(RF_DELAY_HALF_DUPLEX_US); usleep(delayPixelSending); } usleep(RF_DELAY_LESS_PACKET_US); #endif //hm trp #ifdef RADIO_TYPE_HMTRP for(i=0;i<(idPixel);i++) { SendByte(COM_PORT, frameBuff[i]); if(i%(32-1)==0) //~ usleep(RF_DELAY_HALF_DUPLEX_US); usleep(delayPixelSending); } usleep(RF_DELAY_LESS_PACKET_US); #endif }
VOID FloppyBootSetup( VOID ) /*++ Routine Description: This routine is invoked to initialize the floppy boot device before any other floppy operations are attempted. This routine performs the following operations to initialize the device: o Clear the reset and DMA gate flags in the DOR o Reset the floppy by writing the s/w reset in the DSR o Set the program data rate in the CCR o Issue a sense interrupt command and read the four statuses back o Issue a configure command o Issue a specify command Arguments: None. Return Value: None. --*/ { ULONG i,j; // // Begin by clearing the reset and DMA gate flags in the DOR. // WRITE_REGISTER_UCHAR(&FLOPPY_CONTROL->DigitalOutput, 0x0c); // // Reset the floppy controller by setting the s/w reset bit in the DSR. // WRITE_REGISTER_UCHAR(&FLOPPY_CONTROL->MsrDsr.DataRateSelect, 0x80); // // Set the data rate in the CCR. // // WRITE_REGISTER_UCHAR(&FLOPPY_CONTROL->DirCcr.ConfigurationControl, 0); if (FwWaitForDeviceInterrupt(1 << (FLOPPY_VECTOR - DEVICE_VECTORS - 1), FW_FLOPPY_TIMEOUT)) { // FwPrint("Floppy setup timeout\r\n"); return; } // // Issue the sense interrupt command and read back the status and // relative cylinder number from the controller. This is done for // each of the four possible devices. Note that the output is always // ignored. // for (i = j = 0; i <= 3; i++) { SendByte(COMMND_SENSE_INTERRUPT); DebugByte[j++] = ReceiveByte(); DebugByte[j++] = ReceiveByte(); } // // Issue the configuration command. // SendByte( COMMND_CONFIGURE ); // command SendByte( 0x00 ); // required 0 SendByte( 0x58 ); // implied seeks, disable polling & threshold = 8 SendByte( 0x00 ); // precompensation track = 0 // // Issue the specify command. // SendByte( COMMND_SPECIFY ); // command SendByte( 0xdf ); // step rate time=d, head unload=f SendByte( 0x03 ); // head load=1, DMA disabled return; }
/* ============================================================================ // XCH: fVerifySecurity() // This step is optional. Verifies that the security bits have been written correctly ============================================================================ */ signed char fVerifySecurity(void) { /* unsigned char bBlockNumber = 0;//wly */ bTargetAddress = 0x00; #ifdef USE_TP SetTPHigh(); /* Only used of Test Points are enabled */ #endif #ifdef USE_TP SetTPLow(); /* Only used of Test Points are enabled */ #endif SendVector(verify_security, num_bits_verify_security); fIsError = fDetectHiLoTransition(); if (fIsError) return INIT_ERROR; #ifdef USE_TP SetTPHigh(); /* Only used of Test Points are enabled */ #endif #ifdef USE_TP SetTPLow(); /* Only used of Test Points are enabled */ #endif SendVector(wait_and_poll_end, num_bits_wait_and_poll_end); bTargetAddress = 0x00; bTargetDataPtr = 0x00; SendVector(tsync_enable, num_bits_tsync_enable); SendVector(read_write_setup, num_bits_read_write_setup); /* fReadWriteSetup(); */ /* we do SECURITY_BYTES_PER_BANK * 2 because we bTargetAddress += 2 */ while (bTargetAddress < (SECURITY_BYTES_PER_BANK * 2)) { /* Send Read Byte vector and then get a byte from Target */ SendVector(read_byte_v, 4); /* Set the drive here because SendByte() does not */ SetSDATAStrong(); SendByte(bTargetAddress, 7); SetSDATAHiZ(); /* Set to HiZ so Target can drive SDATA */ RunClock(2); /* Run two SCLK cycles between writing and reading */ bTargetDataIN = bReceiveByte(); RunClock(1); SendVector(read_byte_v + 1, 1); /* Send the ReadByte Vector End */ /* Test the Byte that was read from the Target against the original // value (already in the 128-Byte array "abTargetDataOUT[]"). If it // matches, then bump the address & pointer,loop-back and continue. // If it does NOT match abort the loop and return and error. */ if (bTargetDataIN != abTargetDataOUT[bTargetDataPtr]) return BLOCK_ERROR; /* Increment the address by two to accomodate 7-Bit addressing (puts the 7-bit address into MSBit locations for "SendByte()"). */ bTargetDataPtr++; bTargetAddress += 2; } SendVector(tsync_disable, num_bits_tsync_disable); return PASS; }
static BOOLEAN SendByteAck(TCHAR b) { SendByte(b); return Ack(); } /* end SendByteAck() */
//============================================================================ int main(int argc, char* argv[]) { printf("Ultra-simple CFA-632 / CFA-634 command-line communications example.\n"); printf("Crystalfontz America, Inc. http://www.crystalfontz.com\n\n"); printf("Usage:\n"); printf("%s PORT BAUD\n",argv[0]); printf("PORT is something like \"/dev/ttyS0\" or \"/dev/usb/ttyUSB1\"\n"); printf("BAUD is 1200, 2400, 4800, 9600 or 19200\n"); printf("To clear the display, enter \"clear\" as an optional third parameter\n\n"); //If only 0 or 1 parameter is entered, prompt for the missing parameter(s) if(argc < 3) { printf("\nMISSING A PARAMETER. Enter both PORT and BAUD.\n\n"); return(0); } //Check for optional "clear" parameter and set flag if found int cleardisplay=0; if((argc > 3) && (!strcmp(argv[3],"clear"))) cleardisplay=1; int baud; //default the baud to 19200 if(!strcmp(argv[2],"1200")) baud=1200; else if(!strcmp(argv[2],"2400")) baud=2400; else if(!strcmp(argv[2],"4800")) baud=4800; else if(!strcmp(argv[2],"9600")) baud=9600; else baud=19200; if(Serial_Init(argv[1],baud)) { printf("Could not open port \"%s\" at \"%d\" baud.\n",argv[1],baud); return(1); } else printf("\"%s\" opened at \"%d\" baud.\n\n",argv[1],baud); //We will try to be tricky, and send out data that will show up correctly //on both the 634 and 632. //First turn off "scroll" and "wrap" SendByte(20); SendByte(24); //Write out the bottom two lines //on the 634. The 632 will ignore //these lines. //Position to line 4, col 1 SendByte(17); SendByte(0); SendByte(3); if(cleardisplay==1) { //12345678901234567890 SendString(" "); } else { //12345678901234567890 SendString("This is Line 4 *****"); } //Position to line 3, col 1 SendByte(17); SendByte(0); SendByte(2); if(cleardisplay==1) { //12345678901234567890 SendString(" "); } else { //12345678901234567890 SendString("This is Line 3 *****"); } //Write out top two lines of the //634 and both lines of the 632. //Position to line 2, col 1 SendByte(17); SendByte(0); SendByte(1); if(cleardisplay==1) { //12345678901234567890 SendString(" "); } else { //12345678901234567890 SendString("This is Line 2 *****"); } //Position to line 1, col 1 SendByte(17); SendByte(0); SendByte(0); if(cleardisplay==1) { //12345678901234567890 SendString(" "); } else { //12345678901234567890 SendString("This is Line 1 *****"); } if(cleardisplay==1) printf("Display Cleared.\n"); printf("Done.\n\n"); Uninit_Serial(); return 0; }
void sendprgstr(char *s) { char c; while ((c = PRG_RDB(s++))) SendByte(c); }
void CheckBusy( void ) { do SendByte(0xfc); //11111,RW(1),RS(0),0 while(0x80&ReceiveByte()); //BF(.7)=1 Busy }
void BioloidBus::SendCheckSum() { SendByte( ~m_checksum ); WriteBuffer(); }
void cprintf(const char *text) /* sends a string to serial port */ { while(*text != 0) SendByte( *(text++)); }
NS_IMETHODIMP FCGXStream::NextRequest(PRInt32 *_retval) { //TODO : return a different error code indicating protocol error char error[256]; if (!RecvNextBlock(PR_FALSE)) { g_recv.LogProtocolError(mRecvBuf + mRecvOut, mRecvIn - mRecvOut); return NS_ERROR_ABORT; } if (mRecvCurBlockType != bt_BeginRequest) { LogFatal("Expected BeginRequest not received."); g_recv.LogProtocolError(mRecvBuf + mRecvOut, mRecvIn - mRecvOut); CloseConnection(true); return NS_ERROR_ABORT; } // Verify protocol version. PRUint16 version = RecvUint16(); *_retval = RecvByte(); PRBool bCanHandleRequest = (*_retval == RT_Handler || *_retval == RT_Filter); PRBool bCanHandleProtocol = (version == JAXER_PROTOCOL_VERSION || version == 3); if (!bCanHandleProtocol) { sprintf(error, "Connector protocol version (%d) does not match jaxer's (%d). You need to update the web connector or Jaxer.", version, JAXER_PROTOCOL_VERSION); LogFatal(error); } if (!bCanHandleRequest) { sprintf(error, "Jaxer does not understand the request type (%d). You need to update the web connector or Jaxer.", *_retval); LogFatal(error); } mPostDataAfterEndRequest = PR_FALSE; /* * Send back a msg indicating whether we are ok to handle the request */ SendBlockType(bt_BeginRequest); //SendUint16(JAXER_PROTOCOL_VERSION); // protocol version SendUint16(bCanHandleProtocol? version : JAXER_PROTOCOL_VERSION); // protocol version SendByte((bCanHandleRequest && bCanHandleProtocol) ? 1 : 0); //whether we can handle the protocol if (!bCanHandleRequest || !bCanHandleProtocol) { //optionally, we can provide error code (INT32, A short text msg) if (!bCanHandleProtocol) { SendUint16(bre_ProtocolVersionMustBeTheSame); }else { SendUint16(bre_CannotHandleRequestType); } SendUint16(strlen(error)); SendBytes(error, strlen(error)); } nsresult rc = Flush(!bCanHandleRequest || !bCanHandleProtocol); if ( rc != NS_OK) return rc; return (mFD != INVALID_SOCKET && (bCanHandleRequest && bCanHandleProtocol))? NS_OK : NS_ERROR_ABORT; }
/* ----------------CapTouchActiveMode---------------------------------------------- * Determine immediate gesture based on current & previous wheel position * * * * * * * * -------------------------------------------------------------------------------*/ void CapTouchActiveMode() { unsigned char idleCounter, activeCounter; unsigned char gesture, gestureDetected; unsigned char centerButtonTouched = 0; unsigned int wheelTouchCounter = WHEEL_TOUCH_DELAY - 1; gesture = INVALID_GESTURE; // Wipes out gesture history /* Send status via UART: 'wake up' = [0xBE, 0xEF] */ SendByte(WAKE_UP_UART_CODE); SendByte(WAKE_UP_UART_CODE2); idleCounter = 0; activeCounter = 0; gestureDetected = 0; while (idleCounter++ < MAX_IDLE_TIME) { /* Set DCO to 8MHz */ /* SMCLK = 8MHz/8 = 1MHz */ // BCSCTL1 = CALBC1_8MHZ; // DCOCTL = CALDCO_8MHZ; // BCSCTL2 |= DIVS_3; /* SMCLK = 1MHz/4 = 250kHz */ BCSCTL1 = CALBC1_1MHZ; DCOCTL = CALDCO_1MHZ; BCSCTL2 |= DIVS_2; TACCTL0 &= ~CCIE; wheel_position = ILLEGAL_SLIDER_WHEEL_POSITION; wheel_position = TI_CAPT_Wheel(&wheel); /* Process wheel touch/position/gesture if a wheel touch is registered*/ /* Wheel processing has higher priority than center button*/ if(wheel_position != ILLEGAL_SLIDER_WHEEL_POSITION) { centerButtonTouched = 0; /* Adjust wheel position based: rotate CCW by 2 positions */ if (wheel_position < 0x08) { wheel_position += 0x40 - 0x08; } else { wheel_position -= 0x08; /* Adjust wheel position based: rotate CCW by 2 positions */ } wheel_position = wheel_position >>2; // divide by four gesture = GetGesture(wheel_position); /* Add hysteresis to reduce toggling between wheel positions if no gesture * has been TRULY detected. */ if ( (gestureDetected==0) && ((gesture<=1) || (gesture==0x11) || (gesture==0x10))) { if (last_wheel_position != ILLEGAL_SLIDER_WHEEL_POSITION) wheel_position = last_wheel_position; gesture = 0; } /* Turn on corresponding LED(s) */ P1OUT = (P1OUT & BIT0) | LedWheelPosition[wheel_position]; if ((gesture != 0) && (gesture != 16) && (gesture != INVALID_GESTURE)) { /* A gesture has been detected */ if (gestureDetected ==0) { /* Starting of a new gesture sequence */ gestureDetected = 1; /* Transmit gesture start status update & position via UART to PC */ SendByte(GESTURE_START); SendByte(last_wheel_position + GESTURE_POSITION_OFFSET); } /* Transmit gesture & position via UART to PC */ SendByte(gesture); SendByte(wheel_position + GESTURE_POSITION_OFFSET); } else if (gestureDetected==0) { /* If no gesture was detected, this is constituted as a touch/tap */ if (++wheelTouchCounter >= WHEEL_TOUCH_DELAY) { /* Transmit wheel position [twice] via UART to PC */ wheelTouchCounter = 0; SendByte(wheel_position + WHEEL_POSITION_OFFSET ); SendByte(wheel_position + WHEEL_POSITION_OFFSET ); } } else wheelTouchCounter = WHEEL_TOUCH_DELAY - 1; idleCounter = 0; // Reset idle counter activeCounter++; last_wheel_position = wheel_position; } else { /* no wheel position was detected */ if(TI_CAPT_Button(&middle_button))
static int writeByteToSerial(unsigned int byt) { return SendByte(SERIAL_PORT, byt); }
static int BlockReceive( byte *err, trap_elen max_len, byte *p ) { byte buffer[8]; /* storing bytes other than actual data from blocks */ trap_elen i; /* loop index */ trap_elen len; word crc_val; unsigned blkno; int c; int wait; ZeroWaitCount(); BytesReceived = 0; wait = (MaxBaud == MIN_BAUD) ? SEC(1)/2 : SEC(1)/4; /* Receiving bytes before actual data (up to err byte) */ for( i = 1; i <= 7; ++i ) { c = WaitByte( wait ); if( c == SDATA_NO_DATA ) { /* time-out error */ LastResponse = SDATA_NAK; SendByte( SDATA_NAK ); /* send NAK to request resending of block */ return( FAIL ); } buffer[i] = c; } len = (buffer[MLEN+1] << 8) | buffer[MLEN]; /* number of data bytes */ if( len > max_len ) { /* not enough buffer space to store data */ ClearCom(); return( FAIL ); } /* Receiving actual data bytes */ for( i = 0; i < len; ++i ) { c = WaitByte( wait ); if( c == SDATA_NO_DATA ) { /* time-out error */ LastResponse = SDATA_NAK; SendByte( SDATA_NAK ); /* send NAK to request resending of block */ return( FAIL ); } p[i] = c; } /* Receiving the last byte: ETX */ buffer[0] = WaitByte( wait ); if( buffer[0] != SDATA_ETX ) { /* time-out error */ LastResponse = SDATA_NAK; SendByte( SDATA_NAK ); /* send NAK to request resending of block */ return( FAIL ); } *err = buffer[MERR]; /* storing command byte */ blkno = (buffer[MBLKNO+1] << 8) | buffer[MBLKNO]; /* blk# received */ crc_val = (buffer[MCRC+1] << 8) | buffer[MCRC]; /* crc received */ if( CRC( &buffer[MBLKNO], len, p ) != crc_val ) { /* CRC error */ LastResponse = SDATA_NAK; SendByte( SDATA_NAK ); /* send NAK to request resending of block */ return( FAIL ); } if( ReceiveBlkNo != blkno ) { /* incorrect block */ ClearCom(); LastResponse = SDATA_ACK; SendByte( SDATA_ACK ); return( FAIL ); } /* Block received successfully */ LastResponse = SDATA_ACK; SendByte( SDATA_ACK ); ++ReceiveBlkNo; BytesReceived = len; return( SUCCESS ); }
unsigned char ReadData( void ) { CheckBusy(); SendByte(0xfe); //11111,RW(1),RS(1),0 return ReceiveByte(); }
static char *SetupModem( char *parm ) { char *start; unsigned wait; unsigned ch; int data; Baud( MaxBaud ); wait = SEC(3); while( *parm == ' ' && *parm == '\t' ) ++parm; if( *parm == '\0' ) return( NULL ); for( ;; ) { if( *parm == '(' ) { start = ++parm; for( ;; ) { ch = *parm; if( ch == '\0' ) goto done; ++parm; if( ch == ')' ) break; if( ch == '\\' ) { ch = *parm++; switch( ch ) { case '\0': return( TRP_ERR_invalid_modem_string ); case 'r': ch = '\r'; break; case 'n': ch = '\n'; break; } } data = WaitByte( wait ); if( data == SDATA_NO_DATA ) { if( wait != SEC(60) ) { wait = SEC(60); } else { return( TRP_ERR_timeout_on_modem_string ); } --parm; } else { wait = SEC(3); if( data != ch ) parm = start; } } } else { Wait( SEC(1)/5 ); for( ;; ) { ch = *parm; if( ch == '\0' ) goto done; if( ch == '(' ) break; ++parm; if( ch == '\\' ) { ch = *parm++; switch( ch ) { case '\0': return( TRP_ERR_invalid_modem_string ); case '`': Wait( 1 ); break; case '~': Wait( SEC(1) ); break; case 'r': SlowSend( '\r' ); Wait( SEC(1)/2 ); break; case 'n': SlowSend( '\n' ); break; default: SlowSend( ch ); break; } } else { SlowSend( ch ); } } } } done: #ifdef SERVER #define SEND_CHAR '=' #define EXPECT_CHAR '-' #else #define SEND_CHAR '-' #define EXPECT_CHAR '=' #endif wait = 1; for( ;; ) { data = WaitByte( wait ); if( data == EXPECT_CHAR ) break; if( data == SDATA_NO_DATA ) { if( wait != SEC(10) ) { wait = SEC(10); SendByte( SEND_CHAR ); } else { return( TRP_ERR_modem_failed_connection ); } } } if( wait != SEC(10) ) SendByte( SEND_CHAR ); return( NULL ); }
static void SendIndex( unsigned short Index) { SendStartByte( 0, 0); SendByte( (Index>>8)); SendByte( (Index&0xFF)); }
/**************************************************************************** Function: Name Description:查询LCD是否处于忙状态 Input: Output: Notes: *****************************************************************************/ static void Lcd_CheckBusy(void) { do SendByte(0xfc); while(0x80&ReceiveByte()); //BF(.7)=1 Busy }
static void SendData( unsigned short Data) { SendStartByte( 0, 1); SendByte( (Data>>8)); SendByte( (Data&0xFF)); }
/******************坐标系***************/ void SpaceCreate(float A[3][3]) { int idata i,a,b,c,ap,bp,cp; VECTOR idata test[3]; float idata temp; GetAll(&ap,&bp,&cp); for(i=0;i<3;i++) { GetAll(&a,&b,&c); delay(70); if( abs(ap-a)<10 && abs(bp-b)<10 && abs(cp-c)<10 ) { test[i].a=a; test[i].b=b; test[i].c=c; } else i--; ap=a; bp=b; cp=c; } //x暂时借作为临时变量,算标准化过的z A[0][0]=-(test[0].a+test[1].a+test[2].a)/3; A[0][1]=-(test[0].b+test[1].b+test[2].b)/3; A[0][2]=-(test[0].c+test[1].c+test[2].c)/3; temp=sqrt(A[0][0]*A[0][0]+A[0][1]*A[0][1]+A[0][2]*A[0][2]); A[2][0]=A[0][0]/temp; A[2][1]=A[0][1]/temp; A[2][2]=A[0][2]/temp; GetAll(&a,&b,&c); i=0; test[0].a=0; test[0].b=0; test[0].c=0; while( 1 ) { if( i<10 && abs(a-ap)<20 && abs(b-bp)<20 && abs(c-cp)<20 && (abs(a+A[0][0])>130 || abs(b+A[0][1])>130 || abs(c+A[0][2])>130) ) { test[0].a+=a; test[0].b+=b; test[0].c+=c; i++; } if(i==10) break; ap=a; bp=b; cp=c; GetAll(&a,&b,&c); delay(50); } //第一下变化方向 A[1][0]=test[0].a/10+A[0][0]; A[1][1]=test[0].b/10+A[0][1]; A[1][2]=test[0].c/10+A[0][2]; //X轴正向 A[0][0]=A[1][1]*A[2][2]-A[2][1]*A[1][2]; A[0][1]=A[1][2]*A[2][0]-A[2][2]*A[1][0]; A[0][2]=A[1][0]*A[2][1]-A[2][0]*A[1][1]; //X轴标准化 temp=sqrt(A[0][0]*A[0][0]+A[0][1]*A[0][1]+A[0][2]*A[0][2]); A[0][0]=A[0][0]/temp; A[0][1]=A[0][1]/temp; A[0][2]=A[0][2]/temp; //Y轴标准化 A[1][0]=A[2][1]*A[0][2]-A[0][1]*A[2][2]; A[1][1]=A[0][2]*A[2][2]-A[2][0]*A[0][2]; A[1][2]=A[2][0]*A[0][1]-A[0][0]*A[2][1]; SendByte('K'); }
void NcrComPort::ClearText() { SendByte(0x1B); SendByte(0x02); }
/* ============================================================================ // fEraseBlock() // Perform a block erase of the target device. // Returns: // 0 if successful // ERASE_ERROR if timed out on handshake to the device. ============================================================================*/ signed char fEraseBlock(unsigned char bBlockNumber) { unsigned char bTargetDataPtr = 0; SendVector(tsync_enable, num_bits_tsync_enable); SendVector(read_write_setup, num_bits_read_write_setup); /* Set SDATA to Strong Drive here because SendByte() does not */ SetSDATAStrong(); /* Transfer the temporary RAM array into the target. // In this section, a 128-Byte array was specified by #define, so the entire // 128-Bytes are written in this loop. */ bTargetAddress = 0x00; while (bTargetDataPtr < TARGET_DATABUFF_LEN) { SendByte(write_byte_start, 4); /* we need to be able to write 128 bytes from address 0x80 to 0xFF*/ SendByte(bTargetAddress, 7); /* we need to be able to write 128 bytes from address 0x80 to 0xFF*/ SendByte(0, 8); /* load 0x00 */ SendByte(write_byte_end, 3); /* !!!NOTE: // SendByte() uses MSbits, so inc by '2' to put the 0..128 address into // the seven MSBit locations. // // This can be confusing, but check the logic: // The address is only 7-Bits long. The SendByte() subroutine will // send however-many bits, BUT...always reads them bits from left-to- // right. So in order to pass a value of 0..128 as the address using // SendByte(), we have to left justify the address by 1-Bit. // This can be done easily by incrementing the address each time by // '2' rather than by '1'. */ bTargetAddress += 2; /* inc by 2 in order to support a 128 byte address space */ bTargetDataPtr++; } SendVector(set_block_num, num_bits_set_block_num); /* Set the drive here because SendByte() does not. */ SetSDATAStrong(); SendByte(bBlockNumber, 8); SendByte(set_block_num_end, 3); SendVector(tsync_disable, num_bits_tsync_disable); /* Send the program-and-verify vector. */ SendVector(program_and_verify, num_bits_program_and_verify); /* wait for acknowledge from target. */ fIsError = fDetectHiLoTransition(); if (fIsError) return BLOCK_ERROR; /* Send the Wait-For-Poll-End vector */ SendVector(wait_and_poll_end, num_bits_wait_and_poll_end); /*---------------------------------------------------------------- // XCH: the lines below actually implement the erase SROM function // however, Product Engineering recommends using the WRITE SROM // function instead and write all '0' to the block. The function // below is saved for possible future implementation */ /* SendVector(tsync_enable, num_bits_tsync_enable); // SendVector(set_block_num, num_bits_set_block_num); // Set the drive here because SendByte() does not. // SetSDATAStrong(); // SendByte(bBlockNumber,8); // SendByte(set_block_num_end, 3); // SendVector(tsync_disable, num_bits_tsync_disable); // Send the erase-block vector. // SendVector(erase_block, num_bits_erase_block); // wait for acknowledge from target. // if (fIsError == fDetectHiLoTransition()) { // return(BLOCK_ERROR); // } // Send the Wait-For-Poll-End vector // SendVector(wait_and_poll_end, num_bits_wait_and_poll_end); //----------------------------------------------------------------- */ return PASS; }
void NcrComPort::SendString(const char *str) { while (*str) { SendByte(*str++); } }
void cprintf(int comport_number, const char *text) /* sends a string to serial port */ { while(*text != 0) SendByte(comport_number, *(text++)); }
int main() { MYSQL* con ; MYSQL_RES * res ; MYSQL_ROW row ; con = mysql_init(NULL); char *server = "localhost"; char *user = "******"; char *password = "******"; /* set me first */ char *database = "zandu"; // initiate the com port int i, n,cport_nr=16,/* /dev/ttyS0 (COM1 on windows) */ bdrate=9600; /* 9600 baud */ if(OpenComport(cport_nr, bdrate)) { printf("Can not open comport\n"); return(0); } // initiate the mysql connection if (!mysql_real_connect(con, server,user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } //start the main logic char query[100] ; char * storeTime = (char *)malloc(100); char * timeFormat = (char *)malloc(100); timeFormat = "%Y-%m-%d %T"; //sprintf(query,"select * from SendToBot order by timestampdiff(microsecond,time_stamp,current_timestamp) desc"); sprintf(query,"select * from sendtobot"); /* send SQL query */ if (mysql_query(con, query)) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } i = 0 ; int j = 0; while(1) { res = mysql_use_result(con); while( (row = mysql_fetch_row(res) ) != NULL ) { printf("%s\t %s\t %d \t %s\n",row[0],row[3],i,row[2]); int n , j ; int length = strlen(row[0]); for(j = 0 ; j < length ; j ++) { n = SendByte(cport_nr,row[0][j]) ; } n = SendByte(cport_nr,':') ; //To seperate ID from Command length = strlen(row[3]); for(j = 0 ; j < length ; j ++) { n = SendByte(cport_nr,row[3][j]) ; } //n = SendBuf(cport_nr,row[3],2) ; i ++ ; strcpy(storeTime,row[2]) ; } sprintf(query,"delete from sendtobot where time_stamp <= \"%s\"",storeTime); if (mysql_query(con,query)) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } mysql_free_result(res); sprintf(query,"select * from sendtobot order by timestampdiff(microsecond,time_stamp,str_to_date(\'%s\',\'%s\'))desc;",storeTime,timeFormat); //sprintf(query,"select * from sendtobot"); if (mysql_query(con,query)) { fprintf(stderr, "%s\n", mysql_error(con)); exit(1); } } }
// ============================================================================ // PTJ: fReadSecurity() // This reads from SM0 with Read Supervisory SPC command. // Need to have SPC Test Mode enabled before using these commands? // Returns: // 0 if successful // __________ if timed out on handshake to the device. // ============================================================================ signed char fReadSecurity(void) { SendVector(ReadSecuritySetup, num_bits_ReadSecuritySetup); // SendVector(SPCTestMode_enable, num_bits_SPCTestMode_enable); bTargetAddress = 0x00; while (bTargetAddress < (SECURITY_BYTES_PER_BANK * 2)) { //PTJ: we do SECURITY_BYTES_PER_BANK * 2 because we bTargetAddress += 2 //PTJ: TSYNC Enable SendVector(tsync_enable, num_bits_tsync_enable); SendVector(read_security_pt1, num_bits_read_security_pt1); //PTJ: // Set the drive here because SendByte() does not. SetSDATAStrong(); SendByte(bTargetAddress, 7); //PTJ: hardcode MSb of address as 0 in bit stream SendVector(read_security_pt1_end, num_bits_read_security_pt1_end); //PTJ: TSYNC Disable SendVector(tsync_disable, num_bits_tsync_disable); SendVector(read_security_pt2, num_bits_read_security_pt2); SendVector(wait_and_poll_end, num_bits_wait_and_poll_end); SendVector(read_security_pt3, num_bits_read_security_pt3); SetSDATAStrong(); SendByte(bTargetAddress, 7); SendVector(read_security_pt3_end, num_bits_read_security_pt3_end); SendVector(wait_and_poll_end, num_bits_wait_and_poll_end); bTargetAddress += 2; } bTargetAddress = 0x00; bTargetDataPtr = 0x00; SendVector(tsync_enable, num_bits_tsync_enable); //PTJ: 307, added for tsync testing while (bTargetAddress < (SECURITY_BYTES_PER_BANK * 2)) { //PTJ: we do SECURITY_BYTES_PER_BANK * 2 because we bTargetAddress += 2 //Send Read Byte vector and then get a byte from Target SendVector(read_byte_v, 4); // Set the drive here because SendByte() does not SetSDATAStrong(); SendByte(bTargetAddress, 7); RunClock(2); // Run two SCLK cycles between writing and reading SetSDATAHiZ(); // Set to HiZ so Target can drive SDATA bTargetDataIN = bReceiveByte(); RunClock(1); SendVector(read_byte_v + 1, 1); // Send the ReadByte Vector End // Test the Byte that was read from the Target against the original // value (already in the 128-Byte array "abTargetDataOUT[]"). If it // matches, then bump the address & pointer,loop-back and continue. // If it does NOT match abort the loop and return and error. if (bTargetDataIN != abTargetDataOUT[bTargetDataPtr]) // return(BLOCK_ERROR); // Increment the address by two to accomodate 7-Bit addressing // (puts the 7-bit address into MSBit locations for "SendByte()"). bTargetDataPtr++; bTargetAddress += 2; } SendVector(tsync_disable, num_bits_tsync_disable); //PTJ: 307, added for tsync testing return (PASS); }
static int BlockSend( trap_elen num, byte *p, unsigned timeout ) { word crc_value; /* crc value of block */ unsigned wait_time; /* timer for testing time-out */ trap_elen i; /* loop index */ int reply; /* reply message from other machine */ unsigned char crc_low, crc_hi; unsigned char len_low, len_hi; byte extra[3]; /* ..[0]=blkno_low, ..[1]=blkno_hi, ..[2]=err */ unsigned wait; ZeroWaitCount(); extra[2] = PrevErrors = Errors; if( Errors > 255 ) { extra[2] = 255; /* because it is a char, not an int */ } Errors = 0; ClearCom(); /* compose send buffer contents */ len_low = num & 0xff; /* low 8 bits of data block length */ len_hi = num >> 8; /* high 8 bits of data block length */ extra[0] = SendBlkNo & 0xff; /* low 8 bits of send block no */ extra[1] = SendBlkNo >> 8; /* high 8 bits of send block no */ crc_value = CRC( extra, num, p ); /* calculate crc for (blk#+err+data) */ crc_low = crc_value & 0xff; /* low 8 bits of crc_value */ crc_hi = crc_value >> 8; /* high 8 bits of crc_value */ wait = (MaxBaud == MIN_BAUD) ? SEC(2) : SEC(1); for( ;; ) { /* send block loop */ /* send the block */ StartBlockTrans(); SendByte( SDATA_STX ); SendByte( crc_low ); SendByte( crc_hi ); SendByte( len_low ); SendByte( len_hi ); SendByte( extra[0] ); /* blkno_low */ SendByte( extra[1] ); /* blkno_hi */ SendByte( extra[2] ); /* err */ for( i = 0; i < num; ++i ) { SendByte( p[i] ); } SendByte( SDATA_ETX ); StopBlockTrans(); wait_time = WaitCount() + timeout; for( ;; ) { /* wait proper acknowledgement loop */ reply = WaitByte( wait ); /* receive reply */ if( reply == SDATA_NO_DATA ) { if( (timeout != FOREVER) && (WaitCount() >= wait_time) ) { return( FAIL ); /* time-out */ } else { SendByte( SDATA_RLR ); /* request last response */ ++Errors; /* increment error counter */ } } else { if( reply == SDATA_ACK ) { ++SendBlkNo; return( SUCCESS ); /* done, exit from BlockSend() */ } else if( reply == SDATA_NAK ) { /* unsuccessful, re-send block */ ++Errors; break; /* break out of acknowledgement loop; i.e. back to send block loop */ } else if( reply == SDATA_RLR ) { /* request last response */ SendByte( LastResponse ); break; /* break out ackno loop; re-send block */ } else { /* things are totally messed up */ while( WaitByte( SEC(3)/4 ) != SDATA_NO_DATA ) ; /* discard all characters sent */ SendByte( SDATA_RLR ); /* request last response */ ++Errors; } } } } }
void GetAndSendAccGyro(int i2c_handle, int i2c_acc_addr, int i2c_gyro_addr, unsigned int idPayloadNum, unsigned int delaySend, GPS_DATA *last_data, unsigned char rf_buffer_len ) { unsigned int gxvalue, gyvalue, gzvalue, gyrox, gyroy, gyroz; unsigned char buff_data[100], buff_gps_data[40]; //tes clock length //clock_t c0,c1,c2; //double el1,el2; //c0 = clock(); //set buff to all 0 memset(buff_data,0,100); //get g data adxl345_get_gdata(i2c_handle, i2c_acc_addr, &gxvalue, &gyvalue, &gzvalue); //c1 = clock(); //get gyro itg3200_get_gyro_data(i2c_handle, i2c_gyro_addr, &gyrox, &gyroy, &gyroz); //c2 = clock(); //duration //el1 = ((double) c1-c0) / CLOCKS_PER_SEC; //el2 = ((double) c2-c1) / CLOCKS_PER_SEC; //printf("t1 = %f\t t2 = %f\n", el1, el2); //print g and gyro data //printf("\r%.3d %.3d %.3d %.3d %.3d %.3d %.3d %.3d",idPayloadNum, adxl345_normalize_gdata(adxl345_calc_gvalue(gxvalue), 0, 999) , adxl345_normalize_gdata(adxl345_calc_gvalue(gyvalue), 0, 999), adxl345_normalize_gdata(adxl345_calc_gvalue(gzvalue),0,999),itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyrox), 0, 999) , itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyroy), 0, 999), itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyroz),0,999), idPayloadNum); //c0 = clock(); //format the data header+gyro acc snprintf(buff_data, 34, "%c%.3d %.3d %.3d %.3d %.3d %.3d %.3d ", 13, idPayloadNum, adxl345_normalize_gdata(adxl345_calc_gvalue(gxvalue), 0, 999) , adxl345_normalize_gdata(adxl345_calc_gvalue(gyvalue), 0, 999), adxl345_normalize_gdata(adxl345_calc_gvalue(gzvalue),0,999), itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyrox), 0, 999) , itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyroy), 0, 999), itg3200_normalize_gyrodata(itg3200_calc_gyro_value(gyroz),0,999) ); //c1 = clock(); //~ printf("%s", buff_data); //send the data //~ SendBuf(COM_PORT, buff_data, 29); //~ cprintf(COM_PORT, buff_data); //~ usleep(delaySend); //get gps data //~ GetAndFormatGPSData(i2c_handle, buff_gps_data, last_data); GetAndFormatGPSData(i2c_handle, &buff_data[29], last_data); //send the gps data //~ SendBuf(COM_PORT, buff_gps_data, 37); //~ usleep(RF_DELAY_US); //tail //~ snprintf(buff_data, 5, " %.3d", idPayloadNum); //~ snprintf(&buff_data[64], 35, " %26.3s%4.3dX", ID_NAME, idPayloadNum); snprintf(&buff_data[66], 35, " %3.3s%4.3d", ID_NAME, idPayloadNum); //send the data //~ SendBuf(COM_PORT, buff_data, 4); //c2 = clock(); //el1 = ((double) c1-c0) / CLOCKS_PER_SEC; //el2 = ((double) c2-c1) / CLOCKS_PER_SEC; //printf("t1 = %f\t t2 = %f\n", el1, el2); //~ buff_data[0] = '\n'; //~ printf("%s\n", buff_data); //~ buff_data[0] = '\r'; unsigned int i; //~ for(i=0;i<96;i+=32) //~ { //~ SendBuf(COM_PORT, &buff_data[i], 32); //~ usleep(delaySend); //~ } //for trw433 #ifdef RADIO_TYPE_TRW433 for(i=0;i<74;i++) { SendByte(COM_PORT, buff_data[i]); //~ if(i%(rf_buffer_len-1)==0) if(i%(16-1)==0) usleep(delaySend); } #endif //for hm-trp #ifdef RADIO_TYPE_HMTRP for(i=0;i<74;i++) { SendByte(COM_PORT, buff_data[i]); //~ if(i%(rf_buffer_len-1)==0) if(i%(32-1)==0) usleep(delaySend); } #endif //~ SendByte(COM_PORT, 13); //~ SendByte(COM_PORT, 'A'); usleep(delaySend); }
//Not in use for sending NMEA sentences through the serial port void SerialPort::writeByte(unsigned char byte) { if(open) { SendByte(portNumber, byte); } }