int do_test() { Gpio gpio; if (gpio.start() < 0) { return -1; } gpio.configgpio(LED_CNF | LED_pinR); gpio.configgpio(LED_CNF | LED_pinG); gpio.configgpio(LED_CNF | LED_pinB); gpio.gpiowrite(LED_pinR, LED_OFF); gpio.gpiowrite(LED_pinG, LED_OFF); gpio.gpiowrite(LED_pinB, LED_OFF); printf("off\n"); sleep(2); gpio.gpiowrite(LED_pinR, LED_ON); gpio.gpiowrite(LED_pinG, LED_OFF); gpio.gpiowrite(LED_pinB, LED_OFF); printf("red\n"); sleep(2); gpio.gpiowrite(LED_pinR, LED_OFF); gpio.gpiowrite(LED_pinG, LED_ON); gpio.gpiowrite(LED_pinB, LED_OFF); printf("green\n"); sleep(2); gpio.gpiowrite(LED_pinR, LED_OFF); gpio.gpiowrite(LED_pinG, LED_OFF); gpio.gpiowrite(LED_pinB, LED_ON); printf("blue\n"); sleep(2); gpio.gpiowrite(LED_pinR, LED_OFF); gpio.gpiowrite(LED_pinG, LED_OFF); gpio.gpiowrite(LED_pinB, LED_OFF); printf("off\n"); gpio.stop(); return 0; }
// Exemple : Blink diode pin 4 int main(int argc, char *argv[]) { Gpio gpio; // The GPIO struct sigaction sigactionStruct; sigactionStruct.sa_handler = sigHandler; sigactionStruct.sa_flags = 0; sigemptyset(&sigactionStruct.sa_mask); if(sigaction(SIGINT, &sigactionStruct, NULL) == -1) { cerr << "SIGACTION FAILED : " << string(strerror(errno)) << endl; return(EXIT_FAILURE); } gpio.addPin(4, OUT); // ADD PIN 4 (OUT) while(true) { gpio.setValueOf(4, HIGH); // WRITE 1 IN PIN 4 sleep(1); gpio.setValueOf(4, LOW); // WRITE 0 IN PIN 4 sleep(1); if(interceptedInteruption) { cout << "\nInteruption : the GPIO is going to be deleted" << endl; gpio.~Gpio(); //Delete the GPIO break; } } return(EXIT_SUCCESS); }
bool dispatch(Msg& msg) { PT_BEGIN() _gpio.init(); _gpio.setMode(Gpio::OUTPUT_PP); while (true) { timeout(_msecInterval); PT_YIELD_UNTIL( msg.is(_mqtt, SIG_CONNECTED) || msg.is(_mqtt, SIG_DISCONNECTED) || timeout()); switch (msg.signal) { case SIG_TICK: { _gpio.write(_isOn); _isOn = !_isOn; break; } case SIG_CONNECTED: { _msecInterval = 500; break; } case SIG_DISCONNECTED: { _msecInterval = 100; break; } default: { } } } PT_END() ; }
/** * Start a thread to constantly monitor all the input pins we are * interested in. When a state change is detected we store the * time of the change. This creates a buffer so we can still see * changes that happened a short time ago (so we don't miss any). * * It also writes PWM outputs and is responsible for writing random * data, sine waves etc. to these outputs. */ bool Gpio::startMonitor() { if (!mInit){ fprintf(stderr, "GPIO not initialised\n"); return false; } // Do we have anything to monitor? if (mMonitorList.size() == 0) return true; bool usingPwm = false; for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); if (obj->getType() == PWM){ // Don't start outputting PWM until we execute a relevant command mMonType[pin] = INACTIVE; mMonMutex[pin] = PTHREAD_MUTEX_INITIALIZER; // Set to full range initially (range map is in millis) mRangeMapMin[pin] = 0; mRangeMapMax[pin] = 100000; usingPwm = true; } else { // Input pins are always monitored initMonitorInput(pin); } } if (usingPwm){ // Start ServoBlaster. We use this instead of hardware // PWM as there is only one hardware PWM pin on the Pi // and hardware PWM interferes with analog audio. if (!startServoBlaster()) return false; } // Start monitor thread if (pthread_create(&mMonitorId, NULL, monitor, NULL) != 0){ fprintf(stderr, "** Failed to start gpio monitor\n"); return false; } // Wait for monitor to start for (int retries = 0; retries < 15; retries++){ if (mMonitorRunning) return true; Engine::sleep(200); } printf("** Failed to start gpio monitor\n"); return false; }
int main(int argc, char *argv[]) { gpioInit(); Gpio gpio; (argc == 1) ? gpio.laserOff() : gpio.laserOn(); cout << "argc: " << argc << endl; }
int main () { Gpio E (Gpio::E); E.setOutPin(led); while (1) { E.ChangePinState(led); delay_ms(1000); } }
void main_remi() { char buf[27] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' ,'n', 'o', 'p' ,'q' ,'r', 's','t','u','v','w','x','y','z',' '}; // Setup STM32 system (clock, PLL and Flash configuration) SystemInit(); Gpio *gpioA = STM32F103::getGpioA(); // Set default port behavior GpioConfiguration portConfig(Gpio::AF_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ); gpioA->configure(portConfig); Uart *uart1 = STM32F103::getUart1(); UartConfiguration uart1Config; uart1Config.baudrate = 9600; uart1Config.stopBit = Uart::UART_1_STOPBIT; uart1Config.parityEnable = Uart::UART_PARITY_DISABLE; uart1Config.wordLenght = Uart::UART_WORD_LENGTH_8BIT; uart1->configure(uart1Config); //Uart *uart2 = STM32F103::getUart2(); // Uart2 config // Tag each Uart with their respective source uart1->setTag(Peripheral::Controller); //uart2->setTag(Peripheral::Drive); // Configure blinking led GpioPinConfiguration ledPinConfig; ledPinConfig.pin = Gpio::GP_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ; gpioA->getPin(0)->configure(ledPinConfig); GpioPin *led = gpioA->getPin(0); // Blink led while(1) { led->setHigh(); // On for(uint32_t i=0; i<1000000; i++){ uart1->poll(); } uart1->write((char *)buf, 27); led->setLow(); // Off for(uint32_t i=0; i<1000000; i++){ uart1->poll(); } } }
int main() { Gpio B (Gpio::B); B.settingPin (pin); while (1) { B.ChangePinState (pin); delay_ms (1000); } }
int main () { Buffer <uint8_t> val (5); Gpio * pins [2]; Gpio D (Gpio::Port::D); D.settingPin(led); pins[0] = &D; pins[0]->setPin(led); while (1) { D.toglePin (led); delay_ms(1000); } }
// ----------------------------------------------------------------------------- // Signal Handler static void sighandler (int sig) { g.close(); cout << endl << "everything was closed."<< endl << "Have a nice day !" << endl; exit (EXIT_SUCCESS); }
bool Gpio::stopPwmRange(int startPin, int endPin) { if (!mInit){ fprintf(stderr, "GPIO not initialised\n"); return false; } for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); if (mMonType[pin] != MON_IN && pin >= startPin && pin <= endPin) resetPwm(pin, -1); } return true; }
bool Gpio::setStateRange(int state, int startPin, int endPin) { if (!mInit){ fprintf(stderr, "GPIO not initialised\n"); return false; } int pwmVal; if (state == 0) pwmVal = 0; else pwmVal = 100000; for (std::list<Gpio*>::iterator iter = mOutputList.begin(); iter != mOutputList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); if (obj->getType() == OUT_PIN && pin >= startPin && pin <= endPin) digitalWrite(obj->getPin(), state); } for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); if (obj->getType() == PWM && pin >= startPin && pin <= endPin){ if (mLastValue[pin] != pwmVal) resetPwm(pin, pwmVal); } } return true; }
bool Gpio::startPwmRange(MonitorType pwmType, int startPin, int endPin, int param1, int param2, int param3, int param4, int param5, bool loop) { bool res = true; for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); if (mMonType[pin] != MON_IN && pin >= startPin && pin <= endPin){ if (!obj->startPwm(pwmType, param1, param2, param3, param4, param5, loop)) { res = false; } } } return res; }
void XmlReader::parseGpios() { std::string entries = findTag("gpios"); if(entries.length() > 0) { std::vector<std::string> lines = Tools::explode(";", entries); for(int l=0; l<lines.size(); l++) { if(lines[l].length() > 0) { std::vector<std::string> words = Tools::explode(":", lines[l]); Gpio g; for(int w=0; w<words.size(); w++) { if(typeid(words.at(0))==typeid(std::string)) g.setName(words[0]); if(typeid(words.at(1))==typeid(std::string)) g.setGpio(atoi(words[1].c_str())); } gpios.push_back(g); } } } }
void blinky() { // Setup STM32 system (clock, PLL and Flash configuration) SystemInit(); Gpio *gpioA = STM32F103::getGpioA(); // Configure blinking led GpioPinConfiguration ledPinConfig; ledPinConfig.pin = Gpio::GP_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ; gpioA->getPin(0)->configure(ledPinConfig); GpioPin *led = gpioA->getPin(0); while(1) { led->setHigh(); // On for(uint32_t i=0; i<1000000; i++); led->setLow(); // Off for(uint32_t i=0; i<1000000; i++); } }
/** * Runs in a separate thread */ void *Gpio::monitor(void *arg) { mMonitorRunning = true; while (mMonitorRunning){ double now = Engine::timeNow(); for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; int pin = obj->getPin(); switch (mMonType[pin]) { case INACTIVE: break; case MON_IN: monitorInput(pin, now); break; case PWM_RANDOM: monitorPwmRandom(pin, now); break; case PWM_LINEAR: monitorPwmLinear(pin, now); break; case PWM_SINE: monitorPwmSine(pin, now); break; default: printf("Unknown monitor pin type\n", mMonType[pin]); mMonitorRunning = false; pthread_exit(NULL); } } Engine::sleep(10); } pthread_exit(NULL); }
// ----------------------------------------------------------------------------- int main (int argc, char **argv) { g.open(); led.setMode (Pin::ModeOutput); // the led pin is an output led.write (0); // turn off the led // sighandler() intercepts CTRL+C signal (SIGINT, sighandler); signal (SIGTERM, sighandler); cout << "Press Ctrl+C to abort ..." << endl; for (;;) { led.toggle(); // blinking led clk.delay (1000); cout << '.' << flush; // print one point per second } return 0; }
// This example code is in the public domain. #include <iostream> #include <csignal> #include <cstdlib> #include <sysio/clock.h> #include <sysio/gpio.h> using namespace std; using namespace Sysio; // <DANGER> Be careful !!! Before launching this program : // -> Check that the pin below is well connected to an LED ! <- const int ledPin = 0; // Header Pin 11: GPIO17 for RPi, GPIOA0 for NanoPi Clock clk; // the clock of our program used for time calculation... Gpio g; // our GPIO port Pin & led = g.pin (ledPin); // led is a reference on pin 11 of the GPIO // ----------------------------------------------------------------------------- // Signal Handler static void sighandler (int sig) { g.close(); cout << endl << "everything was closed."<< endl << "Have a nice day !" << endl; exit (EXIT_SUCCESS); } // ----------------------------------------------------------------------------- int main (int argc, char **argv) {
void main_francois() { // Setup STM32 system (clock, PLL and Flash configuration) SystemInit(); Gpio *gpioA = STM32F103::getGpioA(); Gpio *gpioB = STM32F103::getGpioB(); Gpio *gpioC = STM32F103::getGpioC(); // Set default port behavior GpioConfiguration portConfig(Gpio::FLOATING_INPUT); gpioA->configure(portConfig); // Configure blinking led GpioPinConfiguration ledPinConfig; ledPinConfig.pin = Gpio::GP_PUSH_PULL_OUTPUT | Gpio::OUTPUT_SPEED_50MHZ; gpioA->getPin(0)->configure(ledPinConfig); GpioPin *led = gpioA->getPin(0); // Create the usb port Usb* usb = STM32F103::getUsb(); // Create a new NES controller interface AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_DISABLE; // JTAG remap NesControllerInterface* nesInterface = new NesControllerInterface(gpioB->getPin(3), gpioB->getPin(4), gpioC->getPin(5)); usb->addEventListener(nesInterface); usb->listenForDevice(); while(!usb->deviceDetected()); //debug // Blink led fast led->setHigh(); // On for(uint32_t i=0; i<100000; i++); led->setLow(); // Off for(uint32_t i=0; i<100000; i++); usb->enumerateDevice(); // Blink led while(1) { //if(usb->deviceDetected()) { /*led->setHigh(); // On for(uint32_t i=0; i<100000; i++); led->setLow(); // Off for(uint32_t i=0; i<100000; i++);*/ //if(!usb->deviceEnumerated()) { //debug // Blink led fast /*GPIOA->BSRR |= 0x01; // On for(uint32_t i=0; i<100000; i++); GPIOA->BRR |= 0x01; // Off for(uint32_t i=0; i<100000; i++); usb->enumerateDevice();*/ //} //else { usb->serviceHid(); //} //} /* led->setHigh(); // On for(uint32_t i=0; i<1000000; i++); led->setLow(); // Off for(uint32_t i=0; i<1000000; i++); */ // Simulate an external interrupt //EXTI->SWIER |= EXTI_SWIER_SWIER1; } }
bool Gpio::startServoBlaster() { // Stop ServoBlaster if it's already running mServoBlasterPid = Engine::findProcess(SB_COMMAND); if (mServoBlasterPid != -1) stopServoBlaster(); if (Engine::displayOn) printf("Starting ServoBlaster (%s)\n", SB_COMMAND); mServoBlasterPid = fork(); if (mServoBlasterPid == -1){ fprintf(stderr, "** Failed to create ServoBlaster process\n"); return false; } if (mServoBlasterPid != 0){ // This is the parent process // Make sure ServoBlaster started int status; for (int retries = 0; retries < 15; retries++){ if (waitpid(mServoBlasterPid, &status, WNOHANG) != -1){ sleep(1); mServoBlasterOut = open(SB_DEVICE, O_WRONLY|O_SYNC); if (mServoBlasterOut == -1){ fprintf(stderr, "** Failed to open %s\n", SB_DEVICE); return false; } return true; } Engine::sleep(200); } fprintf(stderr, "ServoBlaster failed to start\n"); return false; } // Make ServoBlaster use same pin mapping as wiringPi. // We are mapping wiringPi pin number to physical pin number. const int pinMap[] = {11,12,13,15,16,18,22,7,3,5,24,26,19,21,23,8,10}; int servoBlasterPin[MAX_PWM_PINS]; // ServoBlaster needs to know which pins we are using for PWM for (int i = 0; i < MAX_PWM_PINS; i++) servoBlasterPin[i] = 0; for (auto iter = mMonitorList.begin(); iter != mMonitorList.end(); iter++) { Gpio *obj = *iter; if (obj->getType() == PWM){ int pin = obj->getPin(); servoBlasterPin[pin] = pinMap[pin]; } } // First arg is the pin list char argv1[256]; sprintf(argv1, "--p1pins=%d", servoBlasterPin[0]); char addStr[64]; for (int i = 1; i < MAX_PWM_PINS; i++){ sprintf(addStr, ",%d", servoBlasterPin[i]); strcat(argv1, addStr); } // Second arg is the cycle time char argv2[256]; sprintf(argv2, "--cycle-time=%dus", SB_CYCLE_TIME); const char *argv[16]; argv[0] = SB_COMMAND; argv[1] = argv1; argv[2] = argv2; for (int i = 0;; i++){ argv[i+3] = SB_PARAMS[i]; if (SB_PARAMS[i] == NULL) break; } // redirect stdout and stderr freopen("/tmp/servoblaster.log", "w", stdout); freopen("/tmp/servoblaster.log", "w", stderr); // Try from current dir first char command[256]; sprintf(command, "./%s", SB_COMMAND); execv(command, (char* const*)argv); // execv only returns if an error occurs // Now try from PATH execvp(SB_COMMAND, (char* const*)argv); // execv only returns if an error occurs fprintf(stderr, "** Failed to start ServoBlaster using command:\n"); fprintf(stderr, "%s", SB_COMMAND); for (int i = 0; argv[i] != NULL; i++) fprintf(stderr, " %s", argv[i]); fprintf(stderr, "\n"); return true; }
int main(int argc, char* argv[]) { int status = 0; char *device; char *function; char *json; rapidjson::Document jsonDoc; ExpLed expLedObj; Gpio gpioObj; int verbosity = UBUS_INTF_VERBOSE; int debugLevel = UBUS_INTF_DEBUG; //// initialization // allocate memory for the pointers device = new char[1024]; function = new char[1024]; json = new char[1024]; // parse the command line arguments if (UBUS_INTF_VERBOSE) printf("Parsing arguments:\n"); for (int i = 1; i < argc; i++) { if ( strcmp(argv[i], "-device") == 0 ) { // get the device name strcpy( device, argv[++i] ); if (UBUS_INTF_VERBOSE) printf("\tparsing device: %s\n", device); } else if ( strcmp(argv[i], "-function") == 0 ) { // get the function name strcpy( function, argv[++i] ); if (UBUS_INTF_VERBOSE) printf("\tparsing function: %s\n", function); } else if ( strcmp(argv[i], "-json") == 0 ) { // get the json strcpy( json, argv[++i] ); if (UBUS_INTF_VERBOSE) printf("\tparsing json: %s\n", json); } else if ( strcmp(argv[i], "-verbose") == 0 ) { // change the verbosity setting verbosity = 1; } else if ( strcmp(argv[i], "-debug") == 0 ) { // change the debug setting debugLevel = 1; } } // class initialization expLedObj.SetVerbosity(verbosity); expLedObj.SetDebugMode(debugLevel); gpioObj.SetVerbosity(verbosity); gpioObj.SetDebugMode(debugLevel); // check device against list of existing devices /* TODO: make this cleaner */ if (UBUS_INTF_VERBOSE) printf("Running process on "); if (strcmp( device, "expled") == 0) { if (UBUS_INTF_VERBOSE) printf("expLed Object:\n\n"); expLedObj.Process(function, json); } else if (strcmp( device, "gpio") == 0) { if (UBUS_INTF_VERBOSE) printf("gpio Object:\n\n"); gpioObj.Process(function, json); } //// clean-up // free dynamically allocated memory delete[] device; delete[] function; delete[] json; return 0; }
int Input::number() { Gpio *gpio = m_monitor->gpio(); return gpio->value(); }
int main(int argc, char **argv) { Gpio gpio; /// open device (/dev/mem) if (gpio.openDevice() < 0) { std::cerr << __func__ << ":" << __LINE__ << " openDevice failed" << std::endl; return 0; } #if 0 /// set all gpio's as output - skip Gpio2 (i2c SCL) and Gpio3 (i2c data) for (int i = 0; i < GPIO::GpioSize; i++) { if (GPIO::GpioList[i] == GPIO::Gpio2) continue; /// i2c scl if (GPIO::GpioList[i] == GPIO::Gpio3) continue; /// i2c data gpio.setGpioDirection(GPIO::GpioList[i], GPIO::GpioOutput); } #endif int output = GPIO::Gpio4; gpio.setGpioDirection(output, GPIO::GpioOutput); /// toggle outputs //for (int loop = 0; loop < 100; loop++) { while (true) { /// wait for MicroSeconds microseconds usleep(MicroSeconds); /// switch all gpio's on - skip Gpio2 and Gpio3- this is i2c SCL and sda #if 0 std::cout << "Turning all gpio's on" << std::endl; for (int i = 0; i < GPIO::GpioSize; i++) { if (GPIO::GpioList[i] == GPIO::Gpio2) continue; if (GPIO::GpioList[i] == GPIO::Gpio3) continue; gpio.setGpio(GPIO::GpioList[i], GPIO::GpioOn); } #endif std::cout << "Turning on gpio " << std::dec << output << std::endl; gpio.setGpio(output, GPIO::GpioOn); /// wait for MicroSeconds microseconds usleep(MicroSeconds); std::cout << "Turning off gpio " << std::dec << output << std::endl; gpio.setGpio(output, GPIO::GpioOff); #if 0 /// switch all gpio's off - skip Gpio2 - this is i2c SCL std::cout << "Turning all gpio's off" << std::endl; for (int i = 0; i < GPIO::GpioSize; i++) { if (GPIO::GpioList[i] == GPIO::Gpio2) continue; if (GPIO::GpioList[i] == GPIO::Gpio3) continue; gpio.setGpio(GPIO::GpioList[i], GPIO::GpioOff); } #endif } return 0; }