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; }
/* * \brief Open a serial port. The serial port is registered for further operations. * * \param id the instance id * \param portname the serial port to open, e.g. /dev/ttyUSB0, /dev/ttyACM0, /dev/spidev1.1 * * \return 0 in case of a success, -1 in case of an error */ int serial_open(int id, char* portname) { int ret = 0; if(strstr(portname, "tty")) { serials[id].fd = tty_open(portname); } else if(strstr(portname, "spi")) { serials[id].fd = spi_open(portname); } if(serials[id].fd < 0) { ret = -1; } return ret; }
void imu_init(void) { pin_init(&IMU_MOSI, (unsigned int *)&PORTB, (unsigned int *)&TRISB, (unsigned int *)NULL, 8, -1, 0, 8, (unsigned int *)&RPOR4); pin_init(&IMU_SCK, (unsigned int *)&PORTB, (unsigned int*)&TRISB, (unsigned int *)NULL, 9, -1, 8, 9, (unsigned int*)&RPOR4); pin_init(&IMU_MISO, (unsigned int *)&PORTB, (unsigned int *)&TRISB, (unsigned int *)NULL, 14, -1, 0, 14, (unsigned int *)&RPOR7); pin_init(&ACCEL_CS, (unsigned int*)&PORTB, (unsigned int *)&TRISB, (unsigned int *)NULL, 13, -1, 0, -1, (unsigned int *)NULL); pin_init(&GYRO_CS, (unsigned int *)&PORTB, (unsigned int *)&TRISB, (unsigned int *)NULL, 11, -1, 0, -1, (unsigned int *)NULL); pin_digitalOut(&ACCEL_CS); pin_digitalOut(&GYRO_CS); pin_set(&GYRO_CS); pin_set(&ACCEL_CS); spi_open(&spi1, &IMU_MISO, &IMU_MOSI, &IMU_SCK, 2e6); accel_write(I2CADD, 0x80); //Disable I2C }
int main(int argc, char* argv[]) { unsigned char data = 0xAF; if(argc <= 1){ printf("too few args, try %s /dev/spidev0.0\n",argv[0]); return -1; } // open and configure SPI channel. (/dev/spidev0.0 for example) if(spi_open(argv[1]) < 0){ printf("spi_open failed\n"); return -1; } writeByte (IODIRA, 0x00) ; // Port A -> Outputs writeByte (GPIOA, 0xFF) ; //writeByte (IPOLB, 0x01) ; // invert lsb //writeByte (GPPUB, 0xFF) ; // enable pullups. writeByte (IODIRB, 0xFF) ; // Port B -> Inputs data = readByte (GPIOB) ; printf("RECEIVED: %.2X\n",data); close(spi_fd); return 0; }
/** * Open SPI device with given configuration * * @param self * @param args * @param kwargs * @return none */ static PyObject* py_open(PyObject* self, PyObject* args, PyObject* kwargs){ int ret; char *device; spi_config_t config = {0}; /* Set default values */ config.mode = 0; config.bits_per_word = 8; config.speed = 100000; config.delay = 0; /* Define keywords */ static char *kwlist [] = { "device", "mode", "bits_per_word", "speed", "delay", NULL }; /* Parse arguments */ if(!PyArg_ParseTupleAndKeywords( args, kwargs, "s|iiii", kwlist, &device, &config.mode, &config.bits_per_word, &config.speed, &config.delay)){ return NULL; } /* Open the device */ ret = spi_open(device, config); if(ret < 0 ){ return PyErr_SetFromErrno(PyExc_IOError); }else{ fd = ret; } Py_RETURN_NONE; }
static bool loras_spi_open(LORA* lora) { SPI_MODE mode; LORA_CONFIG *config = &lora->config; mode.cs_pin = config->spi_cs_pin; mode.cpha = 0; mode.cpol = 0; mode.size = 8; mode.io_mode = 1; mode.order = SPI_MSBFIRST; lora->spi.port = config->spi_port; #if defined(STM32) SPI_SPEED speed; unsigned int bus_clock, div; bus_clock = power_get_clock(POWER_BUS_CLOCK); bool found = false; for (speed = SPI_DIV_2; speed <= SPI_DIV_256; ++speed) { div = (1 << (speed+1)); if ((bus_clock / div) <= (LORA_SCK_FREQUENCY_MHZ * 1000000)) { found = true; break; } } if (!found) return false; mode.speed = speed; #elif defined (MK22) mode.baudrate_mbps = LORA_SCK_FREQUENCY_MHZ; //todo: if io mode then control cs externally (iio_complete will notify os that spi transfer is competed) //note: ctrl_cs can be removed (if need) //mode.ctrl_cs = !mode.io_mode; #else #error unsupported #endif spi_open(lora->spi.port, &mode); return true; }
int lpd8806_init(void) { int spi_fd,i; int result; spi_fd=spi_open("/dev/spidev0.0", SPI_MODE_0, 100000, 8); if (spi_fd<0) { return spi_fd; } /* Send a byte acting as a start bit */ for(i=0;i<128;i++) zeros[i]=0; for(i=0;i<128;i++) { result=write(spi_fd,&zeros[i],1); if (result<1) { printf("error!\n"); exit(-1); } } return spi_fd; }
int main(int argc, char* argv[]) { unsigned int data = 0xAAAA; /* if(argc < 1){ printf("too few args, try %s /dev/spidev0.0\n",argv[0]); return -1; } */ // open and configure SPI channel. (/dev/spidev0.0 for example) if((spi_open(argv[1])) < 0){ printf("spi_open failed\n"); return -1; } // send one Byte (0xAAAA) - receive one byte. spi_wr_1b(data,0); printf("RECEIVED: %.2X\n",data); // close SPI channel close(spi_fd); return 0; }
int16_t main(void) { init_clock(); init_ui(); init_pin(); init_spi(); ENC_MISO = &D[1]; ENC_MOSI = &D[0]; ENC_SCK = &D[2]; ENC_NCS = &D[3]; pin_digitalOut(ENC_NCS); pin_set(ENC_NCS); spi_open(&spi1, ENC_MISO, ENC_MOSI, ENC_SCK, 2e6); InitUSB(); // initialize the USB registers and serial interface engine while (USB_USWSTAT!=CONFIG_STATE) { // while the peripheral is not configured... ServiceUSB(); // ...service USB requests } while (1) { ServiceUSB(); // service any pending USB requests } }
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; }
int poweron_self_check() { int ret = -1; int timeout = 0; char set_system_time[50]; flying_attitude_s *p; //--------------spi initial------------------ ret=spi_open(); printf("CPLD logic version:%d\n",get_fpga_version()); printf("----------------------------------------------------------------\n"); #ifndef debug if(ret<0) fault_status_return(ret); #endif /* ret=adc_init(); #ifndef debug if(ret<0) fault_status_return(ret); #endif */ //---------------imu initial----------------- ret = sensor_open(); #ifndef debug if (ret < 0) { fault_status_return(ret); } #endif pressure_sensor_init(); set_flying_status(AIRCRAFT_PREPARING); if(command==0){ //UAV is working in normal mode // reset CPLD ,this should be check later ,if CPLD should be reset when CPU recovers from failure. reset_control_register(CTRL_REG_MASK_MANUAL); // wait for flying attitude sensor data while (timeout <= 600) { sleep(1); if(flying_attitude_sensor_is_active()) break; timeout++; } if (timeout >600) { print_err("flying attitude sensor is inactive, please check serial port is connected\n"); goto exit; } print_debug("Flying attitude sensor is active\n"); p=get_flying_attitude(); //printf("system beijing time %d-%d-%d,%d:%d:%d\n",p->year,p->month,p->day,p->hour+8,p->min,p->sec); sprintf(set_system_time,"date -s \"%d-%d-%d %d:%d:%d\"",p->year+2000,p->month,p->day,p->hour+8,p->min,p->sec); //printf("%s\n",set_system_time); system(set_system_time); }else if(command==1){ //UAV is working in test mode reset_control_register(CTRL_REG_MASK_MANUAL); printf("uav is working in test mode,IMU is by passed,using test data instead\n"); }else if(command==2){ //UAV is in mannual mode ,for pwm data capture set_flying_status(AIRCRAFT_MANUAL_MODE); set_control_register(CTRL_REG_MASK_MANUAL); set_system_status(SYS_PREPARE_SETTING); printf("UAV is now working in data capturing mode\n"); }else{ printf(" error command,please check the usage:\n"); printf(" usage: uav [command] [gap] ]\n"); printf(" [command]: 0--normal mode,used when run in the air\n"); printf(" [command]: 1--test mode,used for platform test.use this mode \n"); printf(" when no IMU connected ,\n"); printf(" [command]: 2--manual mode,used when capturing PWM data\n"); printf(" [frequency]: the frequency (ms/frame) in which UAV send fly status data\n"); } generate_file_name(log_file_name); if((fp_fly_status=fopen(log_file_name,"wb+"))==NULL){ printf("can not open file:%s\n",log_file_name); } heli_configuration_init(); control_parameter_init(); servo_test_enable=0; while (1) { if(get_system_status() < SYS_PREPARE_STEERING_TEST){ flying_status_return(1); usleep(500000); }else if(get_system_status() == SYS_PREPARE_STEERING_TEST){ steering_test(); usleep(20000); }else if(get_system_status() == SYS_PREPARE_TAKEOFF){ return 0; } /* if (get_system_status() >= SYS_PREPARE_SETTING) { print_debug("Link is ready\n"); return 0; } link_testing_send(); usleep(20000); //20ms */ } exit: sensor_close(); return ret; }
/*************************************************************************** main program ***************************************************************************/ int main(int argc, char* argv[]) { /*************************************************************************** Initialize variables ***************************************************************************/ int ret; unsigned int n = 0; //----- SET SPI MODE ----- //SPI_MODE_0 (0,0) CPOL = 0, CPHA = 0, Clock idle low, data is clocked in on rising edge, output data (change) on falling edge //SPI_MODE_1 (0,1) CPOL = 0, CPHA = 1, Clock idle low, data is clocked in on falling edge, output data (change) on rising edge //SPI_MODE_2 (1,0) CPOL = 1, CPHA = 0, Clock idle high, data is clocked in on falling edge, output data (change) on rising edge //SPI_MODE_3 (1,1) CPOL = 1, CPHA = 1, Clock idle high, data is clocked in on rising, edge output data (change) on falling edge uint8_t lcd_spi_config = SPI_MODE_0; uint8_t ads_spi_config = SPI_MODE_1; int ShmID; pid_t pid_stdin; pid_t pid_pwm; Controller *ctlPTR; //this is the key structure that holds all the shared data. /*************************************************************************** setup shared memory ***************************************************************************/ ShmID = shmget(IPC_PRIVATE, sizeof(Controller), IPC_CREAT | 0666); if (ShmID < 0) { fprintf(stderr,"reflowControl Exiting - could not initialize shared memory area (shmget)\n"); exit(1); } ctlPTR = (Controller *) shmat(ShmID, NULL, 0); //assign controller if ((void *) ctlPTR == (void *) -1) { fprintf(stderr,"reflowControl Exiting - could not attach to shared memory area (shmat)\n"); exit(1); } initializePID(ctlPTR); /*************************************************************************** setup ADS, LCD, other GPIO ***************************************************************************/ sleep(2); //sleep for 2 seconds at start to make sure Node program has started listening for IO streams //make sure output is not buffered (this program generally a child to a nodejs program) and set signal handler setbuf(stdout, NULL); //set stdout to not buffer output setbuf(stderr, NULL); //set stderr to not buffer output signal(SIGINT, sig_handler_main); //capture signal interrupt ^C to cleanly shutdown signal(SIGTERM, sig_handler_main); //capture process termination signal to cleanly shutdown //Initialize GPIO - see http://elinux.org/RPi_Low-level_peripherals#C_2 // Set up gpi pointer for direct register access setup_io(); // Set GPIO pin 23 SSR1_GPIO to output INP_GPIO(SSR1_GPIO); // must use INP_GPIO before we can use OUT_GPIO OUT_GPIO(SSR1_GPIO); GPIO_CLR = 1<<SSR1_GPIO; //make sure output is turned off // Set GPIO pin 22 BUZZER_GPIO to output INP_GPIO(BUZZER_GPIO); // must use INP_GPIO before we can use OUT_GPIO OUT_GPIO(BUZZER_GPIO); GPIO_SET = 1<<BUZZER_GPIO; //make sure output is turned off - Buzzer is PNP, so pin high is buzzer off. // Set GPIO pin 17 LCD_RS_GPIO to output INP_GPIO(LCD_RS_GPIO); // must use INP_GPIO before we can use OUT_GPIO OUT_GPIO(LCD_RS_GPIO); // Initialize LCD ret = spi_open(&lcd_fd, 0, lcd_spi_config); //initialize lcd_fd, 0 means device 0 (LCD), SPI_MODE_0 if (ret != 0) { fprintf(stderr,"reflowControl Exiting - Could not initialize LCD\n"); exit(1); } lcd_init(); lcd_clear(); // LCD clear lcd_display_string(0,"Reflow Start", &ctlPTR->spiSemaphore); // display startup message // Initialize ADS Thermocouple chip ret=spi_open(&ads_fd, 1, ads_spi_config); if (ret != 0) { fprintf(stderr,"reflowControl Exiting - could not initialize ADS thermocouple chip\n"); exit(1); } /*************************************************************************** fork child process to manage SSR ***************************************************************************/ pid_pwm = fork(); switch(pid_pwm) { case -1: fprintf(stderr,"reflowControl Exiting - could not fork a child process for PWM (fork)\n"); exit(1); break; case 0: //child process child_main(ctlPTR); break; default: //main process printf("{\"item\": \"childProcess\", \"value\": \"PID_PWM\", \"pid\": %d}\n", pid_pwm); /*************************************************************************** fork child process to manage stdin ***************************************************************************/ pid_stdin = fork(); switch(pid_stdin) { case -1: fprintf(stderr,"reflowControl Exiting - could not fork a child process for stdin (fork)\n"); exit(1); break; case 0: //child process stdin_main(ctlPTR); break; default: //main process printf("{\"item\": \"childProcess\", \"value\": \"PID_STDIN\", \"pid\": %d}\n", pid_stdin); while (1) { n++; delay_ms(MS_SAMPLES); sampleTemp(&ctlPTR->tc1, &ctlPTR->spiSemaphore); if (n >= NSAMPLES) { ctlPTR->tc1.value = sampleMean(&ctlPTR->tc1); ctlPTR->tc1.stdev = sampleStddev(&ctlPTR->tc1); printMeasurementJSON(&ctlPTR->tc1); ctlPTR->tc1.n = 0; ctlPTR->pv = ctlPTR->tc1.value; n = 0; } } break; } } //exit kill(pid_pwm, SIGKILL); shutdown(); return(0); }
void arch_gettod(int *year, int *month, int *date, int *hour, int *min, int *sec) { #ifdef CONFIG_NIOS_SPI /********************************************************************/ /* Read the CMOS clock on the Microtronix Datacom O/S Support card. */ /* Use the SPI driver code, but circumvent the file system by using */ /* its internal functions. */ /********************************************************************/ int hr; struct /*********************************/ { /* The SPI payload. Warning: the */ unsigned short register_addr; /* sizeof() operator will return */ unsigned char value; /* a length of 4 instead of 3! */ } spi_data; /*********************************/ if ( spi_open( NULL, NULL ) ) { printk( "Cannot open SPI driver to read system CMOS clock.\n" ); *year = *month = *date = *hour = *min = *sec = 0; return; } spi_lseek( NULL, clockCS, 0 /* == SEEK_SET */ ); spi_data.register_addr = clock_write_control; spi_data.value = 0x40; // Write protect spi_write( NULL, (const char *)&spi_data, 3, NULL ); spi_data.register_addr = clock_read_sec; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); *sec = (int)bcd2char( spi_data.value ); spi_data.register_addr = clock_read_min; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); *min = (int)bcd2char( spi_data.value ); spi_data.register_addr = clock_read_hour; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); hr = (int)bcd2char( spi_data.value ); if ( hr & 0x40 ) // Check 24-hr bit hr = (hr & 0x3F) + 12; // Convert to 24-hr *hour = hr; spi_data.register_addr = clock_read_date; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); *date = (int)bcd2char( spi_data.value ); spi_data.register_addr = clock_read_month; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); *month = (int)bcd2char( spi_data.value ); spi_data.register_addr = clock_read_year; spi_data.value = 0; spi_read( NULL, (char *)&spi_data, 3, NULL ); *year = (int)bcd2char( spi_data.value ); spi_release( NULL, NULL ); #else *year = *month = *date = *hour = *min = *sec = 0; #endif }
void as5048_init() { float freq = 1000000; spi_open(&spi1,&D[1],&D[0],&D[2],freq); }
/* Not all the QUPs can be used Number of QUPs available: SPIPD_DEVICE_COUNT in SpiDriver.h Config what QUP to use: core\buses\spi\src\config\spi_[chipset].c */ int spi_driver_enable(void) { DEBUG_PRINTF("SPI Driver enable...", 0, 0); int i, k; int success=1; uint32 rc; spi_transaction_t read_transaction_info; spi_transaction_t write_transaction_info; uint8 *rd_data = NULL; uint8 *wr_data = NULL; uint32 TransferCount = 1; uint32 APTTEST_SPI_MAX_BUF_SIZE = 10; SpiInit(); // Allocate uncached, physically contiguous buffers // for the read and write data rd_data = (uint8 *)malloc((uint32)APTTEST_SPI_MAX_BUF_SIZE); if (NULL == rd_data) { //tzt_log("test_spi: Malloc for rd_data failed"); goto cleanup; } wr_data = (uint8 *)malloc((uint32)APTTEST_SPI_MAX_BUF_SIZE); if (NULL == wr_data) { //tzt_log("test_spi: Malloc for wr_data failed"); goto cleanup; } for (i = 0; i < APTTEST_SPI_MAX_BUF_SIZE; i++) { wr_data[i] = (uint8)(i + 10); rd_data[i] = 1; } read_transaction_info.buf_virt_addr = (void *)rd_data; read_transaction_info.buf_phys_addr = (void *)rd_data; //Vin: figure this out read_transaction_info.buf_len = APTTEST_SPI_MAX_BUF_SIZE; write_transaction_info.buf_virt_addr = (void *)wr_data; write_transaction_info.buf_phys_addr = (void *)wr_data; //Vin: figure this out write_transaction_info.buf_len = APTTEST_SPI_MAX_BUF_SIZE; rc = spi_open(SPI_DEVICE_5); DEBUG_PRINTF("spi_open: %x", rc, 0); // Perform a full duplex transfer for (k = 0; k < TransferCount; k++) { rc = spi_full_duplex(SPI_DEVICE_5, &test_spi_config, &write_transaction_info, &read_transaction_info); DEBUG_PRINTF("spi_full_duplex: %x", rc, 0); // Compare data written and data read back for (i = 0; i < APTTEST_SPI_MAX_BUF_SIZE; i++) { if (rd_data[i] != wr_data[i]) { success = 0; break; } } } DEBUG_PRINTF("SPI Driver enable...complete? %d", success, 0); if (!success) { for (i = 0; i < APTTEST_SPI_MAX_BUF_SIZE; i++) { DEBUG_PRINTF("Read:%d, Write:%d", rd_data[i], wr_data[i]) } return -1; } return 0; cleanup: if (NULL != rd_data) { free(rd_data); } if (NULL != wr_data) { free(wr_data); } return -2; }
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; }
int main(int argc, char* argv[]) { int ret; int i; uint8_t spi_config=0; double tval; int repeat=0; int period=1; char fname[128]; char tstring[128]; char tstring2[128]; time_t mytime; time_t desiredtime; struct timespec tstime; int not_finished=1; int elapsed=0; int showtime=0; // initialise GPIO setup_io(); INP_GPIO(LCD_RS_GPIO); // must use INP_GPIO before we can use OUT_GPIO OUT_GPIO(LCD_RS_GPIO); // parse inputs dofile=0; if (argc>2) { if (strcmp(argv[1], "msg")==0) // print to the lcd { spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } lcd_display_string(0,argv[2]); close(lcd_fd); exit(0); } } if (argc>1) { if (strcmp(argv[1], "-h")==0) // print help { printf("%s [sec] [filename]\n", argv[0]); printf("%s msg <message in quotes>\n", argv[0]); exit(0); } if (strcmp(argv[1], "lcdinit")==0) // initialize the LCD display { spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } lcd_init(); close(lcd_fd); exit(0); } if (strcmp(argv[1], "withtime")==0) { showtime=1; } else { sscanf(argv[1], "%d", &period); // period between measurements repeat=1; } if (argc>3) { if (strcmp(argv[2], "msg")==0) // print to the lcd { spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } lcd_init(); lcd_display_string(0,argv[3]); lcd_initialised=1; } } } if (argc>2) { strcpy(fname, argv[2]); // file name dofile=1; if (argc>4) { if (strcmp(argv[3], "msg")==0) // print to the lcd { spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } lcd_init(); lcd_display_string(0,argv[4]); lcd_initialised=1; } } } if (dofile) { outfile=fopen(fname, "w"); } // open SPI for ADS1118 spi_config |= SPI_CPHA; ret=spi_open(&ads_fd, 1, spi_config); if (ret!=0) // SPI error { printf("Exiting\n"); exit(1); } if (repeat==0) { // display a single measurement and exit tval=get_measurement(); if (showtime) { mytime = time(NULL); sprintf(tstring, "%d", mytime); unixtime2string(tstring, tstring2); printf("%s %#.1f\n", tstring2, tval); } else { printf("%#.1f\n", tval); } close(ads_fd); exit(0); } // open up SPI for LCD spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } if (lcd_initialised==0) lcd_init(); if (dofile) { // line 1 of the output file will contain the three column descriptions fprintf(outfile, "Time HH:MM:SS,Elapsed Sec,Temp C\n"); } // Align on an integer number of seconds and get current time mytime = time(NULL); tstime.tv_sec=mytime+1; tstime.tv_nsec=0; clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tstime, NULL); mytime++; desiredtime=mytime; signal(SIGINT, sig_handler); while(not_finished) { tval=get_measurement(); for (i=1; i<10; i++) { delay_ms(10); tval=tval+get_measurement_fast(); } tval=tval/10; // print the time, elapsed counter and temperature sprintf(tstring, "%d", mytime); unixtime2string(tstring, tstring2); if (mytime==desiredtime) { printf("%s %d %#.1f\n", tstring2, elapsed, tval); if (dofile) { fprintf(outfile, "%s,%d,%#.1f\n", tstring2, elapsed, tval); fflush(outfile); } desiredtime=desiredtime+period; } sprintf(tstring, "%s %#.1f", tstring2, tval); lcd_display_string(1, tstring); // now we sleep for a certain time mytime++; tstime.tv_sec=mytime; elapsed++; clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &tstime, NULL); } close(ads_fd); // LCD requires opposite clock polarity spi_config=0; ret=spi_open(&lcd_fd, 0, spi_config); if (ret!=0) { printf("Exiting\n"); exit(1); } lcd_init(); lcd_clear(); // LCD clear lcd_display_string(0,"Hello"); // display "ADS1118" close(lcd_fd); 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; }
void gz_spi_initialize() { spi_open("/dev/spidev0.0"); initialized = 1; }
/** * @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; }
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; }
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; }
/* * @ LCD IO init */ static void LCD_io_init() { spi_open(GPIOR_LCD_CH, 1000000); GPIOR_CFGIO_OUTPUT(LCD_PORT, LCD_DC_PIN | LCD_RST_PIN); LCD_PLAT_INIT(); }
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)); }