Forum | Documentation | Website | Blog

Skip to content
Snippets Groups Projects
Commit a1a494f7 authored by Jason Kridner's avatar Jason Kridner
Browse files

books/beaglebone-cookbook: move code to git submodule repo

parent fe09b1cb
Branches
Tags
No related merge requests found
Showing
with 9 additions and 584 deletions
image: beagle/sphinx-build-env:latest
variables:
GIT_SUBMODULE_STRATEGY: recursive
stages:
- deploy
......
[submodule "books/beaglebone-cookbook/code"]
path = books/beaglebone-cookbook/code
url = https://git.beagleboard.org/beagleboard/beaglebone-cookbook-code.git
......@@ -170,15 +170,13 @@ Connect your Bone to the Internet and log into it. From the command line run:
.. code-block::
bone$ git clone git@github.com:MarkAYoder/BoneCookbook.git
bone$ cd BoneCookbook/docs
bone$ git clone https://git.beagleboard.org/beagleboard/beaglebone-cookbook-code
bone$ cd beaglebone-cookbook-code
bone$ ls
You can look around from the command line, or explore from Visual Sudio Code.
If you ar using VSC, go to the *File* menu and select *Open Folder ...* and
select BoneCookbook/docs. Then explore. You'll find there is a directory
for each chapter and most chapters have a *code* directory for the sample
scripts and a *figures* directory for the figures.
select beaglebone-cookbook-code. Then explore.
.. _basics_wire_breadboard:
......
#!/usr/bin/env node
// Install with: npm install nmea
// Need to add exports.serialParsers = m.module.parsers;
// to the end of /usr/local/lib/node_modules/bonescript/serial.js
var b = require('bonescript');
var nmea = require('nmea');
var port = '/dev/ttyO4';
var options = {
baudrate: 9600,
parser: b.serialParsers.readline("\n")
};
b.serialOpen(port, options, onSerial);
function onSerial(x) {
if (x.err) {
console.log('***ERROR*** ' + JSON.stringify(x));
}
if (x.event == 'open') {
console.log('***OPENED***');
}
if (x.event == 'data') {
console.log(String(x.data));
console.log(nmea.parse(x.data));
}
}
#!/usr/bin/env node
//////////////////////////////////////
// analogin.js
// Reads the analog value of the light sensor.
//////////////////////////////////////
const fs = require("fs");
const ms = 500; // Time in milliseconds
const pin = "2"; // light sensor, A2, P9_37
const IIOPATH='/sys/bus/iio/devices/iio:device0/in_voltage'+pin+'_raw';
console.log('Hit ^C to stop');
// Read every 500ms
setInterval(readPin, ms);
function readPin() {
var data = fs.readFileSync(IIOPATH).slice(0, -1);
console.log('data = ' + data);
}
// Bone | Pocket | AIN
// ----- | ------ | ---
// P9_39 | P1_19 | 0
// P9_40 | P1_21 | 1
// P9_37 | P1_23 | 2
// P9_38 | P1_25 | 3
// P9_33 | P1_27 | 4
// P9_36 | P2_35 | 5
// P9_35 | P1_02 | 6
#!/usr/bin/env python3
#//////////////////////////////////////
# analogin.py
# Reads the analog value of the light sensor.
#//////////////////////////////////////
import time
import os
pin = "2" # light sensor, A2, P9_37
IIOPATH='/sys/bus/iio/devices/iio:device0/in_voltage'+pin+'_raw'
print('Hit ^C to stop')
f = open(IIOPATH, "r")
while True:
f.seek(0)
x = float(f.read())/4096
print('{}: {:.1f}%, {:.3f} V'.format(pin, 100*x, 1.8*x), end = '\r')
time.sleep(0.1)
# // Bone | Pocket | AIN
# // ----- | ------ | ---
# // P9_39 | P1_19 | 0
# // P9_40 | P1_21 | 1
# // P9_37 | P1_23 | 2
# // P9_38 | P1_25 | 3
# // P9_33 | P1_27 | 4
# // P9_36 | P2_35 | 5
# // P9_35 | P1_02 | 6
pcm.!default {
type plug
slave {
pcm "hw:1,0"
}
}
ctl.!default {
type hw
card 1
}
#!/usr/bin/node
// 'childprocess' help at:
// http://nodejs.org/api/child_process.html\
// #child_process_child_process_spawn_command_args_options
"use strict";
var b = require('bonescript'),
spawn = require('child_process').spawn;
var audioRate = 48000,
bufferSize = 4800,
format = "S16_LE"; // 16-bit signed, little endian
var audioIn = spawn(
"/usr/bin/arecord",
[
"-c2", "-r"+audioRate, "-f"+format, "-traw",
"--buffer-size="+bufferSize, "--period-size="+bufferSize, "-N"
]
);
var audioOut = spawn(
"/usr/bin/aplay",
[
"-c2", "-r"+audioRate, "-f"+format, "-traw",
"--buffer-size="+bufferSize, "--period-size="+bufferSize, "-N"
]
);
audioIn.stdout.on('data', function(data) {
audioOut.stdin.write(data);
});
audioIn.on('close', function(code) {
if(code !== 0) {
console.log('arecord process exited with code: ' + code);
audioOut.stdin.end();
}
})
audioOut.on('close', function(code) {
if(code !== 0) {
console.log('aplay process exited with code: ' + code);
}
})
\ No newline at end of file
/*
* Copyright (C) 2013 Nathaniel R. Lewis - http://nathanielrlewis.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Enable eQEP2 on the Beaglebone White and Black
* These pins don't conflict with the HDMI
*/
/dts-v1/;
/plugin/;
/ {
compatible = "ti,beaglebone", "ti,beaglebone-black";
/* identification */
part-number = "bone_eqep2";
version = "00A0";
fragment@0 {
target = <&am33xx_pinmux>;
__overlay__ {
pinctrl_eqep2: pinctrl_eqep2_pins {
pinctrl-single,pins = <
0x038 0x24 /* P8_16 = GPIO2_12 = EQEP2_index, MODE4 */
0x03C 0x24 /* P8_15 = GPIO2_13 = EQEP2_strobe, MODE4 */
0x030 0x34 /* P8_12 = GPIO2_10 = EQEP2A_in, MODE4 */
0x034 0x34 /* P8_11 = GPIO2_11 = EQEP2B_in, MODE4 */
>;
};
};
};
fragment@1 {
target = <&epwmss2>;
__overlay__ {
status = "okay";
};
};
fragment@2 {
target = <&eqep2>;
__overlay__ {
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_eqep2>;
count_mode = < 0 >;
/* 0 - Quadrature mode, normal 90 phase offset cha & chb.
1 - Direction mode. cha input = clock, chb input = direction */
swap_inputs = < 0 >; /* Are chan A & chan B swapped? (0-no,1-yes) */
invert_qa = < 1 >; /* Should we invert the channel A input? */
invert_qb = < 1 >; /* Should we invert the channel B input?
These are inverted because my encoder outputs drive transistors
that pull down the pins */
invert_qi = < 0 >; /* Should we invert the index input? */
invert_qs = < 0 >; /* Should we invert the strobe input? */
status = "okay";
};
};
};
#!/usr/bin/env node
// Test this
var b = require('bonescript');
var encoder = '';
function printStatus(x) {
console.log('x.value = ' + x.value);
console.log('x.err = ' + x.err);
}
function onEncoderReady(e) {
if(e.event == 'return') {
b.encoderRead(encoder, printStatus);
}
}
b.encoderOpen(encoder, {}, onEncoderReady);
toggle1
toggle2
get
getset
getsetEvent
toggleLED
#
# Programs
#
all: toggle1 toggle2 get getset getsetEvent toggleLED
toggle1: toggle1.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
toggle2: toggle2.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
get: get.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
getset: getset.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
getsetEvent: getsetEvent.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
toggleLED: toggleLED.c
$(CC) $(LDFLAGS) -o $@ $^ -lgpiod
#
# Objects
#
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm toggle1 toggle2 get getset getsetEvent toggleLED
libgpiod is a new C library and tools for interacting with the linux GPIO
character device.
Detailed information is
[here](https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/README)
and [Adafruit](https://blog.adafruit.com/2018/11/26/sysfs-is-dead-long-live-libgpiod-libgpiod-for-linux-circuitpython/)
also has information.
One of the advantages of gpiod is that it can toggle multiple bits on the same
gpio chip at the same time. The toggle2 examples show how it's done.
The directory contains examples of using gpiod with **C** and **python** to read/write
a gpio pin.
File | Description
---- | -----------
[toggle1](toggle1.c) | Toggles one pin as fast as possible. (300KHz in C, 57KHz in python)
[toggle2](toggle2.c) | Toggles two pins as fast as possible. (280KHz in C, 55KHz in python)
[get](get.c) | Reads an input pin and prints its value.
[getset](getset.c) | Reads an input pin and writes its value to an output pin. (5us delay in C, 20 us Delay in python)
[getsetEvent](getset.c) | Like **getset**, but uses events. (40 us delay in C, 75 us delay in python)
[toggleLED](toggleLED.c) | Toggles the four built in USR LEDs.
> Tip: Use **gpioinfo** to lookup chip and line numbers for various pins.
# See: https://elinux.org/EBC_Exercise_51_GPIO_aggregator
# Insert the module
sudo modprobe gpio-aggregator
# Go to the aggregator
cd /sys/bus/platform/drivers/gpio-aggregator
# Fix the modes
sudo chgrp gpio *
sudo chmod g+w *
# See what's there before adding a new chip
gpiodetect
# gpiochip0 [gpio-0-31] (32 lines)
# gpiochip1 [gpio-32-63] (32 lines)
# gpiochip2 [gpio-64-95] (32 lines)
# gpiochip3 [gpio-96-127] (32 lines)
# Add a new chip mapping P9_14, P9_16, P9_18 and P9_22
gpioinfo | grep -e chip -e P9_1[468] -e P9_22
# gpiochip0 - 32 lines:
# line 2: "P9_22 [spi0_sclk]" "gpio-aggregator.0" input active-high [used]
# line 4: "P9_18 [spi0_d1]" "gpio-aggregator.0" output active-high [used]
# gpiochip1 - 32 lines:
# line 18: "P9_14 [ehrpwm1a]" "gpio-aggregator.0" output active-high [used]
# line 19: "P9_16 [ehrpwm1b]" "gpio-aggregator.0" input active-high [used]
# gpiochip2 - 32 lines:
# gpiochip3 - 32 lines:
echo "gpio-32-63 18,19 gpio-0-31 4,2" > new_device
# Check to see if they are there
gpiodetect
# gpiochip0 [gpio-0-31] (32 lines)
# gpiochip1 [gpio-32-63] (32 lines)
# gpiochip2 [gpio-64-95] (32 lines)
# gpiochip3 [gpio-96-127] (32 lines)
# gpiochip4 [gpio-aggregator.0] (4 lines)
gpioinfo | tail -6
# line 31: "NC" unused input active-high
# gpiochip4 - 4 lines:
# line 0: unnamed unused output active-high
# line 1: unnamed unused input active-high
# line 2: unnamed unused input active-high
# line 3: unnamed unused output active-high
# Turn them all on, then off
gpioset gpiochip4 0=1 1=1 2=1 3=1
gpioset gpiochip4 0=0 1=0 2=0 3=0
#!/usr/bin/env python3
# //////////////////////////////////////
# bulk_blink.py
# Toggles given pins as fast as it can.
# Given pins must be on the same gpiochip
# P9_14 is line 18 P9_16 is line 19.
# Run gpioinfo to see which pins are where.
# Wiring: Attach an oscilloscope to P9_14 and P9_16 to see the squarewave or
# uncomment the sleep and attach an LED.
# Setup: sudo apt update; pip install gpiod
# See: https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/python/examples
# //////////////////////////////////////
import sys
import time
import gpiod
try:
if len(sys.argv) > 2:
LED_CHIP = sys.argv[1]
LED_LINE_OFFSETS = []
for i in range(len(sys.argv) - 2):
LED_LINE_OFFSETS.append(int(sys.argv[i + 2]))
else:
raise Exception()
# pylint: disable=broad-except
except Exception:
print(
"Usage:"
+ " python3 -m gpiod.test.bulk_blink <chip> <line offset1>"
+ " [<line offset2> ...]"
)
sys.exit()
chip = gpiod.Chip(LED_CHIP)
lines = chip.get_lines(LED_LINE_OFFSETS)
lines.request(consumer='Bulk Blink', type=gpiod.LINE_REQ_DIR_OUT)
off = [0] * len(LED_LINE_OFFSETS)
on = [1] * len(LED_LINE_OFFSETS)
while True:
lines.set_values(off)
time.sleep(0.25)
lines.set_values(on)
time.sleep(0.25)
// //////////////////////////////////////
// get.c
// Get the value of P8_13. P8_13 is line 23 on chip 0.
// Wiring: Attach a switch to P8_13 and 3.3V
// Setup: sudo apt update; sudo apt install libgpiod-dev
// See: https://github.com/starnight/libgpiod-example/blob/master/libgpiod-led/main.c
// //////////////////////////////////////
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#define CONSUMER "Consumer"
int main(int argc, char **argv)
{
int chipnumber = 0;
unsigned int line_num = 23; // GPIO Pin P8_13
struct gpiod_chip *chip;
struct gpiod_line *line;
int i, ret;
chip = gpiod_chip_open_by_number(chipnumber);
if (!chip) {
perror("Open chip failed\n");
goto end;
}
line = gpiod_chip_get_line(chip, line_num);
if (!line) {
perror("Get line failed\n");
goto close_chip;
}
ret = gpiod_line_request_input(line, CONSUMER);
if (ret < 0) {
perror("Request line as intput failed\n");
goto release_line;
}
/* Get */
while(1) {
printf("%d\r", gpiod_line_get_value(line));
usleep(1000);
}
release_line:
gpiod_line_release(line);
close_chip:
gpiod_chip_close(chip);
end:
return 0;
}
#!/usr/bin/env python3
# //////////////////////////////////////
# get.py
# Get the value of P8_13. P8_13 is line 23 on chip 0.
# Wiring: Attach a switch to P8_13 and 3.3V
# Setup: sudo apt uupdate; sudo apt install libgpiod-dev
# See: https://github.com/starnight/libgpiod-example/blob/master/libgpiod-led/main.c
# //////////////////////////////////////
import gpiod
import sys
if len(sys.argv) < 3: # Use P8_13 if not given
CHIP='0'
offsets=[13]
else:
CHIP=sys.argv[1]
offsets = []
for off in sys.argv[2:]:
offsets.append(int(off))
chip = gpiod.Chip(CHIP)
lines = chip.get_lines(offsets)
lines.request(consumer=sys.argv[0], type=gpiod.LINE_REQ_DIR_IN)
print("Hit ^C to stop")
while True:
vals = lines.get_values()
for val in vals:
print(val, end=' ')
print('\r', end='')
#!/bin/bash
# Reads P8_13 via gpiod. P8_13 is chip 0 line 23
echo Hit ^c to stop
while true; do
gpioget 0 23 | tr \\n \\r
done
\ No newline at end of file
// //////////////////////////////////////
// getset.c
// Get the value of P8_16 and write it to P9_14.
// P8_16 is line 14 on chip 1. P9_14 is line 18 of chip 1.
// Wiring: Attach a switch to P8_16 and 3.3V and an LED to P9_14.
// Setup: sudo apt uupdate; sudo apt install libgpiod-dev
// See: https://github.com/starnight/libgpiod-example/blob/master/libgpiod-led/main.c
// //////////////////////////////////////
#include <gpiod.h>
#include <stdio.h>
#include <unistd.h>
#define CONSUMER "Consumer"
int main(int argc, char **argv)
{
int chipnumber = 1;
unsigned int getline_num = 14; // GPIO Pin P8_16
unsigned int setline_num = 18; // GPIO Pin P9_14
unsigned int val;
struct gpiod_chip *chip;
struct gpiod_line *getline, *setline;
int i, ret;
chip = gpiod_chip_open_by_number(chipnumber);
if (!chip) {
perror("Open chip failed\n");
goto end;
}
getline = gpiod_chip_get_line(chip, getline_num);
if (!getline) {
perror("Get line failed\n");
goto close_chip;
}
setline = gpiod_chip_get_line(chip, setline_num);
if (!setline) {
perror("Set line failed\n");
goto close_chip;
}
ret = gpiod_line_request_input(getline, CONSUMER);
if (ret < 0) {
perror("Request line as input failed\n");
goto release_line;
}
ret = gpiod_line_request_output(setline, CONSUMER, 0);
if (ret < 0) {
perror("Request line as output failed\n");
goto release_line;
}
/* Get */
while(1) {
val = gpiod_line_get_value(getline);
gpiod_line_set_value(setline, val);
// printf("%d\r", val);
// usleep(1000);
}
release_line:
gpiod_line_release(getline);
gpiod_line_release(setline);
close_chip:
gpiod_chip_close(chip);
end:
return 0;
}
#!/usr/bin/env python3
# //////////////////////////////////////
# getset.py
# Get the value of P8_16 and write it to P9_14.
# P8_16 is line 14 on chip 1. P9_14 is line 18 of chip 1.
# Wiring: Attach a switch to P8_16 and 3.3V and an LED to P9_14.
# Setup: sudo apt uupdate; sudo apt install libgpiod-dev
# See: https://github.com/starnight/libgpiod-example/blob/master/libgpiod-led/main.c
# //////////////////////////////////////
# Based on https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/python/examples
import gpiod
import sys
CONSUMER='getset'
CHIP='1'
getoffsets=[14] # P8_16
setoffests=[18] # P9_14
chip = gpiod.Chip(CHIP)
getlines = chip.get_lines(getoffsets)
getlines.request(consumer=CONSUMER, type=gpiod.LINE_REQ_DIR_IN)
setlines = chip.get_lines(setoffests)
setlines.request(consumer=CONSUMER, type=gpiod.LINE_REQ_DIR_OUT)
print("Hit ^C to stop")
while True:
vals = getlines.get_values()
# for val in vals:
# print(val, end=' ')
# print('\r', end='')
setlines.set_values(vals)
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment