Ejemplo n.º 1
0
int main(int argc, char **argv)
{
	std::string dev = "/dev/spidev0.1";
	int spi;
	int r;
	
	r = spi_open(&spi, dev, LCD_SPI_MODE, LCD_SPI_BITS_PER_WORD, LCD_SPI_SPEED);
	if (r < 0) {
		fprintf(stderr, "Unable to open SPI bus 0.1 , error (%d,%d) : %s", r, errno, strerror(errno));
		return 1;
	} else {
		std::cout << "SPI 0.1 open." << std::endl;
	}
	
	lcd_init(&spi);
	
	std::cout << "Fill black." << std::endl;
	lcd_fill(&spi, 0x0000);
	delayms(500);
	
	std::cout << "Color test..." << std::endl;
	for(uint16_t color=0;color <= 0xffff; color++) {
		lcd_fill2(&spi, 200, 130, 280, 190, color);
		//delayms(100);
	}
	
	std::cout << "Fill black." << std::endl;
	lcd_fill(&spi, 0x0000);
	
	r = spi_close(&spi);
	std::cout << "SPI 0.1 closed. (" << ((int)r) << ")" << std::endl;
	return 0;
}
Ejemplo n.º 2
0
void tc(int pi)
{
   int h, x, b, e;
   char buf[128];

   printf("SPI tests.");

   /* this test requires a MCP3202 on SPI channel 1 */

   h = spi_open(pi, 1, 50000, 0);
   CHECK(12, 1, h, 0, 0, "spi open");


   for (x=0; x<5; x++)
   {
      sprintf(buf, "\x01\x80");
      b = spi_xfer(pi, h, buf, buf, 3);
      CHECK(12, 2, b, 3, 0, "spi xfer");
      if (b == 3)
      {
         time_sleep(1.0);
         printf("%d ", ((buf[1]&0x0F)*256)|buf[2]);
      }
   }

   e = spi_close(pi, h);
   CHECK(12, 99, e, 0, 0, "spi close");
}
Ejemplo n.º 3
0
Archivo: main.c Proyecto: L3w1s-L1u/uav
int main( int argc,char *argv[])
{
	int ret = -1;
	while (ret < 0 ){
		ret = poweron_self_check();
	}
	while (get_flying_status() < AIRCRAFT_READY) {
		usleep(500000);
		flying_status_return();
	}
	while (get_flying_status() < AIRCRAFT_TAKEOFF) {
		flying_status_return();
		usleep(40000);
	}
	auto_flying_start();
	while (1) {
		usleep(20000);
		flying_status_return();
	}
	sensor_close();
	adc_close();
	spi_close();
	exit(0);
	return 0;
}
int spi_driver_disable(void)
{
  DEBUG_PRINTF("SPI Driver disable...", 0, 0);
  spi_close(SPI_DEVICE_5);
  DEBUG_PRINTF("SPI Driver disable...complete", 0, 0);
  return 0;
}
/**
 * @brief Enable or disable spi "clk always on" in idle
 *
 * @param[in/out] handle  Pointer to the bus information
 * @param[in]     spi_clk_always_on flag status
 *
 * @return SNS_DDF_SUCCESS if the operation was done successfully.
 *         Otherwise SNS_DDF_EDEVICE, SNS_DDF_EBUS, SNS_DDF_EINVALID_PARAM, or
 *         SNS_DDF_EFAIL to indicate an error has occurred.
 */
sns_ddf_status_e sns_ddf_comm_bus_spi_set_clk_always_on
(
    const sns_ddf_handle_t    handle,
    bool                      spi_clk_always_on
)
{
#if SNS_DDF_COMM_BUS_SPI_ENABLE_DRIVER
  spi_device_id_t   spi_dev_id;

  if ( handle == NULL )
  {
    SNS_PRINTF_STRING_ERROR_0(SNS_DBG_MOD_DSPS_DDF, "arg is NULL");
    return SNS_DDF_EINVALID_PARAM;
  }
  if ( ((sns_ddf_sensor_info_s*)handle)->bus != SNS_DDF_BUS_SPI )
  {
       return SNS_DDF_EINVALID_PARAM;
  }

  ((sns_ddf_sensor_info_s*)handle)->spi_s.cfg->spi_clk_always_on = spi_clk_always_on;


  spi_dev_id = ((sns_ddf_sensor_info_s*)handle)->spi_s.dev_id;

  //TODO  change clk state
  if ( spi_open( spi_dev_id ) != SPI_SUCCESS )
  {
    return SNS_DDF_EBUS;
  }
  spi_close( spi_dev_id );
#endif

  return SNS_DDF_SUCCESS;
}
Ejemplo n.º 6
0
int lpd8806_close(int spi_fd) {

	int result;

	result=spi_close(spi_fd);

	return result;
}
Ejemplo n.º 7
0
static int lua_spi_close(lua_State *L) {
    spi_t *spi;
    int ret;

    spi = luaL_checkudata(L, 1, "periphery.SPI");

    if ((ret = spi_close(spi)) < 0)
        return lua_spi_error(L, ret, spi_errno(spi), "Error: %s", spi_errmsg(spi));

    return 0;
}
Ejemplo n.º 8
0
Archivo: spi.c Proyecto: z80/bt-board
int spi_deinit(void)
{
    LOG(DEBUG, "spi_nrefs=%d, spi_dev_open=%d", spi_nrefs, spi_dev_open);

    if (spi_nrefs) {
        if (spi_dev_open)
            if (spi_close() < 0)
                return -1;
        spi_nrefs = 0;
    }
    return 0;
}
Ejemplo n.º 9
0
/**
 * Close file descriptor for SPI bus
 * 
 * @param self
 * @param args
 * @return none
 */
static PyObject* py_close(PyObject* self, PyObject* args){

    int ret;

    ret = spi_close(fd);
    if(ret < 0){
        return PyErr_SetFromErrno(PyExc_IOError);
    }else{
        fd = 0;
    }

    Py_RETURN_NONE;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	int ret = 0;
	int ss, sp, j;
	int doing = 1;

#ifdef IMX
	int retuid;
	retuid = setuid(0);     // root me!
    if (retuid == -1) {
    	perror("Could not setuid.\n");
        exit(-10);
    }
#endif
	
	since_start();			// initialize the count of when we started execution
	spi_open();

	// Read the size of our LED string
	// Use the correct map for the string size
	ss = NUM_GLOBES;
	sp = ss * 3;			// Number of color units in string

	// Allocate space for the frame transmit buffer
	txbuf = malloc(sp + 3);
	txbuf[sp+1] = txbuf[sp+2] = txbuf[sp] = 0x00;		// Last byte always null for end of sequence signalling

	// Ok, we're ready to start, so call the setup
	setup(argc, argv);
	synchronize(1);	// And setup the sync function

	while (doing) {
		//memset((void*) txbuf, (int) 0x80, (size_t) sp);  // Clear the string quickly
		doing = loop(since_start());
		synchronize(20000000);					// 50 fps or 20 msec/frame
		spi_send(txbuf, (sp + 1));		// Try to transmit the frame
	}
	free(txbuf);		// Always clean up after yourself!
	spi_close();

	return 0;
}
/*-------------------------------------------
| Name:dev_stm32f4xx_spi_x_close
| Description:
| Parameters:
| Return Type:
| Comments:
| See:
---------------------------------------------*/
int dev_stm32f4xx_spi_x_close(desc_t desc){
  board_stm32f4xx_spi_info_t * p_spi_info = (board_stm32f4xx_spi_info_t*)ofile_lst[desc].p;
  //
  if(!p_spi_info)
   return -1;
  // 
  if(ofile_lst[desc].oflag & O_RDONLY) {
      if(!ofile_lst[desc].nb_reader) {
         p_spi_info->desc_r = -1;
      }
   }
   //
   if(ofile_lst[desc].oflag & O_WRONLY) {
      if(!ofile_lst[desc].nb_writer) {
         p_spi_info->desc_w = -1;
      }
   }
   //
   if(p_spi_info->desc_r<0 && p_spi_info->desc_w<0) {
      spi_close(&p_spi_info->spi_descriptor);
   }

   return 0;
}
int main(int argc, char **argv)
{
	int r;
	uint64_t td_b, td_e, td;
	uint64_t total_time_demo_start, total_time_demo_end;
	
	r = spi_open();
	if (r < 0) {
		fprintf(stderr, "Unable to open bmc2835 lib & config SPI bus.\n");
		return 1;
	} else {
		fprintf(stdout, "bcm2835 library & SPI configured.\n");
	}
	
	total_time_demo_start = get_ticks();
	
	fprintf(stdout, "LCD init. ");
	td_b = get_ticks();
	lcd_init();
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	
	fprintf(stdout, "Fill black. ");
	td_b = get_ticks();
	lcd_fill(0x0000);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	delayms(500);
	
	fprintf(stdout, "Fill red. ");
	td_b = get_ticks();
	lcd_fill(0xF800);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	delayms(500);
	
	fprintf(stdout, "Fill green. ");
	td_b = get_ticks();
	lcd_fill(0x07E0);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	delayms(500);
	
	fprintf(stdout, "Fill blue. ");
	td_b = get_ticks();
	lcd_fill(0x001F);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	delayms(500);
	
	
	fprintf(stdout, "Fill white. ");
	td_b = get_ticks();
	lcd_fill(0xffff);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	delayms(500);
	
	fprintf(stdout, "Fill black. ");
	td_b = get_ticks();
	lcd_fill(0x0000);
	td_e = get_ticks();
	td = (uint64_t)(td_e - td_b);
	fprintf(stdout,"Time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	
	total_time_demo_end = get_ticks();
	td = (uint64_t)(total_time_demo_end - total_time_demo_start);
	fprintf(stdout,"\nTotal LCD test time: %9.3f" "ms\n",(float)((uint64_t)td/1000.0f));
	
	spi_close();
	fprintf(stdout, "bcm2835 library closed.\n");
	
	return 0;
}
Ejemplo n.º 13
0
int main (void)
{
    unsigned int ret;
    tpruss_intc_initdata pruss_intc_initdata = PRUSS_INTC_INITDATA;
    
    printf("\nINFO: Starting %s application.\r\n", "Lockbox");
    /* Initialize the PRU */
    prussdrv_init ();		
    
    /* Open PRU Interrupt */
    ret = prussdrv_open(PRU_EVTOUT_0);
    if (ret)
    {
        printf("prussdrv_open open failed\n");
        return (ret);
    }
    
    /* Get the interrupt initialized */
    prussdrv_pruintc_init(&pruss_intc_initdata);

    /* Initialize example */
    printf("\tINFO: Initializing application.\r\n");
    LOCAL_exampleInit(PRU_NUM);
    
    /* Execute code on PRU 1 */
    printf("\tINFO: Executing PRU1 code.\r\n");
    prussdrv_exec_program (1, "./prucode1.bin");

    /* Execute code on PRU 1 */
    printf("\tINFO: Executing PRU0 code.\r\n");
    prussdrv_exec_program (0, "./prucode0.bin");

	/* Set up SPI0  */
	spi0_fd = spi_init("/dev/spidev1.0",2);
	//daisy-chain setup
//	unsigned char spi00init[3]={128,0,1};
//	spi_transfer(spi0_fd,spi00init,3,2);
//	spi_close(spi0_fd);
//	unsigned char spi01init[6]={128,0,0,128,0,0};
//	spi_transfer(spi0_fd,spi01init,6,2);
//	spi0_fd = spi_init("/dev/spidev1.0",0);
	
	/* Set up SPI1 */
	spi1_fd = spi_init("/dev/spidev2.0",0);
	//make sure all pins are connected
	unsigned char spi10init[3]={64,255};
	spi_transfer(spi0_fd,spi10init,2,0);

	/* Execute main loop which communicates with both PRU and host computer */
    mainloop();
    
    /* Wait until PRU0 has finished execution */
    printf("\tINFO: Waiting for HALT command.\r\n");

    prussdrv_pru_wait_event (PRU_EVTOUT_0);
    printf("\tINFO: PRU1 completed transfer.\r\n");
    prussdrv_pru_clear_event (PRU0_ARM_INTERRUPT);
    
    /* Disable PRUs and close memory mapping*/
    prussdrv_pru_disable(0);  //PRU0 off 
    prussdrv_pru_disable(1);  //PRU1 off
    prussdrv_exit();
    munmap(ddrMem, 0x0FFFFFFF);
    close(mem_fd);
	
	spi_close(spi0_fd);
	spi_close(spi1_fd);
	
    return(0);
}
Ejemplo n.º 14
0
int main(int argc, char **argv) {

	int spi_fd,i;
	unsigned char zeros[128],data[128];
	int result;

	int lr,lg,lb,rr,rg,rb;

	/* color left */
	if (argc>1) {
                get_color(argv[1],&lr,&lg,&lb);
        }
        else {
                lr=63;
                lg=0;
                lb=0;
        }


	/* color right */
	if (argc>2) {
                get_color(argv[2],&rr,&rg,&rb);
        }
        else {
                rr=0;
                rg=0;
                rb=0;
        }


	spi_fd=spi_open("/dev/spidev0.0", SPI_MODE_0, 100000, 8);
	if (spi_fd<0) {
		exit(-1);
	}

	/* Send a byte acting as a start bit */

	for(i=0;i<128;i++) zeros[i]=0;
	for(i=0;i<128;i++) data[i]=128;

	for(i=0;i<128;i++) {
		result=write(spi_fd,&zeros[i],1);
		if (result<1) {
			printf("error!\n");
			exit(-1);
		}
	}

#define MAX_BRIGHTNESS 64

	int bar=0;

	int height=0;

	unsigned char ch;

	while(1) {
		scanf("%c",&ch);

		printf("Pressed %d\n",ch);

		if (ch=='i') {
			bar++;
			if (bar>32) bar=32;
		}
		if (ch=='m') {
			bar--;
			if (bar<0) bar=0;
		}

		for(i=0;i<32;i++) {
			if (i<bar) {
				data[(i*3)+0]=128+lg;
				data[(i*3)+1]=128+lr;
				data[(i*3)+2]=128+lb;
			} else {
				data[(i*3)+0]=128+rg;
				data[(i*3)+1]=128+rr;
				data[(i*3)+2]=128+rb;
			}
		}

		for(i=0;i<128;i++) {
			result=write(spi_fd,&data[i],1);
			if (result<1) {
				printf("error!\n");
				exit(-1);
			}
		}

		for(i=0;i<128;i++) {
			result=write(spi_fd,&zeros[i],1);
			if (result<1) {
				printf("error!\n");
				exit(-1);
			}
		}
	}

	spi_close(spi_fd);

	return 0;
}
Ejemplo n.º 15
0
int main(int argc, char ** argv){

	int randptr, i;

	spi_init();

	wishbone_read((unsigned char *)buffer, 2, 0x0000);

	if (buffer[1] != 0xde || buffer[0] != 0xad) {
		fprintf(stderr, "Invalid ID: 0x%02x%02x.  Did you load the FPGA?\n", buffer[1], buffer[0]);
		spi_close();
		exit(1);
	}


/*
	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Address
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0002);

	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Data
	buffer[1] = 0xBE;
	buffer[0] = 0xEF;

	wishbone_write((unsigned char *)buffer, 2, 0x0001);

	// Write
	buffer[1] = 0;
	buffer[0] = 3;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Address
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0002);

	buffer[1] = 0;
	buffer[0] = 3;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Data
	buffer[1] = 0xF0;
	buffer[0] = 0x0D;

	wishbone_write((unsigned char *)buffer, 2, 0x0001);

	// Write
	buffer[1] = 0;
	buffer[0] = 3;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);
*/

	for (i = 0; i < 256; i++) {

	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Address
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0002);

	buffer[1] = 0;
	buffer[0] = i;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Read
	buffer[1] = 0;
	buffer[0] = 1;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);
	usleep(10);

	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	wishbone_read((unsigned char *)buffer, 2, 0x0001);
	fprintf(stderr, "0x%02x: 0x%02x%02x\n", i, buffer[1], buffer[0]);

	}


	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Address
	buffer[1] = 0;
	buffer[0] = 1;

	wishbone_write((unsigned char *)buffer, 2, 0x0002);

	buffer[1] = 0;
	buffer[0] = 1;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Read
	buffer[1] = 0;
	buffer[0] = 1;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	usleep(10);

	// Reset
	buffer[1] = 0;
	buffer[0] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	wishbone_read((unsigned char *)buffer, 2, 0x0001);
	fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]);




/*
	// Address
	buffer[0] = 0;
	buffer[1] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Read
	buffer[0] = 1;
	buffer[1] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	sleep(1);

	// Reset
	buffer[0] = 0;
	buffer[1] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Data
	wishbone_read((unsigned char *)buffer, 2, 0x0001);

	fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]);




	// Address
	buffer[0] = 0;
	buffer[1] = 10;

	wishbone_write((unsigned char *)buffer, 2, 0x0003);

	// Read
	buffer[0] = 1;
	buffer[1] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	sleep(1);

	// Reset
	buffer[0] = 0;
	buffer[1] = 0;

	wishbone_write((unsigned char *)buffer, 2, 0x0004);

	// Data
	wishbone_read((unsigned char *)buffer, 2, 0x0001);

	fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]);


*/









	spi_close();
	return 0;

}
/**
*  @brief Performs SPI data transfer
*
* @param[in]   handle        The I/O port handle that identifies a device. This
*                            is given to drivers as part of initialization.
* @param[out]  read_buffer   Pointer to the buffer to which data read is deposited to.
*                            NULL allowed for write operation.
* @param[in]   read_len      Maximum number of bytes that can be stored in read_buffer.
*                            0 allowed for write operation.
* @param[in]   write_buffer  Pointer to buffer that contains the data to be written.
* @param[in]   write_len     Maximum number of bytes that can be stored in write_len.
* @param[out]  read_count    Number of bytes transfered.
*
* @return SNS_DDF_SUCCESS if the operation was done successfully.
*         Otherwise SNS_DDF_EINVALID_PARAM or SNS_DDF_EBUS to indicate the error.
*
*/
sns_ddf_sensor_e sns_ddf_spi_data_transfer
(
    const sns_ddf_handle_t  handle,
    uint8_t*                read_buffer,  //NULL allowed for write operation
    uint32_t                read_len,
    const uint8_t*          write_buffer,
    uint32_t                write_len,
    uint32_t*               read_count
)
{
#if SNS_DDF_COMM_BUS_SPI_ENABLE_DRIVER
  SPI_RESULT        spi_result; //spi_errors.h
  spi_transaction_t read_transaction_info;
  spi_transaction_t write_transaction_info;
  spi_device_id_t   spi_dev_id;

  if ( handle       == NULL ||
       write_buffer == NULL ||
       write_len    == 0 )
  {
    return SNS_DDF_EINVALID_PARAM;
  }

  //NOTE: 8994 uses only spi_dev_id = SPI_DEVICE_12;
  spi_dev_id = ((sns_ddf_sensor_info_s*)handle)->spi_s.dev_id;

  read_transaction_info.buf_virt_addr = (void *)read_buffer;
  read_transaction_info.buf_phys_addr = (void *)read_buffer;
  read_transaction_info.buf_len       = read_len;

  write_transaction_info.buf_virt_addr = (void *)write_buffer;
  write_transaction_info.buf_phys_addr = (void *)write_buffer;
  write_transaction_info.buf_len       = write_len;


  if ( EnableSPI == false )
  {
    if ( read_count != NULL )
    {
      *read_count = read_len; //public API backward compatibility
    }
    return SNS_DDF_SUCCESS;
  }

  spi_result = spi_open( spi_dev_id );
  if ( spi_result != SPI_SUCCESS )
  {
    return SNS_DDF_EBUS;
  }

  // Perform a full duplex transfer ----------------------
  spi_result = spi_full_duplex( spi_dev_id,
                                ((sns_ddf_sensor_info_s*)handle)->spi_s.cfg,
                                &write_transaction_info, &read_transaction_info );
  if ( spi_result != SPI_SUCCESS )
  {
    spi_close(spi_dev_id);
    return SNS_DDF_EBUS;
  }

  spi_close( spi_dev_id );

  if ( read_count != NULL )
  {
    *read_count = read_len;  //public API backward compatibility
    //NOTE: *write_count / *read_count not implemented in SPI driver
    //Those should be the actual number of bytes written/read
  }
#endif

  return SNS_DDF_SUCCESS;
}
Ejemplo n.º 17
0
int main(){



	int fd = spi_open("/dev/spidev0.0");
	spi_mode(fd, SPI_MODE_1);
	// spi_mode(fd,  SPI_NO_CS | SPI_MODE_2);
	spi_speed(fd, MHZ_32);
	dumpstat("SPI device 0: ",fd);

	// uint16_t command = MCP3208_START_BIT | MCP3208_SINGLE_ENDED

	printf("size %d\n", sizeof(MCP_CHAN_7));

	// uint32_t foo = MCP_CHAN_7;
	// uint32_t mcp_tx = ((uint32_t)MCP_CHAN_7) << 14;
	// uint32_t mcp_rx = 0;

	uint8_t tx[] = {1,8 + 0 << 4,0,0};
	uint8_t rx[4] = {0}; 


	struct spi_ioc_transfer mcp_tr ={
		.tx_buf = (unsigned long)&tx,
		.rx_buf = (unsigned long)&rx,
		.len = 4,
		.delay_usecs = 0,
		.speed_hz = KHZ_500,
		.bits_per_word = 8,
	};


	while(1){
		spi_transfer(fd, &mcp_tr, 1);

		// printf ("B "BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_tx >> 24));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_tx >> 16));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_tx >> 8));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_tx));
		// printf("\tbuf_tx: %u\n", mcp_tx);

		// mcp_rx |= 0xff000000;
		// mcp_rx &= 0x00ffffff;
		// mcp_rx = mcp_rx >> 0;

		uint32_t ret = 0;
		ret |= (uint32_t)rx[3];
		ret |= (uint32_t)rx[2] << 8;
		ret |= (uint32_t)rx[1] << 16;
		// ret |= (uint32_t)rx[0] << 24;

		print_byte(rx[0]);
		print_byte(rx[1]);
		print_byte(rx[2]);
		print_byte(rx[3]);
		printf(" rx %d", ret >> 6);
		printf("\n");

		// printf("%d\n", rx);

		// printf ("\nA "BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_rx >> 24));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_rx >> 16));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_rx >> 8));
		// printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(mcp_rx));
		// printf("\tbuf_rx: %u\n", mcp_rx);

		nanosleep(&requested,&remaining);
	}

	// uint16_t command = get_mcp_channel_command(0);
	// printf ("Byte 00 "BYTETOBINARYPATTERN"\n", BYTETOBINARY((uint8_t)command));
	// printf ("Byte 01 "BYTETOBINARYPATTERN"\n", BYTETOBINARY((uint8_t)command >> 8));

	// printf ("Byte 00 "BYTETOBINARYPATTERN"\n", BYTETOBINARY((uint8_t)0x8));
	// printf ("Byte 01 "BYTETOBINARYPATTERN"\n", BYTETOBINARY((uint8_t)0x10));
	// printf("command %d %s\n", command, &buf);

	// dumpstat("SPI device 0: ",fd);

	spi_close(fd);

}

static void print_byte(uint8_t byte){
	printf (""BYTETOBINARYPATTERN" ", BYTETOBINARY(byte));
} 
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
	/* SELECT */
	int max_fd;
	fd_set readfds;
	struct timeval timeout;
	/* END SELECT */
	int i,j,ret;
	unsigned char bufout[BUF_SIZE];
	struct avr_msg dummy_msg = {t: 255, v: 254};
	struct avr_msg status_msg = {t: 255, v: 0};
	long dt_ms = 0;

	clock_gettime(CLOCK_REALTIME, &time_now);

	clock_gettime(CLOCK_REALTIME, &spi_time_prev);

	//we use this to measure UDP connection time each second
	clock_gettime(CLOCK_REALTIME, &udp_time_prev);

	int option;
	verbose = 1;
	background = 0;
	echo = 0;
	while ((option = getopt(argc, argv,"dep:fv:u:y:")) != -1) {
		switch (option)  {
			case 'd': background = 1; verbose=0; break;
			case 'p': portno = atoi(optarg);  break;
			case 'v': verbose = atoi(optarg);  break;
			case 'y': initTimeout = atoi(optarg);  break;
			case 'f': spi=0; break;
			case 'e': echo=1; break;
			case 'u': strcpy(socket_path,optarg); break;
			default:
				  print_usage();
				  return -1;
		}
	}

	signal(SIGTERM, catch_signal);
	signal(SIGINT, catch_signal);

	unix_sock = 0;
	for (i=0; i<MAX_UNIX_CLIENTS; i++) { 
		sock[i] = 0;
		sock_type[i] = -1;
		if (i>0) {
			buf_c[i] = 0;
		}
	}

	unix_sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (unix_sock < 0) {
		perror("opening unix socket");
		exit(1);
	}

	usock = socket(AF_INET, SOCK_DGRAM, 0);
	if (usock < 0) {
		perror("opening datagram socket");
		exit(1);
	}

	/* Create name sock, usock */
	bzero((char *) &address, sizeof(address));
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons(portno);

	if (bind(usock, (struct sockaddr *) &address, sizeof(struct sockaddr_in))) {
		perror("binding datagram socket");
		exit(1);
	}

	printf("Socket created on port %i\n", portno);


	/* UNIX */
	bzero((char *) &local, sizeof(local));
	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, socket_path);
	unlink(local.sun_path);
	locallen = strlen(local.sun_path) + sizeof(local.sun_family);
	if (bind(unix_sock, (struct sockaddr *) &local, locallen)) {
		perror("binding unix socket");
		exit(1);
	}


	flog_init(CFG_PATH);
	log_mode = flog_getmode();

	if (listen(unix_sock,3) < 0) {
		perror("listen");
		stop=1;
	}

	if (background) {
		if (daemon(0,1) < 0) { 
			perror("daemon");
			return -1;
		}
		if (verbose) printf("Running in the background\n");
	}


	if (spi) {
		ret = spi_init();
		if (ret < 0) {
			printf("Error initiating SPI! %i\n",ret);
			stop = 1;
		}
	}

	reset_avr();

	clock_gettime(CLOCK_REALTIME, &spi_last_msg);

	if (verbose) printf("Starting main loop\n");

	while (!stop) {
		FD_ZERO(&readfds);
		max_fd = unix_sock;
		FD_SET(unix_sock, &readfds);
		for (i=0;i<MAX_UNIX_CLIENTS;i++) {
			if (sock[i]<=0) continue;
			FD_SET(sock[i], &readfds);
			max_fd = sock[i]>max_fd?sock[i]:max_fd;
		}
		FD_SET(usock, &readfds);
		max_fd = usock>max_fd?usock:max_fd;

		timeout.tv_sec = 0;
		timeout.tv_usec = MSG_PERIOD*1000L; //ms 
		int sel = select( max_fd + 1 , &readfds , NULL , NULL , &timeout);
		if ((sel<0) && (errno!=EINTR)) {
			perror("select");
			stop=1;
		}

		clock_gettime(CLOCK_REALTIME, &time_now);

		//check for orphan UDP connections
		dt = TimeSpecDiff(&time_now,&udp_time_prev);
		dt_ms = dt->tv_sec*1000 + dt->tv_nsec/1000000;
		if (dt_ms>1000) {
			udp_time_prev = time_now;
			for (i=0;i<MAX_UDP_CLIENTS;i++)
				if (uclients[i]>0) {
					uclients[i]--;
					if (uclients[i]<=0) {
						if (verbose) printf("Client %i timeout.\n",i);
					}
				}
		}
		//check UDP
		if (!stop && FD_ISSET(usock, &readfds)) {
                        ret = 0;
                        int t = 0;
                        do {
                                t = recvfrom(usock, ubuf+ret, BUF_SIZE-ret, MSG_DONTWAIT, (struct sockaddr *)&tmpaddress, &addrlen);
                                if (t>0) ret+=t;
                        } while (t>0);
			if (ret<=0) {
				printf("UDP recvfrom error? %i\n",ret);
			} else {
				int msg_c = ret / LOCAL_MSG_SIZE;
				if (verbose) printf("UDP received %i msgs\n", msg_c);
				for (i=0;i<msg_c;i++) { 
					struct local_msg m;
					unpack_lm(ubuf+i*LOCAL_MSG_SIZE,&m);
					process_udp_msg(&m,&tmpaddress); 
				}
			}
		}

		//If something happened on the master socket , then its an incoming connection
		if (!stop && FD_ISSET(unix_sock, &readfds)) {
			int t = accept(unix_sock, NULL, NULL);
			if (t<0) {
				perror("accept");
				continue;
			}
			for (i=0;i<MAX_UNIX_CLIENTS;i++)
				if (sock[i] == 0) {
					if (verbose) printf("Incoming client: %i\n",i);
					sock[i] = t;
					sock_type[i] = -1;
					buf_c[i] = 0;
					break;
				}
			if (i==MAX_UNIX_CLIENTS) {
				printf("AVRSPI: No space in connection pool! Disconnecting client.\n");
				close(t);
			}
		} 
		for (i=0;(i<MAX_UNIX_CLIENTS) && (!stop) && sock[i]>0;i++) {
			if (FD_ISSET(sock[i], &readfds)) {
				if (sock_type[i]==-1) {
					ret = read(sock[i],&sock_type[i],1);
					if (ret<=0) {
						perror("Reading error");
						close(sock[i]);
						sock[i] = 0;
					}
					continue;
				}
				ret = read(sock[i] , buf[i]+buf_c[i], BUF_SIZE - buf_c[i]); 
				if (ret < 0) {
					perror("Reading error");
					close(sock[i]);
					sock[i] = 0;
				}
				else if (ret == 0) {	//client disconnected
					if (verbose) printf("Client %i disconnected.\n",i);
					close(sock[i]);
					sock[i] = 0;
					buf_c[i] = 0;
				} else { //got data
					buf_c[i] += ret;
					if (verbose) printf("Received: %i bytes. Buf size: %i\n",ret,buf_c[i]);
					process_socket_queue(i);
				}
			}
		}
		//process of SPI received messages
		for (i=0;i<spi_buf_c;i++) {
			process_avr_msg(&spi_buf[i]);
			avr2local(&spi_buf[i],&local_buf[local_buf_c++]);
		}
		spi_buf_c = 0;

		//send out any available messages to clients
		if (local_buf_c*LOCAL_MSG_SIZE>BUF_SIZE) {
			printf("output buffer overflow (bufout)!");
			local_buf_c = 0;
		}

		for (j=0;j<local_buf_c;j++) {
			if (verbose>=2) printf("To clients: c: %u, t: %u, v: %i\n",local_buf[j].c,local_buf[j].t,local_buf[j].v);
			//local_buf[j].c = 0;
			pack_lm(bufout+j*LOCAL_MSG_SIZE,&local_buf[j]);
		}

		if (local_buf_c) {
			if (verbose) printf("To clients msgs: %i bytes: %i\n",local_buf_c,local_buf_c*LOCAL_MSG_SIZE);
			for (int k=0;k<MAX_UNIX_CLIENTS;k++) {
				if (sock[k]!=0 && sock_type[k]==0) { 
					ret = send(sock[k], bufout, local_buf_c*LOCAL_MSG_SIZE, MSG_NOSIGNAL );
					if (ret == -1) {
						if (verbose) printf("Lost connection to client %i.\n",k);
						close(sock[k]);
						sock[k] = 0;
					}
				}
			}
			for (int k=0;k<MAX_UDP_CLIENTS;k++) {
				if (uclients[k]>0) { 
					ret = sendto(usock,bufout,LOCAL_MSG_SIZE,0,(struct sockaddr *)&uaddress[k],addrlen);
					if (ret<0) {
						printf("Error sending datagram packet\n");
						uclients[k] = 0;
					}
				}
			}
		}

		local_buf_c = 0;

		do_avr_init(); 
		flog_loop();

		//ping avr if needed
		dt = TimeSpecDiff(&time_now,&spi_time_prev);
		dt_ms = dt->tv_sec*1000 + dt->tv_nsec/1000000;
		if (dt_ms>=MSG_PERIOD) {
			spi_time_prev = time_now;
			if (spi) for (i=msg_counter;i<MSG_RATE;i++) 
					if (i==msg_counter && autoconfig && avrstatus<5) spi_sendMsg(&status_msg);
					else spi_sendMsg(&dummy_msg);
			msg_counter = 0;
		}

	}

	if (echo) spi_close();

	bufout[0] = 1; //disconnect msg
	for (int k=0;k<MAX_UNIX_CLIENTS;k++) {
		if (sock[k]!=0) 
			send(sock[k], bufout, LOCAL_MSG_SIZE, MSG_NOSIGNAL );
	}

	close(unix_sock);
	mssleep(1000);

	if (verbose) {
		printf("closing\n");
		fflush(NULL);
	}

	for (i=0;i<MAX_UNIX_CLIENTS;i++)
		if (sock[i]!=0) close(sock[i]);


	close(usock);

}
Ejemplo n.º 19
0
int main(int argc, char *argv[]) 
{

	uid_t uid;
	uint8_t SN[10];
	uint16_t CType=0;
	uint8_t SN_len=0;
	char status;
	int tmp,i;

	char str[255];
	char *p;
	char sn_str[23];
	pid_t child;
	int max_page=0;
	uint8_t page_step=0;

	FILE * fmem_str;
	char save_mem=0;
	char fmem_path[255];
	uint8_t use_gpio=0;
	uint8_t gpio=255;
	uint32_t spi_speed=10000000L;
	int fd = -1 ;

//by myself
	unsigned char blockaddr = (unsigned char)atoi(argv[1]);
	unsigned char key_passwd = (unsigned char)atoi(argv[2]) ;
	int n = 0;
	unsigned char statu = 0;
	unsigned char data_test[16];

	for(n = 0; n < 6; n++) {
		data_test[n] = 0x00;
	}
	data_test[6] = 0xff ;
	data_test[7] = 0x07;
	data_test[8] = 0x80 ;
	data_test[9] = 0x69 ;

	for(n=10;n<16;n++){
		data_test[n] = 0xFF ;
	}
	
#if 1
	if(argc < 3) {
		printf("command error and try again like this : ./a.out 1 \n");
		return -1;
	}
#endif
	if( (fd = spi_open() )< 0) return -1 ;
	/*
	 * spi mode
	 */
	unsigned char mode = 3;
//	unsigned char mode = 1;
	unsigned char mode_t ;
	unsigned char bits = 8 ;
	unsigned int  speed = 120000000 ;
	int ret = -1 ;
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		printf("can't set spi mode");

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

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

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

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		printf("can't set max speed hz");

	unsigned int  speed_t ;
	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed_t);
	if (ret == -1)
		printf("can't get max speed hz");

	printf("spidev hw info : mode:%d  bits:%d speed:%d\n",mode_t,bits_t,speed_t) ;

//many changes in InitRc522 function, please check it.	
	printf("we will read block [%d] value !\n",blockaddr);

	printf("rc522 is soft_rest ....\n");
	PcdReset();
#if 1	
	printf("rc522 open antenna ... \n");
	usleep(100*1000);
	PcdAntennaOn();
	
	memset(Tmpbuff,0,20);

	printf("now find tag .....\n");
	while(1) {
	 statu = PcdRequest(PICC_REQALL,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("find the tag and the tag type is :");
		for(n = 0; n < (sizeof(Tmpbuff) / sizeof(Tmpbuff[0])); n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	continue ;
	 }
	 
	 printf("Now is running Anticoll ....\n");
	 statu = PcdAnticoll(PICC_ANTICOLL1, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("Anticoll success and the tag sn is ");
		for(n = 0; n < (sizeof(Tmpbuff) / sizeof(Tmpbuff[0])); n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
		printf("Anticoll faild !\n");
	 	continue ;
	 }

	 printf("Now start select an tag .... \n");
	 statu = PcdSelect(PICC_ANTICOLL1, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("select tag is success !\n");
	 }else {
	 	printf("sorry,select tag faild !\n");
		continue ;
	 }

	 printf("Now start authstate ... \n");
	 statu = PcdAuthState(PICC_AUTHENT1A, blockaddr, key, Tmpbuff);
	// statu = PcdAuthState(PICC_AUTHENT1B, blockaddr, key, Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("authstate success !\n");
	 }else {
	 	printf("authstate faild and continue find tag....\n");
		continue ;
	 }
#if 1
	 if(key_passwd == 3 ) {
		 printf("Now start write [%d] blockaddr... \n",key_passwd);
		 statu = PcdWrite(key_passwd, data_test);
		 if(statu == TAG_OK) {
				printf("write success !\n");
		 }else {
		 	printf("write faild !\n");
			continue ;
		 }

		statu = PcdRead(key_passwd,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("read success and the data is ");
		for(n = 0; n < 16; n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	printf("read faild and continue find tag ....\n");
		continue ;
	 }

	 }else {
		 printf("[%d] address is only read !\n",blockaddr);
	 }
#endif
	 printf("Now start read [%d] addresss ... \n",blockaddr);
	 statu = PcdRead(blockaddr,Tmpbuff);
	 if(statu == TAG_OK) {
	 	printf("read success and the data is ");
		for(n = 0; n < 16; n++) {
			printf("0x%x ",Tmpbuff[n]);
		}
		printf("\n");
	 }else {
	 	printf("read faild and continue find tag ....\n");
		continue ;
	 }

	 printf("Now sleep the picc \n");
	 PcdHalt();
	 break ;
	}

//	InitRc522();
#if 0

	while(1) {
		status= find_tag(&CType);
		printf("status is [%d] :Ctype [%x] \n",status,CType) ;
		if (status==TAG_NOTAG) {
			printf("find tag again !\n") ;
			usleep(200000);
			continue;
		}else if ((status!=TAG_OK)&&(status!=TAG_COLLISION)) {
			printf("status!=TAG_OK)&&(status!=TAG_COLLISION again \n") ;
			continue;
		}
		printf("Ctype is %d\n",CType);
		if (select_tag_sn(SN,&SN_len)!=TAG_OK) {
			printf("select_tag_sn(SN,&SN_len)!=TAG_OK) again \n") ;
			continue;
		}

		read_tag_str(0,str);
		printf("str:%s\n",str) ;
		PcdHalt();
		break  ;
	}
#endif
#endif
	printf("now start close spi orpe.....\n");
	spi_close() ; 

	return 0;

}
Ejemplo n.º 20
0
int main(int argc, char **argv) {

	int spi_fd,j;
	int value[2];
	unsigned char data[3];
	int result;
	double voltage,current,power,deltav,ref;
	struct timeval tv;
	double seconds,start_seconds;

	gettimeofday(&tv,NULL);
	start_seconds=(double)tv.tv_sec+((double)(tv.tv_usec))/1000000.0;

	spi_fd=spi_open("/dev/spidev0.0", SPI_MODE_0, SPEED, 8);
	if (spi_fd<0) {
		exit(-1);
	}

	while(1) {

		for(j=0;j<2;j++) {

			/* Send a byte acting as a start bit */
			data[0] = 1;

			/* Ask for differential output */
			/* High/Low */
			data[1] = ((j & 0x7) << 4);
			data[1] |=0x80;

			/* Don't care, need 3 bytes before response */
			data[2] = 0;

			result=spi_writeread(spi_fd, data,
						sizeof(data), SPEED, 8 );
			if (result<0) {
				exit(-1);
			}

			/* 3-byte result */
			/* XXXXXXXX */
			/* XXXXX098 */
			/* 76543210 */
			value[j] = ((data[1]&0x3) << 8) | (data[2] & 0xff);
			//printf("\t%d",value[j]);
		}
		ref=4.90;
		voltage=((double)value[0])/1024.0;
		voltage*=ref;
		deltav=voltage/20.0;
		current=deltav/0.1;
		power=ref*current;

		gettimeofday(&tv,NULL);

		seconds=(double)tv.tv_sec+((double)(tv.tv_usec))/1000000.0;

		printf("%f %.3lf\n",seconds-start_seconds,power);
		usleep(1000000);

	}

	spi_close(spi_fd);

	return 0;
}
Ejemplo n.º 21
0
int main(void) {
	spi_t spi;
	spi_bit_order_t MSB_FIRST;
	uint8_t buf[1] = {0x00};
	uint8_t buf0[1];
	int8_t buf2[7];
	uint8_t buf1[7] = {0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x80}; // To change the gain to 64, change the last byte(0x80) to (0xA8) or 32 => (0xA0)
	char buffer [8];
	unsigned char byte;
	int32_t desired_bits;
	int i, j;
	int size = 6;
	int32_t offset;
	int nsamples=N_SAMPLES;
	long samples[nsamples];
	float spread_percent = SPREAD / 100.0 /2.0;
	float filter_low, filter_high;
	long tmp_avg=0;
	long tmp_avg2;

	
    /* Open spidev0.0 with mode 0 and max speed 1MHz */
    if (spi_open(&spi, "/dev/spidev0.0", 0, 1000000) < 0) {
        fprintf(stderr, "spi_open(): %s\n", spi_errmsg(&spi));
        exit(1);
    }
	
	/* Set_Offset */

	i=0;
	j=0;
		printf("Wait: Getting Tare\n");

		while(i<=nsamples)
		{	/* Shift out 1 byte of 0x00 and read DOUT */
		
			if (spi_transfer(&spi, buf, buf0, sizeof(buf)) < 0) 
			{
			        fprintf(stderr, "spi_transfer(): %s\n", spi_errmsg(&spi));
			        exit(1);
			}
		
			if(buf0[0] == 0x00)
			{
			spi_transfer(&spi, buf1, buf2, sizeof(buf2));
			desired_bits = get_bits(buf2);
			samples[i] = desired_bits;
			i++;
			}
		}
		
		for(i=0;i<nsamples;i++)
		{		
		tmp_avg += samples[i];
		}
	//usleep(6000);
  		

  tmp_avg = tmp_avg / nsamples;


  tmp_avg2 = 0;
  j=0;

  filter_low =  (float) tmp_avg * (1.0 - spread_percent);
  filter_high = (float) tmp_avg * (1.0 + spread_percent);

//  printf("%d %d\n", (int) filter_low, (int) filter_high);

  for(i=0;i<nsamples;i++) {
	if ((samples[i] < filter_high && samples[i] > filter_low) || 
            (samples[i] > filter_high && samples[i] < filter_low) ) {
		tmp_avg2 += samples[i];
	        j++;
	}
  }

  if (j == 0) {
    printf("No data to consider: Change the spread or the number of samples\n");
   exit(255);

  }


	offset = tmp_avg2/j;
	//offset = tmp_avg;	
	printf("Offset: %d\n", offset);
	printf("Starting...\n" );
usleep(5000000);
while(1)
{
	 
	/* Shift out 1 byte of 0x00 and read DOUT */
	if (spi_transfer(&spi, buf, buf0, sizeof(buf)) < 0) 
	{
	        fprintf(stderr, "spi_transfer(): %s\n", spi_errmsg(&spi));
	        exit(1);
	}
	/*If DOUT is 0x00, Shift out 4 bytes that represents 24 pulses + 1 of set gain(128)  */
	if(buf0[0] == 0x00){
		spi_transfer(&spi, buf1, buf2, sizeof(buf2));
		desired_bits = get_bits(buf2);
	}
	
	printf("Value: %d grams\n", (desired_bits - offset)/scale);

	
}
    spi_close(&spi);
    return 0;
}
Ejemplo n.º 22
0
/*!
    \brief closes an opened spi communication port

	\param	 		fd			-	file descriptor of an opened SPI channel

	\return			upon successful completion, the function shall return 0.
					Otherwise, -1 shall be returned

    \sa             spi_Open
	\note
    \warning
*/
int spi_Close(Fd_t fd)
{
    spi_close((void *)fd);
    return 0;
}
Ejemplo n.º 23
0
void fifo_close(unsigned char id){
	fifo_array[id].open = -1 ;
	if(id == 0){
		spi_close();
	}
}
Ejemplo n.º 24
0
Archivo: main.c Proyecto: lwalkera/R2C2
int main() {
	// DeInit NVIC and SCBNVIC
	NVIC_DeInit();
	NVIC_SCBDeInit();

	/* Configure the NVIC Preemption Priority Bits:
	 * two (2) bits of preemption priority, six (6) bits of sub-priority.
	 * Since the Number of Bits used for Priority Levels is five (5), so the
	 * actual bit number of sub-priority is three (3)
	 */
	NVIC_SetPriorityGrouping(0x05);

	NVIC_SetVTOR(0x00000000);

	#ifdef	UARTDEBUG
		uart_init();
	#endif

	BlockDevInit();

#ifdef	UARTDEBUG
	if (1) {
		U32 size;
		BlockDevGetSize(&size);
		DBG("Found SD card of size %d", size);
		BlockDevGetBlockLength(&size);
		DBG("block length %d", size);
	}
#endif

	if (bootloader_button_pressed() || (user_code_present() == 0)) {
		DBG("entering bootloader");
		init_usb_msc_device();

		for (;usb_msc_not_ejected();)
			USBHwISR();

		DBG("usb ejected, rebooting");

		USBHwConnect(FALSE);
		spi_close();
	}
	else {
		if ((r = f_mount(0, &fatfs)) == FR_OK) {
			if ((r = f_open(&f, "/firmware.bin", FA_READ | FA_OPEN_EXISTING)) == FR_OK) {
				unsigned int fs = f_size(&f);
				DBG("found firmware.bin with %u bytes", fs);
				if ((fs > 0) && (fs <= USER_FLASH_SIZE)) {
					U8 buffer[FLASH_BUF_SIZE];
					for (unsigned int i = 0; i < fs; i += FLASH_BUF_SIZE) {
						unsigned int j = FLASH_BUF_SIZE;
						if (i + j > fs)
							j = fs - i;
						DBG("writing %d-%d", i, i+j);
						if ((r = f_read(&f, buffer, j, &j)) == FR_OK) {
							// pad last block to a full sector size
							while (j < FLASH_BUF_SIZE) {
								buffer[j++] = 0xFF;
							}
							write_flash((unsigned int *) (USER_FLASH_START + i), (char *) &buffer, j);
						}
						else {
							DBG("read failed: %d", r);
							i = fs;
						}
					}
					r = f_close(&f);
					r = f_unlink("/firmware.bck");
					r = f_rename("/firmware.bin", "/firmware.bck");
				}
			}
			else {
				DBG("open \"/firmware.bin\" failed: %d", r);
			}
			#ifdef	GENERATE_FIRMWARE_CUR
				if (f_open(&f, "/firmware.bck", FA_READ | FA_OPEN_EXISTING)) {
					f_close(&f);
				}
				else {
					// no firmware.bck, generate one!
					if (f_open(&f, "/firmware.bck", FA_WRITE | FA_CREATE_NEW) == FR_OK) {
						U8 *flash = (U8 *) USER_FLASH_START;

						f_close(&f);
					}
				}
			#endif
			// elm-chan's fatfs doesn't have an unmount function
			// f_umount(&fatfs);
		}
		else {
			DBG("mount failed: %d", r);
		}
		spi_close();

		if (user_code_present()) {
			DBG("starting user code...");
			execute_user_code();
		}
		else {
			DBG("user code invalid, rebooting");
		}
	}
	NVIC_SystemReset();
}
Ejemplo n.º 25
0
static void loras_spi_close(LORA* lora)
{
    spi_close(lora->spi.port);
}