int main (void) { int pin, button ; printf ("Banana Pro wiringPi + LNDigital test program\n") ; printf ("===========================================\n") ; printf ("\n") ; printf ( "This program reads the buttons and uses them to toggle the first 4\n" "outputs. Push a button once to turn an output on, and push it again to\n" "turn it off again.\n\n") ; // Always initialise wiringPi. Use wiringPiSys() if you don't need // (or want) to run as root wiringPiSetupSys () ; piFaceSetup (LN_DIGITAL_BASE) ; // Enable internal pull-ups & start with all off for (pin = 0 ; pin < 8 ; ++pin) { pullUpDnControl (LN_DIGITAL_BASE + pin, PUD_UP) ; digitalWrite (LN_DIGITAL_BASE + pin, 0) ; } // Loop, scanning the buttons for (;;) { for (button = 0 ; button < 4 ; ++button) scanButton (button) ; delay (5) ; } return 0 ; }
// _____________________________________________________________________ void CRaspiGPIO::setPinModeInput(unsigned int gpio_num, unsigned int pullup_down) { pinMode(gpio_num, INPUT); pullUpDnControl(gpio_num, pullup_down); QString txt; QString tooltip; if (pullup_down == PUD_UP) { txt+="Iu"; tooltip = "Input with pull UP"; } else if (pullup_down == PUD_DOWN) { txt+="Id"; tooltip = "Input with pull DOWN"; } else { txt+="I"; tooltip = "Digital Input"; } QLabel *lbl = m_ihm.findChild<QLabel*>(PREFIX_MODE_GPIO + QString::number(gpio_num)); if (lbl) { lbl->setText(txt); lbl->setToolTip(tooltip); lbl->setEnabled(true); } QLabel *lbl_name = m_ihm.findChild<QLabel*>(PREFIX_GPIO_NAME + QString::number(gpio_num)); if (lbl_name) { lbl_name->setEnabled(true); } // On ne peut pas forcer l'état sur une entrée QCheckBox *checkbox = m_ihm.findChild<QCheckBox*>(PREFIX_CHECKBOX_WRITE + QString::number(gpio_num)); if (checkbox) { checkbox->setEnabled(false); } m_raspi_pins_config[gpio_num] = tRaspiPinConfig { INPUT, pullup_down, 0}; readPin(gpio_num); }
int main (void) { int pin, button ; printf ("Raspberry Pi wiringPiFace test program\n") ; printf ("======================================\n") ; if (piFaceSetup (200) == -1) exit (1) ; // Enable internal pull-ups for (pin = PIFACE_BASE ; pin < (PIFACE_BASE + 8) ; ++pin) pullUpDnControl (pin, PUD_UP) ; for (;;) { for (button = 0 ; button < 4 ; ++button) scanButton (button) ; delay (1) ; } return 0 ; }
int main (void) { if ((i2c = open(i2c_filename, O_RDWR)) < 0) { perror("Failed to open the i2c bus"); return 1; } if (ioctl(i2c, I2C_SLAVE, I2C_SLAVE_ADDR) < 0) { perror("Failed to acquire bus access and/or talk to slave.\n"); return 1; } // Setup interrupt handler wiringPiSetup(); pinMode(INTERRUPT_PIN, INPUT); pullUpDnControl (INTERRUPT_PIN, PUD_UP); wiringPiISR(INTERRUPT_PIN, INT_EDGE_FALLING, interrupt_handler); while(1) sleep(100000); // Will never happen... return 0; }
int Setup_IO(int Mute_Pin, int Dbg){ if (Dbg) printf("GPIO Initialisation\n"); // setup GPIO if (wiringPiSetup() == -1){ printf ("Unable to setup wiringPi: %s\n", strerror (errno)); return -1; } if (Dbg) printf("GPIO Initialised, Setting Pullup. Pin is %i\n", Mute_Pin); // setup GPIO as input with pull-up // pull up is needed as button common is grounded pinMode (Mute_Pin, INPUT); pullUpDnControl (Mute_Pin, PUD_UP); if (Dbg) printf("Setting GPIO Interrupt\n"); if(wiringPiISR (Mute_Pin, INT_EDGE_FALLING, &switchInterrupt) < 0){ printf ("Unable to setup interrupt: %s\n", strerror (errno)); return -2; } }
int main(void) { if(wiringPiSetup() == -1){ //when initialize wiringPi failed, print messa ge to screen printf("setup wiringPi failed !\n"); return -1; } pinMode(LedPin, OUTPUT); pinMode(TiltPin, INPUT); pullUpDnControl(TiltPin, PUD_UP); while(1){ if(digitalRead(TiltPin) == 0){ digitalWrite(LedPin, LOW); //led on printf("led on...\n"); }else{ digitalWrite(LedPin, HIGH); //led off printf("...led off\n"); } } return 0; }
int main (void) { wiringPiSetupGpio (); pinMode (greenPin, OUTPUT); pinMode (redPin, OUTPUT); pinMode (keyPin, INPUT); pinMode (bigredPin, OUTPUT); pinMode (pushPin, INPUT); pullUpDnControl (keyPin, PUD_UP); pullUpDnControl (pushPin, PUD_UP); pwmWrite (redPin, 255); pwmWrite (bigredPin, 255); pwmWrite (greenPin, 255); digitalWrite (bigredPin, LOW); while (1) { if (status == 5) { digitalWrite (bigredPin, HIGH); delay (150); digitalWrite (bigredPin, HIGH); delay (150); } if (status == 3) { digitalWrite (bigredPin, HIGH); } else { digitalWrite (bigredPin, LOW); } if (status == 4) { digitalWrite (greenPin, HIGH); } else { digitalWrite (greenPin, LOW); } if (digitalRead (pushPin)) { // push button is released } else { if (status == 3) { status = 4; digitalWrite (bigredPin, LOW); pid_t pid = fork (); if (pid == -1) { // error, no child created } else if (pid == 0) { execl ("/usr/bin/python", "/usr/bin/python", "/usr/local/bin/udns.py", NULL); } else { // parent int statval; if (waitpid (pid, &statval, 0) == -1) { // handle error } else { printf ("%i\n", WEXITSTATUS (statval)); if (WEXITSTATUS (statval) == 1) { printf ("success\n"); status = 4; } else { printf ("failure\n"); status = 5; } } } } } if (digitalRead (keyPin)) { digitalWrite (redPin, HIGH); delay (75); digitalWrite (redPin, LOW); delay (75); digitalWrite (redPin, LOW); status = 1; } else { digitalWrite (redPin, HIGH); if (status < 3) { if (is_change_needed () == 1) { status = 3; } else { status = 5; } } } } return 0; }
int main (int argc, char **argv) { if ( argc != 2 ) /* argc should be 2 for correct execution */ { /* We print argv[0] assuming it is the program name */ printf( "usage: %s <degrees to move>\n", argv[0] ); return 1; } /* take from: https://www.securecoding.cert.org/confluence/display/seccode/INT06-C.+Use+strtol()+or+a+related+function+to+convert+a+string+token+to+an+integer */ const char* const c_str = argv[1]; char *end; int degrees; errno = 0; const long sl = strtol(c_str, &end, 10); if (end == c_str) { fprintf(stderr, "%s: not a decimal number\n", c_str); return 1; } else if ('\0' != *end) { fprintf(stderr, "%s: extra characters at end of input: %s\n", c_str, end); return 1; } else if ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno) { fprintf(stderr, "%s out of range of type long\n", c_str); return 1; } else if (sl > INT_MAX) { fprintf(stderr, "%ld greater than INT_MAX\n", sl); return 1; } else if (sl < INT_MIN) { fprintf(stderr, "%ld less than INT_MIN\n", sl); return 1; } else { degrees = (int)sl; } buttonPressed = 0; wiringPiSetup () ; /* Setup the micro switch pin */ pinMode (SWITCH_PIN, INPUT); pullUpDnControl (SWITCH_PIN, PUD_DOWN); wiringPiISR (SWITCH_PIN, INT_EDGE_RISING, &buttonPressedInt) ; /* setup the motor output pins */ int pin; for (pin = 0 ; pin < 4 ; ++pin){ pinMode (pin, OUTPUT); digitalWrite (pin, 0); } while (!buttonPressed) moveMotor(1); moveMotor(degrees); return 0; }
/** * init and run the application */ int main(int argc, char *argv[]) { if(argc < 2) { printf("signalCount: usage: signalCounter [endpoint] (trigger_interval_ms)\n"); return 1; } // store endpoint strcpy(endPointUrl, argv[1]); printf("Using [%s] as endpoint URL\n", endPointUrl); // store trigger interval, if we have one if(argc == 3) { char* p; // will be set to the "first invalid character" set by strtol errno = 0; triggerInterval = strtol(argv[2], &p, 10); if (*p != '\0' || errno != 0) { fprintf(stderr, "invalid trigger interval [%s]\n", argv[2]); return 1; } } printf("Using [%d] for trigger interval\n", triggerInterval); // init the wiringPi library if (wiringPiSetup () < 0) { fprintf(stderr, "Unable to setup wiringPi: %s\n", strerror (errno)); return 1 ; } // set up an interrupt on our input pin if (wiringPiISR(PIN_INPUT, INT_EDGE_BOTH, &signalIsr) < 0) { fprintf(stderr, "Unable to setup ISR: %s\n", strerror (errno)); return 1 ; } // configure the output pin for output. Output output output pinMode(PIN_OUTPUT, OUTPUT); pinMode(PIN_INPUT, INPUT); // pull the internal logic gate down to 0v - we don't want it floating around pullUpDnControl(PIN_INPUT, PUD_DOWN); // blink 3 times - we're ready to go ledBlink(300); delay(300); ledBlink(300); delay(300); ledBlink(300); // send a test signal count with the current timestamp fileRecordSignalCount(getCurrentMilliseconds()); printf("signalCount started\n"); for(;;) { delay(1000); // this thread will submit any count files that have not been sent printf("about to run cleanup thread\n"); processCountFile(); } return 0; }
int main(void) { // variables char val = 0; float dist = 0; int xx = 0; struct timespec tim, tim2; // tim holds the desired sleep time, tim2 is filled with the remaining time if error occurs tim.tv_sec = 0; tim.tv_nsec = 500000000L; // 1/2 second sleep time // gpio initialization wiringPiSetup(); pinMode(0,OUTPUT); // stop sign signal digitalWrite(0,LOW); pinMode(7,OUTPUT); // vibration motor signal digitalWrite(0,LOW); pinMode(15,INPUT); // power switch pullUpDnControl(15, PUD_DOWN); // open default camera 0 VideoCapture capture(0); if(!capture.isOpened()) { // TODO need to send a message to pcb cout<<"ERROR: webcam problem\n"; return 1; } // read current status of power switch xx = digitalRead(15); // 3 1/2 second vibrations to indicate power on digitalWrite(7,HIGH); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,LOW); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,HIGH); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,LOW); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,HIGH); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,LOW); // play power on sound track over speaker system("omxplayer -o local /home/pi/capstone/gdr_rasp/audio/ready2.mp3"); // main loop while(1) { // check for shutdown command xx = digitalRead(15); if(xx == 0) { // 2 1/2 second vibrations to indicate power off digitalWrite(7,HIGH); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,LOW); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,HIGH); if(nanosleep(&tim,&tim2) == EXIT_FAILURE) return EXIT_FAILURE; digitalWrite(7,LOW); // play power down audio file system("omxplayer -o local /home/pi/capstone/gdr_rasp/audio/power_off.mp3"); // shutdown raspberry pi system("shutdown now"); } Mat frame; // holds a captured frame capture >> frame; // get a new frame from camera // process image Mat red = colorDetect(frame); Mat out = shapeDetect(red, &dist); // display processed image (testing only) XXX /* imshow("result", out); */ // print distance (testing only) XXX /* printf("%f\n",dist); */ // write pin high if within 6 ft of stop sign if(val <= 90 && val > 20) { digitalWrite(0,HIGH); } digitalWrite(0,LOW); dist = 0; // if any key is pressed exit (needed for displaying image) XXX /* if(waitKey(30) >= 0) break; */ } return 0; }
/* ------------------ Start Here ----------------------- */ int main(int argc, char *argv[]) { /* Logging */ setlogmask(LOG_UPTO(LOG_INFO)); openlog(DAEMON_NAME, LOG_CONS | LOG_PERROR, LOG_USER); syslog(LOG_INFO, "Daemon starting up"); /* This daemon can only run as root. So make sure that it is. */ if (geteuid() != 0) { syslog(LOG_ERR, "This daemon can only be run by root user, exiting"); exit(EXIT_FAILURE); } /* Make sure the file '/usr/bin/gpio' exists */ struct stat filestat; if (stat("/usr/bin/gpio", &filestat) == -1) { syslog(LOG_ERR, "The program '/usr/bin/gpio' is missing, exiting"); exit(EXIT_FAILURE); } /* Ensure only one copy */ /* Common user should be able to read the pid file so that they need not use 'sudo' with 'service buttonshutdownd-inv status' to read daemon status. The correct PID file permission should be: 1. Read & Write permission for owner 2. Read permission for group and others */ const int PIDFILE_PERMISSION = 0644; int pidFilehandle = open(PID_FILE, O_RDWR | O_CREAT, PIDFILE_PERMISSION); if (pidFilehandle == -1) { /* Couldn't open lock file */ syslog(LOG_ERR, "Could not open PID lock file %s, exiting", PID_FILE); exit(EXIT_FAILURE); } /* Try to lock file */ if (lockf(pidFilehandle, F_TLOCK, 0) == -1) { /* Couldn't get lock on lock file */ syslog(LOG_ERR, "Could not lock PID lock file %s, exiting", PID_FILE); exit(EXIT_FAILURE); } /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) exit(EXIT_FAILURE); /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) exit(EXIT_SUCCESS); /* Get and format PID */ char szPID[16]; sprintf(szPID, "%d\n", getpid()); // Call 'getpid()', don't use 'pid' variable /* write pid to lockfile */ write(pidFilehandle, szPID, strlen(szPID)); /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) /* Log the failure */ exit(EXIT_FAILURE); /* Change the current working directory */ if (chdir("/") < 0) /* Log the failure */ exit(EXIT_FAILURE); /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Daemon-specific initializations */ /* Add a process termination handler for handling daemon stop requests */ signal(SIGTERM, &Daemon_Stop); /* Initialize 'wiringPi' library */ if (wiringPiSetup() == -1) { syslog(LOG_ERR, "'wiringPi' library couldn't be initialized, exiting"); exit(EXIT_FAILURE); } /* Setup pin mode and interrupt handler */ pinMode(PIN, INPUT); pullUpDnControl(PIN, PUD_UP); sleep(2); if (wiringPiISR(PIN, INT_EDGE_FALLING, &Button_Pressed) == -1) { syslog(LOG_ERR, "Unable to set interrupt handler for specified pin, exiting"); exit(EXIT_FAILURE); } /* The Big Loop 1. When pressed for less than 2 secs, shutdown system 2. When pressed for 2 secs or more, restart system */ while (true) { /* Daemon hearbeat Just wait until there's an interrupt or system shutdown */ sleep(60); } }
int main(void) { //printf("InfiniteLooper--based on patest_record.c\n"); //fflush(stdout); //Record for a few seconds. data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; data.frameIndex = 0; numSamples = totalFrames * NUM_CHANNELS; numBytes = numSamples * sizeof(SAMPLE); // From now on, recordedSamples is initialised. // 5 minutes of record buffer allocated 5% of free // on rPi zero. could record 90 minutes on rPi 0 //++++++++++++++++++++++++++++++++++++++++++++++++++++ data.recordedSamples = (SAMPLE*) malloc( numBytes ); //++++++++++++++++++++++++++++++++++++++++++++++++++++ if( data.recordedSamples == NULL ) { //printf("Could not allocate record array.\n"); goto done; } else { //printf("allocated %d bytes\n", numBytes ); } ringbufferWPTR = 0; ringbufferRPTR = 0; all_complete = FALSE; // ****************************************** doState(S_INIT, data.recordedSamples); // ****************************************** // we do the recording set-up just once and cycle power // to do it again. This initialization should be moved to // ilooper_audio if multiple recordings are implemented err = Pa_Initialize(); if( err != paNoError ) goto done; // default input device inputParameters.device = Pa_GetDefaultInputDevice(); if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default input device.\n"); goto done; } inputParameters.channelCount = 2; //stereo input inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; //Record some audio. -------------------------------------------- err = Pa_OpenStream ( &stream, &inputParameters, NULL, // &outputParameters, SAMPLE_RATE, // ADC sample rate is a constant FRAMES_PER_BUFFER, //we won't output out of range samples so //don't bother clipping them //paClipOff, // ***wm6h for this app, let's clip paNoFlag, recordCallback, &data ); if( err != paNoError ) goto done; // the output sample rate is checked in playback() err = Pa_IsFormatSupported( &inputParameters, NULL, SAMPLE_RATE ); if( err == paFormatIsSupported ) { //printf("\n ADC samplerate is supported %d, FPB %d\n", \ // SAMPLE_RATE, FRAMES_PER_BUFFER); } else { //printf("\n ADC samplerate is NOT supported\n"); goto done; } //printf(" %s\n", Pa_GetVersionText()); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //GPIO-0 access for Green LED and test //rPi J8-11 and gnd J8-6 if(wiringPiSetup () < 0 ) { fprintf(stderr, "Unable to setup wiringPi: %s\n", strerror(errno)); return 1; } pinMode (LED_PIN, OUTPUT) ; digitalWrite (LED_PIN, OFF) ; pinMode (BUTTON_PIN, INPUT) ; //pullUpDnControl(BUTTON_PIN, PUD_OFF); pullUpDnControl(BUTTON_PIN, PUD_UP); pinMode (DIRECTION_PIN, INPUT) ; pullUpDnControl(DIRECTION_PIN, PUD_UP); pinMode (REBOOT_PIN, INPUT) ; pullUpDnControl(REBOOT_PIN, PUD_UP); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // underway--shift ship's colors--all ahead 8K sps // err = Pa_StartStream( stream ); if( err != paNoError ) goto done; // ============================================================================= // ============================================================================= // collecting samples phase // ****************************************** doState(S_COLLECTING, data.recordedSamples); // ****************************************** // we are running the callbacks while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { Pa_Sleep(500); if(buttonPress == TRUE) { Pa_Sleep(100); all_complete = TRUE; //stop the sample interrupt, exit while loop } else { // no button press // give the state machine a chance to run // ****************************************** doState(currentSTATE, (void*) NULL); // ****************************************** } } // ============================================================================= // ============================================================================= if( err < 0 ) goto done; // all stop err = Pa_CloseStream( stream ); if( err != paNoError ) goto done; buttonValue = digitalRead(BUTTON_PIN); //printf("button = %d\n", buttonValue); if(buttonValue == 0) { //if button still pressed, it's a hold buttonHold = TRUE; //printf("button hold\n"); //fflush(stdout); } else { //else, it's a button press buttonPress = FALSE; //acknowledged, reset flag //printf("button pressed\n"); //fflush(stdout); } // Measure maximum peak amplitude. // we could indicate over-driving/clipping the audio // or AGC it max = 0; average = 0.0; for( i=0; i<numSamples; i++ ) { val = data.recordedSamples[i]; if( val < 0 ) val = -val; // ABS if( val > max ) { max = val; } average += val; } average = average / (double)numSamples; //printf("sample max amplitude = "PRINTF_S_FORMAT"\n", max ); //printf("sample average = %lf\n", average ); // Write recorded data to a file. #if WRITE_TO_FILE { // the file size should be 5 minutes of 8K samples * 2 // the entire ring buffer is recorded without regard to the // read/write pointers. Make sense of the file by editing it in // Audacity // todo: write the file in correct time order using rd/wr pointers FILE *fid; fid = fopen("recorded.raw", "wb"); if( fid == NULL ) { //printf("Could not open file."); } else { fwrite( data.recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); fclose( fid ); //printf("Wrote data to 'recorded.raw'\n"); } } #endif // initial state after recording // all future state changes from within state machine if(buttonHold == FALSE) { // ****************************************** doState(S_REWIND_10, (void*) NULL); // ****************************************** } else { // ****************************************** doState(S_REWIND_PLAYBACK, (void*) NULL); // ****************************************** } // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| while (1) { // advance state in the state machine // ****************************************** doState(currentSTATE, (void*) NULL); // ****************************************** Pa_Sleep(100); if(terminate != FALSE) goto done; } // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| done: Pa_Terminate(); if( data.recordedSamples ) // Sure it is NULL or valid. free( data.recordedSamples ); if( err != paNoError ) { fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); fatalError(); err = 1; // Always return 0 or 1, but no other return codes. } return err; }
/* * + *---------------------------------------+ * | Prototype: void key_init(void); | * | Return Type: void | * | Arguments: None | * | Description: Initialize pins and | * | Keypad. | * +---------------------------------------+ */ void key_init(){ wiringPiSetupGpio (); pinMode (col0, OUTPUT); // column 0 pinMode (col1, OUTPUT); // column 1 pinMode (col2, OUTPUT); // column 2 pinMode (col3, OUTPUT); // column 3 pinMode (col4, OUTPUT); // column 4 pinMode (col5, OUTPUT); // column 5 digitalWrite (col0, LOW); digitalWrite (col1, LOW); digitalWrite (col2, LOW); digitalWrite (col3, LOW); digitalWrite (col4, LOW); digitalWrite (col5, LOW); pinMode (row0, INPUT); // row 1 pinMode (row1, INPUT); // row 2 pinMode (row2, INPUT); // row 3 pinMode (row3, INPUT); // row 4 pinMode (row4, INPUT); // row 1 pinMode (row5, INPUT); // row 2 pinMode (row6, INPUT); // row 3 pinMode (row7, INPUT); // row 4 pinMode (row8, INPUT); // row 4 pinMode (row9, INPUT); // row 4 pullUpDnControl (row0, PUD_DOWN); // row 1 pullUpDnControl (row1, PUD_DOWN); // row 1 pullUpDnControl (row2, PUD_DOWN); // row 1 pullUpDnControl (row3, PUD_DOWN); // row 1 pullUpDnControl (row4, PUD_DOWN); // row 1 pullUpDnControl (row5, PUD_DOWN); // row 1 pullUpDnControl (row6, PUD_DOWN); // row 1 pullUpDnControl (row7, PUD_DOWN); // row 2 pullUpDnControl (row8, PUD_DOWN); // row 3 pullUpDnControl (row9, PUD_DOWN); // row 4 pullUpDnControl (up, PUD_DOWN); // Directional Switch Up pullUpDnControl (down, PUD_DOWN); // Directional Switch Down pullUpDnControl (left, PUD_DOWN); // Directional Switch Left }
int main (void) { int i, j ; int led, button ; unsigned int start, stop ; printf ("Raspberry Pi PiFace Reaction Timer\n") ; printf ("==================================\n") ; if (piFaceSetup (PIFACE) == -1) exit (1) ; // Enable internal pull-ups for (i = 0 ; i < 8 ; ++i) pullUpDnControl (PIFACE + i, PUD_UP) ; // Main game loop: // Put some random LED pairs up for a few seconds, then blank ... for (;;) { printf ("Press any button to start ... \n") ; fflush (stdout) ; for (;;) { led = rand () % 4 ; light (led, 1) ; delay (10) ; light (led, 0) ; button = 0 ; for (j = 0 ; j < 4 ; ++j) button += digitalRead (PIFACE + j) ; if (button != 4) break ; } waitForNoButtons () ; printf ("Wait for it ... ") ; fflush (stdout) ; led = rand () % 4 ; delay (rand () % 500 + 1000) ; light (led, 1) ; start = millis () ; for (button = -1 ; button == -1 ; ) { for (j = 0 ; j < 4 ; ++j) if (digitalRead (PIFACE + j) == 0) // Pushed { button = j ; break ; } } stop = millis () ; button = 3 - button ; // Correct for the buttons/LEDs reversed light (led, 0) ; waitForNoButtons () ; light (led, 1) ; if (button == led) { printf ("You got it in %3d mS\n", stop - start) ; } else { printf ("Missed: You pushed %d - LED was %d\n", button, led) ; for (;;) { light (button, 1) ; delay (100) ; light (button, 0) ; delay (100) ; i = 0 ; for (j = 0 ; j < 4 ; ++j) i += digitalRead (PIFACE + j) ; if (i != 4) break ; } waitForNoButtons () ; } light (led, 0) ; delay (4000) ; } return 0 ; }
int main(int argc, char **argv) { EP_STAT estat; gcl_name_t gclname; char *gclpname = LOG_NAME; bool show_usage = false; char *log_file_name = NULL; int opt; while ((opt = getopt(argc, argv, "D:g:L:p:")) > 0) { switch (opt) { case 'D': ep_dbg_set(optarg); break; case 'g': gclpname = optarg; break; case 'L': log_file_name = optarg; break; case 'p': ButtonPin = atoi(optarg); break; default: show_usage = true; break; } } argc -= optind; argv += optind; if (show_usage || argc > 0) { fprintf(stderr, "Usage: %s [-D dbgspec] [-g gclname] [-p buttonpin]\n", ep_app_getprogname()); exit(EX_USAGE); } // initialize wiringPi library (must be root!) printf("Initializing wiringPi library:\n"); wiringPiSetupGpio(); pinMode(ButtonPin, INPUT); pullUpDnControl(ButtonPin, PUD_UP); //XXX should probably give up root privileges here if (log_file_name != NULL) { // open a log file (for timing measurements) printf("Opening log file:\n"); LogFile = fopen(log_file_name, "a"); if (LogFile == NULL) printf("Cannot open log file: %s\n", strerror(errno)); setlinebuf(LogFile); } // initialize the GDP library printf("Initializing GDP library:\n"); estat = gdp_init(NULL); if (!EP_STAT_ISOK(estat)) { ep_app_error("GDP Initialization failed"); exit(EX_UNAVAILABLE); } // convert the name to internal form printf("Converting name %s to internal form:\n", gclpname); estat = gdp_gcl_parse_name(gclpname, gclname); if (!EP_STAT_ISOK(estat)) { ep_app_error("Illegal GCL name syntax:\n\t%s", gclpname); exit(EX_NOINPUT); } // open the GCL for writing printf("Opening GCL for writing:\n"); estat = gdp_gcl_open(gclname, GDP_MODE_AO, &PiGcl); if (!EP_STAT_ISOK(estat)) { char sbuf[100]; ep_app_error("Cannot open GCL:\n %s", ep_stat_tostr(estat, sbuf, sizeof sbuf)); exit(EX_NOINPUT); } // arrange to call a function on edge triggers (void) wiringPiISR(ButtonPin, INT_EDGE_BOTH, &changefunc); while (true) sleep(3600); ep_app_abort("Impossible exit"); }
// --------------------------------------------------------------------------- // Initialises encoder and button GPIOs. // --------------------------------------------------------------------------- void encoderInit( uint8_t gpioA, uint8_t gpioB, uint8_t gpioC ) { /* Need to check validity of GPIO numbers! */ wiringPiSetupGpio(); encoder.gpioA = gpioA; encoder.gpioB = gpioB; // Set encoder GPIO modes. pinMode( encoder.gpioA, INPUT ); pinMode( encoder.gpioB, INPUT ); pullUpDnControl( encoder.gpioA, PUD_UP ); pullUpDnControl( encoder.gpioB, PUD_UP ); // Register interrupt functions. switch ( encoder.mode ) { case SIMPLE_1: wiringPiISR( encoder.gpioA, INT_EDGE_RISING, &setDirectionSimple ); break; case SIMPLE_2: wiringPiISR( encoder.gpioA, INT_EDGE_BOTH, &setDirectionTable ); break; case SIMPLE_4: wiringPiISR( encoder.gpioA, INT_EDGE_BOTH, &setDirectionTable ); wiringPiISR( encoder.gpioB, INT_EDGE_BOTH, &setDirectionTable ); break; case HALF: wiringPiISR( encoder.gpioA, INT_EDGE_BOTH, &setDirectionHalf ); wiringPiISR( encoder.gpioB, INT_EDGE_BOTH, &setDirectionHalf ); break; default: wiringPiISR( encoder.gpioA, INT_EDGE_BOTH, &setDirectionFull ); wiringPiISR( encoder.gpioB, INT_EDGE_BOTH, &setDirectionFull ); break; } // Set states. encoderDirection = 0; // Only set up a button if there is one. if ( gpioC != 0xFF ) { /* Need to check validity of GPIO number! */ button.gpio = gpioC; // Set button gpio mode. pinMode( button.gpio, INPUT ); pullUpDnControl( button.gpio, PUD_UP ); // Register interrupt function. wiringPiISR( button.gpio, INT_EDGE_FALLING, &setButtonState ); // Set state. buttonState = 0; } return; }
void Gpio::setPullDown() { pullUpDnControl(m_pin, PUD_DOWN); }
void Gpio::setPullUp() { pullUpDnControl(m_pin, PUD_UP); }
void VoxMain::run() { int modesw = 3; uint64_t cnt = 0; timeval tvchk = {0, 0}; timeval tvcur = {0, 0}; std::string datastr = ""; INFORMATION("(MAIN) start of loop"); pinMode(modesw, INPUT); pullUpDnControl(modesw, PUD_UP); gettimeofday(&tvchk, NULL); while(!m_exit) { int onoff = digitalRead(modesw); gettimeofday(&tvcur, NULL); if(onoff == LOW) { std::string retstr = ""; if(m_mode > MD5) --m_mode; else m_mode = MD1; NOTICE("mode changed: mode=%d", m_mode); if(m_mode == MD1) // control { } else if(m_mode == MD2) // vision { //if(!createProcess("/home/pi/mjpg-streamer/stop_mjpg.sh", retstr)) // ERROR("(MAIN) failed to stop mjpg-streamer"); } else if(m_mode == MD3) // voice { } Servo* servo = VoxControl::getInstance().getServo(); servo->setNeutral(); VoxPlayer::getInstance().play("", false); delay(300); } if(timeSpan(tvchk, tvcur) >= 1.0f) { cpuUsage(); tvchk.tv_sec = tvcur.tv_sec; tvchk.tv_usec = tvcur.tv_usec; } if((cnt % 100) == 0) { std::vector<std::string> addrs; getLocalIPString(addrs); m_myip = ""; for(size_t i = 0; i < addrs.size(); i++) { std::string acls = ""; extractSubString(acls, addrs[i].c_str(), 0, '.'); if(isPositiveNumber(acls)) { if(acls != "127") m_myip += addrs[i] + ", "; } } m_myip = strTrim(m_myip, " ,"); std::string retstr = ""; if(createProcess("/usr/bin/vcgencmd measure_temp", retstr)) { strRemove(retstr, "temp="); strRemove(retstr, "'C"); m_cputemp = atof(retstr.c_str()); } m_appmem = getRss(); } if((cnt % 2) == 0) { bool voice = VoxVoice::getInstance().isRunning(); datastr = strFormat("%s|%d|%d|%d|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%d|%d|%d|%.1f|%d|%d|%s|%s", m_myip.c_str(), abs(MD1 - m_mode) + 1, m_stat, VoxSensor::getInstance().isFreeze(), VoxSensor::getInstance().getTemperature(), VoxSensor::getInstance().getHumidity(), VoxSensor::getInstance().getDistF(), VoxSensor::getInstance().getDistB(), VoxSensor::getInstance().getDistL(), VoxSensor::getInstance().getDistR(), m_cpuusage, m_cputemp, (float)(m_appmem / 1024.0 / 1024.0), VoxVision::getInstance().isFollowing(), VoxVision::getInstance().getPosX(), VoxVision::getInstance().getPosY(), VoxVision::getInstance().getRadius(), VoxVision::getInstance().getBallCount(), (voice) ? VoxVoice::getInstance().readyToGo() : 0, (voice) ? VoxVoice::getInstance().getReq().c_str() : "", (voice) ? VoxVoice::getInstance().getRsp().c_str() : "" ); writeDataFile(datastr); } delay(150); ++cnt; } pinMode(modesw, OUTPUT); digitalWrite(modesw, LOW); INFORMATION("(MAIN) end of loop"); }
int main(int argc, char * argv[]) { int pos = 125; long min, max; long gpiodelay_value = 250; // was 50 snd_mixer_t *handle; snd_mixer_selem_id_t *sid; const char *card = "default"; // Previous linux driver's mixer name // const char *selem_name = "Playback Digital"; // const char *selem_name = "PCM"; const char *selem_name = "Digital"; // Linux 4.1.6-v7+ #810 int x, mute_state; long i, currentVolume; printf("IQaudIO.com Pi-DAC Volume Control support Rotary Encoder) v1.5 Aug 30th 2015\n\n"); wiringPiSetup (); /* pull up is needed as encoder common is grounded */ pinMode (ENCODER_A, INPUT); pullUpDnControl (ENCODER_A, PUD_UP); pinMode (ENCODER_B, INPUT); pullUpDnControl (ENCODER_B, PUD_UP); encoderPos = pos; // Setup ALSA access snd_mixer_open(&handle, 0); snd_mixer_attach(handle, card); snd_mixer_selem_register(handle, NULL, NULL); snd_mixer_load(handle); snd_mixer_selem_id_alloca(&sid); snd_mixer_selem_id_set_index(sid, 0); snd_mixer_selem_id_set_name(sid, selem_name); snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid); snd_mixer_selem_get_playback_volume_range(elem, &min, &max); if (DEBUG_PRINT) printf("Returned card VOLUME range - min: %ld, max: %ld\n", min, max); // Minimum given is mute, we need the first real value min++; // Get current volume if (x = snd_mixer_selem_get_playback_volume (elem, SND_MIXER_SCHN_FRONT_LEFT, ¤tVolume)) { printf("%d %s\n", x, snd_strerror(x)); } else if (DEBUG_PRINT) printf("Current ALSA volume LEFT: %ld\n", currentVolume); if (x = snd_mixer_selem_get_playback_volume (elem, SND_MIXER_SCHN_FRONT_RIGHT, ¤tVolume)) { printf("%d %s\n", x, snd_strerror(x)); } else if (DEBUG_PRINT) printf("Current ALSA volume RIGHT: %ld\n", currentVolume); /* monitor encoder level changes */ wiringPiISR (ENCODER_A, INT_EDGE_BOTH, &encoderPulse); wiringPiISR (ENCODER_B, INT_EDGE_BOTH, &encoderPulse); // Now sit and spin waiting for GPIO pins to go active... while (1) { if (encoderPos != pos) { // get current volume if (x = snd_mixer_selem_get_playback_volume (elem, SND_MIXER_SCHN_FRONT_LEFT, ¤tVolume)) { printf("%d %s\n", x, snd_strerror(x)); } else if (DEBUG_PRINT) printf(" Current ALSA volume: %ld\n", currentVolume); // Adjust for MUTE if (currentVolume < min) { currentVolume = 0; if (DEBUG_PRINT) printf(" Current ALSA volume set to min: %ld\n", currentVolume); } // What way did the encoder go? if (encoderPos > pos) { pos = encoderPos; currentVolume = currentVolume + 10; // Adjust for MAX volume if (currentVolume > max) currentVolume = max; if (DEBUG_PRINT) printf("Volume UP %d - %ld", pos, currentVolume); } else if (encoderPos < pos) { pos = encoderPos; currentVolume = currentVolume - 10; // Adjust for MUTE if (currentVolume < min) currentVolume = 0; if (DEBUG_PRINT) printf("Volume DOWN %d - %ld", pos, currentVolume); } if (x = snd_mixer_selem_set_playback_volume_all(elem, currentVolume)) { printf(" ERROR %d %s\n", x, snd_strerror(x)); } else if (DEBUG_PRINT) printf(" Volume successfully set to %ld using ALSA!\n", currentVolume); } // Check x times per second, MAY NEED TO ADJUST THS FREQUENCY FOR SOME ENCODERS */ delay(gpiodelay_value); /* check pos x times per second */ } // We never get here but should close the sockets etc. on exit. snd_mixer_close(handle); }
void myPullUpDnControl (struct wiringPiNodeStruct *node, int pin, int pud) { pullUpDnControl (pin + 16 + 8, pud) ; }
int main(int argc, char *argv[]) { char inputString[InputLength] , *tempPtr; int rc; pthread_mutex_init(&mutex, NULL); pthread_mutex_init(&mutex_2, NULL); pthread_mutex_init(&mutex_log, NULL); pthread_mutex_init(&Mutexlinklist, NULL); pthread_mutex_init(&mutexFTP, NULL); pthread_cond_init(&cond, NULL); pthread_cond_init(&condFTP, NULL); pthread_t barcodeInputThread, watchdogThread; wiringPiSetup(); pinMode(WiringPiPIN_15, OUTPUT); pinMode(WiringPiPIN_16, OUTPUT); pinMode(WiringPiPIN_18, OUTPUT); pinMode(WiringPiPIN_22, INPUT); pinMode(WiringPiPIN_24, INPUT); pullUpDnControl (WiringPiPIN_22, PUD_UP); pullUpDnControl (WiringPiPIN_24, PUD_UP); WatchDogFlag = 1; rc = pthread_create(&watchdogThread, NULL, WatchDogFunction, NULL); assert(rc == 0); while(1) { rc = pthread_create(&barcodeInputThread, NULL, BarcodeInputFunction, NULL); assert(rc == 0); while(list == NULL) { ; } while(digitalRead(WiringPiPIN_24) == 0) { usleep(100000); } printf("ready to cancel barcode\n"); pthread_cancel(barcodeInputThread); pthread_join(barcodeInputThread, NULL); printf("cancel done\n"); while(list != NULL) { memset(inputString, 0, sizeof(char)*InputLength); gets(inputString); if(strncmp(inputString, "XXXP", 4) == 0) { pthread_mutex_lock(&Mutexlinklist); InputNode *p = list; while(p != NULL) { memset(p->UserNo, 0, sizeof(char)*InputLength); tempPtr = inputString + 4; memcpy(p->UserNo, tempPtr, sizeof(inputString)-3); printf("%s %s %s %s %s %s\n", p->ISNo, p->ManagerCard, p->MachineCode, p->UserNo, p->CountNo, p->UPLoadFile); p = p->link; } pthread_mutex_unlock(&Mutexlinklist); break; } printf("UserNo scan error code\n"); } } return 0; }
void SetNTX2BFrequency(char *FrequencyString) { int fd, Frequency; char Command[16]; struct termios options; uint8_t setNMEAoff[] = {0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xA9 }; // First disable transmitter digitalWrite (NTX2B_ENABLE, 0); pinMode (NTX2B_ENABLE, OUTPUT); delayMilliseconds (200); fd = open("/dev/ttyAMA0", O_WRONLY | O_NOCTTY); if (fd >= 0) { tcgetattr(fd, &options); cfsetispeed(&options, B4800); cfsetospeed(&options, B4800); options.c_cflag &= ~CSTOPB; options.c_cflag |= CS8; options.c_oflag &= ~ONLCR; options.c_oflag &= ~OPOST; options.c_iflag &= ~IXON; options.c_iflag &= ~IXOFF; options.c_lflag &= ~ECHO; options.c_cc[VMIN] = 0; options.c_cc[VTIME] = 10; tcsetattr(fd, TCSANOW, &options); // Tel UBlox to shut up write(fd, setNMEAoff, sizeof(setNMEAoff)); tcsetattr(fd, TCSAFLUSH, &options); close(fd); delayMilliseconds (1000); fd = open("/dev/ttyAMA0", O_WRONLY | O_NOCTTY); if (strlen(FrequencyString) < 3) { // Already a channel number Frequency = strtol(FrequencyString, NULL, 16); } else { // Convert from MHz to channel number Frequency = (int)((atof(FrequencyString) - 434.05) / 0.003124); } sprintf(Command, "%cch%02X\r", 0x80, Frequency); printf("NTX2B-FA transmitter now set to channel %02Xh which is %8.4lfMHz\n", Frequency, (double)(Frequency) * 0.003125 + 434.05); // Let enable line float (but Tx will pull it up anyway) delayMilliseconds (200); pinMode (NTX2B_ENABLE, INPUT); pullUpDnControl(NTX2B_ENABLE, PUD_OFF); delayMilliseconds (20); write(fd, Command, strlen(Command)); tcsetattr(fd, TCSAFLUSH, &options); delayMilliseconds (50); close(fd); // Switch on the radio delayMilliseconds (100); digitalWrite (NTX2B_ENABLE, 1); pinMode (NTX2B_ENABLE, OUTPUT); } }
void sf240320_initialize(uint8_t data_bus_width) { // Set up the data pins set_port_mode(false); pullUpDnControl(data_bus.DB0, PUD_DOWN); pullUpDnControl(data_bus.DB1, PUD_DOWN); pullUpDnControl(data_bus.DB2, PUD_DOWN); pullUpDnControl(data_bus.DB3, PUD_DOWN); pullUpDnControl(data_bus.DB4, PUD_DOWN); pullUpDnControl(data_bus.DB5, PUD_DOWN); pullUpDnControl(data_bus.DB6, PUD_DOWN); pullUpDnControl(data_bus.DB7, PUD_DOWN); pullUpDnControl(data_bus.DB8, PUD_DOWN); pullUpDnControl(data_bus.DB9, PUD_DOWN); pullUpDnControl(data_bus.DB10, PUD_DOWN); pullUpDnControl(data_bus.DB11, PUD_DOWN); pullUpDnControl(data_bus.DB12, PUD_DOWN); pullUpDnControl(data_bus.DB13, PUD_DOWN); pullUpDnControl(data_bus.DB14, PUD_DOWN); pullUpDnControl(data_bus.DB15, PUD_DOWN); // Initialize data pins digitalWrite(data_bus.DB0, LOW); digitalWrite(data_bus.DB1, LOW); digitalWrite(data_bus.DB2, LOW); digitalWrite(data_bus.DB3, LOW); digitalWrite(data_bus.DB4, LOW); digitalWrite(data_bus.DB5, LOW); digitalWrite(data_bus.DB6, LOW); digitalWrite(data_bus.DB7, LOW); digitalWrite(data_bus.DB8, LOW); digitalWrite(data_bus.DB9, LOW); digitalWrite(data_bus.DB10, LOW); digitalWrite(data_bus.DB11, LOW); digitalWrite(data_bus.DB12, LOW); digitalWrite(data_bus.DB13, LOW); digitalWrite(data_bus.DB14, LOW); digitalWrite(data_bus.DB15, LOW); // Set up the control pins pinMode(control_bus.data_bus_width, OUTPUT); pinMode(control_bus.dat_com_sel, OUTPUT); pinMode(control_bus.write, OUTPUT); pinMode(control_bus.read, OUTPUT); pinMode(control_bus.reset, OUTPUT); // Initialize control pins if(data_bus_width == 16) { digitalWrite(control_bus.data_bus_width, LOW); write = write_16; } else //if(data_bus_width == 8) { digitalWrite(control_bus.data_bus_width, HIGH); write = write_8; } digitalWrite(control_bus.dat_com_sel, LOW); digitalWrite(control_bus.write, HIGH); digitalWrite(control_bus.read, HIGH); // Reset digitalWrite(control_bus.reset, LOW); delay(120); digitalWrite(control_bus.reset, HIGH); delay(120); // Turn off display write_16(true, 0x28); // Exit sleep mode write_16(true, 0x11); write_16(false, 0x00); // Power control a write_16(true, 0xCB); write_16(false, 0x39); write_16(false, 0x2C); write_16(false, 0x00); write_16(false, 0x34); write_16(false, 0x02); // Power control b write_16(true, 0xCF); write_16(false, 0x00); write_16(false, 0x81); write_16(false, 0x30); // Driver timing control a write_16(true, 0xE8); write_16(false, 0x85); write_16(false, 0x01); write_16(false, 0x79); // Driver timing control b write_16(true, 0xEA); write_16(false, 0x00); write_16(false, 0x00); // Power-on sequence control write_16(true, 0xED); write_16(false, 0x64); write_16(false, 0x03); write_16(false, 0x12); write_16(false, 0x81); // Pump ratio control write_16(true, 0xF7); write_16(false, 0x20); // Power control 1 write_16(true, 0xC0); write_16(false, 0x26); write_16(false, 0x04); // Power cotnrol 2 write_16(true, 0xC1); write_16(false, 0x11); // VCOM control 1 write_16(true, 0xC5); write_16(false, 0x35); write_16(false, 0x3E); // VCOM control 2 write_16(true, 0xC7); write_16(false, 0xBE); // Memory access is BGR write_16(true, 0x36); write_16(false, 0x08); // Frame rate control write_16(true, 0xB1); write_16(false, 0x00); write_16(false, 0x10); // Display function control write_16(true, 0xB6); write_16(false, 0x0A); write_16(false, 0xA2); // Pixel format is 16-bit write_16(true, 0x3A); write_16(false, 0x55); // 3G gamma control is off write_16(true, 0xF2); write_16(false, 0x02); // Gamme curve 3 write_16(true, 0x26); write_16(false, 0x01); // Column address: start at 0x00, end at 0xEF write_16(true, 0x2A); write_16(false, 0x00); write_16(false, 0x00); write_16(false, 0x00); write_16(false, 0xEF); // Page address: start at 0x00, end at 0x13F write_16(true, 0x2B); write_16(false, 0x00); write_16(false, 0x00); write_16(false, 0x01); write_16(false, 0x3F); // Turn on display write_16(true, 0x29); }
/* * Class: com_pi4j_wiringpi_Gpio * Method: pullUpDnControl * Signature: (II)V */ JNIEXPORT void JNICALL Java_com_pi4j_wiringpi_Gpio_pullUpDnControl (JNIEnv *env, jclass obj, jint pin, jint pud) { pullUpDnControl(pin, pud); }
int main(int argc, char* argv[]) { //Getting input from the file for subscribing char ADDRESS[50]; char CLIENTID[23]; char TOPIC[80]; char PORT[5]; FILE* fp = fopen("input_sub.config","r"); fscanf(fp,"%s",ADDRESS); fscanf(fp,"%s",CLIENTID); fscanf(fp,"%s",TOPIC); fscanf(fp,"%s",PORT); sprintf(ADDRESS,"%s:%s",ADDRESS,PORT); fclose(fp); //WiringPi setup wiringPiSetupGpio (); pinMode (LED_1, OUTPUT); pinMode (LED_2, OUTPUT); pinMode (LED_3, OUTPUT); //pinMode (SWITCH_1, INPUT); //pinMode (SWITCH_2, INPUT); //pinMode (SWITCH_3, INPUT); //Pull up input pins pullUpDnControl (SWITCH_1, PUD_UP); pullUpDnControl (SWITCH_2, PUD_UP); pullUpDnControl (SWITCH_3, PUD_UP); //Set Interrupts wiringPiISR(SWITCH_1,INT_EDGE_BOTH,&interruptFunc_1); wiringPiISR(SWITCH_2,INT_EDGE_BOTH,&interruptFunc_2); wiringPiISR(SWITCH_3,INT_EDGE_BOTH,&interruptFunc_3); //Pull down the non ground pins pullUpDnControl (19, PUD_DOWN); pullUpDnControl (26, PUD_DOWN); //Lights Initialization digitalWrite(LED_1,HIGH); digitalWrite(LED_2,LOW); digitalWrite(LED_3,LOW); delay(100); digitalWrite(LED_1,LOW); digitalWrite(LED_2,HIGH); digitalWrite(LED_3,LOW); delay(100); digitalWrite(LED_1,LOW); digitalWrite(LED_2,LOW); digitalWrite(LED_3,HIGH); delay(100); digitalWrite(LED_1, LOW); digitalWrite(LED_2, LOW); digitalWrite(LED_3, LOW); //MQTT Setup for subscribing MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; int rc; int ch; MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_USER, NULL); conn_opts.keepAliveInterval = 100; conn_opts.cleansession = 0; MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered); if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(-1); } printf("Subscribing to topic %s\nfor client %s using QoS %d\n\n" "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS); MQTTClient_subscribe(client, TOPIC, QOS); //Start the new thread if(piThreadCreate(mqttStream) != 0) { printf("ERROR in creating MQTT streaming thread"); } //Main loop int previousBoxStatus_1,previousBoxStatus_2,previousBoxStatus_3; previousBoxStatus_1 = boxStatus_1; previousBoxStatus_2 = boxStatus_2; previousBoxStatus_3 = boxStatus_3; do { //if the previous mode is not the status now publish else do nothing if(previousBoxStatus_1 != boxStatus_1){ delay(debounceDelay); //Time delay after an interrupt for the signal to be stable publishBoxStatus(10,boxStatus_1); previousBoxStatus_1 = boxStatus_1; } if(previousBoxStatus_2 != boxStatus_2){ delay(debounceDelay); //Time delay after an interrupt for the signal to be stable publishBoxStatus(20,boxStatus_2); previousBoxStatus_2 = boxStatus_2; } if(previousBoxStatus_3 != boxStatus_3){ delay(debounceDelay); //Time delay after an interrupt for the signal to be stable publishBoxStatus(30,boxStatus_3); previousBoxStatus_3 = boxStatus_3; } // ch = getchar(); } while(ch!='Q' && ch != 'q'); MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; }
/* * main program */ int main(int argc, char** argv) { //global var time_t sec0, sec1; unsigned int delayPixel= 120000, delayGyrodataSending = 25000; unsigned int idPayload = 303, useKeyboardCmd = 0, buffer_max_num = 64; unsigned char keyChar; int gpioOK = 0; dictionary *iniDict; //ini dictionery char strPathCfg[255]; GPS_DATA last_posx; //init last gps pos last_posx.gps_status = last_posx.gps_loc.lat = last_posx.gps_loc.lon = 0; last_posx.gps_speed = last_posx.gps_altitude = last_posx.gps_time = 0; //show titel #if VERBOSE==1 printf("%s", APP_TITEL); #endif //init pin switch gpioOK = wiringPiSetup(); if(gpioOK != -1) { pinMode(6, INPUT); pullUpDnControl(6, PUD_UP); } else printf("gpio init eror\r\n"); //parsing argumen jika ada if(argc>2) { //default cfg file getcwd(strPathCfg, sizeof(strPathCfg)); strcat(strPathCfg, "/"); strcat(strPathCfg, CFG_NAME); int i; for(i=1;i<(argc-1);i++) { //delay pixel if(strcmp("-d",argv[i])==0) delayPixel = atoi(argv[++i]); //id payload if(strcmp("-i",argv[i])==0) idPayload = atoi(argv[++i]); //pake keyboard ato tidak if(strcmp("-k",argv[i])==0) useKeyboardCmd = atoi(argv[++i]); //gyro send if(strcmp("-g",argv[i])==0) delayGyrodataSending = atoi(argv[++i]); //buffer size if(strcmp("-b",argv[i])==0) buffer_max_num = atoi(argv[++i]); } } else //baca dari cfg file { //load ini file //char strCfg[80]; if(argc==2) { strcpy(strPathCfg, argv[1]); } else { //get cwd if (getcwd(strPathCfg, sizeof(strPathCfg)) != NULL) printf("Current working dir: %s\r\n", strPathCfg); else { strcpy(strPathCfg, argv[1]); } } //check file exists strcat(strPathCfg, "/"); strcat(strPathCfg, CFG_NAME); if(!file_exist(strPathCfg)) { printf("Configuration file %s not found!!!\r\n", strPathCfg ); return(EXIT_FAILURE); } //load from config file printf("Loading configuration file from %s\r\n", strPathCfg); //load ini parser iniDict = iniparser_load(strPathCfg); //read cfg value if(iniDict) { idPayload = iniparser_getint(iniDict,"payload:id",100); delayPixel = iniparser_getint(iniDict,"payload:cam_delay",120000); delayGyrodataSending = iniparser_getint(iniDict,"payload:g_delay",20000); buffer_max_num = iniparser_getint(iniDict,"payload:buffer",64); } } //show config setup printf("======================================\r\n"); printf("Configuration :\r\n"); printf("Delay Pixel = %d uS\r\n", delayPixel); printf("ID Payload = %d\r\n", idPayload); printf("Use Keyboard = %d\r\n", useKeyboardCmd); printf("Gyro Delay = %d uS\r\n", delayGyrodataSending); printf("Buffer = %d byte\r\n", buffer_max_num); printf("======================================\r\n"); //init bus i2c int i2c_hdl = I2C_Init_Bus(i2c_dev, &statusPeripheral); //init start adxl345 ADXL345_Init_Start(i2c_hdl, adxl345_addr, &statusPeripheral); //init itg3200 ITG3200_Init_Start(i2c_hdl, itg3200_addr, &statusPeripheral); //open port unsigned char buffRX[COM_BUFF_NUM]; int buffNumRX; //make it as null string buffRX[COM_BUFF_NUM-1] = 0; if (OpenComport(COM_PORT, COM_SPEED)) { fprintf(stderr, "Open port %d failed : %s\r\n!!!", COM_PORT, strerror(errno)); return errno; } #if VERBOSE==1 printf("communication port opened\r\n"); #endif //tes port com //while(1){ ////ambil perintah dari comport //buffNumRX = PollComport(COM_PORT, buffRX, (COM_BUFF_NUM - 2)); //if (buffNumRX > 0) { ////printf("%d = %s\n", buffNumRX, buffRX); //int i; //for(i=0;i<buffNumRX;i++) //{ //printf("%X %s", buffRX[i], (i<buffNumRX-1) ? "":"\n"); //} //char ss[10]; //snprintf(ss,6,"%d",(buffRX[1]<<8)+buffRX[2]); //printf("id = %s\n", ss); //} //} //open cam CvCapture *camHdl = cvCaptureFromCAM(CV_CAP_ANY); Cam_Init_Start(camHdl, &statusPeripheral); //main loop while (1) { if(useKeyboardCmd) { //dummy keyboard input printf("press command key\r\n"); keyChar = getchar(); //if (keyChar == cmdList[3][0]) //opsState = STATE_EXIT; //if (keyChar == cmdList[2][0]) //opsState = STATE_GET_CAM_DATA; //if (keyChar == cmdList[1][0]) //opsState = STATE_GET_G_DATA; if (keyChar == cmdList[3]) opsState = STATE_EXIT; if (keyChar == cmdList[2]) opsState = STATE_GET_CAM_DATA; if (keyChar == cmdList[1]) opsState = STATE_GET_G_DATA; } //ambil perintah dari comport buffNumRX = PollComport(COM_PORT, buffRX, (COM_BUFF_NUM - 2)); //data diterima -> cek printah if (buffNumRX > 0) { //int i; //unsigned char *chrPos; ////make it null string //if (buffRX[buffNumRX] != 0) //buffRX[buffNumRX] = 0; ////default ops state = idle //opsState = STATE_IDLE; ////add new state //for (i = 0; i < CMD_COUNTER; i++) { //chrPos = strstr(buffRX,cmdList[i]); //if ((chrPos != NULL) && ((chrPos - buffRX + 1) == 1)) { //got a match? ////proses state //opsState = i; //break; //} //} opsState = CheckCommand(cmdList, buffNumRX, buffRX); } //cek tobmol if(gpioOK != -1) { //printf("%d\r\n", digitalRead(6)); //SendByte(COM_PORT, digitalRead(6)+0x30); //usleep(1e5); if(digitalRead(6) == 0) { usleep(5e5); if(digitalRead(6) == 0) opsState = STATE_SHUTDOWN_OS; } } //lakukan proses seuai ops state if (opsState == STATE_EXIT) { #if VERBOSE==1 printf("exiting...\r\n"); //fflush(stdout); #endif break; } //shutdown os if (opsState == STATE_SHUTDOWN_OS) { printf("shutdown...\r\n"); break; } //restart os if (opsState == STATE_RESTART_OS) { printf("restart...\r\n"); break; } //other state switch (opsState) { case STATE_IDLE: //idle state //SendByte(COM_PORT, 's'); break; case STATE_GET_G_DATA: //ambil data g //SendByte(COM_PORT, 'g'); GetAndSendAccGyro(i2c_hdl, adxl345_addr, itg3200_addr, idPayload, delayGyrodataSending, &last_posx, buffer_max_num); break; case STATE_GET_CAM_DATA://ambil data cam //SendByte(COM_PORT, 'c'); #if VERBOSE==1 printf("grab camera start\r\n"); sec0 = time(NULL); #endif GrabAndSendCameraData(camHdl, i2c_hdl, 5, delayPixel, idPayload, &last_posx, buffer_max_num); #if VERBOSE==1 sec1 = time(NULL); printf("grab camera finish in %lds\r\n", (sec1 - sec0)); #endif opsState = STATE_IDLE; //usleep(5e4); //ComportFlush(COM_PORT); //usleep(1.5e6); break; case STATE_GET_STATUS: //ambil status payload snprintf((char*)buffRX, 16, "s,%.3d,%d,%d\r", idPayload, 990, statusPeripheral); //SendBuf(COM_PORT, buffRX, 10); //snprintf((char*)buffRX, 16, "s,%.3d,%d\r", idPayload, 990); cprintf(COM_PORT, buffRX); opsState = STATE_IDLE; //go back to idle #if VERBOSE==1 printf("sendstatus reply = %s\r\n", buffRX); #endif break; case STATE_REINIT_PERIPHERAL: //reinit peripheral //init cam Cam_Init_Start(camHdl, &statusPeripheral); //init bus i2c i2c_hdl = I2C_Init_Bus(i2c_dev, &statusPeripheral); //init start adxl345 ADXL345_Init_Start(i2c_hdl, adxl345_addr, &statusPeripheral); //init itg3200 ITG3200_Init_Start(i2c_hdl, itg3200_addr, &statusPeripheral); opsState = STATE_IDLE; //go back to idle break; case STATE_READ_WRITE_CONFIGURATION: //read/write config file printf("Opening configuration file %s\r\n", strPathCfg); //load ini file iniDict = iniparser_load(strPathCfg); //write if neccessary if(buffRX[1]==1) //write setting { char stmp[10]; //id snprintf(stmp,10,"%d", (buffRX[2]<<8)+buffRX[3]); iniparser_set(iniDict,"payload:id",stmp); //cam delay in ms snprintf(stmp,10,"%d", buffRX[4]*1000); iniparser_set(iniDict,"payload:cam_delay",stmp); //g delay in ms snprintf(stmp,10,"%d", buffRX[5]*1000); iniparser_set(iniDict,"payload:g_delay",stmp); //buffer max snprintf(stmp,10,"%d", buffRX[6]); iniparser_set(iniDict,"payload:buffer",stmp); Save_INI_File(iniDict, strPathCfg); } //reload ini file iniDict = iniparser_load(strPathCfg); //read cfg value if(iniDict) { idPayload = iniparser_getint(iniDict,"payload:id",100); delayPixel = iniparser_getint(iniDict,"payload:cam_delay",120000); delayGyrodataSending = iniparser_getint(iniDict,"payload:g_delay",20000); buffer_max_num = iniparser_getint(iniDict,"payload:buffer",64); } //send reply always snprintf((char*)buffRX, 25, "f,%d,%d,%d,%d\r", idPayload, delayPixel, delayGyrodataSending,buffer_max_num); cprintf(COM_PORT, buffRX); opsState = STATE_IDLE; //go back to idle #if VERBOSE==1 printf("send config reply = %s\r\n", buffRX); #endif break; default: break; } } //release cam cvReleaseCapture(&camHdl); //release port CloseComport(COM_PORT); //close bus closeBus(i2c_hdl); //free ini handler if(iniDict) iniparser_freedict(iniDict); //cek shutdown atau restart switch (opsState) { case STATE_SHUTDOWN_OS: system("sudo shutdown now"); break; case STATE_RESTART_OS: system("sudo shutdown -r now"); break; default: break; } //return return (EXIT_SUCCESS); }
int main(void){ int setup = 0; int result; char str[100],str0[50],str1[50]; char tmp[100]; int i, n=0; int pos = NOT_FOUND; unsigned int maxMillis=1000; int tx=0; a=1; b=1; p_a=0; p_b=0; num=0;num2=0; strcpy(path,home); strcat(path,scripts); setup = wiringPiSetup(); pinMode(rRED,OUTPUT); pinMode(rGREEN,OUTPUT); pinMode(rSW,INPUT); /* read main menu */ printf("Main menu:%s\n",Mname); Mmax=read_file(Mname, Mbuf); /* read level menu */ Lmax=read_file(Lname, Lbuf); /* read date&time menu */ Dmax=read_file(Dname, Dbuf); /* Get current menu item */ /* char *menu_name, *file_name, *freq, *s_rate */ strcpy(tmp,Mbuf[num]); menu_name=strtok(tmp,","); file_name=strtok(NULL,","); freq=strtok(NULL,","); s_rate=strtok(NULL,","); date_time="2016/04/15,00:00:00"; printf("%s %s %s %s %s\n",menu_name,file_name,freq,s_rate,date_time); /* menue Line1 */ strcpy(str,cmd); strcat(str, menu_name); printf("%s",menu_name); system(str); // Display 1st line // /* menue Line 2 */ strcpy(str,cmd2); strcat(str,Lbuf[num2]); system(str); // Display 2nd line // /* indicate boot finish */ flashLED(rRED,2); flashLED(rGREEN,2); pullUpDnControl(rSW, PUD_UP); pullUpDnControl(rA, PUD_UP); pullUpDnControl(rB, PUD_UP); wiringPiISR(rA, INT_EDGE_BOTH, click_a); wiringPiISR(rB, INT_EDGE_BOTH, click_b); while(setup != -1){ usleep(10000); if(digitalRead(rSW)==0) { // Push SW pressed // printf("[%s %s %s %s %s]\n",menu_name,file_name,freq,s_rate,date_time); // printf("SW_level_stat:%d\n",SW_level_stat); n = 0; digitalWrite(rGREEN,1); // light GREEN LED switch (SW_level_stat){ case 1: // Level setting SW_level_stat=0; num=last_tx; proc(0); break; case 2: // Level setting SW_level_stat=0; num=last_tx; proc(0); break; case 0: // Main menu selection switch (num){ case 0: // Power level setting SW_level_stat=1; // proc(0); break; case 1: // Date&Time setteing SW_level_stat=2; // proc(0); break; case 2: // Fixed Latitude & Longtude setting break; default: ; } proc(0); strcpy(str,file_name); for(i=0;i<100;i++){ str[i]=0x00; } if(atoi(s_rate) !=0){ // sample strcpy(str,path); if(strpos(file_name,".txt")>0 || strpos(file_name,".csv")>0){ strcat(str,"sim_start.sh ");// generate rela-time I/Q data } else { strcat(str,"transmit2.sh "); // Use pre-generated I/Q data // Trim(str); // strcat(str,file_name); // Replay file name } Trim(str); strcat(str,file_name); // Replay file name Trim(str); strcat(str," "); strcpy(str1,Lbuf[num2]); // Replay POWER Trim(str1); strcat(str,str1); // transmit2.sh file_name POWER strcat(str," "); strcat(str,freq); strcat(str," "); Trim(s_rate); strcat(str,s_rate); strcat(str," ");strcat(str,Dbuf[num3]); strcat(str,"&"); // transmit2.sh file_name POWER& Trim(str); last_tx=num; // printf("\n[Tx shell cmd:%s]\n",str); system(str); // 実行 } else { system(file_name); // 単純なshell実行 } break; } while (digitalRead(rSW)==0) { // Waite until SW pressed usleep(1000); n++; if ( n > SW_long ) digitalWrite(rRED,1); } usleep(200000); // Avoid chattering } else { digitalWrite(rGREEN,0); // Now SW released, put off LED } if (n > SW_long ){ // KILL process when SW pushed long duration if(SW_level_stat==0){ system("/home/pi/kill_proc.sh"); digitalWrite(rRED,1); usleep(500000); digitalWrite(rRED,0); n=0; } else { SW_level_stat=0; proc(0); } } now = millis(); if(( now - prev ) > 1000){ // LED update while Tx working tx=tx_blink(tx); prev = now; } } }
int main(void) { // int i, mask1, mask2, mask3 ; // char * filename = "/usr/local/bin/gpio" ; char command[254] ; struct threadParams thrPrm1, thrPrm2; wiringPiSetup() ; strcpy(command, "gpio load i2c 400") ; system (command) ; int fd = wiringPiI2CSetup (0x24) ; if (!fd) { printf ("Failed to initialize I2C\n"); return 1; } thrPrm1.fd = fd; thrPrm2.fd = fd; signal ( SIGINT, sig_handler) ; // wiringPiI2CWriteReg8 (fd, MCP23x17_IOCON, IOCON_INIT) ; // wiringPiI2CWriteReg8 (fd, MCP23x17_IOCON, 0b01100100) ; // mirror interrupts, disable sequential mode, open drain // unsigned int nInt = wiringPiI2CReadReg8 (fd, MCP23x17_IOCON ); // Read // printf("IOCONA="); bin_prnt_byte(nInt); // thrPrm1.old = wiringPiI2CReadReg8 (fd, MCP23x17_OLATA) ; // thrPrm2.old = wiringPiI2CReadReg8 (fd, MCP23x17_OLATB) ; // bin_prnt_byte(thrPrm1.old); // bin_prnt_byte(thrPrm2.old); // set up on INTA on pin 5,6,7 as output` // wiringPiI2CWriteReg8 (fd, MCP23x17_IODIRA, 0xE0) ; strcpy(command, "gpio edge 0 falling") ; system (command) ; pinMode( 0, INPUT) ; pullUpDnControl (0, PUD_UP) ; //digitalWrite (0, HIGH) ; pthread_create( &thrPrm1.tid, NULL, &myThread, &thrPrm1) ; pthread_create( &thrPrm2.tid, NULL, &blinkerThread, &thrPrm2) ; printf("Thread created...\n") ; wiringPiISR( 0, INT_EDGE_FALLING, &ServiceInt) ; printf("Created ISR...\n") ; printf("Waiting for threads to finish...\n") ; pthread_join(thrPrm1.tid, NULL) ; pthread_join(thrPrm2.tid, NULL) ; // strcpy(command,"gpio reset") ; // system (command) ; printf("Exiting...\n") ; return EXIT_SUCCESS; }
/* ********************************************************************************* * dht22_read_int * * Read function based on interrupt processing * argument r describes the repeat index number (meaningful if we have large * numbers of repeats. * This -i option seems to take less time to come to results, however its system time * to reach that result is higher than the original (brute force) timer result. ********************************************************************************* */ int dht22_read_int(int r) { uint8_t j,i; uint8_t linex; int time_interval = 0; int attempts = 0; int result = 0; // We want at least ONE successful read of the sensor values. while ((result == 0) && (attempts++ < 100)) { j=0; stop_ints = 1; // Disable interrupts for the moment time_interval = 0; delay(50); // XXX Necessary? pullUpDnControl (DHT22PIN, PUD_UP); // Start with a HIGH value digitalWrite(DHT22PIN,HIGH); delay(5); // Wait a little, 5 millisec for(i=0; i<5; i++) dht22_val[i]=0; // Initialize result to 0 // Send the request pulse // pinMode(DHT22PIN,OUTPUT); digitalWrite(DHT22PIN,LOW); delay(24); // Wait 18 milli seconds digitalWrite(DHT22PIN,HIGH); delayMicroseconds(18); // Pull up 20-40 uSec // Switch to input mode, enable interrupts // Set pin mode to input pinMode(DHT22PIN,INPUT); piHiPri (10); // Give this program higher interrupt than std stop_ints = 0; //pullUpDnControl (DHT22PIN, PUD_UP); // Set data to a HIGH value // Receive bits, wait for interrupts to finish // start_time = micros(); p_index = 0; // Initialize index edgeTimeStamp[1] = start_time; while (1) { delayMicroseconds(5); time_interval = micros() - start_time; if ( time_interval > 12000 ) // 40 bits * (50+75) usec max = 6000 usec { if (debug) printf("\n\nERROR: Timeout, p_index: %d, interval: %d uSec\n", p_index, time_interval); break; } if ( p_index > 41 ) { if (debug) printf("\n\nERROR: p_index overflow, p_index: %d, interval: %d uSec\n", p_index, time_interval); break; } } start_time = 0; // Reset timer piHiPri (0); linex=0; if (verbose) printf("Printing values, %d found:\n", p_index); for (i=0; i< p_index; i++) { // useless transitions are ignored. But the difference between 0 and 1 is not just the // typical value of 28uSec or 70uSec. This is because the system itself takes time as well to evaluate // transitions if (i>=1) { dht22_val[j/8]<<=1; // Shift one bit to left if (pulse_array[i] > 110) // "0"=50+28 uSec, "1"=50+70uSec { dht22_val[j/8]|=1; // Make lsb 1 (else it remains 0) } j++; } if (verbose) { printf("%3d|", pulse_array[i]); if (linex <= 0) { printf("\n"); linex=8; } linex--; } }// for if (verbose) { printf("\n"); printf("values: "); for (i=0; i<5; i++) { printf("%3d.",dht22_val[i]); } printf("\n"); } // verify checksum and print the verified data humidity = (float) (dht22_val[0]*256+dht22_val[1])/10; temperature = (float) (dht22_val[2]*256+dht22_val[3])/10; if((j>=40)&&(dht22_val[4]==((dht22_val[0]+dht22_val[1]+dht22_val[2]+dht22_val[3])& 0xFF))) { printf("UDP %2d, humidity: %3.1f; temperature: %3.1f; INT. ", r+1, humidity, temperature); if (dflg) { send_2_server(sockfd, humidity, temperature); } else { if (debug) { printf("Invalid Checksum Msg: %2d, humidity: %2.1f; temperature: %2.1f; INT. \n", r+1, humidity, temperature); } }//else result = 1; } else { if (verbose) { printf("Invalid Checksum Msg: %2d, humidity: %2.1f; temperature: %2.1f; INT. \n", r+1, humidity, temperature); } } //delay(1100); // Really necessary? }//while return(attempts); }