# libgpio example on Beaglebone



## Phishfry (Feb 6, 2018)

I am messing with libgpio and I modified the example below to work with the Beaglebone.
http://www.claydowling.com/blog:blinking_lights_with_gpio
The difference with the Beaglebone is it uses 4 gpio controllers. Labeled gpioc0-gpioc3.
Each has 32 pins assigned.
I wanted to use blink.c to run the onboard LED's for some easy testing.
This meant I needed to use gpioc1, pin 21. By default libgpio's open_gpio function defaults to gpioc0.
I noticed Emmanuel's example includes the 'unit' controller.
So i used that and it works. There are Pins 21,22,23,24 available to manipulate. All on gpioc1.

```
#include <inttypes.h>
    #include <libgpio.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
 
    gpio_handle_t handle = -1;
    int pin = 21;
    int unit = 1;
    int main(int argc, char **argv)
    {
       int low_time = 1;
       int high_time = 1;
       int ch;
 
       while((ch = getopt(argc, argv, "h:l:")) != -1) {
           switch(ch) {
           case 'h':
               high_time = strtol(optarg, NULL, 10);
               break;
           case 'l':
               low_time = strtol(optarg, NULL, 10);
               break;
           case '?':
           default:
               fprintf(stderr, "%s [-l low_time -h high_time]\n",
                   argv[0]);
               return EXIT_FAILURE;
           }
       }
 
       handle = gpio_open(unit);
       if (-1 == handle) {
           perror("gpio");
           return EXIT_FAILURE;
       }
       gpio_pin_output(handle, pin);
       while(1) {
           gpio_pin_high(handle, pin);
           sleep(high_time);
           gpio_pin_low(handle, pin);
           sleep(low_time);
       }
 
       return EXIT_SUCCESS;
    }
```


----------



## Phishfry (Feb 6, 2018)

Can anyone give some insight as to the "while h:l statement".
Is this a feature which allows command line argument like `blink.app 5:5` to change the low / high time from the default 1:1 seconds?
I am lost with strtol(optarg,NULL, 10); Is that 10 seconds? What does 10 represent?
Thanks


----------



## ondra_knezour (Feb 6, 2018)

Phishfry said:


> I am lost with strtol(optarg,NULL, 10); Is that 10 seconds? What does 10 represent?


It is numerical base of the converted number. 10 means it is decimal number, not hex or octal for example.


----------



## Phishfry (Feb 6, 2018)

Why are they converting numbers in the section of code? It seems like it should be a simple high - low and I wonder what that section does.
Is this a high-low tick- tock back and forth function?


----------



## Phishfry (Feb 6, 2018)

high_time and low_time are declared with a value before the section.


----------



## ondra_knezour (Feb 6, 2018)

I lost all my C-fu about 20 years ago and it was low quality Fu event then, but I would guess you are getting characters from command line so you have to convert them to numbers before using them in timers.

And the while loop is straightforward I think - While getting command line options, if it is h, convert to number and save to high_time, if it is l, convert to number and save to low_time, if it is something else, print usage info to stderr and exit.


----------



## ondra_knezour (Feb 6, 2018)

Phishfry said:


> high_time and low_time are declared with a value before the section.


Yes, they are and you can change them here. So flow is following - Set default value for both, check if user wants another values, if he does, update given variable, if he did something wrong, exit with error, else proceed.

Set some reasonable defaults and update them with user input if any exists is common way how to do that.


----------



## Phishfry (Feb 6, 2018)

OK I got it figured out. That section sets the -l and -h command options.

```
root@BBB3:/libgpio # ./blinky21.app -l
blinky21.app: option requires an argument -- l
./blinky21.app [-l low_time -h high_time]
root@BBB3:/libgpio # ./blinky21.app -l 3 -h 3
```
This blinks it at 3 seconds instead of 1 second.


----------



## Phishfry (Feb 6, 2018)

OK so 1 second high-low cycle is pretty boring.
I want millsecond instead of seconds for interval. How can I do that?

My first thought was try to use a decimal like this:
int low_time = .1
That didn't work because of data type, so I used:
double low_time=.1
That compiled but it did not seem give me any faster interval.

What do I need to change for shorter sleep time?


----------



## Snurg (Feb 6, 2018)

Use usleep() instead of sleep().

Googleing `freebsd c timer functions` gives nice result. This for example is a nice intro, considering also controller needs.

Edit: You might like to google for `am335x_pwm` too. But that is more complex stuff...


----------



## Phishfry (Feb 7, 2018)

Thanks that did great. Uses 1,000,000 = 1 second


----------



## Snurg (Feb 7, 2018)

Phishfry 
OT: I got curious about Beaglebone because STM32 / Cortex M7 still seems not supported by arm-eabi-gcc. (Had bought one kit some time ago only to find out one needs Windows+Eclipse for compiling that... Bleech...)
So I'd like to ask you, when using Beaglebone, can I use HDMI for console output and USB keyboard using FreeBSD, or is it necessary to do things via ssh only? Because I am thinking about getting a BeagleBone too...


----------



## Phishfry (Feb 7, 2018)

BBB HDMI support hit in FreeBSD11 so anything greater than that has HDMI enabled by default.

I will say for messing with PWM that FreeBSD 10.4 has PWM enabled by default with sysctl's available. No HDMI though.
Newer FreeBSD needs to have dtb modified to have working PWM. I still have one running 10.4 to avoid this hassle.

I had to use another way to flash the eMMC for FreeBSD11.
I write an FreeBSD BBB image to microSD but after writing image I gpart resize and growfs.
Then I mount and copy the FreeBSD 11 BBB image onto the microSD card in the root dir.
Boot up off the microSD card and use dd to write the image to /dev/mmcsd1.
I stole the idea from this post.
https://forums.freebsd.org/threads/61551/#post-354484

I have used the crochet script copy-to-emmc.sh but it was failing for me with FreeBSD 11.


----------



## Snurg (Feb 7, 2018)

Thank you very much!
Sounds great! I know it's not yet so well-supported like on Linux, but I'd like to avoid Linux (don't need it for my purposes, just some timers and digital in/outputs and i2c).
Will order a BBB today


----------



## Phishfry (Feb 7, 2018)

In the future I want to use microSD for writing temperature data from onewire. Instead of wear and tear on the eMMC.
I had bad luck with my RRD database on a USB thumbdrive.
It would become stuck(unresponsive) or knocked offline every 4-6 days. I did not have it auto mounted so that experiment ended badly.
I think BBB will make a better candidate with eMMC and microSD.
I might even build a NanoBSD for the purpose.


----------



## Snurg (Feb 7, 2018)

Hmm just reading around a bit how to avoid eMMC. Seems possible to boot directly off microSD...

Regarding USB thumbdrives, I have very bad experiences too.
Even brands like Verbatim were very disappointing, sometimes lived only for days.

In my experience it seems better to use Samsung microSD in an USB-microSD adapter. This way one can be sure to have high-quality flash memory. Didn't have a Samsung SD failure yet. But let's see what will come with BBB wearing it out 

Edit: This thread says that /boot/uEnv.txt determines the sequence which possible boot devices are checked.  <still reading>


----------



## Phishfry (Feb 7, 2018)

I have found a line of industrial microSD card that are worthy. Apacer.

Booting off the microSD card works well. I prefer the eMMC so I can use microSD slot for RRD database.
Will see how well it works. USB storage mounting was disappointing.
Was writing to disk every 10 seconds.

The boot sequence on BBB is also influenced by a switch. Hold it down to switch boot device on startup.

Analog support is one of the reasons I am back to my original Arm board.
https://obsigna.net/?p=660


----------



## aragats (Feb 7, 2018)

Snurg said:


> This thread says that /boot/uEnv.txt determines the sequence which possible boot devices are checked.


The boot sequence is defined by 5 LSBs of SYSCON register, which are wired to the LCD_DATAx pins (x=0..15), the official Technical Reference Manual has a comprehensive description on page 5028. The BBB schematic has a brief description. The installed switch _S2_ sets bit 2 low to force booting from micro-SD card (MMC0).
Regarding using u-boot's files like uEnv.txt etc.: they are read by u-boot, which means it's *already* loaded - either from eMMC (MMC1) or from micro-SD (MMC0). So, yes, then you can "forward" your booting process to another device, but first you have to "get" to that file.


----------



## aragats (Feb 7, 2018)

Snurg said:


> can I use HDMI for console output and USB keyboard using FreeBSD, or is it necessary to do things via ssh only?


I see no reason to use HDMI unless you want to run a graphical application. I agree, that SSH is not always convenient since e.g. you have to know the IP address.
IMO it's much more handy to login via serial terminal which works out of the box (pins 4, 5 and 1 of J1).

Also, there available 7" LCDs ("capes") which can be used to make a stand alone device: 7-beaglebone-capes without any soldering.


----------



## Snurg (Feb 7, 2018)

Phishfry  Apacer seems really interesting, they even seem to offer SLC flashes. Probably much more durable and better data retention (important for my application).
aragats According to an (old) Rev. A3 schematic these LCD pins seem to be centered by 2x 100k between GND and Vcc. Meaning boot device could be selected by a tristate buffer turned on for the first (few) seconds after power-on/reset. Simple 555 could control that. So one could directly select the boot device without need for modifying u-boot, if I understand correctly. Would be very sweet.

I want to build sort of home controller via touch screen, so HDMI+touch is most important factor for me. Currently searching and looking around about support level state. Seems to be some support on FreeBSD for some time already


----------



## aragats (Feb 7, 2018)

Snurg said:


> HDMI+touch is most important factor for me


The Newhaven LCDs I mentioned above *are* touch screens. They have capacitive touch panel with i2c interface.


----------



## aragats (Feb 7, 2018)

Phishfry said:


> In the future I want to use microSD ... Instead of wear and tear on the eMMC.





Snurg said:


> just reading around a bit how to avoid eMMC.


I envision an "ideal" system which boots off eMMC but uses it in read-only mode. All user data go to micro-SD.
Thus you'll have a reliable system without mechanical contacts and with removable storage.
Also, do not forget that eMMC has 8-bit interface whereas micro-SD only 4-bit. There is very noticeable difference in speed.


----------



## aragats (Feb 7, 2018)

Snurg said:


> Meaning boot device could be selected by a tristate buffer turned on for the first (few) seconds after power-on/reset.


If you decide to not use any LCD at all, you do not need to control those pins dynamically, i.e. just leave them configured as inputs and tie to vcc/ground all times.


----------



## Phishfry (Feb 7, 2018)

I wanted to note that obsigna website instructions for ADC work on FreeBSD 11.1 as well as -CURRENT

Next up tonight potentiometer tests on AIN1



aragats said:


> I envision an "ideal" system which boots off eMMC but uses it in read-only mode. All user data go to micro-SD.


That was my thought too with a NanoBSD build to preserve the eMMC cells.


----------



## Snurg (Feb 7, 2018)

aragats said:


> The Newhaven LCDs I mentioned above *are* touch screens. They have capacitive touch panel with i2c interface.


Just perfect   Will look around for a distributor in Germany 



aragats said:


> I envision an "ideal" system which boots off eMMC but uses it in read-only mode. All user data go to micro-SD.
> Thus you'll have a reliable system without mechanical contacts and with removable storage.
> Also, do not forget that eMMC has 8-bit interface whereas micro-SD only 4-bit. There is very noticeable difference in speed.


Hmm, good point... like eMMC as part of "extended firmware" containing OS and application, and microSD as "drive", containing user data, sensor logs etc...



aragats said:


> If you decide to not use any LCD at all, you do not need to control those pins dynamically, i.e. just leave them configured as inputs and tie to vcc/ground all times.


oh yes  with HDMI no need for LCD pins 

this all makes me really appetite!


----------



## Phishfry (Feb 7, 2018)

I use the HDMI because this is a development environment for me. I like the option.
If I ever come up with a deployable option I would go BBB Green for lack of HDMI.


----------



## Snurg (Feb 7, 2018)

There are several companies selling touchscreens for BBB. Still not sure which is best. Preferring one that's best supported, and can be re-ordered later (often bad with chinese suppliers).

And then there is the question of WiFi support. Still looking around and trying to find out whether it is possible to combine such cape with touchscreen cape. Are they stacked like with Arduinos' shields?

Have to leave soon for some hours, appointment at dentist. Feeling like a board going to the soldering oven *shudder*.


----------



## aragats (Feb 7, 2018)

Snurg said:


> There are several companies selling touchscreens for BBB. Still not sure which is best.


So, we have 2 types: resistive and capacitive and 3 possible interfaces: AIN, I2C and USB.
If it's a resistive touchscreen, it's most likely AIN (using 4 analog inputs), may be also USB. Capacitive touch panel operates with absolute coordinates, thus does not require calibration, most likely have I2C interface. I wouldn't use one with USB interface since it will occupy the single USB connector.


Snurg said:


> there is the question of WiFi support


First of all it has to be supported by FreeBSD. WiFi adapters may have 3 different interfaces: USB, SDIO and Ethernet. The latter is rare, but is very convenient since doesn't require any driver at all, I know one good and tested example, which also supports AP mode. I guess, USB adapters are the easiest, for SDIO ones you'll have to load an overlay to configure the corresponding pins. Also, if you you want to use the existing micro-SD slot for other purposes, you'll have to use MMC2 for such WiFi module. I believe you can find all the signals on P8 and P9 connectors, but will have to attach a passive adapter.


----------



## Snurg (Feb 7, 2018)

Great tips, aragats!
You definitely have done much research for what is actually good.

Yes, the touchscreen must be capacitive.
Calibration sucks. 
And even worse, I experienced a bad drift with resistive touchscreen. Had an Arduino with resistive TS lying for a few years in a drawer, and it was heavily drifted (buttons' sensitive areas had moved a lot) when I turned it on again. I2C is definitely the way to go, the USB must remain free.

And the example Wifi module you linked at, this looks great!
Aside of the good documentation, it seems to be a manufacturer one can expect the stuff will be available next year, too. So no need for a blue beagle!

I'll order the BBB when I come back from the toothdriller.
The TS and WiFi aren't necessary anyway before I learnt to set up the OS etc on the BBB, so I have time for selecting the best.

This info was extremely helpful 
Thank you very much again


----------



## aragats (Feb 7, 2018)

Maybe I was wrong about recommending Newhaven displays, I cannot find any evidence of its touch panel support by FreeBSD.
They use FT5xx6 from FocalTech (FT5x06.pdf and/or FT5x46.pdf). Of course, the protocol is described, and one can write a driver based on another _i2c_ one, or maybe it just works.
By the way, this question about them has never been answered.
I'll try to test the one I have, will have to install Xorg etc., maybe later this week. In Linux Xorg works with it using the regular _*evdev*_ input driver "on top of" _*edt-ft5x06*_ kernel module.


----------



## Phishfry (Feb 7, 2018)

I see this LCD works.
https://kernelnomicon.org/?p=486

I also see some newer units from Seeed


----------



## aragats (Feb 7, 2018)

Yeah, but it's only 480x272 and the touchpanel is resistive...
I guess, that means any resistive touchpanel is supported: they all use AIN0...AIN3.
The datasheet is here. Its' good that only 16 LCD lines are used, saves more GPIOs for other purposes.


----------



## Nicola Mingotti (Feb 8, 2018)

Oh guys, i red the thread yesterday night, i envy you so much that you are woking on the BeagleBone, that is pure joy! I had all the stuff working in Liunx: PWM, ADC, PRUS. I hope soon i can try all those features with FreeBSD.

For Phishfry, I agree with aragats about *connecting to the BBB*, the serial cable is the first choice for first connections. After that I reccoment you set up an IP and connect via ssh, then you can sshfs or use Emacs in tramp-mode which is my preferred way for remote programming.  
There was a nice thing in Linux that I had no time to test in BSD, you can connect via *RNDIS*-usb-gadgets (Ethernet via USB). This is the uber-solution because with 1 USB cable you can power the BBB and contol it via ssh.  

About *wifi*, I tested the BBB running FreeBSD-11.1 as AP, with ALFA AWUS036NH, it works. Also device ALFA AWUUS036NEH works but I don't remember if i tested it in AP mode. 

About *microSD*. My miroSSD of choice is SanDisk Ultra class 10, 16 GB; I have 4-5 of those and they worked well in the last 6 months. I prefer to put all in the eMMC when the device is ready for deployment, micoSSD is just another thing on board that can fail with non negligible probability 


Bye
Nicola


----------



## Phishfry (Feb 8, 2018)

Nicola Mingotti said:


> you can connect via *RNDIS*-usb-gadgets


I used this method on FreeBSD 10 via the OTG USB port. Something changed on FreeBSD 11 and it shows up different now.


----------



## Phishfry (Feb 8, 2018)

This post has the details from both consoles.
This worked on FreeBSD -CURRENT but in 11 RELEASE it now shows up as an ue0 ethernet device not a storage device.
Maybe it is now similar to Linux and uses RNDIS.


----------



## Nicola Mingotti (Feb 9, 2018)

Phishfry said:


> This post has the details from both consoles.
> This worked on FreeBSD -CURRENT but in 11 RELEASE it now shows up as an ue0 ethernet device not a storage device.
> Maybe it is now similar to Linux and uses RNDIS.



Now I am deep into the development of a web application (which I hope will make me richer;P). As soon as it reaches a stable state (matter of weeks) I will plug in my BeagleBones and try it. The BeagleBone is the most interesting comptuer I ever bought. I think I learnt more things in 1 year fightinig with the BBB than in 20 years on desktop/laptop computers. It is also so cheap I don't fear much to experiment with electronics and eventually to burn one


----------



## Snurg (Feb 9, 2018)

The parcel with the BBB just arrived!
It seems genuine Farnell original.
Had to search a while, before deciding to buy at a reputable distributor, as many shops here offer clones of doubtful origin.

Now I am digging deep in my electronics parts boxes.
1488+1489 (datestamped 8201 and 8207...), RS-232 nullmodem cable, switching power supply +- 5 and 12V, sized about 2 cigarette boxes, 2.54mm rastered PCBs already unearthed.
I am glad I left some basic stuff when I dumped the ancient electronics stuff many years ago 

Now I am thinking about how best to protect the Beagle from my cats.
They are quite electric.
I guess a simple nose touch could easily shock that poor Beagle to death.


----------



## tingo (Feb 11, 2018)

Cool. Please remember that the IO pins (gpio) on the BBB is 3.3V not 5V.


----------

