char* getstr(char* buff) { int i = 0; int j = 0; //serialFlush(fd); while(!serialDataAvail(fd) && i<1000) { i++; delay(10); } if (i== 1000) { printf("sem dados no serial\n"); buff = "erro"; return(buff); } while(serialDataAvail(fd)>0) { delay(10); buff[j] = serialGetchar(fd); j++; } buff[j] = 0; printf("%s \n", buff); //debug return(buff); }
int drcSetup (const int pinBase, const int numPins, const char *device) { int fd ; int ok, tries ; time_t then ; struct wiringPiNodeStruct *node ; if ((fd = serialOpen (device, 115200)) < 0) return wiringPiFailure (WPI_ALMOST, "Unable to open DRC device (%s): %s", device, strerror (errno)) ; delay (10) ; // May need longer if it's an Uno that reboots on the open... // Flush any pending input while (serialDataAvail (fd)) (void)serialGetchar (fd) ; ok = FALSE ; for (tries = 1 ; tries < 5 ; ++tries) { serialPutchar (fd, '@') ; then = time (NULL) + 2 ; while (time (NULL) < then) if (serialDataAvail (fd)) { if (serialGetchar (fd) == '@') { ok = TRUE ; break ; } } if (ok) break ; } if (!ok) { serialClose (fd) ; return wiringPiFailure (WPI_FATAL, "Unable to communidate with DRC device") ; } node = wiringPiNewNode (pinBase, numPins) ; node->fd = fd ; node->pinMode = myPinMode ; node->pullUpDnControl = myPullUpDnControl ; node->analogRead = myAnalogRead ; node->digitalRead = myDigitalRead ; node->digitalWrite = myDigitalWrite ; node->pwmWrite = myPwmWrite ; return 0 ; }
int main() { int fdControlCount; int* fdControls; int ret; int avail; int len; printf("HELLO WORLD\n"); int play_ok = 0; int i; if(la_init_controls(&fdControls, &fdControlCount)) { fprintf(stderr, "E: init controls\n"); return -1; } if(la_init_ecran()) { la_lcdHome(); la_lcdPutChar('S'); la_lcdPutChar('A'); } while(1) { avail = serialDataAvail(fdsArduino[0]); if(avail > 0) { la_control_input_one(fdsArduino[0]); } avail = serialDataAvail(0); while(avail > 0) { fprintf(stdout, "GOT %i\n", avail); len = getline(&buf, &buf_len, stdin); if(len>0) { fprintf(stdout, "%s",buf); } serialPuts(fdsArduino[0], buf); avail-=len; } usleep(5000); } return 0; }
/******************************************************************** * 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 } }
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"; }
int main () { int fd,i=0; fd= serialOpen("/dev/ttyAMA0",115200); if(fd < 0) { printf("Opening serial failed.\n"); return 0; } while(i<10) { delay(500); serialPutchar(fd,i); i++; //printf("serialDataAvail: %d\n", serialDataAvail(fd)); if(serialDataAvail(fd) >= 1) { printf ("->%d\n", serialGetchar(fd)); fflush (stdout); } } printf("Serial port closing.\n"); serialClose(fd); return 0; }
int main () { printf("Program started.\n"); int ser_handle; // the serial connection (file descriptor) if ((ser_handle = serialOpen("/dev/ttyAMA0", BAUD_RATE)) < 0) { fprintf(stderr, "Unable to open serial device: %s\n", strerror(errno)); return 1 ; } else printf("Serial open\n"); int counter = 0; int avail_bytes; for(;;) { if(avail_bytes = serialDataAvail(ser_handle)) { serialPutchar(ser_handle,serialGetchar(ser_handle)); counter = counter + 1; if(counter%100 == 0) { printf("Byte %i has been passed on\n", counter); } } } }
static ERL_NIF_TERM serial_data_avail_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); } int data_avail = serialDataAvail(handle); return enif_make_int(env, data_avail); }
int serial_bytes_available(int serial_id) { //TODO verific sau las sa dea segfault? struct serial_bus *sb = serial_buses[serial_id]; if(!sb) return -1; if(sb->fd < 0) { sb->fd = serialOpen(sb->bus, sb->speed); } return serialDataAvail(sb->fd); }
/* * Return recieved string from serial line. Function returns number of characters recieved. ****************************************************************************** */ int serialReceive(char * response, int serialLine ){ int i = 0; delay(300); while ( serialDataAvail (serialLine) > 0 ) { response[i] = serialGetchar (serialLine) ; i++; } response[i] = 0; return i; }
void serialthread::run() { buffer.clear(); while(app_exit == false) { if ( device_id > 0 ) { //std::cout<< "read"<<std::endl; if ( serialDataAvail(device_id) != 0) { //std::cout<<"check"<<std::endl; countert1 = 0; int a = serialGetchar(device_id); char lc = (char)a; if (lc != '\n' ) { buffer.push_back(lc); } else { //process buffer process(); } } else { countert1++; if (countert1 > 50 && buffer.size() != 0) { countert1 = 0; //process buffer process(); } if ( countert1 > 55 ) { countert1 = 0; } } } msleep(1); } }
bool SerialComm::ReadRAW() { // printf("%s\n", __FUNCTION__); bool bReturn = false; sBuffer bufferIn; //= &VariablesIn.Buffer; unsigned char CRC = 0; int j=0; while (serialDataAvail(fd)) { int ch = serialGetchar(fd); // printf("%d:%X ", j, ch); bufferIn.u8[j++] = (unsigned char) ch; //CRC ^= (unsigned char) ch; } // printf("\n"); for (int i=0; i<(j-1); i++) { CRC ^= bufferIn.u8[i]; } // printf("%s::Red %d bytes\n", __FUNCTION__, j); if ((bufferIn.u8[j-1]==CRC)&&(143==j)) { bufferIn.len = j; for (int i=0; i<j; i++) { VariablesIn.Buffer.u8[i] = bufferIn.u8[i]; } for (int i=0; i<7; i++) { // printf("%d:%d ", i, VariablesIn.Names.Digital[i]); } for (int i=0; i<54; i++) { // printf("%d:%d ", i, VariablesIn.Names.Analog[i]); } // printf("\n"); VariablesIn.Buffer.len = bufferIn.len; bReturn = true; // printf("%s::CRC %d\n", __FUNCTION__, CRC); printf("%s::Temp: %d\t%d\t%d\t%d\t%d\t%d\n", __FUNCTION__, VariablesIn.Names.Analog[41], VariablesIn.Names.Analog[42], VariablesIn.Names.Analog[43], VariablesIn.Names.Analog[44], VariablesIn.Names.Analog[45], VariablesIn.Names.Analog[46]); printf("%s::Analog: %d\t%d\t%d\t%d\t%d\t%d\n", __FUNCTION__, VariablesIn.Names.Analog[9], VariablesIn.Names.Analog[12], VariablesIn.Names.Analog[29], VariablesIn.Names.Analog[28], VariablesIn.Names.Analog[34], VariablesIn.Names.Analog[37]); } return bReturn; }
void loop(){ // Pong every 3 seconds if(millis()-time>=3000){ serialPuts (fd, "Pong!\n"); // you can also write data from 0-255 // 65 is in ASCII 'A' serialPutchar (fd, 65); time=millis(); } // read signal if(serialDataAvail (fd)){ char newChar = serialGetchar (fd); printf("%c", newChar); fflush(stdout); } }
int main () { int fd ; int count ; unsigned int nextTime ; if ((fd = serialOpen ("/dev/ttyAMA0", 115200)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } if (wiringPiSetup () == -1) { fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ; return 1 ; } nextTime = millis () + 300 ; for (count = 0 ; count < 256 ; ) { if (millis () > nextTime) { printf ("\nOut: %3d: ", count) ; fflush (stdout) ; serialPutchar (fd, count) ; nextTime += 300 ; ++count ; } delay (3) ; while (serialDataAvail (fd)) { printf (" -> %3d", serialGetchar (fd)) ; fflush (stdout) ; } } printf ("\n") ; return 0 ; }
char *readRFID(){ int data; int i; int number; char *rfid_number = (char *) malloc(25 * sizeof(char)); char read = '0'; init(); while(read == '0'){ number = 0; data=serialDataAvail(handle); if(data > 0){ for(i=1;i<=data;i++){ number += snprintf(rfid_number+number,15-number,"%03d",serialGetchar(handle)); } read = '1'; } } printf("%s\n\r",rfid_number); return rfid_number; }
int initUart() { int i = 0; fd = serialOpen("/dev/ttyACM0",9600); if(fd < 0){return 1;} delay(1000); serialPutchar(fd,'t'); delay(1000); while(extension == " "){ while(serialDataAvail(fd) >= 1) { extensionID[i] = serialGetchar(fd); if(i == 10){ break; } i++; } extension = extensionID; } for(i=0;i<10;i++){printf("%c",extensionID[i]);} printf("\n%s \n",extension); return 0; }
int setup_ctl_ctl(const char *table){ // Pong every 3 seconds if(millis()-t >= 5000){ // you can also write data from 0-255 command_ctl("rd!"); //command("vo!"); // command("vc!"); t=millis(); } // read signal /*if(serialDataAvail(fd)){ char newChar = serialGetchar(fd); printf("%c", newChar); fflush(stdout); }*/ if(serialDataAvail(fd)){ char c = serialGetchar(fd); //printf("XX: %c\n", c); if(c == '#') { str_to_struct(str, table); i = 1; count_raute++; pthread_cond_signal(¬ready); pthread_mutex_unlock(&lock); }else{ str[i] = c; i++; } fflush(stdout); } return count_raute; }
int main (){ int fd,i,Flag,FirstBuf,t; int Num_Avail; char buffer[80]; unsigned int TimeNow,TimeStart; unsigned char counter; int all_count=0; unsigned char ucStra[6],ucStrw[6],ucStrAngle[6]; float Value[3]; if ((fd = serialOpen ("/dev/ttyAMA0", 115200)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } softPwmCreate(7,0,20); TimeStart = millis(); for(;;) { if (Flag == 0) { Flag = 1; while(1) { FirstBuf = serialGetchar(fd); if(FirstBuf == 0x55) { for(t = 0;t < 10;t++) { FirstBuf = serialGetchar(fd); } break; } } } serialFlush(fd); delay(10); Num_Avail = serialDataAvail (fd); read(fd,buffer,Num_Avail); for(counter;counter < strlen(buffer) - 7;counter++) { if(buffer[counter]==0x55) { switch(buffer [counter + 1]) { case 0x51: ucStra[0]=buffer[counter + 2]; ucStra[1]=buffer[counter + 3]; ucStra[2]=buffer[counter + 4]; ucStra[3]=buffer[counter + 5]; ucStra[4]=buffer[counter + 6]; ucStra[5]=buffer[counter + 7]; break; case 0x52: ucStrw[0]=buffer[counter + 2]; ucStrw[1]=buffer[counter + 3]; ucStrw[2]=buffer[counter + 4]; ucStrw[3]=buffer[counter + 5]; ucStrw[4]=buffer[counter + 6]; ucStrw[5]=buffer[counter + 7]; break; case 0x53: ucStrAngle[0]=buffer[counter + 2]; ucStrAngle[1]=buffer[counter + 3]; ucStrAngle[2]=buffer[counter + 4]; ucStrAngle[3]=buffer[counter + 5]; ucStrAngle[4]=buffer[counter + 6]; ucStrAngle[5]=buffer[counter + 7]; TimeNow = millis(); Value[0] = ((short)(ucStra[1]<<8| ucStra[0]))/32768.0*16; Value[1] = ((short)(ucStra[3]<<8| ucStra[2]))/32768.0*16; Value[2] = ((short)(ucStra[5]<<8| ucStra[4]))/32768.0*16; system("clear"); printf("Num_Avail; %d",Num_Avail); printf("a:%.3f %.3f %.3f ",Value[0],Value[1],Value[2]); Value[0] = ((short)(ucStrw[1]<<8| ucStrw[0]))/32768.0*2000; Value[1] = ((short)(ucStrw[3]<<8| ucStrw[2]))/32768.0*2000; Value[2] = ((short)(ucStrw[5]<<8| ucStrw[4]))/32768.0*2000; printf("w:%.3f %.3f %.3f \n",Value[0],Value[1],Value[2]); Value[0] = ((short)(ucStrAngle[1]<<8| ucStrAngle[0]))/32768.0*180; Value[1] = ((short)(ucStrAngle[3]<<8| ucStrAngle[2]))/32768.0*180; Value[2] = ((short)(ucStrAngle[5]<<8| ucStrAngle[4]))/32768.0*180; printf("A:%.2f %.2f %.2f\r\n",Value[0],Value[1],Value[2]); all_count++; printf("count: %d time: %d\n",all_count,TimeNow - TimeStart); break; } } } } }
int main () { if ((fd = serialOpen ("/dev/ttyAMA0", 38400)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } if (wiringPiSetup () == -1) { fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ; return 1 ; } int file = open("test.jpg",O_RDWR | O_CREAT,0644); printf ("\nTesting Camera"); fflush (stdout); delay (3) ; char h; printf("Press ENTER to continue\n"); scanf("%c",&h); //Waiting for camera data which is ignored while (serialDataAvail (fd)) { serialGetchar(fd); } delay (100) ; int check; char t; printf ("Starting to capture \n"); fflush (stdout); delay(100); check = start_capturing(); if(check == -1) { printf("Error with take picture command\n"); return 1; } delay(100); printf("\nSending read data command\n"); char *data = malloc(sizeof(char)*32); int l = 0; for(l=0;l<32;l++) data[l] = 0; int End = 0; int b = 1; while(!End) { delay(200); read_data(); int j = 0; int k = 0; count = 0; delay(100); while (serialDataAvail (fd)) { printf("In\n"); k++; t = serialGetchar(fd); //Ignoring the response if((k>5) && (j<32) && (!End)) { data[j] = t; //Checking for the end of image if((data[j-1] == 0xFF) && (data[j] == 0xD9)) End = 1; j++; count++; } } //Writing the image to the output file write(file,(void *)data,32); b++; } close(file); return 0 ; }
struct packet getpkt( void ) { int i = 0; int j = 0; int z; char buff[193]; struct packet ret; //serialFlush(fd); for (z=0; z<3; z++) { while(!serialDataAvail(fd) && i<1000) { i++; delay(10); } if (i== 1000) { printf("sem dados no serial\n"); ret.ids[0] = '\0'; ret.idr[0] = '\0'; strcpy(ret.data,"erro"); ret.cs = '\0'; return(ret); } while(serialDataAvail(fd)>0) { delay(10); buff[j] = serialGetchar(fd); j++; } buff[j] = '\0'; printf("%s \n", buff); //debug if (j<23) { ret = errorpkt; strcpy(ret.data,buff); return(ret); } strncpy(ret.ids,buff,12); ret.ids[12] = '\0'; strncpy(ret.idr,buff+12,12); ret.idr[12] = '\0'; strncpy(ret.data,buff+24,(j-25)); ret.data[j-25] = '\0'; ret.cs = buff[j-1]; if (strcmp(ret.data,"CSOK") == 0) return(ret); //excecao para impedir um loop infinito de confirmacao if (strcmp(ret.data,"CSFAIL") == 0) return(ret); //excecao para impedir um loop infinito de confirmacao if (ret.cs == checksum(ret.data)) { send(ret.ids,"CSOK"); return(ret); } } return(errorpkt); }
int main(void){ int pin,gotOne,fd,x,i=0; int myCounter[4]; char data[5]; wiringPiSetup(); //GPIO pin setup pinMode(motor1,OUTPUT); //set pin 0 to control motor1 pinMode(motor2,OUTPUT); //set pin 1 to control motor2 pinMode(motor3,OUTPUT); //set pin 2 to control motor3 pinMode(motor4,OUTPUT); //set pin 3 to control motor4 //setup flowMeter pins to be ISR wiringPiISR(flowMeter1,INT_EDGE_FALLING, &myInterrupt0); wiringPiISR(flowMeter2,INT_EDGE_FALLING, &myInterrupt1); wiringPiISR(flowMeter3,INT_EDGE_FALLING, &myInterrupt2); wiringPiISR(flowMeter4,INT_EDGE_FALLING, &myInterrupt3); //reset all counters to 0 for(pin=0; pin < 4; pin++){ globalCounter[pin] = myCounter [pin] = 0; } printf("Start Bluetooth Communication\n"); fd=serialOpen("/dev/ttyAMA0",9600); //Open serial port and set baud=9600 //Wait for Interrupts to be triggered on specified pins //gotOne only allows "Waiting..." to be placed before //each trigger of the ISR....So not really needed. //Counter also resets for each pin after 11 counts for(;;){ gotOne=0; printf("Waiting...");fflush(stdout); for(;;){ for(pin=0 ;pin < 4; pin++){ if(globalCounter[pin] != myCounter[pin]){ printf("Int on pin %d: Counter:%5d\n",pin,globalCounter[pin]); myCounter[pin] = globalCounter[pin]; ++gotOne; if(myCounter[pin]>10){ myCounter[pin]=globalCounter[pin]=0; } } } if(gotOne != 0){ break; } while(serialDataAvail(fd)){ data[i++]=(char)serialGetchar(fd); if(strcmp(data,"on")==0){ digitalWrite(motor1,HIGH); printf("-> %s\n",data); fflush(stdout); for(x=0;x<i;x++){ data[x]=0; } i=0; } else if(strcmp(data,"off")==0){ digitalWrite(motor1,LOW); printf("-> %s\n",data); fflush(stdout); for(x=0;x<i;x++){ data[x]=0; } i=0; } } } } return 0; }
//============================================================================== // MAIN //============================================================================== int main(int argc,char **argv) { pthread_t test; printf("SFemtoZ!\n"); int c; while ((c = getopt (argc, argv, "t:v")) != -1) switch (c) { case 't': if(pthread_create(&test,NULL,thread_test,optarg)) { printf("error thread test\n"); } break; case 'v': verbose=TRUE; break; } char sfzfile[50]; strcpy(sfzfile,USBPATH); strcat(sfzfile,argv[optind]); printf("Load SFZ: %s\n",sfzfile); loadsfz(sfzfile); //printsfz(); loadsounds(); int fd; if(( fd = serialOpen("/dev/ttyAMA0",57600))<0) { printf("serialOpen ERROR:\n",strerror(errno)); return 1; } if(configuresoundio()!=0) return 1; signal(SIGINT,exit_cli); signal(SIGTERM,exit_cli); run = TRUE; while(run) { if(serialDataAvail(fd)>2) { int type=serialGetchar(fd); while(type!=0x99 && type!= 0xB9) type=serialGetchar(fd); int note=serialGetchar(fd); int vel=serialGetchar(fd); //printf("MIDI%i(%i,%i)\n",type,note,vel); if(type==0x99) noteOn(note,vel); else midiCC(note,vel); } // soundio_wait_events(soundio); } //FINISH pthread_cancel(test); soundio_outstream_destroy(outstream); soundio_device_unref(device); soundio_destroy(soundio); serialClose(fd); freesounds(); freesfz(); return 0; }
int Serial::GetChar (){ if(serialDataAvail(this->fd) > 0){ return serialGetchar(this->fd); } }
int Serial::DataAvail (){ if(serialDataAvail(this->fd) > 0){ return serialDataAvail(this->fd); } }
int main () { int fd ; int count ; unsigned int nextTime ; struct termios options; if (wiringPiSetup () == -1) { fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ; return 1 ; } if ((fd = serialOpen ("/dev/ttyAMA0", 9600)) < 0) { fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ; return 1 ; } tcgetattr(fd, &options); options.c_cflag |= PARENB; options.c_cflag &= ~PARODD; options.c_cflag |= CSTOPB; //options.c_cflag |= PARENB; //options.c_cflag &= ~PARODD; options.c_cflag &= ~CSIZE; options.c_cflag |= CS7; tcsetattr(fd, TCSANOW, &options); //tcsetattr(fd, &options); for (;;) { unsigned char aaa[50]; memset(aaa, 0, sizeof(char)*50); aaa[0] = 0x40; aaa[1] = 0x31; aaa[2] = 0x31; aaa[3] = 0x52; aaa[4] = 0x44; aaa[5] = 0x34; aaa[6] = 0x39; aaa[7] = 0x30; aaa[8] = 0x30; aaa[9] = 0x30; aaa[10] = 0x30; aaa[11] = 0x30; aaa[12] = 0x34; aaa[13] = 0x35; aaa[14] = 0x66; aaa[15] = 0x2a; aaa[16] = 0x0d; aaa[17] = 0x0a; int forCount = 0; for(forCount = 0; forCount < 18; ++forCount) { serialPutchar(fd, aaa[forCount]); printf("%x ", aaa[forCount]); } printf("\n"); sleep(1); while(serialDataAvail(fd)) { char xxx2 = serialGetchar(fd); printf ("%02c", xxx2); } printf("\n"); sleep(1); } return 0 ; }
/* * Class: com_pi4j_wiringpi_Serial * Method: serialDataAvail * Signature: (I)I */ JNIEXPORT jint JNICALL Java_com_pi4j_wiringpi_Serial_serialDataAvail (JNIEnv *env, jobject obj, jint fd) { return serialDataAvail(fd); }
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"); } }
void getDataDevice(){ if(extensionID[0] == 'T' && extensionID[1] == 'M' && extensionID[2] == '4' && extensionID[3] == 'C') { for(requestPin = 0; requestPin < 12; requestPin++) { switch(requestPin) { case 0: serialPuts(fd,"B"); dataTM4[requestPin][0]='B'; serialPuts(fd,"4"); dataTM4[requestPin][1]='4'; break; case 1: serialPuts(fd,"B"); dataTM4[requestPin][0]='B'; serialPuts(fd,"5"); dataTM4[requestPin][1]='5'; break; case 2: serialPuts(fd,"D"); dataTM4[requestPin][0]='D'; serialPuts(fd,"0"); dataTM4[requestPin][1]='0'; break; case 3: serialPuts(fd,"D"); dataTM4[requestPin][0]='D'; serialPuts(fd,"1"); dataTM4[requestPin][1]='1'; break; case 4: serialPuts(fd,"D"); dataTM4[requestPin][0]='D'; serialPuts(fd,"2"); dataTM4[requestPin][1]='2'; break; case 5: serialPuts(fd,"D"); dataTM4[requestPin][0]='D'; serialPuts(fd,"3"); dataTM4[requestPin][1]='3'; break; case 6: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"0"); dataTM4[requestPin][1]='0'; break; case 7: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"1"); dataTM4[requestPin][1]='1'; break; case 8: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"2"); dataTM4[requestPin][1]='2'; break; case 9: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"3"); dataTM4[requestPin][1]='3'; break; case 10: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"4"); dataTM4[requestPin][1]='4'; break; case 11: serialPuts(fd,"E"); dataTM4[requestPin][0]='E'; serialPuts(fd,"5"); dataTM4[requestPin][1]='5'; break; } int j; for(j = 2; j < 5; j++) { dataTM4[requestPin][j] = serialGetchar(fd); } } printf("collection complete \n"); } else if(extensionID[0] == 'T' && extensionID[1] == 'M' && extensionID[2] == '4' && extensionID[3] == 'e') { int i=0; int j=0; serialPuts(fd,"T"); delay(1000); while(serialDataAvail(fd) >= 1) { dataTM4eReceived[i] = serialGetchar(fd); i++; if(i == 256) { break; } } printf("deviceData:%s\n",dataTM4eReceived); for(i = 0; i < 50; i++) { if(dataTM4eReceived[i+2] == 'H') { break; printf("found H\n"); } else { dataTM4eTemp[i] = dataTM4eReceived[i+2]; } } printf("Temperature: %s test\n",dataTM4eTemp); i = i+2; for(j=0;i<50;i++) { if(dataTM4eReceived[i+2] == '/') { break; printf("found / \n"); } else { dataTM4eHum[j] = dataTM4eReceived[i+2]; j++; } } printf("Humidity: %s\n",dataTM4eHum); } else { int i = 0; while(serialDataAvail(fd) >= 1) { data[i] = serialGetchar(fd); i++; } } }
bool CProtocol::read(void){ // reset fully read data mErrorLevel=0; mCommand=0; mAddress=0; mData=0; // only read if there is a filedescriptor/pointer to write to // and only if there is new input and get this input #ifdef RaspberryPi while(mSerial>=0 && serialDataAvail (mSerial)){ uint8_t input = serialGetchar (mSerial); #else //Arduino if(mSerial==NULL) { mErrorLevel=PROTOCOL_ERR_READ; return false; } // only reset pending data if the reading stream changes if(mSerial!=mPrevSerial){ mPrevSerial=mSerial; mBlocks = 0; mWorkData = 0; } while(mSerial->available()){ uint8_t input = mSerial->read(); #endif // check the lead/end/data indicator switch(input&0xC0){ //lead 11 case(0xC0): { // we were still reading! Log an error if(mBlocks!=0) ++mErrorLevel |= PROTOCOL_ERR_LEAD; // read block length or command indicator mBlocks = (input&0x38)>>3; switch(mBlocks){ // save 4 bit command case 0: case 1: mCommand=(input & 0x0F)+1; mBlocks = 0; return true; break; // save block length + first 3 data bits case 7: mWorkData = input & 0x0F; mBlocks -=2; break; default: mWorkData = input & 0x07; mBlocks--; break; } } break; //end 10 case(0x80): { if(mBlocks--==1){ // save data + address mAddress=(input&0x3F)+1; mData=mWorkData; return true; } else{ // log an error, not ready for an address byte, and reset data counters ++mErrorLevel |= PROTOCOL_ERR_DATA; mBlocks=0; } } break; //data 0x default: { if(mBlocks--<2){ // log an error, expecting an address or header byte ++mErrorLevel |= PROTOCOL_ERR_END; mBlocks=0; } else{ // get next 7 bits of data mWorkData<<=7; // dont need &0x7F because first bit is zero! mWorkData|=input; } } break; } // end switch // too many errors, stop reading if((mErrorLevel&PROTOCOL_ERR_MAX)==PROTOCOL_ERR_MAX) return false; } //no new input return false; } //================================================================================ //Send Command/Address //================================================================================ int8_t CProtocol::sendCommand(uint8_t command){ // Only write if there is a Stream/filedescriptor to write to // send lead mask 11 + length 00|0 or 00|1 including the last bit for the 4 bit command uint8_t b ={(0xC0 | ((command-1)&0x0F))}; #ifdef RaspberryPi if(mSerial<0) return-1; serialPutchar (mSerial, b); #else //Arduino if (mSerial==NULL) return-1; mSerial->write(b); #endif return 1; }
void * SerialFunction(void *argument) { #ifdef LogMode Log(s, __func__, __LINE__, "Serial Function entry\n"); #endif int fd; char temp_output[RS232_Length]; int string_count = 0; int getString = 0; int readyToStart = 0; if((fd = serialOpen("/dev/ttyAMA0", 19200)) < 0) { printf("Unable to open serial device: %s\n", strerror(errno)); pthread_exit((void*)"fail"); } while(SerialThreadFlag) { while(serialDataAvail(fd)) { char temp_char_1; temp_char_1 = serialGetchar(fd); //printf("%x ", temp_char_1); //if(temp_char_1 == 0x7D) printf("\n"); if (temp_char_1 == 0x7D && getString == 0 && readyToStart == 1) { //count plus one and memset Count[Total]++; memset(temp_output, 0, sizeof(char)*RS232_Length); string_count = 0; } else if (temp_char_1 == 0x7B) { //default memset(temp_output,0, sizeof(char)*RS232_Length); getString = 1; Count[Total]++; temp_output[string_count] = temp_char_1; string_count++; readyToStart = 1; } else if(temp_char_1 == 0x7D && getString == 1) { //package if(string_count == 48) { pthread_mutex_lock(&mutex_2); memset(output, 0, sizeof(char)*RS232_Length); /*int vers_test_count = 0; for(vers_test_count = 0; vers_test_count < string_count; vers_test_count++) { output[vers_test_count] = temp_output[vers_test_count]; }*/ memcpy(output, temp_output, string_count); updateFlag = 1; pthread_mutex_unlock(&mutex_2); } memset(temp_output, 0, sizeof(char)*RS232_Length); string_count = 0; getString = 0; } else if( getString == 1 && string_count < 48) { temp_output[string_count] = temp_char_1; string_count++; } else; fflush (stdout) ; } } if(fd >= 0) { serialClose(fd); } #ifdef LogMode Log(s, __func__, __LINE__, "Serial Function exit\n"); #endif }