/* manageIncomingData() - manage incoming data from serial port, executing proper functions to store received data * * This function manages incoming data from serial port, executing proper functions to store received data * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::manageIncomingGSMData() { char byteIN[100]; uint8_t a=0; long previous=0; uint8_t answer=0; while(a<100){ byteIN[a]=0; a++; } a=0; serialFlush(PORT_USED); previous=millis(); while(!serialAvailable(PORT_USED) && (millis()-previous)<20000); previous=millis(); while( (millis()-previous) < 2000 ) { while( serialAvailable(PORT_USED) && (millis()-previous) < 2000 ) { byteIN[a]=serialRead(PORT_USED); a++; } } answer=parse_GSM(byteIN); switch( answer ){ case 0: readCall(byteIN); break; case 1: readSMS(byteIN); break; } if(answer==2) return 0; return 1; }
int la_init_controls(int** fdControls, int* fdControlCount) { int ret; ret = wiringPiSetup(); if(ret) return ret; if ((fdsArduino[0] = serialOpen ("/dev/ttyAMA0", 9600)) < 0) { fprintf (stderr, "E: Unable to open serial device: %s\n", strerror (errno)) ; return -1; } serialFlush(fdsArduino[0]); fArduino = fdopen(fdsArduino[0], "r"); buf_len = 128; buf = malloc(buf_len); if(!buf) { fprintf (stderr, "E: Unable to allocate buffer: %s\n", strerror (errno)) ; return -1; } *fdControls = fdsArduino; *fdControlCount = 1; return 0; }
/* Function: Sends a given command to bluetooth module, adding CR+LF. Returns: Parameters: theText: Command to send. Values: */ void WaspBT_Pro::sendCommand(const char* theText) { sprintf(theCommand, "%s\r\n", theText); // Adds CR+LF serialFlush(1); printString(theCommand,PORT_USED); delay(100); }
void Controller::runUart() { int fd = serialOpen(UART_DEVICE, 9600); int bSize = 0; // ilość znaków w buforze while(!endThreads) { bSize = serialDataAvail(fd); if(bSize==8) { // dwa inty czekają na odczyt union IntOrByte { char b[4]; int i; } u; // odczyt kierunku wiatru for (int i =0; i < 4; i++) { //odczytaj 4 bajty u.b[i] = serialGetchar(fd); } this->windDirection = u.i; // odczyt prędkości wiatru u.i = 0; // resetujemy union for (int i =0; i < 4; i++) { //odczytaj 4 bajty u.b[i] = serialGetchar(fd); } this->windSpeed = u.i; } else if(bSize>8) { // zbyt dużo informacji w buforze serialFlush(fd); } chrono::milliseconds sleepDuration(500); this_thread::sleep_for(sleepDuration); } serialClose(fd); dlog << "koniec threadWorker"; }
/******************************************************************** * getDataFromSerial: * * gets the data from the serial (xbee) modules * * and calls parseVfdMessage * ********************************************************************/ int getDataFromSerial() { int strlength = 0; int readlength = 0; // Check if data is available on the serial port if((strlength = serialDataAvail(serialFd)) > 0) // Check if data is available on the port { // Read data into messageFromVfd readlength = read(serialFd, &messageFromVfd, strlength); if(messageFromVfd[readlength - 1] != ENDCHAR) { printf("serial data unaligned! Flushing data in serial buffer. read:<%s>\n", messageFromVfd); serialFlush(serialFd); return 0; } else { messageFromVfd[readlength] = '\0'; //add null terminator to the end of the string printf("VFD-->Pi: %s\n", messageFromVfd); parseVfdMessage(); return 1; } } else { printf("no data on serial\n"); return 0; //no data available or error getting data } }
/******************************************************************** * init: * * initializes the program * ********************************************************************/ void init() { /* Initialize serial port for xbee comm */ wiringPiSetup(); if((serialFd = serialOpen("/dev/ttyAMA0", BAUD_RATE)) < 0) error("error opening serial port"); //initialize the mutex pthread_mutex_init(&flagMutex, NULL); // Set up sig handler for USR1 signal (restart recv thread) if (signal(SIGUSR1, sig_handler) == SIG_ERR) error("error setting up the sig_handler\n"); update.desiredFlowRate = MAX_FLOW; update.frequency = MAX_FREQ; update.VFDState = ON_VFD; // set all flags for first run LOCK(&flagMutex); update.updateFlag = UPDATE_FREQ_STATE | UPDATE_FLOW; UNLOCK(&flagMutex); // Initialize memory and flush remaining serial data serialFlush(serialFd); memset((void*)&data, 0, sizeof(data)); memset((void*)&messageFromServer, 0, sizeof(messageFromServer)); memset((void*)&messageFromVfd, 0, sizeof(messageFromVfd)); // Create thread to monitor the socket and receive messages if( pthread_create(&thread_id, NULL, receive_handler, (void*)&thread_id) < 0) error("could not create recv thread"); }
byte WaspGPRS::sendCommand(char* theText, char* endOfCommand, char* expectedAnswer, int MAX_TIMEOUT, int sendOnce) { int timeout = 0; for (int i = 0; i < 100; i++) received[i] = ' '; int length=sprintf(theCommand, "%s%s", theText,endOfCommand); // try sending the command // wait for serial response timeout = 0; serialFlush(PORT_USED); while(!serialAvailable(PORT_USED) && timeout < MAX_TIMEOUT) { if (!sendOnce || !timeout) { printString(theCommand,PORT_USED); USB.print('T'); } delay(DELAY_ON_SEND); timeout++; }; int answer= waitForData( expectedAnswer, MAX_TIMEOUT, timeout, 0); return answer; }
uint8_t WaspGPRS::sendDataFTP(char* file, char* path, uint8_t id) { char command[100]; char aux='"'; long previous=0; uint8_t answer=0; uint8_t end=0; uint32_t i,j=0; sprintf(command,"AT%s%c,,%c%c,%c%s%c,0%c%c", AT_FTP_SEND, id, aux, aux, aux, file, aux, '\r', '\n'); printString(command,PORT_USED); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) ); delay(10); answer=waitForData("CONNECT",20,0,0); if(answer!=1) return 0; serialFlush(PORT_USED); Utils.strExplode(path,'/'); while( path[i]!='\0' ) { if( path[i]== '/' ) j++; i++; } i=0; SD.ON(); while( j>0 ) { if(!SD.cd(Utils.arguments[i])){ SD.OFF(); return 0; } i++; j--; } i=0; j=0; while( !end ) { printString(SD.cat(file,250*i,250),PORT_USED); while( SD.buffer[j]!='\0' ) j++; if( j<249 ) end=1; i++; j=0; } printString(GPRS_PATTERN,PORT_USED); SD.OFF(); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) ); delay(10); answer=waitForData("OK",20,0,0); if(answer!=1) return 0; return 1; }
/* readURL(url) - access to the specified URL and stores the info read in 'data_URL' variable * * This function access to the specified URL and stores the info read in 'data_URL' variable * * It modifies 'flag' if expected answer is not received after sending a command to GPRS module * * It stores in 'socket_ID' the TCP session ID assigned to the last call to create a socket * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::readURL(const char* url) { char command[30]; char* data=",20"; uint8_t answer=0; long previous=0; uint8_t byteIN=0; uint8_t a=0; if(!configureGPRS()) return 0; if(!createSocket(url,"80",GPRS_CLIENT)) return 0; serialFlush(PORT_USED); sprintf(command,"%s%c%c","GET / HTTP/1.0",'\r','\n'); if(!sendData(command,socket_ID)){ closeSocket(socket_ID); return 0; } waitForData("+KTCP_DATA:",20,0,0); if(readData(socket_ID,GPRS_DATA_LENGTH)<0){ closeSocket(socket_ID); return 0; } while(!closeSocket(socket_ID)) closeSocket(socket_ID); return 1; }
/* sendData(data,socket) - sends 'data' to the specified 'socket' * * This function sends 'data' to the specified 'socket' * * It modifies 'flag' if expected answer is not received after sending a command to GPRS module * * It gets from 'socket_ID' the TCP session ID assigned to the last call of creating a socket * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::sendData(const char* data, uint8_t* socket) { char command[30]; uint8_t answer=0; long previous=0; uint8_t byteIN=0; uint8_t counter=0; uint8_t i=0; while(data[counter]!='\0') counter++; counter+=2; while(socket[i]!='\r') i++; counter+=i-1; serialFlush(PORT_USED); switch(i) { case 1: sprintf(command,"%s%c,%u%c%c",AT_GPRS_TCP_SND,socket[0],counter,'\r','\n'); break; case 2: sprintf(command,"%s%c%c,%u%c%c",AT_GPRS_TCP_SND,socket[0],socket[1],counter,'\r','\n'); break; case 3: sprintf(command,"%s%c%c%c,%u%c%c",AT_GPRS_TCP_SND,socket[0],socket[1],socket[2],counter,'\r','\n'); break; } printString(command,PORT_USED); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<3000) ); delay(10); answer=waitForData("CONNECT",20,0,0); if(answer!=1) return 0; answer=0; counter=0; while( (counter<3) && (answer!=1) ) { serialFlush(PORT_USED); delay(20); writeData(data); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<3000) ); delay(10); answer=waitForData("OK",20,0,0); counter++; } if(answer!=1) return 0; return 1; }
void ESP8266::readResponse(unsigned long timeout, void(*handler)(uint8_t serialResponseStatus)) { switch (state) { case STATE_IDLE: case STATE_CONNECTED: case STATE_SENDING_DATA: case STATE_RESETING: state = STATE_RECIVING_DATA; serialResponseTimestamp = currentTimestamp; serialResponseTimeout = timeout; serialResponseHandler = handler; strcpy(buffer, ""); bufferCursor = 0; //DBG("started listening\r\n"); break; case STATE_RECIVING_DATA: if ((currentTimestamp - serialResponseTimestamp) > serialResponseTimeout || currentTimestamp < serialResponseTimestamp || (bufferFind(responseTrueKeywords) || bufferFind(responseFalseKeywords) || bufferCursor == (SERIAL_RX_BUFFER_SIZE - 1))) { state = STATE_DATA_RECIVED; if (bufferFind(responseTrueKeywords) || bufferCursor == (SERIAL_RX_BUFFER_SIZE - 1)) { //DBG(F("serial true \r\n")); handler(SERIAL_RESPONSE_TRUE); } else if (bufferFind(responseFalseKeywords)) { //DBG(F("serial false \r\n")); handler(SERIAL_RESPONSE_FALSE); } else { //DBG(F("serial timeout \r\n")); handler(SERIAL_RESPONSE_TIMEOUT); } } else { while (_wifiSerial.available() > 0) { if (bufferCursor < (SERIAL_RX_BUFFER_SIZE-1)){ buffer[bufferCursor] = _wifiSerial.read(); bufferCursor++; } else { DBG(F("ESP8266 lib buffer overflow \r\n")); //empty the wifiSerial buffer' serialFlush(); break; } } buffer[bufferCursor] = '\0'; } break; } lastActivityTimestamp = currentTimestamp; //DBG(state); }
/* Function: Turns on bluetooth module. Returns: Parameters: Values: */ void WaspBT_Pro::ON() { Utils.setMuxGPRS(); beginSerial(_baudRate,_uart); setMode(BT_ON); // Power saving serialFlush(1); reset(); }
static ERL_NIF_TERM serial_flush_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { int handle; if (!enif_get_int(env, argv[0], &handle)) { return enif_make_badarg(env); } serialFlush(handle); return atom_ok; }
int main(void) { int handle = serialOpen ("/dev/ttyAMA0", 9600); //Open the Serial port serialFlush(handle); //Clear the stream of old data packets while(1) { serialPutchar (handle, 's'); //Send 's' to the Arduberry char inp=serialGetchar(handle); //Receive the characters from the Arduberry printf("%c",inp); } return 0; }
int serial_flush(int serial_id) { struct serial_bus *sb = serial_buses[serial_id]; if(!sb) return -1; if(sb->fd < 0) { sb->fd = serialOpen(sb->bus, sb->speed); } serialFlush (sb->fd); return 0; }
/* getCellInfo() - gets the information from the cell where the module is connected * * This function gets the information from the cell where the module is connected * * It stores in 'RSSI' and 'cellID' variables the information from the cell * * It modifies 'flag' if expected answer is not received after sending a command to GPRS module * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::getCellInfo() { char command[30]; uint8_t byteIN[200]; long previous=millis(); uint8_t counter=0; uint8_t a,b,c=0; serialFlush(PORT_USED); sprintf(command,"AT%s\r\n",AT_GPRS_CELLID); printString(command,PORT_USED); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<3000) ); previous=millis(); a=0; while( (millis()-previous) < 2000 ) { while( serialAvailable(PORT_USED) && (millis()-previous) < 2000 && (a<200) ) { byteIN[a]=serialRead(PORT_USED); a++; } } a=0; while( counter < 5 ) { while( (byteIN[a]!=',') && (a<200) ) { a++; } a++; counter++; } if(a>=200) return 0; counter=0; while( (byteIN[a]!=',') && (a<200) ) { cellID[c]=byteIN[a]; a++; c++; } a++; while( (byteIN[a]!=',') && (a<200) ) { RSSI[b]=byteIN[a]; delay(10); b++; a++; } return 1; }
/* * Put the Wifi Module into command mode. ****************************************************************************** */ int cmdModeEnable(char * response, int serialLine){ serialFlush(serialLine); delay (300) ; serialPuts(serialLine,"$$$"); delay (300) ; int size = serialReceive(response, serialLine); if (size == 0){ //printf("Nothing read as response\n"); return 0; }else if( strcmp(response, "CMD\r\n") == 0){ return 1; } else { return 0; } }
/* * * name: sendCommand * @param uint8_t* command: pointer to the buffer with the command to be sent * @param uint16_t length: length of the buffer * @return void */ void WaspUART::sendCommand( uint8_t* command, uint16_t length ) { // clear uart buffer before sending command if( _flush_mode == true ) { serialFlush(_uart); } /// print command for (uint16_t i = 0; i < length; i++) { printByte( command[i], _uart ); } delay( _def_delay ); }
/* sendMail() - sends an email * * This function sends an email * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::sendMail(char* from, char* to, char* subject, char* body, char* user, char* passw, char* smtp_server, uint16_t port) { uint8_t counter=0; char command[30]; long previous=0; uint8_t answer=0; if(!setFlowControl()) return 0; if(!configureGPRS()) return 0; if(!setEmailParams(smtp_server, port, from)) return 0; if(!setEmailPwd(user, passw)) return 0; if(!setEmailDestination(to)) return 0; if(!setEmailSubject(subject)) return 0; while( body[counter]!='\0' ) counter++; counter+=2; serialFlush(PORT_USED); sprintf(command,"AT%s1,%u%c%c",AT_SMTP_SEND,counter,'\r','\n'); printString(command,PORT_USED); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) ); delay(10); answer=waitForData("CONNECT",20,0,0); if(answer!=1) return 0; printString(body,PORT_USED); printByte('\r',PORT_USED); printByte('\n',PORT_USED); previous=millis(); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<10000) ); delay(10); answer=waitForData("OK",20,0,0); if(answer!=1) return 0; return 1; }
/* getIMSI() - gets the IMSI from the SIM card * * This function gets the IMSI from the SIM card. It stores the IMSI into 'IMSI' variable. * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::getIMSI() { char command[15]; uint8_t byteIN[20]; long previous=millis(); uint8_t a,b=0; serialFlush(PORT_USED); sprintf(command,"%s\r\n",AT_GPRS_IMSI); printString(command,PORT_USED); while( (!serialAvailable(PORT_USED)) && ((millis()-previous)<3000) ); previous=millis(); a=0; while( (millis()-previous) < 2000 ) { while( serialAvailable(PORT_USED) && (millis()-previous) < 2000 && (a<20) ) { byteIN[a]=serialRead(PORT_USED); a++; } } a=0; while( (byteIN[a]!='\r') && (byteIN[a]!='\n') && (a<20) ) { a++; } if(a>=20) return 0; a++; if(a>=20) return 0; b=0; while( (byteIN[a]!='\r') && (a<20) ) { IMSI[b]=byteIN[a]; a++; b++; } IMSI[b]='\0'; if(b<=10) return 0; return 1; }
void SendMessage::Send() { serialFlush(SerialPort::GetFileDescriptor()); const unsigned char* concatenatedMessage; concatenatedMessage = CreateMessageString(); SerialPort::Send(concatenatedMessage); cout << "Sending Message:\n"; cout << hex << (int) destination << ", "; cout << dec << (int) messageSize << ", "; cout << hex << (int) payloadId << ", "; for (int i = 0; i < messageSize - BaseMessageSize; ++i) { cout << dec << (int) payload[i] << ", "; } cout << hex << (int) checkSum << endl; cout << "Message Complete." << endl; }
int stm32Sync() { int ret = STM_ERR; static unsigned char STM32_INIT = 0x7F; unsigned char r; int rr; int i; printf("Sync"); fflush(stdout); for ( i=0; i<MAXTRY; i++ ) { printf("."); fflush(stdout); rr = serialWrite(board.serial_fd, &STM32_INIT, 1); if ( rr == SER_OK ) { serialFlush(board.serial_fd); rr = serialRead(board.serial_fd, &r, sizeof(r)); if ( rr == SER_OK ) { if ( r==STM32_ACK || r==STM32_NACK) { ret = STM_OK; break; } } } } printf("\n"); if ( ret == STM_OK ) { printf("Connected to board.\n"); } else { printf("Can not connect to board, "); if ( rr == SER_ERR ) { printf(" failed.\n"); } else { printf(" timed-out.\n"); } } return ret; }
int main(void) { uint8_t i; WDT_off(); setup(); PORTB |= (1<<PB7);//DONE _delay_ms(1000); PORTB &= ~(1<<PB7);//DONE // insert a startup delay of 20s to prevent interference with redboot // interrupts are already enabled at this stage // so the pulses are counted but not sent to the deamon // for (i=0; i<4; i++) _delay_ms(5000); serialFlush(); printString("\n"); WDT_on(); for (;;) loop(); return 0; }
/* sendCommand(ATcommand, ATcommand_R) - sends any command to GPRS module * * This function sends any command to GPRS module * * It stores in 'answer_command' variable the answer returned by the GPRS module * * Returns '1' on success and '0' if error */ uint8_t WaspGPRS::sendCommand(char* ATcommand) { char command[30]; uint8_t timeout=0; uint8_t i=0; answer_command[0]='\0'; sprintf(command, "AT%s%c%c", ATcommand,'\r','\n'); serialFlush(PORT_USED); USB.print('d'); while(!serialAvailable(PORT_USED)) { printString(command,PORT_USED); delay(DELAY_ON_SEND); USB.print('e'); } USB.print('a'); while( timeout < 5 ) { while(!serialAvailable(PORT_USED) && timeout < 5) { timeout++; delay(1000); } USB.print('b'); while(serialAvailable(PORT_USED) && timeout < 5){ answer_command[i] = serialRead(PORT_USED); delay(20); i++; timeout=0; if(i>=199) timeout=5; } USB.print('c'); } answer_command[i]='\0'; if( i<5 ) return 0; return 1; }
/* check(void) - Checks if GPRS is connected to the network * * This function checks if GPRS module is connected to the network. If not, it has no sense working with GPRS. * * It sends a command to GPRS module DEFAULT_TIMEOUT times. If GPRS module does not connect within these tries, function * exits. * * Returns '1' when connected and '0' if not */ uint8_t WaspGPRS::check() { char byte; uint8_t timeout=1;///DEFAULT_TIMEOUT; char command[11]; uint8_t answer=0; while(timeout) { sprintf(command,"%s%c%c","AT+CREG?",'\r','\n'); serialFlush(PORT_USED); printString(command,PORT_USED); answer=waitForData("+CREG: 0,1",1,0,0); switch(answer){ case 0: break; case 1: connected = 1; return 1; break; case 2: break; } // delay(1000); USB.print('x'); printString(command,PORT_USED); answer=waitForData("+CREG: 0,5",1,0,0); switch(answer){ case 0: break; case 1: connected = 1; return 1; break; case 2: break; } delay(100); timeout--; } connected = 0; return 0; }
void stmLoader(serialStruct_t *s, FILE *fp, unsigned char overrideParity, unsigned char noSendR) { char c; unsigned char b1, b2, b3; unsigned char i, n; char *jumpAddress; // turn on parity generation if (!overrideParity) serialEvenParity(s); if(!noSendR) { top: printf("Sending R to place Baseflight in bootloader, press a key to continue"); serialFlush(s); c = 'R'; serialWrite(s, &c, 1); getchar(); printf("\n"); } serialFlush(s); printf("Poking the MCU to check whether bootloader is alive..."); // poke the MCU do { printf("p"); fflush(stdout); c = 0x7f; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_SHORT)); printf("STM bootloader alive...\n"); // send GET command do { c = 0x00; serialWrite(s, &c, 1); c = 0xff; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); b1 = serialRead(s); // number of bytes b2 = serialRead(s); // bootloader version for (i = 0; i < b1; i++) getResults[i] = serialRead(s); stmWaitAck(s, STM_RETRIES_LONG); printf("Received commands.\n"); // send GET VERSION command do { c = getResults[1]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); b1 = serialRead(s); b2 = serialRead(s); b3 = serialRead(s); stmWaitAck(s, STM_RETRIES_LONG); printf("STM Bootloader version: %d.%d\n", (b1 & 0xf0) >> 4, (b1 & 0x0f)); // send GET ID command do { c = getResults[2]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); n = serialRead(s); printf("STM Device ID: 0x"); for (i = 0; i <= n; i++) { b1 = serialRead(s); printf("%02x", b1); } stmWaitAck(s, STM_RETRIES_LONG); printf("\n"); /* flash_size: // read Flash size c = getResults[3]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); // if read not allowed, unprotect (which also erases) if (!stmWaitAck(s, STM_RETRIES_LONG)) { // unprotect command do { c = getResults[10]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); // wait for results if (stmWaitAck(s, STM_RETRIES_LONG)) goto top; } // send address if (!stmWrite(s, "1FFFF7E0")) goto flash_size; // send # bytes (N-1 = 1) if (!stmWrite(s, "01")) goto flash_size; b1 = serialRead(s); b2 = serialRead(s); printf("STM Flash Size: %dKB\n", b2<<8 | b1); */ // erase flash erase_flash: printf("Global flash erase [command 0x%x]...", getResults[6]); fflush(stdout); do { c = getResults[6]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); // global erase if (getResults[6] == 0x44) { // mass erase if (!stmWrite(s, "FFFF")) goto erase_flash; } else { c = 0xff; serialWrite(s, &c, 1); c = 0x00; serialWrite(s, &c, 1); if (!stmWaitAck(s, STM_RETRIES_LONG)) goto erase_flash; } printf("Done.\n"); // upload hex file printf("Flashing device...\n"); jumpAddress = stmHexLoader(s, fp); if (jumpAddress) { printf("\nFlash complete, executing.\n"); go: // send GO command do { c = getResults[4]; serialWrite(s, &c, 1); c = 0xff ^ c; serialWrite(s, &c, 1); } while (!stmWaitAck(s, STM_RETRIES_LONG)); // send address if (!stmWrite(s, jumpAddress)) goto go; } else { printf("\nFlash complete.\n"); } }
void WaspXBee::flush() { serialFlush(_uart); }
int serialClose(int fd) { serialFlush(fd); close(fd); return SER_OK; }
int main () { int fd ; int b = 0; int a = 0; int i = 0; char mac[] = "78A5048C47AF"; //green module mac char check[20] = "\0"; if ((fd = serialOpen ("/dev/ttyAMA0", 9600)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } fflush(stdout); serialPuts (fd,"AT+MODE1"); //serve para acordar o modulo delay(500); serialFlush (fd) ; printf("go\n"); serialPuts (fd,"AT+CON"); serialPuts (fd,mac); while(serialDataAvail(fd)==0); //espera a chegada de algum byte na porta serial //o bloco abaixo recebe as informacoes do buffer e copia para a string check i=0; while((serialDataAvail(fd))!=0) { delay(10); check[i] = serialGetchar(fd); i++; } check[i] = 0; //fim do bloco que copia os dados para a string check printf("%s \n", check); //debug if (strcmp(check,"OK+CONNA") == 0) //se verificado que o módulo entendeu o comando, limpa a string e prossegue { check[0] = 0; //se o ble entendeu o comando, limpa a string e prossegue printf("comando recebido\n"); //debug } else { if (strcmp(check,"OK+CONNAOK+CONN") == 0) { check[0] = 0; printf("conectou!\n"); //para o caso da conexão ser estabelecida entre uma tentativa e outra } else return printf("erro!\n"); //se nao, retornar erro desconhecido } while(serialDataAvail(fd)==0); //espera a segunda parte da mensagem //o bloco abaixo recebe as informacoes do buffer e copia para a string check i=0; while((serialDataAvail(fd))!=0) { delay(10); check[i] = serialGetchar(fd); i++; } check[i] = 0; //fim do bloco que copia os dados para a string check if ((strcmp(check,"OK+CONN") == 0)) //verifica se a conexao foi efetuada { check[0] = 0; printf("conectou!\n"); } else { check[0] = 0; printf("conexao falhou!\n"); } }
/* Function: This function reads the data from satellites * Parameters: parse. 0 to return the data string in buffer_GPRS * 1 to parse data and update GPS variables * Returns 1 if success * -1 if timeout * -2 if error */ int8_t WaspGPRS_SIM928A::getGPSData(bool parse) { int8_t answer; int aux, counter; long previous; char aux_str[25]; int8_t x; char* aux_ptr; serialFlush(_socket); strcpy_P(str_aux1, (char*)pgm_read_word(&(table_GPS[1]))); //GNSS_INFO snprintf(str_aux2, sizeof(str_aux2), "%s: ", str_aux1); answer = sendCommand2(str_aux1, str_aux2, ERROR); if (answer == 1) { previous = millis(); answer = 0; counter = 0; do{ // Gets number of available bytes do{ aux = serialAvailable(_socket); //avoid millis overflow problem if( millis() < previous ) previous = millis(); }while((aux == 0) && ((millis()-previous) < 3000)); #if GPRS_debug_mode>0 USB.print(F("Available bytes: ")); USB.println(aux, DEC); #endif // Gets available bytes while (aux > 0){ if (counter < 0) { // Skips first 2 bytes (\r\n) serialRead(_socket); } else if(counter < BUFFER_SIZE) { buffer_GPRS[counter] = serialRead(_socket); } else { serialRead(_socket); } counter++; aux--; } buffer_GPRS[counter] = '\0'; // check if the buffer_GPRS contains "OK" if (strstr(buffer_GPRS, "OK") != NULL) { answer = 1; } //avoid millis overflow problem if( millis() < previous ) previous = millis(); }while((answer == 0) && ((millis()-previous) < 3000)); } else if (answer == 2) { return -2; } else { return -1; } buffer_GPRS[counter - 4] = '\0'; if (parse == 1) { #if GPRS_debug_mode>0 USB.println(buffer_GPRS); #endif GPS_status = atoi(strtok(buffer_GPRS, ",")); // Gets fix status fix_status = atoi(strtok(NULL, ",")); // Gets fix status strcpy(aux_str,strtok(NULL, ",")); // Gets date and time memset(date, '\0', sizeof(date)); strncpy(date, aux_str, 8); memset(UTC_time, '\0', sizeof(UTC_time)); strncpy(UTC_time, aux_str+ 8, 6); latitude = atof(strtok(NULL, ",")); // Gets latitude longitude = atof(strtok(NULL, ",")); // Gets longitude altitude = atof(strtok(NULL, ",")); // Gets altitude speedOG = atof(strtok(NULL, ",")); // Gets speed over ground. Unit is knots. courseOG = atof(strtok(NULL, ",")); // Gets course mode = atoi(strtok(NULL, ",")); // Gets mode HDOP = atof(strtok(NULL, ",")); // Gets HDOP PDOP = atof(strtok(NULL, ",")); // Gets PDOP VDOP = atof(strtok(NULL, ",")); // Gets VDOP sats_in_view = atoi(strtok(NULL, ",")); // Gets sats_in_view sats_in_use = atoi(strtok(NULL, ",")); // Gets sats_in_use SNR = atoi(strtok(NULL, ",")); // Gets SNR #if GPRS_debug_mode>0 USB.print(F("GPS_status: ")); USB.println(GPS_status, DEC); USB.print(F("fix_status: ")); USB.println(fix_status, DEC); USB.print(F("Latitude (in degrees): ")); USB.println(latitude); USB.print(F("Longitude (in degrees): ")); USB.println(longitude); USB.print(F("Date: ")); USB.print(date); USB.print(F(" UTC_time: ")); USB.println(UTC_time); USB.print(F("Altitude: ")); USB.println(altitude); USB.print(F("SpeedOG: ")); USB.println(speedOG); USB.print(F("Course: ")); USB.println(courseOG); USB.print(F("Satellites in view: ")); USB.println(sats_in_view, DEC); USB.print(F("Satellites in use: ")); USB.println(sats_in_use, DEC); USB.print(F("Mode: ")); USB.println(mode,DEC); USB.print(F("SNR: ")); USB.println(SNR,DEC); USB.print("PDOP: "); USB.println(PDOP); USB.print("HDOP: "); USB.println(HDOP); USB.print("VDOP: "); USB.println(VDOP); #endif } return 1; }