Exemple #1
0
void encode_setup(){
    gpio_export(pin_A);
    gpio_export(pin_B);
    gpio_set_dir(pin_A, 0);
    gpio_set_dir(pin_B, 0);
    gpio_set_edge(pin_A, "falling");
    gpio_set_edge(pin_B, "falling");
}
/*********************************************************************************
*	int initialize_button_interrups()
*
*	start 4 threads to handle 4 interrupt routines for pressing and
*	releasing the two buttons.
**********************************************************************************/
int initialize_button_handlers(){
	
	#ifdef DEBUG
	printf("setting up mode & pause gpio pins\n");
	#endif
	//set up mode pin
	if(gpio_export(MODE_BTN)){
		printf("can't export gpio %d \n", MODE_BTN);
		return (-1);
	}
	gpio_set_dir(MODE_BTN, INPUT_PIN);
	gpio_set_edge(MODE_BTN, "both");  // Can be rising, falling or both
	
	//set up pause pin
	if(gpio_export(PAUSE_BTN)){
		printf("can't export gpio %d \n", PAUSE_BTN);
		return (-1);
	}
	gpio_set_dir(PAUSE_BTN, INPUT_PIN);
	gpio_set_edge(PAUSE_BTN, "both");  // Can be rising, falling or both
	
	#ifdef DEBUG
	printf("starting button handling threads\n");
	#endif
	struct sched_param params;
	pthread_attr_t attr;
	params.sched_priority = sched_get_priority_max(SCHED_FIFO)/2;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
   
	set_pause_pressed_func(&null_func);
	set_pause_unpressed_func(&null_func);
	set_mode_pressed_func(&null_func);
	set_mode_unpressed_func(&null_func);
	
	
	pthread_create(&pause_pressed_thread, &attr,			 \
				pause_pressed_handler, (void*) NULL);
	pthread_create(&pause_unpressed_thread, &attr,			 \
				pause_unpressed_handler, (void*) NULL);
	pthread_create(&mode_pressed_thread, &attr,			 \
					mode_pressed_handler, (void*) NULL);
	pthread_create(&mode_unpressed_thread, &attr,			 \
					mode_unpressed_handler, (void*) NULL);
	
	// apply medium priority to all threads
	pthread_setschedparam(pause_pressed_thread, SCHED_FIFO, &params);
	pthread_setschedparam(pause_unpressed_thread, SCHED_FIFO, &params);
	pthread_setschedparam(mode_pressed_thread, SCHED_FIFO, &params);
	pthread_setschedparam(mode_unpressed_thread, SCHED_FIFO, &params);
	 
	return 0;
}
/****************************************************************
 * Main
 ****************************************************************/
int main()
{
    int gpio_fd;
	unsigned int gpio = 68;
	   
    //i2c_init();
    
    //system("chmod 777 /sys/class/gpio");
#if 0    
    system("chmod 777 /sys/class/gpio/export");
    system("echo 68 > export");
    system("chmod 777 /sys/class/gpio/gpio68/direction");
    system("chmod 777 /sys/class/gpio/gpio68/edge");
    system("chmod 777 /sys/class/gpio/gpio68/value");

	gpio_export(gpio);
	gpio_set_dir(gpio, 0);
	gpio_set_edge(gpio, "rising");
	
	gpio_fd = gpio_fd_open(gpio);
	gpio_fd_close(gpio_fd);
#endif
    printf("main finished!");
    	
	return 0;
}
JNIEXPORT jint JNICALL Java_com_robot_et_core_hardware_wakeup_WakeUp_faceWakeUpInit
(JNIEnv *env, jclass cls)
{
    int gpio;
    
    system("setenforce 0");
    system("chmod 777 /sys/class/gpio");
    system("chmod 777 /sys/class/gpio/export");
    system("echo 72 > /sys/class/gpio/export");
    system("chmod 777 /sys/class/gpio/gpio72");
    system("chmod 777 /sys/class/gpio/gpio72/direction");
    system("chmod 777 /sys/class/gpio/gpio72/edge");
    system("chmod 777 /sys/class/gpio/gpio72/value");    
    
    gpio = GPIO_C8;
    
    gpio_export(gpio);
    gpio_set_dir(gpio, 0);
    gpio_set_edge(gpio, (char*)"rising");
    gpioC8_fileId = gpio_fd_open(gpio);
    if (gpioC8_fileId < 0)
    {
        return WAKEUP_FAIL;        
    }

    return gpioC8_fileId;    
}
JNIEXPORT jint JNICALL Java_com_robot_et_core_hardware_wakeup_WakeUp_wakeUpInit
(JNIEnv *env, jclass cls)
{
    int gpio;
    int ret;

    /* i2c init */
    ret = i2c_init();
    if (ret < 0)
    {
        return ret;
    }

    system("setenforce 0");
    system("chmod 777 /sys/class/gpio");
    system("chmod 777 /sys/class/gpio/export");
    system("echo 68 > /sys/class/gpio/export");
    system("chmod 777 /sys/class/gpio/gpio68");
    system("chmod 777 /sys/class/gpio/gpio68/direction");
    system("chmod 777 /sys/class/gpio/gpio68/edge");
    system("chmod 777 /sys/class/gpio/gpio68/value");

    gpio = GPIO_C4;

    gpio_export(gpio);
    gpio_set_dir(gpio, 0);
    gpio_set_edge(gpio, (char*)"rising");
    gpioC4_fileId = gpio_fd_open(gpio);
    if (gpioC4_fileId < 0)
    {
        return WAKEUP_FAIL;        
    }

    return gpioC4_fileId;
}
void remove_edge_detect(unsigned int gpio)
{
    struct epoll_event ev;
    struct gpios *g = get_gpio(gpio);

    if (g == NULL)
        return;

    // delete epoll of fd

    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = g->value_fd;
    epoll_ctl(epfd_thread, EPOLL_CTL_DEL, g->value_fd, &ev);

    // delete callbacks for gpio
    remove_callbacks(gpio);

    // btc fixme - check return result??
    gpio_set_edge(gpio, NO_EDGE);
    g->edge = NO_EDGE;

    if (g->value_fd != -1)
        close(g->value_fd);

    // btc fixme - check return result??
    gpio_unexport(gpio);
    event_occurred[gpio] = 0;

    delete_gpio(gpio);
}
//// MPU9150 IMU ////
int initialize_imu(int sample_rate, signed char orientation[9]){
	printf("Initializing IMU\n");
	//set up gpio interrupt pin connected to imu
	if(gpio_export(INTERRUPT_PIN)){
		printf("can't export gpio %d \n", INTERRUPT_PIN);
		return (-1);
	}
	gpio_set_dir(INTERRUPT_PIN, INPUT_PIN);
	gpio_set_edge(INTERRUPT_PIN, "falling");  // Can be rising, falling or both
		
	linux_set_i2c_bus(1);

	
	if (mpu_init(NULL)) {
		printf("\nmpu_init() failed\n");
		return -1;
	}
 
	mpu_set_sensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS);
	mpu_set_sample_rate(sample_rate);
	
	// compass run at 100hz max. 
	if(sample_rate > 100){
		// best to sample at a fraction of the gyro/accel
		mpu_set_compass_sample_rate(sample_rate/2);
	}
	else{
		mpu_set_compass_sample_rate(sample_rate);
	}
	mpu_set_lpf(188); //as little filtering as possible
	dmp_load_motion_driver_firmware(sample_rate);

	dmp_set_orientation(inv_orientation_matrix_to_scalar(orientation));
  	dmp_enable_feature(DMP_FEATURE_6X_LP_QUAT | DMP_FEATURE_SEND_RAW_ACCEL 
						| DMP_FEATURE_SEND_CAL_GYRO | DMP_FEATURE_GYRO_CAL);

	dmp_set_fifo_rate(sample_rate);
	
	if (mpu_set_dmp_state(1)) {
		printf("\nmpu_set_dmp_state(1) failed\n");
		return -1;
	}
	if(loadGyroCalibration()){
		printf("\nGyro Calibration File Doesn't Exist Yet\n");
		printf("Use calibrate_gyro example to create one\n");
		printf("Using 0 offset for now\n");
	};
	
	// set the imu_interrupt_thread to highest priority since this is used
	// for real-time control with time-sensitive IMU data
	set_imu_interrupt_func(&null_func);
	pthread_t imu_interrupt_thread;
	struct sched_param params;
	pthread_create(&imu_interrupt_thread, NULL, imu_interrupt_handler, (void*) NULL);
	params.sched_priority = sched_get_priority_max(SCHED_FIFO);
	pthread_setschedparam(imu_interrupt_thread, SCHED_FIFO, &params);
	
	return 0;
}
Exemple #8
0
/****************************************************************
 * Main
 ****************************************************************/
int main(int argc, char **argv, char **envp)
{
        struct pollfd fdset;
        int nfds = 1;
        int gpio_in_fd, gpio_out_fd, timeout, rc, value;
        unsigned int gpio_in, gpio_out;
        unsigned long cntr = 0;

        if (argc < 3) {
                printf("Usage: gpio-int <gpio-input-pin> <gpio-output-pin>\n\n");
                printf("Waits for a change in the GPIO pin voltage level and copy its value to output pin\n");
                exit(-1);
        }

        gpio_in = atoi(argv[1]);
        gpio_out = atoi(argv[2]);

        /* initialize input pin */
        gpio_export(gpio_in);
        gpio_set_dir(gpio_in, 0);
        gpio_set_edge(gpio_in, "both");
        gpio_in_fd = gpio_fd_open(gpio_in);

        /* initialize output pin */
        gpio_export(gpio_out);
        gpio_set_dir(gpio_out, 1);
        gpio_out_fd = gpio_fd_open(gpio_out);

        timeout = POLL_TIMEOUT;

        while (1) {
                memset(&fdset, 0, sizeof(fdset));
      
                fdset.fd = gpio_in_fd;
                fdset.events = POLLPRI;

                rc = poll(&fdset, nfds, timeout);

                if (rc < 0) {
                        printf("\npoll() failed!\n");
                        return -1;
                }

                if (fdset.revents & POLLPRI) {
                        printf("\r%lu", ++cntr);
                        gpio_get_value(gpio_in, &value);
                        gpio_set_value(gpio_out, value);
                }

                fflush(stdout);
        }

        gpio_fd_close(gpio_in_fd);
        gpio_fd_close(gpio_out_fd);
        return 0;
}
Exemple #9
0
int sj_gpio_intr_set(int pin, enum gpio_int_mode type) {
  if (type == GPIO_INTR_DISABLE) {
    gpio_remove_handler(pin);
    return 0;
  }

  if (gpio_set_edge(pin, type) < 0) {
    return -1;
  }

  return gpio_set_handler(pin, proxy_handler);
}
Exemple #10
0
int gpio_input_trap_proc()
{
    int shutdown_fd = -1;
    int gpio_shutdown;
    char *buf[MAX_BUF];
    fd_set exceptfds;
    int res;

    gpio_shutdown = GetGpioNumberByFuncName("shutdownSwitch");

    if (-1 != gpio_shutdown) {
        LOG(LOG_NOTICE, "set shutdownSwitch on GPIO %d", gpio_shutdown);
        gpio_export(gpio_shutdown);
        gpio_set_dir(gpio_shutdown, 2);
        gpio_set_value(gpio_shutdown, 1);
        gpio_set_edge(gpio_shutdown, "both");
        //shutdown_fd = gpio_fd_open(gpio_shutdown);
    } else {
        LOG(LOG_NOTICE, "No set shutdownSwitch on GPIO pin");
        return 0;
    }

    // Trap an output GPIO is restric by GPIO driver in Linux kernel
    //   https://github.com/torvalds/linux/commit/d468bf9ecaabd3bf3a6134e5a369ced82b1d1ca1
    // /var/log/kern.log shows:
    //    GPIO chip pinctrl-bcm2835: gpio_lock_as_irq: tried to flag a GPIO set as output for IRQ
    //    gpio-18 (sysfs): failed to flag the GPIO for IRQ
    // But with dummy read() it still works, however if we use poll() to trap POLLPRI
    // system could freeze (could be kernel bugs)
    while (1) {
        shutdown_fd = gpio_fd_open(gpio_shutdown);

        FD_ZERO(&exceptfds);
        FD_SET(shutdown_fd, &exceptfds);
        read(shutdown_fd, buf, MAX_BUF); //dummy read(); any newly opened file is considered changed.

        res = select(shutdown_fd+1,
                     NULL,               // readfds - not needed
                     NULL,               // writefds - not needed
                     &exceptfds,
                     NULL);              // timeout (never)
        if (res > 0 && FD_ISSET(shutdown_fd, &exceptfds)) {
            if (gpio_get_value(gpio_shutdown) == 0) {
                LOG(LOG_NOTICE, "get shutdown signal from GPIO %d", gpio_shutdown);
                Shutdown();
            }
        }
        gpio_fd_close(shutdown_fd);
        read(shutdown_fd, buf, MAX_BUF);
    }

    return 0;
}
int add_edge_detect(unsigned int gpio, unsigned int edge, int bouncetime)
// return values:
// 0 - Success
// 1 - Edge detection already added
// 2 - Other error
{
    pthread_t threads;
    struct epoll_event ev;
    long t = 0;
    struct gpios *g;
    int i = -1;

    i = gpio_event_added(gpio);
    if (i == 0) {    // event not already added
        if ((g = new_gpio(gpio)) == NULL)
            return 2;

        gpio_set_edge(gpio, edge);
        g->edge = edge;
        g->bouncetime = bouncetime;
    } else if (i == edge) {  // get existing event
        g = get_gpio(gpio);
        if ((bouncetime != -666 && g->bouncetime != bouncetime) ||  // different event bouncetime used
            (g->thread_added))                // event already added
            return 1;
    } else {
        return 1;
    }

    // create epfd_thread if not already open
    if ((epfd_thread == -1) && ((epfd_thread = epoll_create(1)) == -1))
        return 2;

    // add to epoll fd
    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = g->value_fd;
    if (epoll_ctl(epfd_thread, EPOLL_CTL_ADD, g->value_fd, &ev) == -1) {
        remove_edge_detect(gpio);
        return 2;
    }
    g->thread_added = 1;

    // start poll thread if it is not already running
    if (!thread_running) {
        if (pthread_create(&threads, NULL, poll_thread, (void *)t) != 0) {
           remove_edge_detect(gpio);
           return 2;
        }
    }
    return 0;
}
int add_edge_detect(unsigned int gpio, unsigned int edge)
// return values:
// 0 - Success
// 1 - Edge detection already added
// 2 - Other error
{
    int fd = fd_lookup(gpio);
    pthread_t threads;
    struct epoll_event ev;
    long t = 0;

    // check to see if this gpio has been added already
    if (gpio_event_add(gpio) != 0)
        return 1;

    // export /sys/class/gpio interface
    gpio_export(gpio);
    gpio_set_direction(gpio, 1); // 1=input
    gpio_set_edge(gpio, edge);

    if (!fd)
    {
        if ((fd = open_value_file(gpio)) == -1)
            return 2;
    }

    // create epfd if not already open
    if ((epfd == -1) && ((epfd = epoll_create(1)) == -1))
        return 2;

    // add to epoll fd
    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = fd;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1)
        return 2;

    // start poll thread if it is not already running
    if (!thread_running)
    {
        if (pthread_create(&threads, NULL, poll_thread, (void *)t) != 0)
            return 2;
    }

    return 0;
}
Exemple #13
0
int add_edge_detect(unsigned int gpio, unsigned int edge, unsigned int bouncetime)
// return values:
// 0 - Success
// 1 - Edge detection already added
// 2 - Other error
{
    pthread_t threads;
    struct epoll_event ev;
    long t = 0;
    struct gpios *g;
    
    // check to see if this gpio has been added already
    if (gpio_event_added(gpio) != 0)
        return 1;

    // create epfd if not already open
    if ((epfd == -1) && ((epfd = epoll_create(1)) == -1))
        return 2;

    if ((g = new_gpio(gpio)) == NULL)
        return 2;
    
    gpio_set_edge(gpio, edge);
    g->bouncetime = bouncetime;

    // add to epoll fd
    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = g->value_fd;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, g->value_fd, &ev) == -1) {
        remove_edge_detect(gpio);
        return 2;
    }

    // start poll thread if it is not already running
    if (!thread_running) {
        if (pthread_create(&threads, NULL, poll_thread, (void *)t) != 0) {
           remove_edge_detect(gpio);
           return 2;
        }
    }
    return 0;
}
void remove_edge_detect(unsigned int gpio)
{
    struct epoll_event ev;
    int fd = fd_lookup(gpio);

    // delete callbacks for gpio
    remove_callbacks(gpio);

    // delete epoll of fd
    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);

    // set edge to none
    gpio_set_edge(gpio, NO_EDGE);

    // unexport gpio
    gpio_event_remove(gpio);

    // clear detected flag
    event_occurred[gpio] = 0;
}
bool iotjs_gpio_open(iotjs_gpio_t* gpio) {
  IOTJS_VALIDATED_STRUCT_METHOD(iotjs_gpio_t, gpio);

  DDDLOG("%s - pin: %d, dir: %d, mode: %d", __func__, _this->pin,
         _this->direction, _this->mode);

  // Open GPIO pin.
  char exported_path[GPIO_PATH_BUFFER_SIZE];
  snprintf(exported_path, GPIO_PATH_BUFFER_SIZE, GPIO_PIN_FORMAT, _this->pin);

  const char* created_files[] = { GPIO_DIRECTION, GPIO_EDGE, GPIO_VALUE };
  int created_files_length = sizeof(created_files) / sizeof(created_files[0]);

  if (!iotjs_systemio_device_open(GPIO_PIN_FORMAT_EXPORT, _this->pin,
                                  exported_path, created_files,
                                  created_files_length)) {
    return false;
  }

  // Set direction.
  if (!gpio_set_direction(_this->pin, _this->direction)) {
    return false;
  }

  // Set mode.
  if (!gpio_set_mode(_this->pin, _this->mode)) {
    return false;
  }

  // Set edge.
  if (!gpio_set_edge(gpio)) {
    return false;
  }

  return true;
}
int blocking_wait_for_edge(unsigned int gpio, unsigned int edge)
// standalone from all the event functions above
{
    int fd = fd_lookup(gpio);
    int epfd, n, i;
    struct epoll_event events, ev;
    char buf;

    if ((epfd = epoll_create(1)) == -1)
        return 1;

    // check to see if this gpio has been added already, if not, mark as added
    if (gpio_event_add(gpio) != 0)
        return 2;

    // export /sys/class/gpio interface
    gpio_export(gpio);
    gpio_set_direction(gpio, 1); // 1=input
    gpio_set_edge(gpio, edge);

    if (!fd)
    {
        if ((fd = open_value_file(gpio)) == -1)
            return 3;
    }

    // add to epoll fd
    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = fd;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1)
    {
        gpio_event_remove(gpio);
        return 4;
    }

    // epoll for event
    for (i = 0; i<2; i++) // first time triggers with current state, so ignore
       if ((n = epoll_wait(epfd, &events, 1, -1)) == -1)
       {
           gpio_event_remove(gpio);
           return 5;
       }

    if (n > 0)
    {
        lseek(events.data.fd, 0, SEEK_SET);
        if (read(events.data.fd, &buf, 1) != 1)
        {
            gpio_event_remove(gpio);
            return 6;
        }
        if (events.data.fd != fd)
        {
            gpio_event_remove(gpio);
            return 7;
        }
    }

    gpio_event_remove(gpio);
    close(epfd);
    return 0;
}
int main(int argc, char *argv[])
{
	int ret = 0;
	int fd;
	int sysfs_fd;

	int no_tty = !isatty( fileno(stdout) );

	fd = open(device, O_RDWR);
	if (fd < 0)
		pabort("can't open device");

	/*
	 * spi mode
	 */
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		pabort("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
	if (ret == -1)
		pabort("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");

	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");

	fprintf(stderr, "spi mode: %d\n", mode);
	fprintf(stderr, "bits per word: %d\n", bits);

	// enable master clock for the AD
	// divisor results in roughly 4.9MHz
	// this also inits the general purpose IO
	gz_clock_ena(GZ_CLK_5MHz,5);

	// enables sysfs entry for the GPIO pin
	gpio_export(drdy_GPIO);
	// set to input
	gpio_set_dir(drdy_GPIO,0);
	// set interrupt detection to falling edge
	gpio_set_edge(drdy_GPIO,"falling");
	// get a file descriptor for the GPIO pin
	sysfs_fd = gpio_fd_open(drdy_GPIO);

	// resets the AD7705 so that it expects a write to the communication register
        printf("sending reset\n");
	writeReset(fd);

	// tell the AD7705 that the next write will be to the clock register
	writeReg(fd,0x20);
	// write 00001100 : CLOCKDIV=1,CLK=1,expects 4.9152MHz input clock
	writeReg(fd,0x0C);
	

	//channel1
	writeReg(fd,0x11);
	// intiates a self calibration and then after that starts converting
	writeReg(fd,0x40);
	  ret = gpio_poll(sysfs_fd,1000);
	  if (ret<1) {
	    fprintf(stderr,"Poll error chennel1 set-up %d\n",ret);
	  }
	
	//channel0
	// tell the AD7705 that the next write will be the setup register
	writeReg(fd,0x10);
	// intiates a self calibration and then after that starts converting
	writeReg(fd,0x40);
		  ret = gpio_poll(sysfs_fd,1000);
	  if (ret<1) {
	    fprintf(stderr,"Poll error chennel0 set-up %d\n",ret);
	  }

	// we read data in an endless loop and display it
	// this needs to run in a thread ideally
	while (1) {

	 //channel0
	  // tell the AD7705 to read the data register (16 bits)
	  writeReg(fd,0x38);
	  	  ret = gpio_poll(sysfs_fd,1000);
	  if (ret<1) {
	    fprintf(stderr,"Poll error read data channel0 %d\n",ret);
	  }

	  // read the data register by performing two 8 bit reads
	  int value0 = readData(fd)-0x8000;
		

	   //channel1
	  // tell the AD7705 to read the data register (16 bits)
	  writeReg(fd,0x39);
	  	  ret = gpio_poll(sysfs_fd,1000);
	  if (ret<1) {
	    fprintf(stderr,"Poll error read data channel0 %d\n",ret);
	  }

	  // read the data register by performing two 8 bit reads
	  int value1 = readData(fd)-0x8000;
		fprintf(stderr,"data0 = %d data1 = %d      \r",value0,value1);

	

	}

	close(fd);
	gpio_fd_close(sysfs_fd);

	return ret;
}
Exemple #18
0
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[7];
	int nfds = 7;
	int gpio_fd1, gpio_fd2, gpio_fd3, gpio_fd4,gpio_fd5,gpio_fd6, timeout, rc;
	char buf[MAX_BUF];
	unsigned int gpio;
	int len;
	char board[HEIGHT][WIDTH];
	int xpos=WIDTH/2;
	int ypos=HEIGHT/2;
        int row;
	int col;
	int colorint=0;
	char color[]={'x','y','z'};	
	for(row=0;row<HEIGHT;row++){
		printf("\n");
		for(col=0;col<WIDTH;col++){
			board[row][col]=' ';
		}
	}

	int res, i2cbus, address, file;
	char filename[20];
	int force = 0;

	i2cbus = lookup_i2c_bus("1");
	printf("i2cbus = %d\n", i2cbus);
	if (i2cbus < 0)
		help();

	address = parse_i2c_address("0x70");
	printf("address = 0x%2x\n", address);
	if (address < 0)
		help();

	file = open_i2c_dev(i2cbus, filename, sizeof(filename), 0);
//	printf("file = %d\n", file);
	if (file < 0
	 || check_funcs(file)
	 || set_slave_addr(file, address, force))
		exit(1);

	// Check the return value on these if there is trouble
	i2c_smbus_write_byte(file, 0x21); // Start oscillator (p10)
	i2c_smbus_write_byte(file, 0x81); // Disp on, blink off (p11)
	i2c_smbus_write_byte(file, 0xe7); // Full brightness (page 15)

//	Display a series of pictures
	

	system("/home/root/homework3/i2csetup.sh");
	board[xpos][ypos]='x';
	printboard(board,file,colorint);
	//printf("wgat");
	/*if (argc < 2) {
		printf("Usage: gpio-int <gpio-pin>\n\n");
		printf("Waits for a change in the GPIO pin voltage level or input on stdin\n");


		FILE* f = fopen("/sys/class/leds/beaglebone\:green\:usr0/brightness", "w");
                FILE* trig = fopen("/sys/class/leds/beaglebone\:green\:usr0/trigger", "w");
 
    		if (trig == NULL){
			printf("oops\n");        			
			exit(EXIT_FAILURE);
		}
    		fprintf(trig, "none");
    		fclose(trig);
		if (fled== NULL){
			printf("oops\n");        			
			exit(EXIT_FAILURE);
		}
		printf("should light up\n");
    		fprintf(fled, "1");
    		fclose(fled);
		usleep(10000000);
		exit(-1);
	}
		*/
	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);


	gpio_export(GPIOIN1);
	gpio_set_dir(GPIOIN1, "in");
	gpio_set_edge(GPIOIN1, "both");  // Can be rising, falling or both
	gpio_fd1 = gpio_fd_open(GPIOIN1, O_RDONLY);

	gpio_export(GPIOIN2);
	gpio_set_dir(GPIOIN2, "in");
	gpio_set_edge(GPIOIN2, "both");  // Can be rising, falling or both
	gpio_fd2 = gpio_fd_open(GPIOIN2, O_RDONLY);
	gpio_export(GPIOIN3);
	gpio_set_dir(GPIOIN3, "in");
	gpio_set_edge(GPIOIN3, "both");  // Can be rising, falling or both
	gpio_fd3 = gpio_fd_open(GPIOIN3, O_RDONLY);

	gpio_export(GPIOIN4);
	gpio_set_dir(GPIOIN4, "in");
	gpio_set_edge(GPIOIN4, "both");  // Can be rising, falling or both
	gpio_fd4 = gpio_fd_open(GPIOIN4, O_RDONLY);

	gpio_export(GPIOIN5);
	gpio_set_dir(GPIOIN5, "in");
	gpio_set_edge(GPIOIN5, "both");  // Can be rising, falling or both
	gpio_fd5 = gpio_fd_open(GPIOIN5, O_RDONLY);

	gpio_export(GPIOIN6);
	gpio_set_dir(GPIOIN6, "in");
	gpio_set_edge(GPIOIN6, "both");  // Can be rising, falling or both
	gpio_fd6 = gpio_fd_open(GPIOIN6, O_RDONLY);

	timeout = POLL_TIMEOUT;
 	FILE* f0 = fopen("/sys/class/leds/beaglebone:green:usr0/trigger", "w");
	FILE* f1 = fopen("/sys/class/leds/beaglebone:green:usr1/trigger", "w");
	FILE* f2 = fopen("/sys/class/leds/beaglebone:green:usr2/trigger", "w");
	FILE* f3 = fopen("/sys/class/leds/beaglebone:green:usr3/trigger", "w");

    	if (f0 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f0, "none");
	fclose(f0);

	if (f1 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f1, "none");
	fclose(f1);

	if (f2 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f2, "none");
	fclose(f2);
	
	if (f3 == NULL){
		exit(EXIT_FAILURE);
	}
	fprintf(f3, "none");
	fclose(f3);
	
			
	while (keepgoing) {
		memset((void*)fdset, 0, sizeof(fdset));
		
		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_fd1;
		fdset[1].events = POLLPRI;

		fdset[2].fd = gpio_fd2;
		fdset[2].events = POLLPRI;

		fdset[3].fd = gpio_fd3;
		fdset[3].events = POLLPRI;

		fdset[4].fd = gpio_fd4;
		fdset[4].events = POLLPRI;

		fdset[5].fd = gpio_fd5;
		fdset[5].events = POLLPRI;

		fdset[6].fd = gpio_fd6;
		fdset[6].events = POLLPRI;


		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
      
		
            
		if (fdset[1].revents & POLLPRI) {
			lseek(fdset[1].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[1].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr3/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				fprintf(f, "1");
				if((xpos+1)<WIDTH){
					board[xpos+1][ypos]='x';
					xpos++;
				}
				printboard(board,file,colorint);
			}
			fclose(f);
				
		}
		if (fdset[2].revents & POLLPRI) {
			lseek(fdset[2].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[2].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr2/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				fprintf(f, "1");
				if((xpos-1)>=0){
					board[xpos-1][ypos]='x';
					xpos--;
				}
				
				printboard(board,file,colorint);

			}
			fclose(f);
				
		}
		if (fdset[3].revents & POLLPRI) {
			lseek(fdset[3].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[3].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr1/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				if((ypos+1)<HEIGHT){
					board[xpos][ypos+1]='x';
					ypos++;
				}
				printboard(board,file,colorint);
				fprintf(f, "1");
			}
			fclose(f);
				
		}
		if (fdset[4].revents & POLLPRI) {
			lseek(fdset[4].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[4].fd, buf, MAX_BUF);
			FILE* f = fopen("/sys/class/leds/beaglebone:green:usr0/brightness", "w");
 
    			if (f == NULL){        			
				exit(EXIT_FAILURE);
			}
			if (buf[0]=='1'){
				fprintf(f, "0");
			}
			if (buf[0]=='0'){
				if((ypos-1)>=0){
					board[xpos][ypos-1]='x';
					ypos--;
				}
				printboard(board,file,colorint);
				fprintf(f, "1");

			}
			fclose(f);
				
		}
		if (fdset[5].revents & POLLPRI) {
			lseek(fdset[5].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[5].fd, buf, MAX_BUF);
			
			if (buf[0]=='0'){
				for(row=0;row<HEIGHT;row++){
				printf("\n");
					for(col=0;col<WIDTH;col++){
						board[row][col]=' ';
					}
					printf("\n");
					system("i2cget -y 1 0x48 0");
					printboard(board,file,colorint);
				}
				
				

			}
			
				
		}
		if (fdset[6].revents & POLLPRI) {
			lseek(fdset[6].fd, 0, SEEK_SET);  // Read from the start of the file
			read(fdset[6].fd, buf, MAX_BUF);
			
			if (buf[0]=='0'){
				if(colorint<=0){
					colorint++;
				}else{
					colorint=0;
				}
				printf("\n");
				system("i2cget -y 1 0x4a 0");
				printboard(board,file,colorint);

			}
			
			
			
				
		}
		/*if (fdset[0].revents & POLLIN) {
			(void)read(fdset[0].fd, buf, 1);
			printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
		}*/
		
		
		
		fflush(stdout);
	}
	
	
	gpio_fd_close(gpio_fd1);
	gpio_fd_close(gpio_fd2);
	gpio_fd_close(gpio_fd3);
	gpio_fd_close(gpio_fd4);
	return 0;
}
Exemple #19
0
int main(int argc, char *argv[])
{

  HueLightResponse *hueLightResponder= NULL;
  HueIPResponse *IPAddr= new HueIPResponse("https://www.meethue.com/api/nupnp");
  http.AddRequest(IPAddr);

  int state = HUE_STATE_NEED_IP;

        struct pollfd fdset[2];
        int nfds = 2;
        int gpio_fd, timeout, rc;
        char *buf[MAX_BUF];
        unsigned int interrupt_line= 17;/*17;*/
        unsigned int reset_line= 4;
        int len;
        int counter=0;

	Stream *theLog = new linuxLog();
        afSPI *theSPI = new linuxSPI();

        gpio_export(interrupt_line);
        gpio_set_dir(interrupt_line, 0);
        gpio_set_edge(interrupt_line, "falling");
        gpio_fd = gpio_fd_open(interrupt_line);

        timeout = POLL_TIMEOUT;

        fprintf(stdout,"Test\n");

        theLib = iafLib::create(0,isr_callback,onAttributeSet_callback,onAttributeSetComplete_callback,theLog,theSPI);
        theLib->mcuISR();

/* we need to hook up and use the reset line */
        gpio_export(reset_line);
        gpio_set_dir(reset_line, 1);
	gpio_set_value(reset_line,0);
    
        timespec sleep_time;
        timespec remaining;
        sleep_time.tv_sec=0;
        sleep_time.tv_nsec=250000;
        nanosleep(&sleep_time,&remaining);
         /* check for E_INTR? and call again? */
	gpio_set_value(reset_line,1);

        while (1) {
                counter++;
                memset((void*)fdset, 0, sizeof(fdset));

                fdset[0].fd = STDIN_FILENO;
                fdset[0].events = POLLIN;

                fdset[1].fd = gpio_fd;
                fdset[1].events = POLLPRI;

                lseek(gpio_fd, 0, SEEK_SET);    /* consume any prior interrupt */
                read(gpio_fd, buf, sizeof (buf));


                rc = poll(fdset, nfds, timeout);

                if (rc < 0) {
                        printf("\npoll() failed!\n");
                        return -1;
                }

                if (rc == 0) {
                        printf(".");
                }

                if (fdset[1].revents & POLLPRI) {
                        len = read(fdset[1].fd, buf, MAX_BUF);
                        printf("\npoll() GPIO %d interrupt occurred\n", interrupt_line);
                lseek(gpio_fd, 0, SEEK_SET);    /* consume interrupt */
                read(gpio_fd, buf, sizeof (buf));

                        theLib->mcuISR();
                }

                if (fdset[0].revents & POLLIN) {
                        (void)read(fdset[0].fd, buf, 1);
                        //printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
                }



		switch (state)
		{
		   case HUE_STATE_NEED_IP:
			// we need to check and see if we have an IP, then we can switch
  			if (IPAddr->completed())
{
                          state = HUE_STATE_HAS_IP;
                          IPAddr->get_ip(hue_ip);
                        fprintf(stderr,"IP: %s\n",hue_ip);
			sprintf(hue_prefix,"http://%s/api/huelibrary/",hue_ip);
                        state = HUE_STATE_HAS_IP;
}
			break;
		   case HUE_STATE_HAS_IP:

                // every so many loops check and start the lights query to update the lights..
		if (counter % 100 == 0)
                {
                   //check to see how many HTTP requests are outstanding
                   if (hueLightResponder == NULL)
                   { 
printf("****initializing new request to get the lights\n");
                      char hue_request[1024];
                      sprintf(hue_request,"%slights",hue_prefix);
                      hueLightResponder =  new HueLightResponse(hue_request,theLib);
                      http.AddRequest(hueLightResponder);
                   }
                   else if (hueLightResponder->completed())
                   {
                      delete hueLightResponder;
                      char hue_request[1024];
                      sprintf(hue_request,"%slights",hue_prefix);
                      hueLightResponder =  new HueLightResponse(hue_request,theLib);
                      http.AddRequest(hueLightResponder);
                   }
                  

                }

                }

  	http.Update();
  	http.Status();
        theLib->loop();
        fflush(stdout);
        }

    gpio_fd_close(gpio_fd);
   return 0;
}
int wiringOliISR (int pin, char *pinName, int mode, void (*function)(void))
{
  pthread_t threadId ;
  pthread_attr_t attr;
  char *modeS ;
  char fName   [64] ;
//  char  pinS [8] ;
//  pid_t pid ;
  int   count, i ;
  char  c ;
  int   bcmGpioPin ;
  // char pinName[10] = {};

  bcmGpioPin = pinGpio(pin) ;

  if (mode != INT_EDGE_SETUP)
  {
    /**/ if (mode == INT_EDGE_FALLING)
      modeS = "falling" ;
    else if (mode == INT_EDGE_RISING)
      modeS = "rising" ;
    else
      modeS = "both" ;

    // There's really no need to fork now,
    // as we're no longer using gpio utility here!
    // if ((pid = fork ()) < 0) {
    //   printf("Failed to fork!\n");
    //   return -1;
    // }

    // if (pid == 0) // Child, exec
    // {
      gpio_export(bcmGpioPin);
      gpio_set_dir(bcmGpioPin, 0, pinName);
      gpio_set_edge(bcmGpioPin, modeS, pinName);
      // sysFds [bcmGpioPin] = gpio_fd_open(bcmGpioPin, pinName);
    // }
    // else    // Parent, wait
    //   wait (NULL) ;
  }

  if (sysFds [bcmGpioPin] == -1)
  {
    sprintf (fName, "/sys/class/gpio/gpio%d%s/value", bcmGpioPin, pinName) ;
    // printf("Opening %s for ISR!\n", fName);
    // if ((sysFds [bcmGpioPin] = open (fName, O_RDWR)) < 0) {
    if ((sysFds [bcmGpioPin] = gpio_fd_open (bcmGpioPin, pinName)) < 0) {
      printf("Failed to gpio_fd_open!\n");
      return -1;
    }
  }

// Clear any initial pending interrupt

  ioctl (sysFds [bcmGpioPin], FIONREAD, &count) ;
  for (i = 0 ; i < count ; ++i)
    read (sysFds [bcmGpioPin], &c, 1) ;

  isrFunctions [bcmGpioPin] = function ;
  pinPass = bcmGpioPin ;
  strcpy(pinPassName, pinName);

  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  pthread_mutex_lock (&pinMutex) ;

  pthread_create (&threadId, &attr, interruptHandler, NULL) ;
  while (pinPass != -1)
    delay (1) ;

  pthread_mutex_unlock (&pinMutex) ;
  pthread_attr_destroy ( &attr );

  return 0 ;
}
Exemple #21
0
/****************************************************************
 * Main
 ****************************************************************/
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[2];
	int nfds = 2;
	int gpio_fd, timeout, rc;
	char *buf[MAX_BUF];
	unsigned int gpio;
	int len;



	if (argc < 2) {
		printf("Usage: gpio-int <gpio-pin>\n\n");
		printf("Waits for a change in the GPIO pin voltage level or input on stdin\n");
		exit(-1);
	}

	gpio = atoi(argv[1]);

	gpio_export(gpio);
	gpio_set_dir(gpio, 0);
	gpio_set_edge(gpio, "rising");
	gpio_fd = gpio_fd_open(gpio);

	timeout = POLL_TIMEOUT;
 
	while (1) {
		memset((void*)fdset, 0, sizeof(fdset));

		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_fd;
		fdset[1].events = POLLPRI;

		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
      
		if (rc == 0) {
			printf(".");
		}
            
		if (fdset[1].revents & POLLPRI) {
			len = read(fdset[1].fd, buf, MAX_BUF);
			printf("\npoll() GPIO %d interrupt occurred\n", gpio);
		}

		if (fdset[0].revents & POLLIN) {
			(void)read(fdset[0].fd, buf, 1);
			printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
		}

		fflush(stdout);
	}

	gpio_fd_close(gpio_fd);
	return 0;
}
int main(int argc, char *argv[]){
	//The gpio port numbers needed to drive the motor
	unsigned int gpio1 = 30;
	unsigned int gpio2 = 31;
	unsigned int gpio3 = 48;
	unsigned int gpio4 = 51;
	unsigned int gpio5 = 15;
	unsigned int gpios[4] = {gpio1, gpio2, gpio3, gpio4};
	int gpio_fd1, gpio_fd2, gpio_fd3, gpio_fd4, gpio_fd5;
	int behavior = atoi(argv[1]);
	int rc;
	int len;
	int nfds = 2;
	//Port numbers for the analog in
	char AnalogIn1[] = "AIN0";
	char AnalogIn2[] = "AIN1";
	//char analogs[] = {AnalogIn1, AnalogIn2};
	//printf("checking init analogs: %s \n", analogs[0]);
	char buf[64];
	//Arrays to hold the values we get back from the sensors
	struct pollfd fdset[2];
	int Sensor1_val;
	int Sensor2_val;
	//int Sensor_sum;
	
	int mode = atoi(argv[1]);
	
	//Initializes the position as zero, but we dont really know where this is
	int pos = 0;
	
	//Set up the gpios so we can use them to drive the motor
	gpio_export(gpio1);
	gpio_export(gpio2);
	gpio_export(gpio3);
	gpio_export(gpio4);
	gpio_export(gpio5);
	
	gpio_set_dir(gpio1, "out");
	gpio_set_dir(gpio2, "out");
	gpio_set_dir(gpio3, "out");
	gpio_set_dir(gpio4, "out");
	gpio_set_dir(gpio5, "in");
	
	gpio_set_edge(gpio5, "rising");
	
	gpio_fd1 = gpio_fd_open(gpio1, O_RDONLY);
	gpio_fd2 = gpio_fd_open(gpio2, O_RDONLY);
	gpio_fd3 = gpio_fd_open(gpio3, O_RDONLY);
	gpio_fd4 = gpio_fd_open(gpio4, O_RDONLY);
	gpio_fd5 = gpio_fd_open(gpio5, O_RDONLY);
	
	int cycle = 0;
	int minValue = 999999;
	int minPosition = 0;
	int Sensor_avg = 0;
	
	
	//Wait for the start button to be pushed before we acutally start doing anything
	printf("Press the start button to begin the program \n");
	len = read(gpio_fd5, buf, 64);
	while(1){
		memset((void*)fdset, 0, sizeof(fdset));
		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
		fdset[1].fd = gpio_fd5;
		fdset[1].events = POLLPRI;
		
		rc = poll(fdset, nfds, 3000);
		
		if(rc < 0){
			printf("Poll failed \n");
		}
		if(fdset[1].revents & POLLPRI){
			lseek(fdset[1].fd, 0, SEEK_SET);
			len = read(fdset[1].fd, buf, 64);
			printf("Triggered \n");
			//pos = problemOne(gpios, pos);
			pos = problemTwo(gpios, AnalogIn1, AnalogIn2, pos, mode);
			//break;
		}
		
		
	}
	
	
	
	
	
	
	
	
	printf("Begining our steps to attempt to come up with ");
	for(cycle = 0; cycle <= MAX_CYCLES; cycle++){
		printf("One cycle number: %d", cycle);
		Sensor1_val = analogIn(AnalogIn1);
		Sensor2_val = analogIn(AnalogIn2);
		Sensor_avg = (Sensor1_val + Sensor2_val)/ 2;
		if(Sensor_avg < minValue){
			minValue = Sensor_avg;
			minPosition = cycle;
		}
		//Should move the IR sensors here
	}
	
	printf("%d\n", minValue);
	
	if(minPosition <=10){
		//Rotate clockwise to position
	}
	else{
		//Rotate counterclockwise to position
	}
	
	while(1){
		Sensor1_val = analogIn(AnalogIn1);
		Sensor2_val = analogIn(AnalogIn2);
		if(Sensor1_val > Sensor2_val){
			//Rotate clockwise once
		}
		else{
			//Rotate counterclockwise 
		}
	}
	
	return 0;
}
Exemple #23
0
int main(int argc, char **argv, char **envp)
{
	signal(SIGINT, signal_handler);

	int i;	

	int buttons[] = BUTTON_GPIO_PINS;
	int button_size = sizeof(buttons)/sizeof(buttons[0]);
	int button_active_edges[] = BUTTON_ACTIVE_EDGES;
	
	int leds[] = LED_GPIO_PINS;
	int led_size = sizeof(leds)/sizeof(leds[0]);

	struct pollfd fdset[button_size];
	int nfds = 4;	

	int gpio_fd[button_size + led_size];
	for(i = 0; i < button_size; i++)
	{
		gpio_export(buttons[i]);
		gpio_set_dir(buttons[i], "in");
		gpio_set_edge(buttons[i], "both");
		gpio_fd[i] = gpio_fd_open(buttons[i], O_RDONLY);
	}
	for(i = 0; i < led_size; i++)
	{
		gpio_export(leds[i]);
		gpio_set_dir(leds[i], "out");
		gpio_fd[i+4] = gpio_fd_open(leds[i], O_RDONLY);
	}

	while(keepgoing)
	{
		memset((void*)fdset, 0, sizeof(fdset));
		for(i = 0; i < button_size; i++)
		{		
			fdset[i].fd = gpio_fd[i];
			fdset[i].events = POLLPRI;
		}
		poll(fdset, nfds, TIMEOUT);
		for(i = 0; i < button_size; i++)
		{
			if(fdset[i].revents & POLLPRI) 
			{	
				char buf[1];
				read(fdset[i].fd, buf, 1);	

				int button_state;
				gpio_get_value(buttons[i], &button_state);
				int led_state = (button_active_edges[i] == button_state);
				gpio_set_value(leds[i], led_state);
				printf("\nButton (GPIO %d) changed state to %d.\n", 
					buttons[i], button_state);
				printf("\tLED (GPIO %d) changed state to %d as a result\n", 
					leds[i], led_state);
			}
		}
		fflush(stdout);
	}

	for(i = 0; i < button_size + led_size; i++)
	{
		gpio_fd_close(gpio_fd[i]);
	}
	printf("\nCtrl-C pressed--exiting...\n");
	return 0;
}
Exemple #24
0
/****************************************************************
 * Main
 ****************************************************************/
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[7];
	//struct pollfd2 fdset2[2];
	int nfds = 7;
	int gpio_fd,gpio_fd2,gpio_fd3,gpio_fd4,gpio_fd5,gpio_fd6,timeout, rc;
	char buf[MAX_BUF];
	int right, down, left, up, shake, exit1;
	int len;

	if (argc < 1) {
		printf("Usage: gpio-int <gpio-pin>\n\n");
		printf("Waits for a change in the GPIO pin voltage level or input on stdin\n");
		exit(-1);
	}

	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);

	right = 7;
	down = 49;
	left = 30;
	up = 60;
	shake = 50;
	exit1 = 31; 
	

	gpio_export(right);
	gpio_set_dir(right, "in");
	gpio_set_edge(right, "rising");  // Can be rising, falling or both
	gpio_fd = gpio_fd_open(right, O_RDONLY);
	gpio_export(down);
	gpio_set_dir(down, "in");
	gpio_set_edge(down, "rising");  // Can be rising, falling or both
	gpio_fd2 = gpio_fd_open(down, O_RDONLY);
	gpio_export(left);
	gpio_set_dir(left, "in");
	gpio_set_edge(left, "rising");  // Can be rising, falling or both
	gpio_fd3 = gpio_fd_open(left, O_RDONLY);
	gpio_export(up);
	gpio_set_dir(up, "in");
	gpio_set_edge(up, "rising");  // Can be rising, falling or both
	gpio_fd4 = gpio_fd_open(up, O_RDONLY);
	gpio_export(shake);
	gpio_set_dir(shake, "in");
	gpio_set_edge(shake, "rising");  // Can be rising, falling or both
	gpio_fd5 = gpio_fd_open(shake, O_RDONLY);
	gpio_export(exit1);
	gpio_set_dir(exit1, "in");
	gpio_set_edge(exit1, "rising");  // Can be rising, falling or both
	gpio_fd6 = gpio_fd_open(exit1, O_RDONLY);

	
	timeout = POLL_TIMEOUT;
 	int count=0;

	int length = 8;
    int height = 8;
    int i;
    int j;
    //int stop = 0;
    int LEDarray [length][height];
    for (i = 0; i < length; i++) {
        for (j = 0; j < height; j++) {
            LEDarray[i][j] = 0;
        } 
    }
    LEDarray [0][0] = 1;

    for (i = 0; i < length; i++) {
        for (j = 0; j < height; j++) {
            printf("%i ", LEDarray [i][j]);
        }
    printf("\n");
    }
    //initialize the start point as 0,0
    int x = 0;
    int y = 0;
    //char input[1];


	while (keepgoing) {
		int rightDir = 0;
		int downDir = 0;
		int leftDir = 0;
		int upDir = 0;
		int setShake = 0;
		int setExit = 0;
		memset((void*)fdset, 0, sizeof(fdset));
		//memset((void*)fdset2, 0, sizeof(fdset2));

		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_fd;
		fdset[1].events = POLLPRI;

		fdset[2].fd = gpio_fd2;
		fdset[2].events = POLLPRI;
		
		fdset[3].fd = gpio_fd3;
		fdset[3].events = POLLPRI;
	
		fdset[4].fd = gpio_fd4;
		fdset[4].events = POLLPRI;

		fdset[5].fd = gpio_fd5;
		fdset[5].events = POLLPRI;
		
		fdset[6].fd = gpio_fd6;
		fdset[6].events = POLLPRI;

		/*
		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_fd2;
		fdset[1].events = POLLPRI;
		*/
		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
      
		if (rc == 0) {
			printf(".\n");
		}
            
		if (fdset[1].revents & POLLPRI) {
			
			lseek(fdset[1].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[1].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			rightDir = 1;
			count++;
		}

		if (fdset[0].revents & POLLIN) {
			(void)read(fdset[0].fd, buf, 1);
			printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
		}
		
		if (fdset[2].revents & POLLPRI) {
			
			lseek(fdset[2].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[2].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			downDir = 1;
			count++;
		}
		if (fdset[3].revents & POLLPRI) {
			
			lseek(fdset[3].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[3].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			leftDir = 1;
			count++;
		}
		if (fdset[4].revents & POLLPRI) {
			
			lseek(fdset[4].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[4].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			upDir = 1;
			count++;
		}
		if (fdset[5].revents & POLLPRI) {
			
			lseek(fdset[5].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[5].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			setShake = 1;
			count++;
		}
		if (fdset[6].revents & POLLPRI) {
			
			lseek(fdset[6].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[6].fd, buf, MAX_BUF);
			//printf("\npoll() GPIO %d interrupt occurred, value=%c, len=%d, count =%d\n",
				 //gpio, buf[0], len, count);
			setExit = 1;
			count++;
		}
				
		if(rightDir == 1){
            		y++;
            		LEDarray [x][y] = 1;
            		//printArray(length, height, LEDarray);
			printf("\n");
            		for (i = 0; i < length; i++) {
                		for (j = 0; j < height; j++) {
                    			printf("%i ", LEDarray [i][j]);
                		}
            		printf("\n");
            		} 
        	}
		else if(downDir == 1){
             		x++;
            		LEDarray [x][y] = 1;
            		//printArray(length, height, LEDarray);
            		for (i = 0; i < length; i++) {
                		for (j = 0; j < height; j++) {
                    			printf("%i ", LEDarray [i][j]);
                		}
            		printf("\n");
            		}
        	}
		else if(leftDir == 1){
             		y--;
            		LEDarray [x][y] = 1;
            		//printArray(length, height, LEDarray);
            		for (i = 0; i < length; i++) {
                		for (j = 0; j < height; j++) {
                    			printf("%i ", LEDarray [i][j]);
                		}
            		printf("\n");
            		}
        	}
		else if(upDir == 1){
             		x--;
			    LEDarray [x][y] = 1;
			    //printArray(length, height, LEDarray);
			    for (i = 0; i < length; i++) {
				for (j = 0; j < height; j++) {
				    printf("%i ", LEDarray [i][j]);
				}
			printf("\n");
			}
        	}
		else if(setShake == 1){
             		//LEDarray = intialZero(length, height, LEDarray);
			for (i = 0; i < length; i++) {
				for (j = 0; j < height; j++) {
				    LEDarray[i][j] = 0;
				} 
			}
			//printArray(length, height, LEDarray);
			for (i = 0; i < length; i++) {
				for (j = 0; j < height; j++) {
				    printf("%i ", LEDarray [i][j]);
				}
			printf("\n");
			}
        	}
		else if(setExit == 1){
             		keepgoing = 0;
			//printArray(length, height, LEDarray);
			for (i = 0; i < length-1; i++) {
				for (j = 0; j < height-1; j++) {
				    printf("%i ", LEDarray [i][j]);
				}
			printf("\n");
			}
        	}
		fflush(stdout);
	}

	gpio_fd_close(gpio_fd);
	gpio_fd_close(gpio_fd2);
	gpio_fd_close(gpio_fd3);
	gpio_fd_close(gpio_fd4);
	gpio_fd_close(gpio_fd5);
	gpio_fd_close(gpio_fd6);
	return 0;
}
Exemple #25
0
/****************************************************************
 * Main
 ****************************************************************/
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[5];
	int nfds = 5;
	int gpio_in_1_fd, gpio_out_1_fd, gpio_in_2_fd, gpio_out_2_fd, gpio_in_3_fd, gpio_out_3_fd, gpio_in_4_fd, gpio_out_4_fd;
	int timeout, rc;
	char buf[MAX_BUF];
	int gpio_in_1, gpio_out_1, gpio_in_2, gpio_out_2, gpio_in_3, gpio_out_3, gpio_in_4, gpio_out_4;
	int len;

	// run with ./etch_gpio 50 115 51 49 20 48 7 112

	if (argc < 9) {
		printf("Usage: %s <gpio-in> <gpio-out>, ... , ... , ...\n\n");
		printf("Interrupt driven output of four buttons, put in pairs of in/out\n");
		exit(-1);
	}

	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);

	gpio_in_1 = atoi(argv[1]);
	gpio_out_1 = atoi(argv[2]);
	gpio_export(gpio_in_1);
	gpio_export(gpio_out_1);
	gpio_set_dir(gpio_in_1, "in");
	gpio_set_dir(gpio_out_1, "out");
	gpio_set_edge(gpio_in_1, "falling");
	gpio_in_1_fd = gpio_fd_open(gpio_in_1, O_RDONLY);
	gpio_out_1_fd = gpio_fd_open(gpio_out_1, O_RDONLY);

	gpio_in_2 = atoi(argv[3]);
	gpio_out_2 = atoi(argv[4]);
	gpio_export(gpio_in_2);
	gpio_export(gpio_out_2);
	gpio_set_dir(gpio_in_2, "in");
	gpio_set_dir(gpio_out_2, "out");
	gpio_set_edge(gpio_in_2, "falling");
	gpio_in_2_fd = gpio_fd_open(gpio_in_2, O_RDONLY);
	gpio_out_2_fd = gpio_fd_open(gpio_out_2, O_RDONLY);

	gpio_in_3 = atoi(argv[5]);
	gpio_out_3 = atoi(argv[6]);
	gpio_export(gpio_in_3);
	gpio_export(gpio_out_3);
	gpio_set_dir(gpio_in_3, "in");
	gpio_set_dir(gpio_out_3, "out");
	gpio_set_edge(gpio_in_3, "falling");
	gpio_in_3_fd = gpio_fd_open(gpio_in_3, O_RDONLY);
	gpio_out_3_fd = gpio_fd_open(gpio_out_3, O_RDONLY);

	gpio_in_4 = atoi(argv[7]);
	gpio_out_4 = atoi(argv[8]);
	gpio_export(gpio_in_4);
	gpio_export(gpio_out_4);
	gpio_set_dir(gpio_in_4, "in");
	gpio_set_dir(gpio_out_4, "out");
	gpio_set_edge(gpio_in_4, "falling");
	gpio_in_4_fd = gpio_fd_open(gpio_in_4, O_RDONLY);
	gpio_out_4_fd = gpio_fd_open(gpio_out_4, O_RDONLY);

	timeout = POLL_TIMEOUT;

	int grid[N][N];
	int i, j;
	for (i = 0; i < N; ++i)
	{
		for (j = 0; j < N; ++j)
		{
			grid[i][j] = 0;
		}
	}
	
	point currentPoint = {.x = 0, .y = 0};
	int currentDirection = NONE;
	int isErasing = 0;
 
	while (keepgoing) {
		memset((void*)fdset, 0, sizeof(fdset));

		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_in_1_fd;
		fdset[1].events = POLLPRI;
		
		fdset[2].fd = gpio_in_2_fd;
		fdset[2].events = POLLPRI;

		fdset[3].fd = gpio_in_3_fd;
		fdset[3].events = POLLPRI;
		
		fdset[4].fd = gpio_in_4_fd;
		fdset[4].events = POLLPRI;

		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
            
		if (fdset[1].revents & POLLPRI) {
			lseek(fdset[1].fd, 0, SEEK_SET);
			len = read(fdset[1].fd, buf, MAX_BUF);
			unsigned int value;
			if (buf[0] == '0') {
				value = 0;
			} else if (buf[0] == '1') {
				value = 1;
			}
			gpio_set_value(gpio_out_1, value);
			currentDirection = UP;
		} else if (fdset[2].revents & POLLPRI) {
			lseek(fdset[2].fd, 0, SEEK_SET);
			len = read(fdset[2].fd, buf, MAX_BUF);
			unsigned int value;
			if (buf[0] == '0') {
				value = 0;
			} else if (buf[0] == '1') {
				value = 1;
			}
			gpio_set_value(gpio_out_2, value);
			currentDirection = DOWN;
		} else if (fdset[3].revents & POLLPRI) {
			lseek(fdset[3].fd, 0, SEEK_SET);
			len = read(fdset[3].fd, buf, MAX_BUF);
			unsigned int value;
			if (buf[0] == '0') {
				value = 0;
			} else if (buf[0] == '1') {
				value = 1;
			}
			gpio_set_value(gpio_out_3, value);
			currentDirection = RIGHT;
		} else if (fdset[4].revents & POLLPRI) {
			lseek(fdset[4].fd, 0, SEEK_SET);
			len = read(fdset[4].fd, buf, MAX_BUF);
			unsigned int value;
			if (buf[0] == '0') {
				value = 0;
			} else if (buf[0] == '1') {
				value = 1;
			}
			gpio_set_value(gpio_out_4, value);
			currentDirection = LEFT;
		} else {
			currentDirection = NONE;
		}

		if (fdset[0].revents & POLLIN) {
			(void)read(fdset[0].fd, buf, 1);
			//printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
			if (buf[0]=='e') {
				isErasing = !isErasing;
			}
		}

		// Evaluate
		currentPoint = updatePoint(currentDirection, currentPoint);
		#ifdef DEBUG
		printf("After Move: %d, %d\n", currentPoint.x, currentPoint.y);
		#endif
		updateBoardBasedOnCurrentPoint(grid, currentPoint, isErasing);

		// Print the N by N matrix
		printGrid(grid, isErasing);
	}

	gpio_fd_close(gpio_in_1_fd);
	gpio_fd_close(gpio_out_1_fd);
	gpio_fd_close(gpio_in_2_fd);
	gpio_fd_close(gpio_out_2_fd);
	gpio_fd_close(gpio_in_3_fd);
	gpio_fd_close(gpio_out_3_fd);
	gpio_fd_close(gpio_in_4_fd);
	gpio_fd_close(gpio_out_4_fd);
	return 0;
}

point updatePoint(int dir, point pt)
{
	point returnPoint;

	#ifdef DEBUG
	printf("Before Move: %d, %d\n", pt.x, pt.y);
	#endif

	switch (dir) {
		case UP:
			#ifdef DEBUG
			printf("Moving up\n");
			#endif
			if (pt.x > 0)
			{
				pt.x--;
			}
			// returnPoint = pt;
			// break;
			return pt;

		case DOWN:
			#ifdef DEBUG
			printf("Moving down\n");
			#endif

			if (pt.x < N-1)
			{
				pt.x++;
			}
			// returnPoint = pt;
			// break;
			return pt;

		case LEFT:
			#ifdef DEBUG
			printf("Moving left\n");
			#endif

			if (pt.y > 0)
			{
				pt.y--;
			}
			// returnPoint = pt;
			// break;
			return pt;

		case RIGHT:
			#ifdef DEBUG
			printf("Moving right\n");
			#endif

			if (pt.y < N-1)
			{
				pt.y++;
			}
			// returnPoint = pt;
			// break;
			return pt;

		case NONE:
			#ifdef DEBUG
			printf("Moving not at all\n");
			#endif

			// returnPoint = pt;
			// break;
			return pt;

		default:
			// Should never get here. Ever.
			// printf("This message should never appear\n");
			break;

		// return returnPoint;
	}
}
Exemple #26
0
static int lua_gpio_newindex(lua_State *L) {
    gpio_t *gpio;
    const char *field;

    gpio = luaL_checkudata(L, 1, "periphery.GPIO");

    if (!lua_isstring(L, 2))
        return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: unknown property");

    field = lua_tostring(L, 2);

    if (strcmp(field, "fd") == 0)
        return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: immutable property");
    else if (strcmp(field, "pin") == 0)
        return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: immutable property");
    else if (strcmp(field, "supports_interrupts") == 0)
        return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: immutable property");
    else if (strcmp(field, "direction") == 0) {
        gpio_direction_t direction;
        int ret;

        const char *value;
        lua_gpio_checktype(L, 3, LUA_TSTRING);
        value = lua_tostring(L, 3);

        if (strcmp(value, "in") == 0)
            direction = GPIO_DIR_IN;
        else if (strcmp(value, "out") == 0)
            direction = GPIO_DIR_OUT;
        else if (strcmp(value, "low") == 0)
            direction = GPIO_DIR_OUT_LOW;
        else if (strcmp(value, "high") == 0)
            direction = GPIO_DIR_OUT_HIGH;
        else
            return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: invalid direction, should be 'in', 'out', 'low', or 'high'");

        if ((ret = gpio_set_direction(gpio, direction)) < 0)
            return lua_gpio_error(L, ret, gpio_errno(gpio), "Error: %s", gpio_errmsg(gpio));

        return 0;
    } else if (strcmp(field, "edge") == 0) {
        gpio_edge_t edge;
        int ret;

        const char *value;
        lua_gpio_checktype(L, 3, LUA_TSTRING);
        value = lua_tostring(L, 3);

        if (strcmp(value, "none") == 0)
            edge = GPIO_EDGE_NONE;
        else if (strcmp(value, "rising") == 0)
            edge = GPIO_EDGE_RISING;
        else if (strcmp(value, "falling") == 0)
            edge = GPIO_EDGE_FALLING;
        else if (strcmp(value, "both") == 0)
            edge = GPIO_EDGE_BOTH;
        else
            return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: invalid edge, should be 'none', 'rising', 'falling', or 'both'");

        if ((ret = gpio_set_edge(gpio, edge)) < 0)
            return lua_gpio_error(L, ret, gpio_errno(gpio), "Error: %s", gpio_errmsg(gpio));

        return 0;
    }

    return lua_gpio_error(L, GPIO_ERROR_ARG, 0, "Error: unknown property");
}
Exemple #27
0
ADCreader::ADCreader()
{
  int ret = 0;

  // set up ringbuffer
  samples = new int[MAX_SAMPLES];
  // pointer for incoming data
  pIn = samples;
  // pointer for outgoing data
  pOut = samples;

  // SPI constants
  static const char *device = "/dev/spidev0.0";
  mode = SPI_CPHA | SPI_CPOL;
  bits = 8;
  speed = 50000;
  delay = 10;
  drdy_GPIO = 22;
  
  // open SPI device
  fd = open(device, O_RDWR);
  if (fd < 0)
    pabort("can't open device");
  
  /*
   * spi mode
   */
  ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
  if (ret == -1)
    pabort("can't set spi mode");
  
  ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
  if (ret == -1)
    pabort("can't get spi mode");
  
  /*
   * bits per word
   */
  ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
  if (ret == -1)
    pabort("can't set bits per word");
  
  ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
  if (ret == -1)
    pabort("can't get bits per word");
  
  /*
   * max speed hz
   */
  ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
  if (ret == -1)
    pabort("can't set max speed hz");
  
  ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
  if (ret == -1)
    pabort("can't get max speed hz");
  
  fprintf(stderr, "spi mode: %d\n", mode);
  fprintf(stderr, "bits per word: %d\n", bits);
  fprintf(stderr, "max speed: %d Hz (%d KHz)\n", speed, speed/1000);
  
  // enable master clock for the AD
  // divisor results in roughly 4.9MHz
  // this also inits the general purpose IO
  gz_clock_ena(GZ_CLK_5MHz,5);
  
  // enables sysfs entry for the GPIO pin
  gpio_export(drdy_GPIO);
  // set to input
  gpio_set_dir(drdy_GPIO,0);
  // set interrupt detection to falling edge
  gpio_set_edge(drdy_GPIO,"falling");
  // get a file descriptor for the GPIO pin
  sysfs_fd = gpio_fd_open(drdy_GPIO);
  
  // resets the AD7705 so that it expects a write to the communication register
  writeReset(fd);
  
  // tell the AD7705 that the next write will be to the clock register
  writeReg(fd,0x20);
  // write 00001100 : CLOCKDIV=1,CLK=1,expects 4.9152MHz input clock
  writeReg(fd,0x0C);
  
  // tell the AD7705 that the next write will be the setup register
  writeReg(fd,0x10);
  // intiates a self calibration and then after that starts converting
  writeReg(fd,0x40);
}
Exemple #28
0
int main(int argc, char** argv){
	//Create an array to store GPIO FDs the switches are connected to
	int switchGPIOFDs[4];
	
	int switchPorts[4] = {50, 51, 3, 2};
	int ledPorts[4] = {30,31,48,60};
	
	int nfds = 5;
	int rc, timeout, value, i;
	struct pollfd fdset[5];

	timeout = POLL_TIMEOUT;

	for(i = 0; i<4 ; i++){
		gpio_export(switchPorts[i]);
		gpio_export(ledPorts[i]);

		gpio_set_dir(switchPorts[i], "in");
		gpio_set_dir(ledPorts[i], "out");

		gpio_set_edge(switchPorts[i], "both");
		
		switchGPIOFDs[i] = gpio_fd_open(switchPorts[i], O_RDONLY);
	}

	//Set signal callback for Ctrl-C
	signal(SIGINT, signal_handler);
	while(keepgoing){
		memset((void*)fdset, 0, sizeof(fdset));
		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
		
		//Set the FDs for the switch GPIOs
		for(i = 0; i<4; i++){
			fdset[i+1].fd = switchGPIOFDs[i];
			fdset[i+1].events = POLLPRI;
		}

		rc = poll(fdset, nfds, timeout);
		
		if(rc < 0) {
			printf("\npoll() failed\n");
			return -1;
		}

		if(rc == 0){
			printf(".");
		}

		for(i=0; i<4; i++){
			if(fdset[i+1].revents & POLLPRI){
				gpio_get_value(switchPorts[i], &value);
				gpio_set_value(ledPorts[i], value);
			}
		}
		fflush(stdout);
	}
	for(i = 0; i<4; i++){
		gpio_fd_close(switchGPIOFDs[i]);
	}	
	return 0;
}
Exemple #29
0
/****************************************************************
 * Main
 ****************************************************************/
int main(int argc, char **argv, char **envp)
{
	struct pollfd fdset[2];
	int nfds = 2;
	int gpio_in_fd, gpio_out_fd, timeout, rc;
	char buf[MAX_BUF];
	int gpio_in, gpio_out;
	int len;

	if (argc < 3) {
		printf("Usage: %s <gpio-in> <gpio-out>\n\n");
		printf("Interrupt driven output\n");
		exit(-1);
	}

	// Set the signal callback for Ctrl-C
	signal(SIGINT, signal_handler);

	gpio_in = atoi(argv[1]);
	gpio_out = atoi(argv[2]);

	gpio_export(gpio_in);
	gpio_export(gpio_out);
	gpio_set_dir(gpio_in, "in");
	gpio_set_dir(gpio_out, "out");
	gpio_set_edge(gpio_in, "both");  // Can be rising, falling or both
	gpio_in_fd = gpio_fd_open(gpio_in, O_RDONLY);
	gpio_out_fd = gpio_fd_open(gpio_out, O_RDONLY);

	timeout = POLL_TIMEOUT;
 
	while (keepgoing) {
		memset((void*)fdset, 0, sizeof(fdset));

		fdset[0].fd = STDIN_FILENO;
		fdset[0].events = POLLIN;
      
		fdset[1].fd = gpio_in_fd;
		fdset[1].events = POLLPRI;

		rc = poll(fdset, nfds, timeout);      

		if (rc < 0) {
			printf("\npoll() failed!\n");
			return -1;
		}
            
		if (fdset[1].revents & POLLPRI) {
			lseek(fdset[1].fd, 0, SEEK_SET);  // Read from the start of the file
			len = read(fdset[1].fd, buf, MAX_BUF);
			unsigned int value;
			if (buf[0] == '0') {
				value = 0;
			} else if (buf[0] == '1') {
				value = 1;
			}
			gpio_set_value(gpio_out, value);
		}

		fflush(stdout);
	}

	gpio_fd_close(gpio_in_fd);
	gpio_fd_close(gpio_out_fd);
	return 0;
}
int blocking_wait_for_edge(unsigned int gpio, unsigned int edge, int bouncetime, int timeout)
// return values:
//    1 - Success (edge detected)
//    0 - Timeout
//   -1 - Edge detection already added
//   -2 - Other error
{
    int n, ed;
    struct epoll_event events, ev;
    char buf;
    struct gpios *g = NULL;
    struct timeval tv_timenow;
    unsigned long long timenow;
    int finished = 0;
    int initial_edge = 1;

    if (callback_exists(gpio))
        return -1;

    // add gpio if it has not been added already
    ed = gpio_event_added(gpio);
    if (ed == edge) {   // get existing record
        g = get_gpio(gpio);
        if (g->bouncetime != -666 && g->bouncetime != bouncetime) {
            return -1;
        }
    } else if (ed == NO_EDGE) {   // not found so add event
        if ((g = new_gpio(gpio)) == NULL) {
            return -2;
        }
        gpio_set_edge(gpio, edge);
        g->edge = edge;
        g->bouncetime = bouncetime;
    } else {    // ed != edge - event for a different edge
        g = get_gpio(gpio);
        gpio_set_edge(gpio, edge);
        g->edge = edge;
        g->bouncetime = bouncetime;
        g->initial_wait = 1;
    }

    // create epfd_blocking if not already open
    if ((epfd_blocking == -1) && ((epfd_blocking = epoll_create(1)) == -1)) {
        return -2;
    }

    // add to epoll fd
    ev.events = EPOLLIN | EPOLLET | EPOLLPRI;
    ev.data.fd = g->value_fd;
    if (epoll_ctl(epfd_blocking, EPOLL_CTL_ADD, g->value_fd, &ev) == -1) {
        return -2;
    }

    // wait for edge
    while (!finished) {
        if ((n = epoll_wait(epfd_blocking, &events, 1, timeout)) == -1) {
            epoll_ctl(epfd_blocking, EPOLL_CTL_DEL, g->value_fd, &ev);
            return -2;
        }
        if (initial_edge) {    // first time triggers with current state, so ignore
            initial_edge = 0;
        } else {
            gettimeofday(&tv_timenow, NULL);
            timenow = tv_timenow.tv_sec*1E6 + tv_timenow.tv_usec;
            if (g->bouncetime == -666 || timenow - g->lastcall > g->bouncetime*1000 || g->lastcall == 0 || g->lastcall > timenow) {
                g->lastcall = timenow;
                finished = 1;
            }
        }
    }

    // check event was valid
    if (n > 0) {
        lseek(events.data.fd, 0, SEEK_SET);
        if ((read(events.data.fd, &buf, 1) != 1) || (events.data.fd != g->value_fd)) {
            epoll_ctl(epfd_blocking, EPOLL_CTL_DEL, g->value_fd, &ev);
            return -2;
        }
    }

    epoll_ctl(epfd_blocking, EPOLL_CTL_DEL, g->value_fd, &ev);
    if (n == 0) {
       return 0; // timeout
    } else {
       return 1; // edge found
    }
}