├── .gitattributes
├── .gitignore
├── JPigpio
├── .gitignore
├── JPigpio.iml
├── META-INF
│ └── MANIFEST.MF
├── Makefile
├── src
│ ├── jpigpio
│ │ ├── Alert.java
│ │ ├── BadValueException.java
│ │ ├── FileIO.java
│ │ ├── GPIO.java
│ │ ├── GPIOListener.java
│ │ ├── JPigpio.java
│ │ ├── NotImplementedException.java
│ │ ├── Pigpio.java
│ │ ├── PigpioException.java
│ │ ├── PigpioSocket.java
│ │ ├── Pulse.java
│ │ ├── SocketLock.java
│ │ ├── Utils.java
│ │ ├── WrongModeException.java
│ │ ├── devices
│ │ │ ├── LCD.java
│ │ │ ├── NRF24L01.java
│ │ │ ├── SP0256.java
│ │ │ ├── Servo.java
│ │ │ ├── Stepper.java
│ │ │ ├── TM1638.java
│ │ │ └── VS1053.java
│ │ ├── impl
│ │ │ ├── CommonPigpio.java
│ │ │ └── SPI.java
│ │ ├── packet
│ │ │ ├── NotificationListener.java
│ │ │ ├── Protocol.java
│ │ │ ├── Rf433rx.java
│ │ │ └── Rf433tx.java
│ │ └── sensors
│ │ │ ├── GY_271.java
│ │ │ ├── HC_SR04.java
│ │ │ ├── MFRC522.java
│ │ │ └── WiiNunchuck.java
│ └── tests
│ │ ├── Test_Blink.java
│ │ ├── Test_DualServoSweep.java
│ │ ├── Test_GY_271.java
│ │ ├── Test_HC_SR04.java
│ │ ├── Test_LCD.java
│ │ ├── Test_LEDs.java
│ │ ├── Test_NRF24L01.java
│ │ ├── Test_Nunchuck.java
│ │ ├── Test_Nunchuck2.java
│ │ ├── Test_NunchuckServos.java
│ │ ├── Test_PCD8544.java
│ │ ├── Test_Rf433Rx.java
│ │ ├── Test_Rf433Tx.java
│ │ ├── Test_SP0256.java
│ │ ├── Test_Serial.java
│ │ ├── Test_ServoSweep.java
│ │ ├── Test_SocketListen.java
│ │ ├── Test_Stepper.java
│ │ ├── Test_TM1638.java
│ │ ├── Test_Template.java
│ │ ├── Test_Timings.java
│ │ ├── Test_VS1053.java
│ │ └── Test_gpioSetAlertFunc.java
└── tests
│ ├── run_Test_Blink.sh
│ ├── run_Test_DualServoSweep.sh
│ ├── run_Test_GY_271.sh
│ ├── run_Test_HC_SR04.sh
│ ├── run_Test_LCD.sh
│ ├── run_Test_NRF24L01_Client.sh
│ ├── run_Test_Nunchuck.sh
│ ├── run_Test_Nunchuck2.sh
│ ├── run_Test_NunchuckServos.sh
│ ├── run_Test_PCD8544.sh
│ ├── run_Test_SP0256.sh
│ ├── run_Test_Stepper.sh
│ ├── run_Test_TM1638.sh
│ ├── run_Test_Timings.sh
│ ├── run_Test_VS1053.sh
│ └── run_Test_gpioSetAlertFunc.sh
├── JPigpioC
├── .cproject
├── .gitignore
├── JPigpioC.c
├── JPigpioC.h
├── JPigpioC.iml
├── JPigpioC.o
├── Makefile
├── jpigpio_Pigpio.h
├── libJPigpioC.so
└── tests
│ ├── Makefile
│ ├── run_test_nunchuck.sh
│ ├── run_test_servo.sh
│ ├── test_nunchuck
│ ├── test_nunchuck.c
│ ├── test_nunchuck.o
│ ├── test_servo
│ ├── test_servo.c
│ └── test_servo.o
├── LICENSE
├── Makefile
├── README.md
├── build.sh
├── examples.md
└── images
├── NoSockets.png
└── Sockets.png
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | #Java
8 | *.java text diff=java eol=crlf
9 |
10 | # Standard to msysgit
11 | *.doc diff=astextplain
12 | *.DOC diff=astextplain
13 | *.docx diff=astextplain
14 | *.DOCX diff=astextplain
15 | *.dot diff=astextplain
16 | *.DOT diff=astextplain
17 | *.pdf diff=astextplain
18 | *.PDF diff=astextplain
19 | *.rtf diff=astextplain
20 | *.RTF diff=astextplain
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Windows image file caches
2 | Thumbs.db
3 | ehthumbs.db
4 |
5 | # Folder config file
6 | Desktop.ini
7 |
8 | # Recycle Bin used on file shares
9 | $RECYCLE.BIN/
10 |
11 | # Compiled java modules
12 | out/
13 | target/
14 |
15 | # IntelliJ IDEA folder
16 | .idea/
17 |
18 | # Log folder
19 | logs/
20 |
21 | # Windows Installer files
22 | *.cab
23 | *.msi
24 | *.msm
25 | *.msp
26 |
27 | # Windows shortcuts
28 | *.lnk
29 |
30 | # =========================
31 | # Operating System Files
32 | # =========================
33 |
34 | # OSX
35 | # =========================
36 |
37 | .DS_Store
38 | .AppleDouble
39 | .LSOverride
40 |
41 | # Thumbnails
42 | ._*
43 |
44 | # Files that might appear in the root of a volume
45 | .DocumentRevisions-V100
46 | .fseventsd
47 | .Spotlight-V100
48 | .TemporaryItems
49 | .Trashes
50 | .VolumeIcon.icns
51 |
52 | # Directories potentially created on remote AFP share
53 | .AppleDB
54 | .AppleDesktop
55 | Network Trash Folder
56 | Temporary Items
57 | .apdisk
58 |
59 |
60 | # Eclipse project files
61 | **/.project
62 | **/.settings
63 | **/.classpath
64 |
--------------------------------------------------------------------------------
/JPigpio/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 |
--------------------------------------------------------------------------------
/JPigpio/JPigpio.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/JPigpio/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 |
3 |
--------------------------------------------------------------------------------
/JPigpio/Makefile:
--------------------------------------------------------------------------------
1 | LIBDIR=/mnt/share/opt/lib
2 |
3 | install:
4 | jar -cvf $(LIBDIR)/Pigpio.jar -C bin jpigpio
5 |
6 | clean:
7 | rm -f $(LIBDIR)/Pigpio.jar
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/Alert.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | public interface Alert {
4 | public void alert(int gpio, int level, long tick);
5 | } // End of Alert
6 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/BadValueException.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | /**
4 | * An extension of the general PigpioException to indicate that a value is invalid
5 | *
6 | */
7 | public class BadValueException extends PigpioException {
8 |
9 | /**
10 | *
11 | */
12 | private static final long serialVersionUID = -5799905929298889801L;
13 |
14 | } // End of class
15 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/FileIO.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.io.IOException;
6 |
7 | /**
8 | * A helper class for some simple file I/O activities.
9 | *
10 | */
11 | public class FileIO {
12 | private File file;
13 | private FileInputStream fis;
14 |
15 | /**
16 | * Constructor to create a wrapper to the file.
17 | * @param file The file to be accessed.
18 | */
19 | public FileIO(File file) {
20 | this.file = file;
21 | } // End of constructor
22 |
23 | /**
24 | * Read up to
size
bytes from the file.
25 | * @param size The maximum size of data to return
26 | * @return An array of data. It may be zero length if there is no data available.
27 | * @throws IOException on IO Exception :-)
28 | */
29 | public byte[] read(int size) throws IOException {
30 | if (fis == null) {
31 | fis = new FileInputStream(file);
32 | }
33 | // Read either the maximum available data or size requested bytes (which ever is smaller)
34 | byte data[] = new byte[Math.min(fis.available(), size)];
35 |
36 | // Don't try and read 0 bytes of data ...
37 | if (data.length > 0) {
38 | fis.read(data);
39 | }
40 | return data;
41 | } // End of close
42 |
43 | /**
44 | * Close the file.
45 | * @throws IOException on IO Exception :-)
46 | */
47 | public void close() throws IOException {
48 | if (fis != null) {
49 | fis.close();
50 | }
51 | fis = null;
52 | } // End of close
53 | } // End of class
54 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/GPIO.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | public class GPIO {
4 | private JPigpio pigpio;
5 | private int pin;
6 |
7 | public GPIO(JPigpio pigpio, int pin) {
8 | assert pigpio != null;
9 |
10 | this.pigpio = pigpio;
11 | this.pin = pin;
12 | }
13 |
14 |
15 | public GPIO(JPigpio pigpio, int pin, int direction) throws PigpioException {
16 | this(pigpio, pin);
17 | setDirection(direction);
18 | }
19 |
20 | public int getDirection() throws PigpioException {
21 | return pigpio.gpioGetMode(pin);
22 | }
23 |
24 | public void setDirection(int direction) throws PigpioException {
25 | pigpio.gpioSetMode(pin, direction);
26 | }
27 |
28 | public void setValue(boolean value) throws PigpioException {
29 | pigpio.gpioWrite(pin, value);
30 | }
31 |
32 | public void setValue(int value) throws PigpioException {
33 | if (value !=0 && value != 1) {
34 | throw new BadValueException();
35 | }
36 | pigpio.gpioWrite(pin, value==1);
37 | }
38 |
39 | public boolean getValue() throws PigpioException {
40 | return pigpio.gpioRead(pin);
41 | }
42 |
43 | public int getPin() {
44 | return pin;
45 | }
46 |
47 | public void setAlert(Alert alert) throws PigpioException {
48 | pigpio.gpioSetAlertFunc(getPin(), alert);
49 | }
50 |
51 | public void setPulldown(int pulldown) throws PigpioException {
52 | pigpio.gpioSetPullUpDown(getPin(), pulldown);
53 | }
54 |
55 | public void delay(long delay, int type) throws PigpioException {
56 | pigpio.gpioDelay(delay, type);
57 | }
58 |
59 | /**
60 | *
61 | * Should only be needed if not mapped by gpio class
62 | *
63 | * @return Pigpio instance
64 | */
65 | public JPigpio getPigpio() {
66 | return pigpio;
67 | }
68 | } // End of class
69 | // End of file
70 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/GPIOListener.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | /**
4 | * Simple interface for implementing GPIO callbacks
5 | */
6 | public abstract class GPIOListener implements Alert{
7 |
8 | // PI_RISING_EDGE = 0
9 | // PI_FALLING_EDGE = 1
10 | // PI_EITHER_EDGE = 2
11 |
12 | public int bit; // bit-map representing respective GPIOs
13 | public int edge;
14 | public int gpio;
15 |
16 | public GPIOListener(int gpio, int edge){
17 | this.gpio = gpio;
18 | this.bit = 1 << this.gpio;
19 | this.edge = edge;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/NotImplementedException.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | /**
4 | * An extension of the general PigpioException to indicate that a function
5 | * was called that has not yet been implemented.
6 | *
7 | */
8 | public class NotImplementedException extends PigpioException {
9 |
10 | /**
11 | *
12 | */
13 | private static final long serialVersionUID = -8827522292144048839L;
14 | } // End of class
15 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/Pigpio.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | import jpigpio.impl.CommonPigpio;
4 |
5 | import java.util.ArrayList;
6 |
7 | /**
8 | * Pigpiod wrapper class using native C++ methods. This class can be used only when executing your application directly at Raspberry Pi device.
9 | * See {@link PigpioSocket class PigpioSocket} for socket based implementation allowing you to develop/debug/run your over network.
10 | *
11 | * See {@link JPigpio interface JPigpio} for full documentation of specific methods.
12 | *
13 | * Methods which are not implemented yet has "Not implemented" in their description.
14 | * All other methods you can consider implemented.
15 | *
16 | * NOTE: if method you are looking for is not implemented, check {@link PigpioSocket class PigpioSocket} - maybe it is implemented there.
17 | */
18 | public class Pigpio extends CommonPigpio {
19 | static {
20 | System.loadLibrary("JPigpioC");
21 | }
22 |
23 | @Override
24 | public native void gpioInitialize() throws PigpioException;
25 |
26 | @Override
27 | public native void gpioTerminate() throws PigpioException;
28 |
29 | /**
30 | * Not implemented
31 | */
32 | @Override
33 | public void reconnect() throws PigpioException{
34 | // do nothing for native interface
35 | return;
36 | }
37 |
38 | @Override
39 | public native void gpioSetMode(int pin, int mode) throws PigpioException;
40 |
41 | @Override
42 | public native int gpioGetMode(int pin) throws PigpioException;
43 |
44 | @Override
45 | public native void gpioSetPullUpDown(int pin, int pud) throws PigpioException;
46 |
47 | @Override
48 | public native boolean gpioRead(int pin) throws PigpioException;
49 |
50 | @Override
51 | public native void gpioWrite(int pin, boolean value) throws PigpioException;
52 |
53 | // ################ NOTIFICATIONS
54 |
55 | /**
56 | * Not implemented
57 | */
58 | @Override
59 | public int notifyOpen() throws PigpioException{
60 | throw new NotImplementedException();
61 | }
62 |
63 | /**
64 | * Not implemented
65 | */
66 | @Override
67 | public void notifyBegin(int handle, int bits) throws PigpioException{
68 | throw new NotImplementedException();
69 | }
70 |
71 | /**
72 | * Not implemented
73 | */
74 | @Override
75 | public void notifyPause(int handle) throws PigpioException{
76 | throw new NotImplementedException();
77 | }
78 |
79 | /**
80 | * Not implemented
81 | */
82 | @Override
83 | public void notifyClose(int handle) throws PigpioException {
84 | throw new NotImplementedException();
85 | }
86 |
87 | /**
88 | * Not implemented
89 | */
90 | @Override
91 | public void setWatchdog(int userGpio, int timeout) throws PigpioException{
92 | throw new NotImplementedException();
93 | }
94 |
95 | // ##################### WAVEFORMS
96 |
97 | /**
98 | * Not implemented
99 | */
100 | @Override
101 | public void waveClear() throws PigpioException {
102 | throw new NotImplementedException();
103 | }
104 |
105 | /**
106 | * Not implemented
107 | */
108 | @Override
109 | public int waveAddGeneric(ArrayList pulses) throws PigpioException{
110 | throw new NotImplementedException();
111 | }
112 |
113 | /**
114 | * Not implemented
115 | */
116 | @Override
117 | public int waveAddSerial(int userGpio, int baud, byte[] data, int offset, int bbBits, int bbStop) throws PigpioException{
118 | throw new NotImplementedException();
119 | }
120 |
121 | /**
122 | * Not implemented
123 | */
124 | @Override
125 | public void waveAddNew() throws PigpioException {
126 | throw new NotImplementedException();
127 | }
128 |
129 | /**
130 | * Not implemented
131 | */
132 | @Override
133 | public boolean waveTxBusy() throws PigpioException {
134 | throw new NotImplementedException();
135 | }
136 |
137 | /**
138 | * Not implemented
139 | */
140 | @Override
141 | public int waveTxStop() throws PigpioException {
142 | throw new NotImplementedException();
143 | }
144 |
145 | /**
146 | * Not implemented
147 | */
148 | @Override
149 | public int waveCreate() throws PigpioException {
150 | throw new NotImplementedException();
151 | }
152 |
153 | /**
154 | * Not implemented
155 | */
156 | @Override
157 | public void waveDelete(int waveId) throws PigpioException {
158 | throw new NotImplementedException();
159 | }
160 |
161 | /**
162 | * Not implemented
163 | */
164 | @Override
165 | public int waveSendOnce(int waveId) throws PigpioException {
166 | throw new NotImplementedException();
167 | }
168 |
169 | /**
170 | * Not implemented
171 | */
172 | @Override
173 | public int waveSendRepeat(int waveId) throws PigpioException {
174 | throw new NotImplementedException();
175 | }
176 |
177 |
178 | // ################ I2C
179 |
180 | @Override
181 | public native int i2cOpen(int i2cBus, int i2cAddr) throws PigpioException;
182 |
183 | @Override
184 | public native void i2cClose(int handle) throws PigpioException;
185 |
186 | @Override
187 | public native int i2cReadDevice(int handle, byte[] data) throws PigpioException;
188 |
189 | @Override
190 | public native void i2cWriteDevice(int handle, byte[] data) throws PigpioException;
191 |
192 | @Override
193 | public native void gpioDelay(long delay) throws PigpioException;
194 |
195 | @Override
196 | public native long gpioTick() throws PigpioException;
197 |
198 | @Override
199 | public long getCurrentTick() throws PigpioException{
200 | return gpioTick();
201 | }
202 |
203 |
204 | @Override
205 | public native void gpioServo(int gpio, int pulseWidth) throws PigpioException;
206 |
207 | @Override
208 | public void setServoPulseWidth(int gpio, int pulseWidth) throws PigpioException {
209 | gpioServo(gpio, pulseWidth);
210 | }
211 |
212 | /**
213 | * Not implemented
214 | */
215 | @Override
216 | public int getServoPulseWidth(int gpio) throws PigpioException{
217 | throw new NotImplementedException();
218 | }
219 |
220 | // ############### PWM
221 |
222 | @Override
223 | public void setPWMDutycycle(int gpio, int dutycycle) throws PigpioException {
224 | throw new NotImplementedException();
225 | }
226 |
227 | /**
228 | * Not implemented
229 | */
230 | @Override
231 | public int getPWMDutycycle(int gpio) throws PigpioException {
232 | throw new NotImplementedException();
233 | }
234 |
235 | /**
236 | * Not implemented
237 | */
238 | @Override
239 | public void setPWMRange(int gpio, int range) throws PigpioException {
240 | throw new NotImplementedException();
241 | }
242 |
243 | /**
244 | * Not implemented
245 | */
246 | @Override
247 | public int getPWMRange(int gpio) throws PigpioException {
248 | throw new NotImplementedException();
249 | }
250 |
251 | /**
252 | * Not implemented
253 | */
254 | @Override
255 | public int getPWMRealRange(int gpio) throws PigpioException {
256 | throw new NotImplementedException();
257 | }
258 |
259 | /**
260 | * Not implemented
261 | */
262 | @Override
263 | public int setPWMFrequency(int gpio, int frequency) throws PigpioException {
264 | throw new NotImplementedException();
265 | }
266 |
267 | /**
268 | * Not implemented
269 | */
270 | @Override
271 | public int getPWMFrequency(int gpio) throws PigpioException {
272 | throw new NotImplementedException();
273 | }
274 |
275 | // ################ SERIAL
276 | /**
277 | * Not implemented
278 | */
279 | @Override
280 | public int serialOpen(String tty, int baudRate, int flags) throws PigpioException {
281 | throw new NotImplementedException();
282 | }
283 |
284 | /**
285 | * Not implemented
286 | */
287 | @Override
288 | public void serialClose(int handle) throws PigpioException {
289 | throw new NotImplementedException();
290 | }
291 |
292 | /**
293 | * Not implemented
294 | */
295 | @Override
296 | public byte serialReadByte(int handle) throws PigpioException {
297 | throw new NotImplementedException();
298 | }
299 |
300 | /**
301 | * Not implemented
302 | */
303 | @Override
304 | public void serialWriteByte(int handle, byte data) throws PigpioException {
305 | throw new NotImplementedException();
306 | }
307 |
308 | /**
309 | * Not implemented
310 | */
311 | @Override
312 | public byte[] serialRead(int handle, int count) throws PigpioException {
313 | throw new NotImplementedException();
314 | }
315 |
316 | /**
317 | * Not implemented
318 | */
319 | @Override
320 | public void serialWrite(int handle, byte[] data) throws PigpioException {
321 | throw new NotImplementedException();
322 | }
323 |
324 | /**
325 | * Not implemented
326 | */
327 | @Override
328 | public int serialDataAvailable(int handle) throws PigpioException {
329 | throw new NotImplementedException();
330 | }
331 |
332 | // ###############
333 |
334 |
335 | @Override
336 | public native void gpioSetAlertFunc(int pin, Alert alert) throws PigpioException;
337 |
338 | @Override
339 | public native void gpioTrigger(int gpio, long pulseLen, boolean level) throws PigpioException;
340 |
341 | @Override
342 | public native int spiOpen(int channel, int baudRate, int flags) throws PigpioException;
343 |
344 | @Override
345 | public native void spiClose(int handle) throws PigpioException;
346 |
347 | @Override
348 | public native int spiRead(int handle, byte[] data) throws PigpioException;
349 |
350 | @Override
351 | public native int spiWrite(int handle, byte[] data) throws PigpioException;
352 |
353 | @Override
354 | public native int spiXfer(int handle, byte[] txData, byte[] rxData) throws PigpioException;
355 |
356 | @Override
357 | /**
358 | * Set whether or not debugging is enabled. True is enabled.
359 | */
360 | public native void setDebug(boolean flag);
361 |
362 |
363 | @Override
364 | public native long gpioxPulseAndWait(int outGpio, int inGpio, long waitDuration, long pulseHoldDuration, boolean pulseLow) throws PigpioException;
365 |
366 | /**
367 | * Not implemented
368 | */
369 | @Override
370 | public void addCallback(GPIOListener gpioListener) throws PigpioException {
371 | throw new NotImplementedException();
372 | }
373 |
374 | /**
375 | * Not implemented
376 | */
377 | @Override
378 | public void removeCallback(GPIOListener cgpioListener) throws PigpioException{
379 | throw new NotImplementedException();
380 | }
381 |
382 | } // End of class
383 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/Pulse.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | /**
4 | * Class to store pulse information
5 | */
6 | public class Pulse {
7 | int gpioOn;
8 | int gpioOff;
9 | int delay;
10 |
11 | /**
12 | * Initialises a pulse.
13 | *
14 | * @param gpioOn
15 | * binary encoded GPIO number {@code (1< 0)
76 | bb.put(ext);
77 |
78 | out.write(bb.array());
79 | out.flush();
80 |
81 | w = replyTimeout;
82 | a = in.available();
83 |
84 | // if by any chance there is no response from pigpiod, then wait up to
85 | // specified timeout
86 | while (w > 0 && a < 16){
87 | w -= 10;
88 | try{ Thread.sleep(10); } catch (InterruptedException e) {}
89 | a = in.available();
90 | }
91 |
92 | // throw exception if response from pigpiod has not arrived yet
93 | if (in.available() < 16)
94 | throw new IOException("Timeout: No response from RPi withing "+ replyTimeout +" ms.");
95 |
96 | resp = Integer.reverseBytes(in.readInt()); // ignore response
97 | resp = Integer.reverseBytes(in.readInt()); // ignore response
98 | resp = Integer.reverseBytes(in.readInt()); // ignore response
99 | resp = Integer.reverseBytes(in.readInt()); // contains error or response
100 | return resp;
101 | }
102 |
103 | /**
104 | * Read all remaining bytes coming from pigpiod
105 | * @param data Array to store read bytes.
106 | * @throws IOException if unbale to read from network
107 | */
108 | public void readBytes(byte[] data) throws IOException {
109 | in.readFully(data);
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/Utils.java:
--------------------------------------------------------------------------------
1 | package jpigpio;
2 |
3 | public class Utils {
4 | /**
5 | * Add a handler to perform a clean termination of pigpio on termination.
6 | * @param pigpio pigpio object to terminate
7 | */
8 | public static void addShutdown(JPigpio pigpio) {
9 | Runtime.getRuntime().addShutdownHook(new Thread(() -> {
10 | try {
11 | pigpio.gpioTerminate();
12 | } catch (Exception e) {
13 | e.printStackTrace();
14 | }
15 | }));
16 | } // End of assShutdown
17 |
18 | public static int mapToInt(int value, int sourceLow, int sourceHigh, int targetLow, int targetHigh) {
19 | double pos = (value-sourceLow)/(double)(sourceHigh - sourceLow);
20 | //System.out.println("Pos: " + pos);
21 | //System.out.println("tHigh - tLow = " + (targetHigh - targetLow));
22 | //System.out.println("r = " + (targetLow + ((targetHigh - targetLow) * pos)));
23 | return (int)(targetLow + ((targetHigh - targetLow) * pos));
24 | }
25 |
26 | /**
27 | * Return a binary string representation of the byte.
28 | * @param value byte to convert
29 | * @return A binary string representation of the byte.
30 | */
31 | public static String byteToBinary(byte value) {
32 | return String.format("%8s", Integer.toBinaryString(value & 0xFF)).replace(' ', '0');
33 | } // End of byteToBinary
34 |
35 | /**
36 | * Return a binary string representation of the first 16 bits of the integer.
37 | * @param value integer to convert
38 | * @return A binary string representation of the first 16 bits of the integer.
39 | */
40 | public static String int16ToBinary(int value) {
41 | //System.out.println(String.format("Value: 0x%x", value));
42 | if (Integer.toUnsignedLong(value) != Integer.toUnsignedLong(value & 0xffff)) {
43 | System.out.println(String.format("Warning: value is: 0x%x while masked value is 0x%x", Integer.toUnsignedLong(value), value & 0xffff));
44 | }
45 | return splitBinary4(String.format("%16s", Integer.toBinaryString(value & 0xffff)).replace(' ', '0'));
46 | } // End of int16ToBinary
47 |
48 | /**
49 | * Given an array of 2 bytes, return an int representation using the 1st byte as
50 | * the MSByte.
51 | * @param word The 2 bytes of data.
52 | * @return An int representation of the two bytes of data.
53 | */
54 | public static int byteWordToInt(byte word[]) {
55 | return (int)((Byte.toUnsignedLong(word[0]) << 8) | Byte.toUnsignedLong(word[1]));
56 | } // End of byteWordToInt
57 |
58 | /**
59 | * Split a binary string into groups of 4 characters separated by spaces
60 | * @param binaryString The original binary string
61 | * @return An expanded binary string with spaces every 4 characters.
62 | */
63 | private static String splitBinary4(String binaryString) {
64 | //System.out.println(binaryString + " " + binaryString.length());
65 | int i=0;
66 | String ret="";
67 | while(i< binaryString.length()) {
68 | if (i>0) {
69 | ret += " ";
70 | }
71 | if (i < binaryString.length()) {
72 | ret += binaryString.substring(i,i+4);
73 | }
74 | else {
75 | ret += binaryString.substring(i);
76 | }
77 | i+=4;
78 | //System.out.println(ret);
79 | }
80 | return ret;
81 | } // End of splitBinary4
82 |
83 | /**
84 | * Set the bit within the int.
85 | * @param value The value in which to set the bit.
86 | * @param bit The bit to set.
87 | * @return The new value with the bit set.
88 | */
89 | public static int setBit(int value, int bit) {
90 | assert bit >=0 && bit<16;
91 | return value | bitMask(bit);
92 | } // End of setBit
93 |
94 | /**
95 | * Set the bit within the byte.
96 | * @param value The value in which to set the bit.
97 | * @param bit The bit to set.
98 | * @return The new value with the bit set.
99 | */
100 | public static byte setBit(byte value, int bit) {
101 | assert bit >=0 && bit<16;
102 | return (byte)(value | bitMask(bit));
103 | } // End of setBit
104 |
105 | /**
106 | * Clear the bit within the int.
107 | * @param value The value in which the bit is to be cleared.
108 | * @param bit The bit to clear.
109 | * @return The value with the bit cleared.
110 | */
111 | public static int clearBit(int value, int bit) {
112 | assert bit >=0 && bit<16;
113 | return value & ~bitMask(bit);
114 | } // End of clear bit
115 |
116 | /**
117 | * Clear the bit within the byte.
118 | * @param value The value in which the bit is to be cleared.
119 | * @param bit The bit to clear.
120 | * @return The value with the bit cleared.
121 | */
122 | public static byte clearBit(byte value, int bit) {
123 | assert bit >=0 && bit<16;
124 | return (byte)(value & ~bitMask(bit));
125 | } // End of clear bit
126 |
127 | /**
128 | * Calculate a bitmask of the bit.
129 | * @param bit The bit to be used to calculate the bitmask.
130 | * @return The value of the bitmask.
131 | */
132 | public static int bitMask(int bit) {
133 | assert bit >=0 && bit<16;
134 | return 1<=0 && bit<16;
145 | return (value & bitMask(bit)) != 0;
146 | } // End of isSet
147 |
148 | /**
149 | * Return true if the corresponding bit of the data is set.
150 | * @param value The data to test.
151 | * @param bit The bit to examine.
152 | * @return True if the corresponding bit in the data is set.
153 | */
154 | public static boolean isSet(byte value, int bit) {
155 | assert bit >=0 && bit<16;
156 | return (value & bitMask(bit)) != 0;
157 | } // End of isSet
158 |
159 | /**
160 | * Dump an array of bytes
161 | * @param data The data to dump
162 | * @return A string representation of the data.
163 | */
164 | public static String dumpData(byte data[]) {
165 | String ret = "";
166 | for (int i=0; i>> 4];
207 | hexChars[j * 2 + 1] = hexArray[v & 0x0F];
208 | }
209 | return new String(hexChars);
210 | }
211 |
212 | public static byte[] bytes2nibbles(byte[] bytes){
213 | byte[] nibb = new byte[bytes.length*2];
214 |
215 | for (int i = 0; i> 4);
217 | nibb[i*2+1] = (byte)(bytes[i] & 0x0F);
218 | }
219 | return nibb;
220 | }
221 |
222 | public static byte[] nibbles2bytes(byte[] nibb){
223 | byte[] bytes = new byte[nibb.length/2];
224 |
225 | for (int i = 0; i");
116 | pigpio.gpioDelay(50000);
117 | write4bits(RS_INSTRUCTION, RW_WRITE, (byte)0b11);
118 | pulseEnable();
119 | pigpio.gpioDelay(4500);
120 | write4bits(RS_INSTRUCTION, RW_WRITE, (byte)0b11);
121 | pulseEnable();
122 | pigpio.gpioDelay(4500);
123 | write4bits(RS_INSTRUCTION, RW_WRITE, (byte)0b11);
124 | pulseEnable();
125 | pigpio.gpioDelay(4500);
126 | write4bits(RS_INSTRUCTION, RW_WRITE, (byte)0b10);
127 | pulseEnable();
128 | functionModeSet();
129 | displayModeSet();
130 | entryModeSet();
131 | }
132 |
133 | public void clear() throws PigpioException {
134 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
135 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
136 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
137 | // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
138 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
139 | System.out.println("clear>");
140 | write(RS_INSTRUCTION, RW_WRITE, LCD_CLEARDISPLAY);
141 | } // End of clear
142 |
143 | public void home() throws PigpioException {
144 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
145 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
146 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
147 | // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | - |
148 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
149 | System.out.println("home >");
150 | write(RS_INSTRUCTION, RW_WRITE, LCD_RETURNHOME);
151 | } // End of home
152 |
153 | private void displayModeSet() throws PigpioException {
154 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
155 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
156 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
157 | // | 0 | 0 | 0 | 0 | 0 | 0 | 1 | D | C | B |
158 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
159 | System.out.println("Display Mode >");
160 | write(RS_INSTRUCTION, RW_WRITE, displayMode);
161 | } // End of displayModeSet
162 |
163 | public void functionModeSet() throws PigpioException {
164 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
165 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
166 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
167 | // | 0 | 0 | 0 | 0 | 1 | DL | N | F | - | - |
168 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
169 | // When DL=0, data is 4 bit.
170 | System.out.println("Function Mode >");
171 | write(RS_INSTRUCTION, RW_WRITE, functionMode);
172 | } // End of functionModeSet
173 |
174 | private void setDDRAMAddress(int address) throws PigpioException {
175 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
176 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
177 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
178 | // | 0 | 0 | 1 | AC6 | AC5 | AC4 | AC3 | AC2 | AC1 | AC0 |
179 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
180 | System.out.println("Set DDRAM Address>");
181 | write(RS_INSTRUCTION, RW_WRITE, (byte)(0b1000000 | (address & 0b1111111)));
182 | } // End of setDDRAMAddress
183 |
184 |
185 | private void entryModeSet() throws PigpioException {
186 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
187 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
188 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
189 | // | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | I/D | S |
190 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
191 | System.out.println("Set setEntryMode>");
192 | write(RS_INSTRUCTION, RW_WRITE, entryMode);
193 | } // End of entryModeSet
194 |
195 | // private boolean isBusy() throws PigpioException {
196 | // // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
197 | // // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
198 | // // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
199 | // // | 0 | 1 | BF | AC6 | AC5 | AC4 | AC3 | AC2 | AC1 | AC0 |
200 | // // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
201 | // System.out.println("Is busy>");
202 | // pigpio.gpioWrite(registerSelectGpio, RS_INSTRUCTION);
203 | // pigpio.gpioWrite(readWriteGpio, RW_READ);
204 | // pigpio.gpioWrite(enableGpio, true);
205 | // pigpio.gpioWrite(enableGpio, false);
206 | // pigpio.gpioWrite(enableGpio, true);
207 | // pigpio.gpioWrite(enableGpio, false);
208 | // return pigpio.gpioRead(db7Gpio);
209 | // } // End of isBusy
210 |
211 | private void writeRAM(byte value) throws PigpioException {
212 | System.out.println("Write RAM>");
213 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
214 | // | RS | RW | DB7 | DB6 | DB5 | DB4 | DB3 | DB2 | DB1 | DB0 |
215 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
216 | // | 0 | 1 | BF | AC6 | AC5 | AC4 | AC3 | AC2 | AC1 | AC0 |
217 | // +----+----+-----+-----+-----+-----+-----+-----+-----+-----+
218 | write(RS_DATA, RW_WRITE, value);
219 | } // End of writeRAM
220 |
221 | private void write4bits(boolean registerSelect, boolean readWrite, byte value) throws PigpioException {
222 | pigpio.gpioWrite(registerSelectGpio, registerSelect);
223 | pigpio.gpioWrite(readWriteGpio, readWrite);
224 | pigpio.gpioWrite(db7Gpio, Utils.isSet(value, 3));
225 | pigpio.gpioWrite(db6Gpio, Utils.isSet(value, 2));
226 | pigpio.gpioWrite(db5Gpio, Utils.isSet(value, 1));
227 | pigpio.gpioWrite(db4Gpio, Utils.isSet(value, 0));
228 |
229 | System.out.println("+----+----+----+----+----+----+");
230 | System.out.println(String.format("| %s | %s | %s | %s | %s | %s |", //
231 | Utils.bitString(registerSelect), //
232 | Utils.bitString(readWrite), //
233 | Utils.bitString(Utils.isSet(value, 3)), //
234 | Utils.bitString(Utils.isSet(value, 2)), //
235 | Utils.bitString(Utils.isSet(value, 1)), //
236 | Utils.bitString(Utils.isSet(value, 0))));
237 | } // End of write
238 |
239 | private void write8bits(boolean registerSelect, boolean readWrite, byte value) throws PigpioException {
240 | throw new NotImplementedException();
241 | // pigpio.gpioWrite(registerSelectGpio, registerSelect);
242 | // pigpio.gpioWrite(readWriteGpio, readWrite);
243 | // pigpio.gpioWrite(db7Gpio, Utils.isSet(value, 7));
244 | // pigpio.gpioWrite(db6Gpio, Utils.isSet(value, 6));
245 | // pigpio.gpioWrite(db5Gpio, Utils.isSet(value, 5));
246 | // pigpio.gpioWrite(db4Gpio, Utils.isSet(value, 4));
247 | // pigpio.gpioWrite(db3Gpio, Utils.isSet(value, 3));
248 | // pigpio.gpioWrite(db2Gpio, Utils.isSet(value, 2));
249 | // pigpio.gpioWrite(db1Gpio, Utils.isSet(value, 1));
250 | // pigpio.gpioWrite(db0Gpio, Utils.isSet(value, 0));
251 |
252 | } // End of write
253 |
254 | /**
255 | * Write data to LCD.
256 | * @param registerSelect
257 | * @param readWrite
258 | * @param value The value to write.
259 | * @throws PigpioException
260 | */
261 | private void write(boolean registerSelect, boolean readWrite, byte value) throws PigpioException {
262 | System.out.println("Write >");
263 | // If we are not in 8bit mode, then write two 4 bit values using the MSBits first.
264 | if (!is8BitMode()) {
265 | write4bits(registerSelect, readWrite, (byte)(value >>> 4));
266 | pulseEnable();
267 | write4bits(registerSelect, readWrite, (byte)(value & 0b1111));
268 | pulseEnable();
269 | } else {
270 | write8bits(registerSelect, readWrite, value);
271 | pulseEnable();
272 | }
273 | } // End of write
274 |
275 |
276 | /**
277 | * Write a text string to the LCD.
278 | * @param text The string of text to write.
279 | * @throws PigpioException when write fails
280 | */
281 | public void write(String text) throws PigpioException {
282 | byte data[] = text.getBytes();
283 | for (int i=0; i
11 | * Create an instance of the Servo class passing in:
12 | *
13 | * - pigpio
14 | * - gpio
15 | * - minVal
16 | * - maxVal
17 | *
18 | *
19 | *
20 | *
21 | * @author kolban
22 | *
23 | */
24 | public class Servo {
25 | private JPigpio pigpio;
26 | private int minVal, maxVal, gpio;
27 | private int minPulseWidth, maxPulseWidth;
28 |
29 | /**
30 | * Instantiate an instance of the servo class.
31 | *
32 | * @param pigpio
33 | * The pigpio object to work against.
34 | * @param gpio
35 | * The gpio that is to be used to control the servo.
36 | * @param minVal
37 | * The minimum value of a control value.
38 | * @param maxVal
39 | * The maximum value of a control value.
40 | */
41 | public Servo(JPigpio pigpio, int gpio, int minVal, int maxVal) {
42 | this.pigpio = pigpio;
43 | this.gpio = gpio;
44 | this.minVal = minVal;
45 | this.maxVal = maxVal;
46 | this.minPulseWidth = Pigpio.PI_MIN_SERVO_PULSEWIDTH;
47 | this.maxPulseWidth = Pigpio.PI_MAX_SERVO_PULSEWIDTH;
48 | } // End of constructor
49 |
50 | /**
51 | * Set a control value
52 | * @param value A value between the minimum and maximum values defined when the class was instantiated.
53 | * @throws PigpioException
54 | */
55 | public void setValue(int value) throws PigpioException {
56 | int mappedVal = Utils.mapToInt(value, minVal, maxVal, minPulseWidth, maxPulseWidth);
57 | System.out.println("Mapped val = " + mappedVal);
58 | pigpio.gpioServo(gpio, mappedVal);
59 | } // End of setValue
60 |
61 | /**
62 | * Stop being a servo
63 | * @throws PigpioException
64 | */
65 | public void stop() throws PigpioException {
66 | pigpio.gpioServo(gpio, Pigpio.PI_SERVO_OFF);
67 | } // End of stop
68 | } // End of Servo
69 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/devices/Stepper.java:
--------------------------------------------------------------------------------
1 | package jpigpio.devices;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.WrongModeException;
6 |
7 | /**
8 | * Control a stepper motor
9 | *
10 | */
11 | public class Stepper {
12 | private JPigpio pigpio;
13 |
14 | private int blueGpio; // IN1
15 | private int pinkGpio; // IN2
16 | private int yellowGpio; // IN3
17 | private int orangeGpio; // IN4
18 |
19 | // The step counter state
20 | private int step = 0;
21 |
22 | // Step 0 - Blue/Pink
23 | // Step 1 - Pink/Yellow
24 | // Step 2 - Yellow/Orange
25 | // Step 3 - Orange/Blue
26 |
27 | // The step data for a full step, high torque
28 | private int stepData[][] = {{1,1,0,0},{0,1,1,0},{0,0,1,1}, {1,0,0,1}};
29 |
30 | /**
31 | * Create an instance of the Stepper object used to control the stepper motor.
32 | * @param pigpio The pigpio controller
33 | * @param blueGpio The blue gpio pin (IN1)
34 | * @param pinkGpio The pink gpio pin (IN2)
35 | * @param yellowGpio The yellow gpio pin (IN3)
36 | * @param orangeGpio The orange gpio pin (IN4)
37 | * @throws PigpioException
38 | */
39 | public Stepper(JPigpio pigpio, int blueGpio, int pinkGpio, int yellowGpio, int orangeGpio) throws PigpioException {
40 | this.pigpio = pigpio;
41 | this.blueGpio = blueGpio; // IN1
42 | this.pinkGpio = pinkGpio; // IN2
43 | this.yellowGpio = yellowGpio; // IN3
44 | this.orangeGpio = orangeGpio; // IN4
45 |
46 | // Check that the pins have the correct modes.
47 | if (pigpio.gpioGetMode(blueGpio) != JPigpio.PI_OUTPUT) {
48 | throw new WrongModeException(blueGpio);
49 | }
50 | if (pigpio.gpioGetMode(pinkGpio) != JPigpio.PI_OUTPUT) {
51 | throw new WrongModeException(pinkGpio);
52 | }
53 | if (pigpio.gpioGetMode(yellowGpio) != JPigpio.PI_OUTPUT) {
54 | throw new WrongModeException(yellowGpio);
55 | }
56 | if (pigpio.gpioGetMode(orangeGpio) != JPigpio.PI_OUTPUT) {
57 | throw new WrongModeException(orangeGpio);
58 | }
59 |
60 | // Set the initial state of the motor.
61 | setData();
62 | } // End of constructor
63 |
64 | /**
65 | * Set the GPIO pins as a function of our current step state.
66 | * 0 = 1100
67 | * 1 = 0110
68 | * 2 = 0011
69 | * 3 = 1001
70 | * @throws PigpioException
71 | */
72 | private void setData() throws PigpioException {
73 | pigpio.gpioWrite(blueGpio, stepData[step][0] != 0);
74 | pigpio.gpioWrite(pinkGpio, stepData[step][1] != 0);
75 | pigpio.gpioWrite(yellowGpio, stepData[step][2] != 0);
76 | pigpio.gpioWrite(orangeGpio, stepData[step][3] != 0);
77 | } // End of setData
78 |
79 | /**
80 | * Move the stepper forward one step.
81 | * @throws PigpioException
82 | */
83 | public void forward() throws PigpioException{
84 | step = (step+1)%4;
85 | setData();
86 | } // End of forward
87 |
88 | /**
89 | * Move the stepper backwards one step.
90 | * @throws PigpioException
91 | */
92 | public void backward() throws PigpioException {
93 | step = (step-1)%4;
94 | setData();
95 | } // End of backward
96 | } // End of class
97 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/devices/TM1638.java:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2015 Neil Kolban
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the version 3 GNU General Public License as
6 | published by the Free Software Foundation.
7 |
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 |
13 | You should have received a copy of the GNU General Public License
14 | along with this program. If not, see .
15 | */
16 |
17 | package jpigpio.devices;
18 |
19 | import jpigpio.GPIO;
20 | import jpigpio.JPigpio;
21 | import jpigpio.PigpioException;
22 | import jpigpio.WrongModeException;
23 |
24 | /**
25 | * A data sheet can be found at Datasheet.
26 | *
27 | * This code is based upon work performed by Ricardo Batista in his project called "tm1638-library" found here:
28 | * https://code.google.com/p/tm1638-library/.
29 | *
30 | *author Neil Kolban
31 | *email kolban1@kolban.com
32 | *date 2015-05-23
33 | */
34 | public class TM1638 {
35 | private JPigpio pigpio;
36 | private GPIO stbGpio; // When strobe is high, chip is disabled.
37 | private GPIO clkGpio; // Clock in data on a rising edge
38 | private GPIO dioGpio; // Data input and output
39 |
40 | private boolean isTestMode;
41 | private boolean isFixedAddress;
42 | private boolean isReadKeys;
43 | private boolean isDisplayOn;
44 | private int brightness;
45 |
46 | private final byte DATA_COMMAND = (byte)0b01000000;
47 | private final byte ADDRESS_COMMAND = (byte)0b11000000;
48 | private final byte DISPLAY_COMMAND = (byte)0b10000000;
49 | private final byte TEST_MODE = (byte)(1<<3);
50 | private final byte FIXED_ADDRESS = (byte)(1<<2);
51 | private final byte READ_KEYS = (byte)(0b10);
52 | private final byte DISPLAY_ON = (byte)(1<<3);
53 |
54 | // The bits are displayed by mapping shown below:
55 | //
56 | // -- 0 --
57 | // | |
58 | // 5 1
59 | // -- 6 --
60 | // 4 2
61 | // | |
62 | // -- 3 -- .7
63 | //
64 | // definition for standard hexadecimal numbers
65 | private final byte NUMBER_FONT[] = {
66 | 0b00111111, // 0
67 | 0b00000110, // 1
68 | 0b01011011, // 2
69 | 0b01001111, // 3
70 | 0b01100110, // 4
71 | 0b01101101, // 5
72 | 0b01111101, // 6
73 | 0b00000111, // 7
74 | 0b01111111, // 8
75 | 0b01101111, // 9
76 | 0b01110111, // A
77 | 0b01111100, // B
78 | 0b00111001, // C
79 | 0b01011110, // D
80 | 0b01111001, // E
81 | 0b01110001 // F
82 | };
83 |
84 | public TM1638(JPigpio pigpio, GPIO stbGpio, GPIO clkGpio, GPIO dioGpio) throws PigpioException {
85 | this.pigpio = pigpio;
86 | this.stbGpio = stbGpio;
87 | this.clkGpio = clkGpio;
88 | this.dioGpio = dioGpio;
89 |
90 | isTestMode = false;
91 | isFixedAddress = false;
92 | isReadKeys = false;
93 | isDisplayOn = false;
94 | brightness = 0b111;
95 |
96 | // Validate that the GPIOs are in the correct modes.
97 | if (stbGpio.getDirection() != JPigpio.PI_OUTPUT) {
98 | throw new WrongModeException(stbGpio.getPin());
99 | }
100 | if (clkGpio.getDirection() != JPigpio.PI_OUTPUT) {
101 | throw new WrongModeException(clkGpio.getPin());
102 | }
103 | if (dioGpio.getDirection() != JPigpio.PI_OUTPUT) {
104 | throw new WrongModeException(dioGpio.getPin());
105 | }
106 |
107 | // Set the clock initially low
108 | clkGpio.setValue(JPigpio.PI_HIGH);
109 | setStrobe(true);
110 |
111 |
112 | pigpio.gpioDelay(100);
113 | setStrobe(false);
114 | setDataCommand(false, false, false);
115 | sendDataCommand();
116 | setStrobe(true);
117 |
118 | pigpio.gpioDelay(100);
119 | setStrobe(false);
120 | setDisplay(true);
121 | setBrightness(0b111);
122 | sendDisplayCommand();
123 | setStrobe(true);
124 |
125 | pigpio.gpioDelay(100);
126 | setStrobe(false);
127 | sendAddress(0);
128 | for (int i=0; i< 16; i++) {
129 | writeByte((byte)0b10000000);
130 | }
131 | setStrobe(true);
132 |
133 | } // End of constructor
134 |
135 | /**
136 | * Write a digit to the data stream. A digit is a set of LED segments
137 | * lit in such a way that they show a numeric digit.
138 | * @param digit The digit to display. The values are between 0 and 15 inclusive. Values
139 | * between 10 and 15 are the letters a-f corresponding to hex values.
140 | * 10 - A
141 | * 11 - b
142 | * 12 - C
143 | * 13 - d
144 | * 14 - E
145 | * 15 - F
146 | * @throws PigpioException
147 | */
148 | private void writeDigit(int digit) throws PigpioException {
149 | byte value = NUMBER_FONT[digit & 0b1111];
150 | writeByte(value);
151 | } // End of writeDigit
152 |
153 | public void writeNumber(int number) throws PigpioException {
154 | assert number >= 0;
155 | // 12345678
156 | // 10000000
157 | int multi = 10000000;
158 | while(multi >= 10) {
159 | if (number > multi) {
160 | break;
161 | }
162 | multi = multi / 10;
163 | }
164 | setStrobe(false);
165 | sendAddress(0);
166 | for (int i=0; i<8; i++) {
167 | if (multi > 0) {
168 | writeDigit(number / multi);
169 | number = number % multi;
170 | multi = multi / 10;
171 | } else {
172 | writeByte((byte)0);
173 | }
174 | // Skip the LEDs
175 | writeByte((byte)(0));
176 | }
177 | setStrobe(true);
178 | }
179 |
180 | private void setDataCommand(boolean isTestMode, boolean isFixedAddress, boolean isReadKeys) {
181 | this.isTestMode = isTestMode;
182 | this.isFixedAddress = isFixedAddress;
183 | this.isReadKeys = isReadKeys;
184 | } // End of setCommand
185 |
186 | private void sendDataCommand() throws PigpioException {
187 | byte value = DATA_COMMAND;
188 | if (isTestMode) {
189 | value |= TEST_MODE;
190 | }
191 | if (isFixedAddress) {
192 | value |= FIXED_ADDRESS;
193 | }
194 | if (isReadKeys) {
195 | value |= READ_KEYS;
196 | }
197 | writeByte(value);
198 | } // End of sendDataCommand
199 |
200 | private void sendAddress(int address) throws PigpioException {
201 | byte value = (byte)((address & 0b1111) | DATA_COMMAND);
202 | writeByte(value);
203 |
204 | } // End of setAddress
205 |
206 | private void setDisplay(boolean isDisplayOn) {
207 | this.isDisplayOn = isDisplayOn;
208 | }
209 |
210 | private void setBrightness(int brightness) {
211 | this.brightness = brightness & 0b111;
212 | }
213 |
214 | private void sendDisplayCommand() throws PigpioException {
215 | byte value = DISPLAY_COMMAND;
216 | if (isDisplayOn) {
217 | value |= DISPLAY_ON;
218 | }
219 | value |= (byte)(brightness & 0b111);
220 | writeByte(value);
221 | } // End of sendDisplayCommand
222 |
223 | private void writeByte(byte value) throws PigpioException {
224 | pigpio.gpioShiftOut(dioGpio, clkGpio, false, JPigpio.PI_LSBFIRST, value);
225 | }
226 |
227 | private void setStrobe(boolean value) throws PigpioException {
228 | stbGpio.setValue(value);
229 | }
230 | } // End of class
231 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/impl/CommonPigpio.java:
--------------------------------------------------------------------------------
1 | package jpigpio.impl;
2 |
3 | import jpigpio.GPIO;
4 | import jpigpio.JPigpio;
5 | import jpigpio.PigpioException;
6 |
7 | public abstract class CommonPigpio implements JPigpio {
8 |
9 | /**
10 | * Shift out a byte of data to a given pin. Note that this function is implemented in
11 | * Javacode.
12 | * @param gpioData The gpio to which to write the data.
13 | * @param gpioClock The clock gpio to pulse. The clock level is high.
14 | * @param bitOrder The order of the bits
15 | * @param value The value of the byte to write.
16 | * @throws PigpioException on pigpiod error
17 | */
18 | @Override
19 | public void gpioShiftOut(int gpioData, int gpioClock, boolean bitOrder, byte value) throws PigpioException {
20 | gpioShiftOut(gpioData, gpioClock, true, bitOrder, value);
21 | }
22 | @Override
23 | public void gpioShiftOut(GPIO gpioData, GPIO gpioClock, boolean bitOrder, byte value) throws PigpioException {
24 | gpioShiftOut(gpioData, gpioClock, true, bitOrder, value);
25 | }
26 |
27 | /**
28 | * Shift out a byte of data to a given pin. Note that this function is implemented in
29 | * Javacode.
30 | * @param gpioData The gpio to which to write the data.
31 | * @param gpioClock The clock gpio to pulse.
32 | * @param clockLevel The value of the clock pulse
33 | * @param bitOrder The order of the bits
34 | * @param value The value of the byte to write.
35 | * @throws PigpioException on pigpiod error
36 | */
37 | @Override
38 | public void gpioShiftOut(int gpioData, int gpioClock, boolean clockLevel, boolean bitOrder, byte value) throws PigpioException {
39 |
40 | boolean bit;
41 | for (int i = 0; i < 8; i++) {
42 | if (bitOrder == PI_LSBFIRST) {
43 | bit = ((value & 0x01) != 0);
44 | value = (byte) (value >> 1);
45 | } else {
46 | bit = ((value & 0x80) != 0);
47 | value = (byte) (value << 1);
48 | }
49 | gpioWrite(gpioData, bit);
50 | // Trigger this clock in high for 10 usecs
51 | gpioTrigger(gpioClock, 10, clockLevel);
52 | } // End of each bit
53 | } // End of gpioShiftOut
54 |
55 | @Override
56 | public void gpioShiftOut(GPIO gpioData, GPIO gpioClock, boolean clockLevel, boolean bitOrder, byte value) throws PigpioException {
57 |
58 | boolean bit;
59 | for (int i = 0; i < 8; i++) {
60 | if (bitOrder == PI_LSBFIRST) {
61 | bit = ((value & 0x01) != 0);
62 | value = (byte) (value >> 1);
63 | } else {
64 | bit = ((value & 0x80) != 0);
65 | value = (byte) (value << 1);
66 | }
67 | gpioData.setValue(bit);
68 | // Trigger this clock in high for 10 usecs
69 | gpioTrigger(gpioClock.getPin(), 10, clockLevel);
70 | } // End of each bit
71 | } // End of gpioShiftOut
72 |
73 | @Override
74 | public void gpioDelay(long delay, int type) throws PigpioException {
75 | switch (type) {
76 | case JPigpio.PI_MICROSECONDS:
77 | gpioDelay(delay);
78 | break;
79 | case JPigpio.PI_SECONDS:
80 | delay = delay * 1000;
81 | case JPigpio.PI_MILLISECONDS:
82 | try {
83 | Thread.sleep(delay);
84 | } catch (Exception e) {
85 | e.printStackTrace();
86 | }
87 | break;
88 | } // End of switch
89 |
90 | } // End of gpioDelay
91 |
92 | } // End of class
93 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/impl/SPI.java:
--------------------------------------------------------------------------------
1 | package jpigpio.impl;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.Utils;
6 |
7 | public class SPI {
8 | private int handle;
9 | private JPigpio pigpio;
10 | private boolean debug;
11 |
12 | public SPI(JPigpio pigpio, int channel, int baudRate, int flags) throws PigpioException {
13 | this.pigpio = pigpio;
14 | this.debug = false;
15 | handle = pigpio.spiOpen(channel, baudRate, flags);
16 | } // End of constructor
17 |
18 | public void close() throws PigpioException {
19 | pigpio.spiClose(handle);
20 | } // End of close
21 |
22 | public void read(byte data[]) throws PigpioException {
23 | pigpio.spiRead(handle, data);
24 | if (debug) {
25 | System.out.println("spiRead: " + Utils.dumpData(data));
26 | }
27 | } // End of read
28 |
29 | public void write(byte data[]) throws PigpioException {
30 | if (debug) {
31 | System.out.println("spiWrite: " + Utils.dumpData(data));
32 | }
33 | pigpio.spiWrite(handle, data);
34 |
35 | } // End of write
36 |
37 | public void xfer(byte txData[], byte rxData[]) throws PigpioException {
38 | if (debug) {
39 | System.out.print("xfer: " + Utils.dumpData(txData));
40 | }
41 | pigpio.spiXfer(handle, txData, rxData);
42 | if (debug) {
43 | System.out.println(" " + Utils.dumpData(rxData));
44 | }
45 | } // End of xfer
46 |
47 | public byte xfer(byte txData) throws PigpioException {
48 | byte txData1[] = {txData};
49 | byte rxData[] = new byte[1];
50 | xfer(txData1, rxData);
51 | return rxData[0];
52 | }
53 | } // End of class
54 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/packet/NotificationListener.java:
--------------------------------------------------------------------------------
1 | package jpigpio.packet;
2 |
3 | import jpigpio.GPIOListener;
4 |
5 | /**
6 | * NotificationListener is object, which after being registered with NotificationRouter (see class PigpioSocket)
7 | * receives notifications coming from Pigpiod. Every relevant notification (NotificationRouter filters out those
8 | * notifications irrelevant for specific NotificationListener object based on EDGE and GPIO pin which listener
9 | * is registered for) triggers calling method alert.
10 | */
11 | public class NotificationListener extends GPIOListener {
12 |
13 | protected int count = 0;
14 | protected boolean reset = false;
15 |
16 | protected int byteErrorCount = 0; //byte error count
17 | protected int datagramErrorCount = 0;
18 |
19 |
20 | public NotificationListener(int userGpio, int edge){
21 | super(userGpio, edge);
22 | }
23 |
24 | public void alert(int gpio, int level, long tick){
25 | count++;
26 | }
27 |
28 | public int countCalled(){
29 | return count;
30 | }
31 |
32 | public void countReset(){
33 | count = 0;
34 | }
35 |
36 | public int byteErrorCount(){
37 | return byteErrorCount;
38 | }
39 |
40 | public int datagramErrorCount(){
41 | return datagramErrorCount;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/packet/Protocol.java:
--------------------------------------------------------------------------------
1 | package jpigpio.packet;
2 |
3 | /**
4 | * Class defining properties of RF communication signaling.
5 | */
6 | public class Protocol {
7 |
8 | /**
9 | * datagram data size (in bytes)
10 | */
11 | public int DATA_SIZE = 5;
12 |
13 | //############# DATAGRAMS
14 | /**
15 | * datagram length in bytes (always double of DATA_SIZE because datagrams are constructed out of nibbles (4bit))
16 | */
17 | public int DGRM_LENGTH = DATA_SIZE*2;
18 |
19 | public int DGRM_REPEAT = 5;
20 | /**
21 | * repeat transmission of each datagram this many times to make sure at least one got through
22 | */
23 | public int DGRM_REPEAT_TX = DGRM_REPEAT;
24 |
25 | /**
26 | * report this many same datagrams as a single datagram (eliminate duplicates)
27 | */
28 | public int DGRM_REPEAT_RX = DGRM_REPEAT;
29 |
30 | public int DGRM_RX_TIMEOUT = 1000000; // datagram timeout (microseconds)
31 |
32 | /**
33 | * Set this to False to discard datagrams where encoding error was detected.
34 | * Under normal operation it makes no sense to keep such datagrams.
35 | */
36 | public boolean DGRM_KEEP_ON_ENCODING_ERROR = false;
37 |
38 |
39 | //############# SIGNALING
40 | /**
41 | * gap between two datagrams (microsec)
42 | */
43 | public int TX_PULSE_MSGGAP = 10800;
44 |
45 | /**
46 | * duration of high pulse (microsec)
47 | */
48 | public int TX_PULSE_HIGH = 280;
49 |
50 | /**
51 | * duration of low pulse (microsec)
52 | */
53 | public int TX_PULSE_LOW = 980;
54 |
55 | /**
56 | * pulse too short to be considered meaningful (microsec)
57 | */
58 | public int RX_PULSE_TOOSHORT = 150;
59 |
60 | /**
61 | * short pulse = 1 (one) (microsec)
62 | */
63 | public int RX_PULSE_ONE = 500;
64 |
65 | /**
66 | * long pulse = 0 (zero) (microsec)
67 | */
68 | public int RX_PULSE_ZERO = 2000;
69 |
70 | /**
71 | * gap between datagrams (microsec)
72 | */
73 | public int RX_PULSE_MSGGAP = 5000;
74 |
75 | //############# ENCODING
76 | public int[] SYMBOL = new int[] // encoding of 4 bit nibbles into 8 bits (= byte) => error detection
77 | {0xF6,0xEE,0xED,0xEB,0xDE,0xDD,0xDB,0xBE,0xBD,0xBB,0xB7,0x7E,0x7D,0x7B,0x77,0x6F};
78 |
79 | public int sym2nibble(int symbol){
80 | int s = -1;
81 | int i = 0;
82 | while (i < 16 && s < 0)
83 | if (SYMBOL[i] == symbol)
84 | s = i;
85 | else
86 | i++;
87 | return s;
88 | }
89 |
90 | public int nibble2sym(int nibble){
91 | return SYMBOL[nibble & 0x0F];
92 | }
93 |
94 | /**
95 | * Set maximum transmitted datagram size in bytes.
96 | * @param size size in bytes
97 | */
98 | public void setDataSize(int size){
99 | DATA_SIZE = size;
100 | DGRM_LENGTH = DATA_SIZE*2;
101 | }
102 |
103 | /**
104 | * Set transmission repeat count. By repeating transmission multiple times you are increasing probability to
105 | * receive data on the other end.
106 | * This also sets receiver repeat count - eliminating duplicate datagrams caused by repetitive transmissions.
107 | * @param repeatCount Count how many times datagram is going to be transmitted.
108 | */
109 | public void setRepeatCount(int repeatCount){
110 | DGRM_REPEAT = repeatCount;
111 | DGRM_REPEAT_TX = DGRM_REPEAT;
112 | DGRM_REPEAT_RX = DGRM_REPEAT;
113 | }
114 |
115 | public void setRxRepeatCount(int rxRepeatCount) {
116 | DGRM_REPEAT_RX = rxRepeatCount;
117 | }
118 |
119 | public void setTxRepeatCount(int txRepeatCount) {
120 | DGRM_REPEAT_TX = txRepeatCount;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/packet/Rf433rx.java:
--------------------------------------------------------------------------------
1 | package jpigpio.packet;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.Utils;
6 |
7 | import java.util.ArrayList;
8 |
9 | /**
10 | * Class implementing RF 433 MHz communication receiver (e.g. XD-RF-5V).
11 | * It implements NotificationReceiver which is decoding pulses based on preset Protocol
12 | * (you can tweak signalling by creating your own Protocol). NotificationListener is plugged
13 | * to PigpioSocket NotificationRouter, receiving every notification received from pigpiod daemon.
14 | * Received datagrams can be accessed via method get()
15 | *
16 | * Work is based on Robert Tidey LightwaveRF code https://github.com/roberttidey/LightwaveRF
17 | */
18 | public class Rf433rx {
19 |
20 | JPigpio pi;
21 | int rxGpio;
22 |
23 | NotificationListener cb;
24 |
25 | // Protocol describing signal levels, datagram length etc.
26 | Protocol protocol;
27 |
28 | /**
29 | * ArrayList of datagrams received from transmitter.
30 | */
31 | ArrayList datagrams = new ArrayList<>();
32 |
33 | /**
34 | * Class handling all notifications coming from pigpiod.
35 | * Technically this means this class analyzes signals received by pigpiod
36 | * and creates datagrams out of them.
37 | */
38 | class RxNotificationListener extends NotificationListener {
39 |
40 | final int RX_STATE_IDLE = 0;
41 | final int RX_STATE_MSGSTARTFOUND = 1;
42 | final int RX_STATE_BYTESTARTFOUND = 2;
43 | final int RX_STATE_GETBYTE = 3;
44 |
45 | boolean datagramError = false;
46 |
47 | int messageTick = 0;
48 | long lastTick = 0;
49 | long pulse = 0;
50 | int state = RX_STATE_IDLE;
51 | //int data1 = 0;
52 |
53 | int repeatCount = 0;
54 | boolean duplicate = false;
55 |
56 | int dataBit = 0;
57 | int dataByte = 0;
58 |
59 | byte[] datagram = new byte[protocol.DGRM_LENGTH];
60 |
61 | int data = 0;
62 |
63 | String pulses = "";
64 |
65 | RxNotificationListener(int userGpio, int edge){
66 | super(userGpio, edge);
67 | try {
68 | lastTick = pi.getCurrentTick();
69 | } catch (PigpioException e) {
70 | // TODO: handle somehow
71 | }
72 | }
73 |
74 | @Override
75 | public void alert(int gpio, int level, long tick){
76 | int trans = 0;
77 |
78 | count++; // increase called count for statistical purposes
79 |
80 | if (level == pi.PI_TIMEOUT) { // TIMEOUT notification received from PIGPIO?
81 | try {
82 | pi.setWatchdog(rxGpio, 0); // Switch watchdog off.
83 | } catch (PigpioException e) {
84 | // TODO: handle somehow
85 | }
86 | return;
87 | }
88 |
89 | pulse = Utils.tickDiff(lastTick, tick);
90 | lastTick = (int)tick;
91 |
92 | if (pulse < protocol.RX_PULSE_TOOSHORT) // very short pulse - ignore it
93 | return;
94 | else if (state == RX_STATE_IDLE && pulse <= protocol.RX_PULSE_MSGGAP) // quick check to see worth proceeding
95 | return;
96 | else if (pulse < protocol.RX_PULSE_ONE) { // normal short pulse
97 | trans = level + 2;
98 | pulses += "1";
99 | } else if (pulse < protocol.RX_PULSE_ZERO) { // normal long pulse
100 | trans = level + 4;
101 | pulses += "0";
102 | } else if (pulse > protocol.RX_PULSE_MSGGAP) { // gap between datagrams
103 | trans = level + 6;
104 | pulses += " ";
105 | } else
106 | trans = 8;
107 |
108 | // state machine
109 | switch (state) {
110 | //-----------------------------
111 | case RX_STATE_IDLE:
112 | if (trans == 7) { // 1 after datagram gap
113 | state = RX_STATE_MSGSTARTFOUND;
114 | duplicate = true;
115 | }
116 | break;
117 | //-----------------------------
118 | case RX_STATE_MSGSTARTFOUND:
119 | if (trans == 2) // nothing to do, wait for next 1
120 | trans = trans;
121 | else if (trans == 3) { // start of byte detected
122 | dataByte = 0;
123 | state = RX_STATE_BYTESTARTFOUND;
124 | } else
125 | state = RX_STATE_IDLE;
126 | break;
127 | //-----------------------------
128 | case RX_STATE_BYTESTARTFOUND:
129 | if (trans == 2)
130 | trans = trans;
131 | else if (trans == 3) { // 1 160->500
132 | data = 0;
133 | dataBit = 0;
134 | state = RX_STATE_GETBYTE;
135 | } else if (trans == 5) { // 0 500->1500
136 | data = 0;
137 | dataBit = 1;
138 | state = RX_STATE_GETBYTE;
139 | } else
140 | state = RX_STATE_IDLE;
141 | break;
142 | //-----------------------------
143 | case RX_STATE_GETBYTE:
144 | if (trans == 2)
145 | trans = trans;
146 | else if (trans == 3) { // 1 160->500
147 | data = data << 1 | 1;
148 | dataBit += 1;
149 | } else if (trans == 5) { // 0 500->1500
150 | data = data << 2 | 2;
151 | dataBit += 2;
152 | } else
153 | state = RX_STATE_IDLE;
154 |
155 | // check if byte complete
156 | if (dataBit >= 8) {
157 |
158 | data = protocol.sym2nibble(data);
159 |
160 | // negative means: not found in nibbles => byte error
161 | if (data < 0) {
162 | datagramError = true;
163 | byteErrorCount++;
164 | } else {
165 | // first received byte different from the same byte from previous datagram
166 | // means this datagram is not a duplicate of the previous one
167 | if (data != datagram[dataByte]) {
168 | duplicate = false;
169 | repeatCount = 0;
170 | }
171 |
172 | datagram[dataByte] = (byte) data;
173 | }
174 |
175 | dataByte++;
176 | dataBit = 0;
177 | pulses = "";
178 |
179 | if (dataByte >= protocol.DGRM_LENGTH) { //datagram complete?
180 | //System.out.println("#1 datagram received: "+datagram.toString());
181 |
182 | if (Utils.tickDiff(messageTick, (int) lastTick) > protocol.DGRM_RX_TIMEOUT || messageTick == 0) {
183 | repeatCount = 0;
184 | duplicate = false;
185 | } else if (duplicate)
186 | repeatCount++;
187 |
188 | if (repeatCount >= protocol.DGRM_REPEAT_RX){
189 | repeatCount = 0;
190 | duplicate = false;
191 | }
192 |
193 | // if no datagram error (or ignoring datagram errors) and not duplicate
194 | // System.out.println("#2 conditions: "+ protocol.DGRM_KEEP_ON_ENCODING_ERROR + " : " + datagramError + " # " + duplicate);
195 | if ((protocol.DGRM_KEEP_ON_ENCODING_ERROR || !datagramError) && !duplicate) {
196 | // System.out.println("#3 datagram processed: "+datagram.toString());
197 | datagrams.add(Utils.nibbles2bytes(datagram));
198 | }
199 |
200 | state = RX_STATE_IDLE;
201 | //messageTick = messageTick;
202 | messageTick = (int)tick;
203 |
204 | if (datagramError)
205 | datagramErrorCount++;
206 | datagramError = false;
207 |
208 | } else
209 | state = RX_STATE_BYTESTARTFOUND;
210 | }
211 | break;
212 | }
213 |
214 | }
215 |
216 | }
217 |
218 |
219 | public Rf433rx(JPigpio pi, int rxGpio, Protocol protocol) throws PigpioException{
220 | this.pi = pi;
221 | this.rxGpio = rxGpio;
222 | this.protocol = protocol;
223 |
224 | pi.gpioSetMode(rxGpio, JPigpio.PI_INPUT);
225 |
226 | setCallback(new RxNotificationListener(rxGpio, JPigpio.PI_EITHER_EDGE));
227 |
228 | }
229 |
230 | public void setCallback(NotificationListener notificationListener) throws PigpioException{
231 | this.cb = notificationListener;
232 | pi.addCallback(cb);
233 | }
234 |
235 | /**
236 | * Get one packet from available packets.
237 | * Check if there are packets available before calling this method.
238 | * @return Datagram.
239 | * IMPORTANT: Datagram contains nibbles 4bit) stored in bytes.
240 | * @throws IndexOutOfBoundsException if there is no datagram available
241 | */
242 | public byte[] get() throws IndexOutOfBoundsException {
243 | return datagrams.remove(0);
244 | }
245 |
246 | /**
247 | * Returns number of packets available for pickup
248 | * @return
249 | * Number of datagrams available.
250 | */
251 | public int available(){
252 | return datagrams.size();
253 | }
254 |
255 | /**
256 | * Terminate receiving thread, cancel further notifications from pigpiod.
257 | * @throws PigpioException on pigpiod error
258 | */
259 | public void terminate() throws PigpioException{
260 | if (cb != null) {
261 | pi.removeCallback(cb);
262 | pi.setWatchdog(rxGpio, 0);
263 | cb = null;
264 | }
265 |
266 | }
267 |
268 | /**
269 | * Simple statistics of byte errors detected while receiving datagrams.
270 | * High number of errors might mean low signal strength or too long datagrams.
271 | * @return byte error count
272 | */
273 | public int byteErrorCount(){
274 | return cb.byteErrorCount();
275 | }
276 |
277 | /**
278 | * Simple statistics returning number of errors in datagrams.
279 | * @return number of errors in datagrams.
280 | */
281 | public int datagramErrorCount(){
282 | return cb.datagramErrorCount();
283 | }
284 |
285 |
286 | }
287 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/packet/Rf433tx.java:
--------------------------------------------------------------------------------
1 | package jpigpio.packet;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.Pulse;
6 | import jpigpio.Utils;
7 |
8 | import java.util.ArrayList;
9 |
10 | /**
11 | * Class implementing 433 MHz transmitter (e.g. FS1000A) using pigpiod daemon.
12 | * Specific protocol (high/low signal duration, datagram/message length etc. can be cofigured
13 | * by passing different Protocol object to the constructor of this class.
14 | *
15 | * Work is based on Robert Tidey LightwaveRF code https://github.com/roberttidey/LightwaveRF
16 | *
17 | * Example usage: see Test_Rf433Tx
18 | */
19 | public class Rf433tx {
20 | JPigpio pi;
21 | int txGpio; // GPIO pin transmitter is connected to
22 | int txBit;
23 |
24 | Protocol protocol;
25 | Transmitter transmitter;
26 |
27 | /**
28 | * Inner class responsible for converting pulses to pigpiod waves and transmitting them in a separate thread.
29 | */
30 | class Transmitter implements Runnable {
31 |
32 | Thread thread;
33 | boolean stop = false;
34 | boolean error = false;
35 | boolean busy = false;
36 | Exception lastEx;
37 | JPigpio pi;
38 |
39 | ArrayList> wavePulses = new ArrayList<>();
40 |
41 | Transmitter(JPigpio jPigpio){
42 | this.pi = jPigpio;
43 | }
44 |
45 | @Override
46 | public void run(){
47 | int waveId=-1;
48 | while (!stop){
49 | try {
50 | if (wavePulses.size() > 0 && !pi.waveTxBusy()) {
51 |
52 | busy = true;
53 |
54 | //pi.waveTxStop();
55 | pi.waveAddNew();
56 |
57 | // Set TX high and wait to get agc of RX trained
58 | pi.gpioWrite(txGpio,true);
59 | Thread.sleep(protocol.TX_PULSE_MSGGAP / 1000);
60 |
61 | // create wave & "upload" it to pigpiod for transmitting
62 | pi.waveAddGeneric(wavePulses.remove(0));
63 | waveId = pi.waveCreate();
64 |
65 | // repeat packet sending according to protocol parameters
66 | for (int r = 0; r < protocol.DGRM_REPEAT_TX && !stop; r++) {
67 | pi.waveSendOnce(waveId);
68 | Thread.sleep(50);
69 | while (pi.waveTxBusy()) {
70 | Thread.sleep(2); // empiric value of 2ms
71 | }
72 | }
73 |
74 | // removeListener waveform after it has been transmitted
75 | pi.waveDelete(waveId);
76 |
77 | busy = false;
78 |
79 | } else // nothing to send or busy => sleep
80 | Thread.sleep(10);
81 | } catch (InterruptedException e) {
82 | //TODO: not expecting this to happen
83 | } catch (PigpioException e) {
84 | error = true;
85 | lastEx = e;
86 | System.out.println("Error: while sending wave "+waveId);
87 | }
88 |
89 | }
90 |
91 | }
92 |
93 | /**
94 | * Add pulse to transmitter queue
95 | * @param pulse Pulse to be transmitted
96 | */
97 | void addWave( ArrayList pulse){
98 | this.wavePulses.add(pulse);
99 | }
100 |
101 | /**
102 | * Read status of transmitter.
103 | * @return true if not transmitting and there are no pulses waiting to be transmitted
104 | * @throws PigpioException
105 | */
106 | boolean ready() throws PigpioException {
107 | return this.wavePulses.size() == 0 && !busy;
108 | }
109 |
110 | void start(){
111 | if (thread == null)
112 | {
113 | thread = new Thread (this);
114 | thread.setName("WaveTransmitter");
115 | thread.start ();
116 | }
117 | }
118 |
119 | /**
120 | * Stop transmitter
121 | * @throws PigpioException
122 | */
123 | void stop() throws PigpioException{
124 | this.stop = true;
125 | pi.waveTxStop();
126 | }
127 |
128 | }
129 |
130 | public Rf433tx(JPigpio pi, int txGpio, Protocol protocol) throws PigpioException {
131 | this.pi = pi;
132 | this.txGpio = txGpio;
133 | this.txBit = (1<< txGpio);
134 |
135 | this.protocol = protocol;
136 | this.transmitter = new Transmitter(pi);
137 | this.transmitter.start();
138 |
139 | pi.waveClear();
140 | pi.gpioSetMode(txGpio, JPigpio.PI_OUTPUT);
141 | }
142 |
143 | /**
144 | * Construct array of pulses from datagram data
145 | * @param data Data (4bit nibbles) to be transmitted
146 | * @return ArrayList of Pulses
147 | */
148 | public ArrayList constructMessagePulses(byte[] data){
149 | ArrayList wf;
150 | int dataByte;
151 |
152 | // Define a single datagram waveform
153 | wf = new ArrayList<>();
154 | // Pre Message low gap
155 | wf.add(new Pulse(0, txBit, protocol.TX_PULSE_MSGGAP));
156 | // Message start pulse
157 | wf.add(new Pulse(txBit, 0, protocol.TX_PULSE_HIGH));
158 | wf.add(new Pulse(0, txBit, protocol.TX_PULSE_HIGH));
159 |
160 | for(byte i: data){
161 | wf.add(new Pulse(txBit,0,protocol.TX_PULSE_HIGH));
162 | wf.add(new Pulse(0, txBit, protocol.TX_PULSE_HIGH));
163 | dataByte = protocol.nibble2sym(i);
164 | for (byte j = 0; j<8; j++)
165 | if ((dataByte & (0x80>>j)) != 0){
166 | wf.add(new Pulse(txBit,0,protocol.TX_PULSE_HIGH));
167 | wf.add(new Pulse(0, txBit, protocol.TX_PULSE_HIGH));
168 | } else
169 | wf.add(new Pulse(0, 0, protocol.TX_PULSE_LOW));
170 |
171 | }
172 |
173 | // Message end pulse
174 | wf.add(new Pulse(txBit,0,protocol.TX_PULSE_HIGH));
175 | wf.add(new Pulse(0, txBit, protocol.TX_PULSE_HIGH));
176 |
177 | return wf;
178 | }
179 |
180 |
181 | /**
182 | * Converts provided data to waveforms using properties of Protocol
183 | * and transmits waveforms repeatedly (if required by Protocol).
184 | *
185 | * @param data data to be transmitted
186 | * @return
187 | * 0 - everything is OK
188 | * -1 - data
189 | * @throws PigpioException on pigpiod error
190 | */
191 | public int put (byte[] data) throws PigpioException{
192 | if (data.length != protocol.DATA_SIZE)
193 | return -1;
194 |
195 | return putNibbles(Utils.bytes2nibbles(data));
196 | }
197 |
198 | /**
199 | * Converts provided nibbles (4bit stored in 8bit) to waveforms using properties of Protocol
200 | * and transmits waveforms repeatedly (if required by Protocol).
201 | *
202 | * @param nibbles
203 | * nibbles stored in bytes to transmit.
204 | * @return
205 | * 0 - everything is OK
206 | * -1 - data
207 | * @throws PigpioException
208 | */
209 | int putNibbles (byte[] nibbles) throws PigpioException{
210 | int ret = 0;
211 | ArrayList wf;
212 |
213 | if (nibbles.length < protocol.DGRM_LENGTH)
214 | return -1;
215 |
216 | wf = constructMessagePulses(nibbles);
217 | transmitter.addWave(wf);
218 |
219 | return ret;
220 |
221 | }
222 |
223 |
224 | /**
225 | * Returns TRUE if available for another transmission.
226 | * @return
227 | * TRUE/FALSE
228 | * @throws PigpioException on pigpiod error
229 | */
230 | public synchronized boolean ready() throws PigpioException {
231 | return transmitter.ready();
232 | }
233 |
234 |
235 | /**
236 | * Terminates transmission of all waveforms.
237 | * @throws PigpioException on pigpiod error
238 | */
239 | public void terminate() throws PigpioException{
240 | transmitter.stop();
241 | pi.waveClear();
242 | }
243 |
244 |
245 | }
246 |
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/sensors/GY_271.java:
--------------------------------------------------------------------------------
1 | package jpigpio.sensors;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 |
6 | /**
7 | * The GY-271 is a module that provides a multi axis magnetic field measurement that is typically used to provide a compass. It is based on the Honeywell HMC5883L IC. The module
8 | * uses I2C for communications.
9 | *
10 | * This Java class provides a wrapper to its low level functions for use with Pigpio.
11 | *
12 | * author Neil Kolban
13 | * date 2015-05-06
14 | */
15 | public class GY_271 {
16 |
17 |
18 | // REGISTER_CONFIG_A (0)
19 | // +----+-----+------------------------------------+
20 | // | | 7 | Reserved. Must be 0 |
21 | // +----+-----+------------------------------------+
22 | // | MA | 6:5 | Samples per measurement |
23 | // +----+-----+------------------------------------+
24 | // | DO | 4:2 | Output rate in measurements/second |
25 | // +----+-----+------------------------------------+
26 | // | MS | 1:0 | Measurement configuration |
27 | // +----+-----+------------------------------------+
28 | public static final int SAMPLES_1 = 0b00;
29 | public static final int SAMPLES_2 = 0b01;
30 | public static final int SAMPLES_4 = 0b10;
31 | public static final int SAMPLES_8 = 0b11;
32 | private static final int SAMPLE_MASK = 0b1100000;
33 |
34 | public static final int OUTPUT_RATE_0_75 = 0b000;
35 | public static final int OUTPUT_RATE_1_5 = 0b001;
36 | public static final int OUTPUT_RATE_3 = 0b010;
37 | public static final int OUTPUT_RATE_7_5 = 0b011;
38 | public static final int OUTPUT_RATE_15 = 0b100;
39 | public static final int OUTPUT_RATE_30 = 0b101;
40 | public static final int OUTPUT_RATE_75 = 0b110;
41 | private static final int OUTPUT_RATE_MASK = 0b11100;
42 |
43 | // REGISTER_CONFIG_B (1)
44 | // +----+-----+----------------------+
45 | // | GN | 7:5 | Gain |
46 | // +----+-----+----------------------+
47 | // | MA | 4:0 | Reserved. Must be 0 |
48 | // +----+-----+----------------------+
49 | public static final int GAIN_1370 = 0b000;
50 | public static final int GAIN_1090 = 0b001;
51 | public static final int GAIN_0820 = 0b010;
52 | public static final int GAIN_0660 = 0b011;
53 | public static final int GAIN_0440 = 0b100;
54 | public static final int GAIN_0390 = 0b101;
55 | public static final int GAIN_0330 = 0b110;
56 | public static final int GAIN_0230 = 0b111;
57 | private static final int GAIN_MASK = 0b11100000;
58 |
59 | // REGISTER_MODE (2)
60 | // +----+-----+----------------------+
61 | // | HS | 7 | High speed I2C |
62 | // +----+-----+----------------------+
63 | // | | 6:2 | Reserved. Must be 0 |
64 | // +----+-----+----------------------+
65 | // | MD | 1:0 | Operating mode |
66 | // +----+-----+----------------------+
67 | public static final int MODE_CONTINUOUS = 0b00;
68 | public static final int MODE_SINGLE = 0b01;
69 | public static final int MODE_IDLE = 0b10;
70 | private static final int MODE_MASK = 0b11;
71 |
72 |
73 | // These are the different registers in the environment
74 | private static final int REGISTER_CONFIG_A = 0;
75 | private static final int REGISTER_CONFIG_B = 1;
76 | private static final int REGISTER_MODE = 2;
77 | private static final int REGISTER_DATA_X_MSB = 3;
78 | private static final int REGISTER_DATA_X_LSB = 4;
79 | private static final int REGISTER_DATA_Z_MSB = 5;
80 | private static final int REGISTER_DATA_Z_LSB = 6;
81 | private static final int REGISTER_DATA_Y_MSB = 7;
82 | private static final int REGISTER_DATA_Y_LSB = 8;
83 | private static final int REGISTER_STATUS = 9;
84 | private static final int REGISTER_IDENT_A = 10;
85 | private static final int REGISTER_IDENT_B = 11;
86 | private static final int REGISTER_IDENT_C = 12;
87 |
88 | /**
89 | * The address of the GY-271 on the I2C bus
90 | */
91 | private final int GY_271_I2C_ADDRESS = 0x1E; // GY-271 I2C address
92 | /**
93 | * The I2C bus we use on the Pi
94 | */
95 | private final int PI_I2CBUS = 1;
96 |
97 | private int xValue = 0;
98 | private int yValue = 0;
99 | private int zValue = 0;
100 |
101 | /**
102 | * The Pigpio interface
103 | */
104 | private JPigpio pigpio;
105 | /**
106 | * The handle to the I2C device
107 | */
108 | private int handle;
109 |
110 | /**
111 | * Construct the object for this class.
112 | * @param pigpio The reference to the Pigpio controller
113 | */
114 | public GY_271(JPigpio pigpio) {
115 | this.pigpio = pigpio;
116 | } // End of constructor
117 |
118 | /**
119 | * Initialize the GY-271
120 | *
121 | * @throws PigpioException on pigpiod error
122 | */
123 | public void initialize() throws PigpioException {
124 | // Open a connection on I2C to the GY-271 device.
125 | handle = pigpio.i2cOpen(PI_I2CBUS, GY_271_I2C_ADDRESS);
126 |
127 | // Select register 2 and set for continuous measurement
128 | setMode(MODE_CONTINUOUS);
129 | setSamples(SAMPLES_1);
130 | setOutputRate(15);
131 | setGain(GAIN_1090);
132 |
133 | pigpio.gpioDelay(500);
134 | } // End of initialize
135 |
136 | /**
137 | * Close our usage of the I2C bus.
138 | *
139 | * @throws PigpioException on pigpiod error
140 | */
141 | public void close() throws PigpioException {
142 | pigpio.i2cClose(handle);
143 | } // End of close
144 |
145 | public void readValue() throws PigpioException {
146 | byte selectRegister[] = { REGISTER_DATA_X_MSB };
147 | pigpio.i2cWriteDevice(handle, selectRegister);
148 | pigpio.gpioDelay(100, JPigpio.PI_MILLISECONDS);
149 |
150 | // Read 6 bytes of data corresponding to the 3 pairs of bytes
151 | byte data[] = new byte[6];
152 | pigpio.i2cReadDevice(handle, data);
153 | xValue = data[0] << 8 | data[1];
154 | zValue = data[2] << 8 | data[3];
155 | yValue = data[4] << 8 | data[4];
156 | // byte data[] = new byte[1];
157 | // pigpio.i2cReadDevice(handle, data);
158 | // xValue = data[0] << 8;
159 | // pigpio.i2cReadDevice(handle, data);
160 | // xValue |= data[0];
161 | // pigpio.i2cReadDevice(handle, data);
162 | // zValue = data[0] << 8;
163 | // pigpio.i2cReadDevice(handle, data);
164 | // zValue |= data[0];
165 | // pigpio.i2cReadDevice(handle, data);
166 | // yValue = data[0] << 8;
167 | // pigpio.i2cReadDevice(handle, data);
168 | // yValue |= data[0];
169 |
170 | } // End of readValue
171 |
172 | public int getX() {
173 | return xValue;
174 | } // End of getX
175 |
176 | public int getY() {
177 | return yValue;
178 | } // End of getY
179 |
180 | public int getZ() {
181 | return zValue;
182 | } // End of getZ
183 |
184 | @Override
185 | public String toString() {
186 | return String.format("x: %d, y: %d, z: %d", getX(), getY(), getZ());
187 | } // End of toString
188 |
189 | /**
190 | * Get the device id. A normal device will have an id of "H43".
191 | *
192 | * @return The string representation of the device
193 | * @throws PigpioException on pigpiod error
194 | */
195 | public String getId() throws PigpioException {
196 | byte selectRegister[] = { REGISTER_IDENT_A };
197 | pigpio.i2cWriteDevice(handle, selectRegister);
198 | byte data[] = new byte[3];
199 | pigpio.i2cReadDevice(handle, data);
200 | return new String(data);
201 | } // End of getId
202 |
203 | public void setGain(int value) throws PigpioException {
204 | writeRegister(REGISTER_CONFIG_B, (byte)(readRegister(REGISTER_CONFIG_B) & ~GAIN_MASK | (value << 5)));
205 | } // End of setGain
206 |
207 | public void setMode(int value) throws PigpioException {
208 | writeRegister(REGISTER_MODE, (byte)(readRegister(REGISTER_MODE) & ~MODE_MASK | value ));
209 | } // End of setMode
210 |
211 | public void setSamples(int value) throws PigpioException {
212 | writeRegister(REGISTER_CONFIG_A, (byte)(readRegister(REGISTER_CONFIG_A) & ~SAMPLE_MASK | (value << 5)));
213 | } // End of setSamples
214 |
215 | public void setOutputRate(int value) throws PigpioException {
216 | writeRegister(REGISTER_CONFIG_A, (byte)(readRegister(REGISTER_CONFIG_A) & ~OUTPUT_RATE_MASK | (value << 2)));
217 | } // End of setOutputRate
218 |
219 | public byte getStatus() throws PigpioException {
220 | return readRegister(REGISTER_STATUS);
221 | } // End of getStatus
222 |
223 | private byte readRegister(int register) throws PigpioException {
224 | byte data[] = { (byte) register };
225 | pigpio.i2cWriteDevice(handle, data);
226 | pigpio.i2cReadDevice(handle, data);
227 | return data[0];
228 | } // End of readRegister
229 |
230 | private void writeRegister(int register, byte value) throws PigpioException {
231 | byte data[] = { (byte) register, value };
232 | pigpio.i2cWriteDevice(handle, data);
233 | } // End of write register
234 | } // End of class
235 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/sensors/HC_SR04.java:
--------------------------------------------------------------------------------
1 | package jpigpio.sensors;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.WrongModeException;
6 |
7 | public class HC_SR04 {
8 | private JPigpio pigpio;
9 | private int triggerGpio;
10 | private int echoGpio;
11 | /**
12 | * Construct the object for this class.
13 | * @param pigpio The reference to the Pigpio controller
14 | */
15 | public HC_SR04(JPigpio pigpio, int triggerGpio, int echoGpio) throws PigpioException {
16 | this.pigpio = pigpio;
17 | this.triggerGpio = triggerGpio;
18 | this.echoGpio = echoGpio;
19 | if (pigpio.gpioGetMode(triggerGpio) != JPigpio.PI_OUTPUT) {
20 | throw new WrongModeException(triggerGpio);
21 | }
22 | if (pigpio.gpioGetMode(echoGpio) != JPigpio.PI_INPUT) {
23 | throw new WrongModeException(echoGpio);
24 | }
25 | } // End of constructor
26 |
27 | /**
28 | * Get the delay in microseconds for a trigger/echo
29 | * @return The time in microseconds between a trigger and an echo response
30 | * @throws PigpioException on pigpiod error
31 | */
32 | public long getDelay() throws PigpioException {
33 | long delay = pigpio.gpioxPulseAndWait(triggerGpio, echoGpio, 50000, 10, false);
34 | return delay;
35 | } // End of getDelay
36 |
37 |
38 | /**
39 | * Get the sensor measured distance to the target in meters.
40 | * @return The distance to the target in meters or -1 if not determined.
41 | * @throws PigpioException on pigpiod error
42 | */
43 | public double getMetricDistance() throws PigpioException {
44 | long delay = getDelay();
45 | if (delay == -1) {
46 | return -1.0;
47 | }
48 | return delay / 1000000.0 * 340.39 / 2.0;
49 | } // End of getMetricDistance
50 |
51 | /**
52 | * Get the distance in inches of detection or -1 if no object detected.
53 | * @return The distance in inches to object.
54 | * @throws PigpioException on pigpiod error
55 | */
56 | public double getImperialDistance() throws PigpioException {
57 | double metricDistance = getMetricDistance();
58 | if (metricDistance == -1.0) {
59 | return -1.0;
60 | }
61 | // Convert meters to inches
62 | return metricDistance * 39.3701;
63 | } // End of getImperialDistance
64 |
65 | } // End of class HC_SR04
66 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/jpigpio/sensors/WiiNunchuck.java:
--------------------------------------------------------------------------------
1 | package jpigpio.sensors;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 |
6 | /**
7 | * Wrapper for WiiNunchuck. The Wii Nunchuck is an I2C device and hence has to be connected
8 | * to the SDA and SCL pins of the Pi.
9 | *
10 | * To use this class:
11 | *
12 | * - Initialize Pigpio
13 | * - Call initialize()
14 | * - Call readValue()
15 | * - get the data fields ...
16 | *
17 | *
18 | * author Neil Kolban
19 | * date 2015-04-30
20 | *
21 | */
22 | public class WiiNunchuck {
23 | private final int NUNCHUCK_DEVICE = 0x52;
24 | private final int PI_I2CBUS = 1;
25 | private JPigpio pigpio;
26 | private int handle;
27 | private byte joyX;
28 | private byte joyY;
29 | private byte accelX;
30 | private byte accelY;
31 | private byte accelZ;
32 | private boolean buttonC;
33 | private boolean buttonZ;
34 |
35 | public WiiNunchuck(JPigpio pigpio) {
36 | this.pigpio = pigpio;
37 | } // End of constructor
38 |
39 | /**
40 | * Initialize the Nunchuck
41 | * @throws PigpioException
42 | */
43 | public void initialize() throws PigpioException {
44 | handle = pigpio.i2cOpen(PI_I2CBUS, NUNCHUCK_DEVICE);
45 | byte data[] = { 0x40, 0x00 };
46 | pigpio.i2cWriteDevice(handle, data);
47 | pigpio.gpioDelay(500);
48 | } // End of initialize
49 |
50 | public void close() throws PigpioException {
51 | pigpio.i2cClose(handle);
52 | } // End of close
53 |
54 | /**
55 | * Read a value from the Wii Nunchuck.
56 | * @throws PigpioException
57 | */
58 | public void readValue() throws PigpioException {
59 | byte data2[] = { 0x00 };
60 | pigpio.i2cWriteDevice(handle, data2);
61 | pigpio.gpioDelay(200);
62 | byte data3[] = new byte[6];
63 | pigpio.i2cReadDevice(handle, data3);
64 |
65 | byte bytes[] = data3;
66 | // (d) 1 2 4 8 16 32 64 128
67 | // (h) 1 2 4 8 10 20 40 80
68 | joyX = bytes[0];
69 | joyY = bytes[1];
70 |
71 | accelX = (byte)((bytes[2] << 2) | ((bytes[5] & 0xc0) >> 6));
72 | accelY = (byte)((bytes[3] << 2) | ((bytes[5] & 0x30) >> 4));
73 | accelZ = (byte)((bytes[4] << 2) | ((bytes[5] & 0x0c) >> 2));
74 | buttonC = ((bytes[5] & 0x02) >> 1) == 1;
75 | buttonZ = (bytes[5] & 0x01) == 1;
76 | //System.out.println(String.format("Data: %d %d %d %d %d %d", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]));
77 | } // End of readValue
78 |
79 | public byte getJoyX() {
80 | return joyX;
81 | }
82 |
83 | public byte getJoyY() {
84 | return joyY;
85 | }
86 |
87 | public byte getAccelX() {
88 | return accelX;
89 | }
90 |
91 | public byte getAccelY() {
92 | return accelY;
93 | }
94 |
95 | public byte getAccelZ() {
96 | return accelZ;
97 | }
98 |
99 | public boolean isButtonC() {
100 | return buttonC;
101 | }
102 |
103 | public boolean isButtonZ() {
104 | return buttonZ;
105 | }
106 |
107 | @Override
108 | public String toString() {
109 | return String.format("joyX=%d joyY=%d accelX=%d accelY=%d accelZ=%d buttonC=%b buttonZ=%b", //
110 | Byte.toUnsignedInt(joyX), Byte.toUnsignedInt(joyY), Byte.toUnsignedInt(accelX), Byte.toUnsignedInt(accelY), Byte.toUnsignedInt(accelZ), buttonC, buttonZ);
111 | } // End of toString
112 | } // End of class
113 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Blink.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 |
8 | /**
9 | * Set a pin high and then low forever. The pin is commonly connected to an LED to cause it to
10 | * blink on and off.
11 | *
12 | * author Neil Kolban
13 | * date 2015-04-26
14 | *
15 | */
16 | public class Test_Blink {
17 | /**
18 | * This is the gpio pin to set output and pulse on and off.
19 | */
20 | private final int BLINK_PIN = 17;
21 |
22 |
23 | /**
24 | * Bootstrap the application.
25 | * @param args Standard application arguments (not used).
26 | */
27 | public static void main(String args[]) {
28 | System.out.println("Test_Blink");
29 | Test_Blink app = new Test_Blink();
30 | app.run();
31 | }
32 |
33 | /**
34 | * Define a run function to perform the work in the context of an
35 | * instance of the class.
36 | */
37 | public void run() {
38 | try {
39 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
40 | JPigpio pigpio = new Pigpio();
41 |
42 | // Initialize our library
43 | pigpio.gpioInitialize();
44 | Utils.addShutdown(pigpio);
45 |
46 | // Set the gpio pin to its output mode
47 | pigpio.gpioSetMode(BLINK_PIN, JPigpio.PI_OUTPUT);
48 |
49 | // Loop forever
50 | while (true) {
51 | // Set the pin high to light the LED
52 | pigpio.gpioWrite(BLINK_PIN, JPigpio.PI_HIGH);
53 | pigpio.gpioDelay(500 * 1000);
54 |
55 | // Set the pin low to darken the LED
56 | pigpio.gpioWrite(BLINK_PIN, JPigpio.PI_LOW);
57 | pigpio.gpioDelay(500 * 1000);
58 | }
59 | } catch (PigpioException e) {
60 | e.printStackTrace();
61 | }
62 | } // End of run
63 | } // End of class
64 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_DualServoSweep.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 |
7 | public class Test_DualServoSweep {
8 | private final int servoPin1 = 17;
9 | private final int servoPin2 = 18;
10 | private final int min = 500;
11 | private final int max = 2500;
12 |
13 | public static void main(String args[]) {
14 | System.out.println("Starting Test_ServoSweep");
15 | Test_DualServoSweep app = new Test_DualServoSweep();
16 | app.run();
17 | }
18 |
19 | public void run() {
20 |
21 | try {
22 | //JPigpio pigpio = new PigpioSocket("localhost", 8888);
23 | JPigpio pigpio = new Pigpio();
24 | pigpio.gpioInitialize();
25 |
26 | int servoSweepDuration = 5000; // Time in ms
27 | int direction = 0; // 0 = up, 1 = down
28 | while (true) {
29 | long startTime = pigpio.gpioTick();
30 | int sweepTime = servoSweepDuration * 1000 / 2;
31 | long delta = pigpio.gpioTick() - startTime;
32 | while (delta < sweepTime) {
33 | // Position is going to be between 0 and 1 and represents
34 | // how far along the sweep we are.
35 | double position = (double) delta / sweepTime * (max - min);
36 |
37 | int timeToWriteHighUSecs;
38 | if (direction == 0) {
39 | timeToWriteHighUSecs = (int) (min + position);
40 | } else {
41 | timeToWriteHighUSecs = (int) (max - position);
42 | }
43 |
44 | System.out.println(String.format("Setting pulse width %d, delta=%d, startTime=%d\n", timeToWriteHighUSecs, delta, startTime));
45 | //timeToWriteHighUSecs = 1500;
46 | pigpio.gpioServo(servoPin1, timeToWriteHighUSecs);
47 | pigpio.gpioServo(servoPin2, timeToWriteHighUSecs);
48 | System.out.println("A");
49 | pigpio.gpioDelay(20);
50 | System.out.println("B");
51 |
52 | long x = pigpio.gpioTick();
53 | System.out.println("x = " + x);
54 | delta = pigpio.gpioTick() - startTime;
55 | } // End of a sweep in one direction
56 |
57 | // We have ended a sweep, let us now go in the other direction!
58 | System.out.println("End sweep");
59 | // Switch direction
60 | if (direction == 0) {
61 | direction = 1;
62 | } else {
63 | direction = 0;
64 | }
65 | } // End of while true
66 |
67 | } catch (PigpioException e) {
68 | e.printStackTrace();
69 | }
70 | }
71 | }
72 | /*
73 | *
74 | * int main(void) { int rc = gpioInitialise(); if (rc < 0) {
75 | * printf("gpioInitialise() failed: %d\n", rc); exit(-1); } int pwmPin = 17; int
76 | * servoSweepDuration = 500; // Time in ms
77 | *
78 | * printf("pwmPin pin = %d\n", pwmPin);
79 | * printf("servoSweepDuration = %d seconds\n", servoSweepDuration);
80 | *
81 | * int direction = 0; // 0 = up, 1 = down while(1) { unsigned int startTime =
82 | * gpioTick(); unsigned int sweepTime = servoSweepDuration * 1000 / 2; unsigned
83 | * int delta = gpioTick() - startTime; while(delta < sweepTime) { // Position is
84 | * going to be between 0 and 1 and represents how far along the sweep // we are.
85 | * double position = (double)delta/sweepTime;
86 | *
87 | * unsigned int timeToWriteHighUSecs; position = -0.4; if (direction == 0) {
88 | * timeToWriteHighUSecs = (position + 1.0) * 1000; } else { timeToWriteHighUSecs
89 | * = (2.0 - position) * 1000; }
90 | *
91 | * printf("Setting pulse width %d, %d, %d\n", timeToWriteHighUSecs, delta,
92 | * startTime); gpioServo(pwmPin, timeToWriteHighUSecs); gpioDelay(20 * 1000);
93 | *
94 | * delta = gpioTick() - startTime; } // End of a sweep in one direction
95 | *
96 | * // Switch direction if (direction == 0) { direction = 1; } else { direction =
97 | * 0; } } // End of while true return 0; }
98 | */
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_GY_271.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.sensors.GY_271;
7 |
8 | public class Test_GY_271 {
9 |
10 | public static void main(String[] args) {
11 | Test_GY_271 app = new Test_GY_271();
12 | app.run();
13 | }
14 |
15 | public void run() {
16 | try {
17 | JPigpio pigpio = new Pigpio();
18 | pigpio.gpioInitialize();
19 |
20 | GY_271 gy_271 = new GY_271(pigpio);
21 | gy_271.initialize();
22 | pigpio.gpioDelay(1000);
23 | gy_271.setGain(GY_271.GAIN_1090);
24 | pigpio.gpioDelay(1000);
25 | System.out.println("Device id: " + gy_271.getId());
26 | while (true) {
27 | //System.out.println("Status: " + gy_271.getStatus());
28 | gy_271.readValue();
29 | System.out.println("Values: " + gy_271.toString());
30 | // while((gy_271.getStatus() & 0b10) != 0) {
31 | // System.out.println("Locked");
32 | // pigpio.gpioDelay(100, JPigpio.PI_MICROSECONDS);
33 | // }
34 | pigpio.gpioDelay(500, JPigpio.PI_MILLISECONDS);
35 | } // End of while true
36 | } catch (PigpioException e) {
37 | e.printStackTrace();
38 | }
39 | } // End of run
40 | } // End of Test_Nunchuck2
41 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_HC_SR04.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 | import jpigpio.sensors.HC_SR04;
8 |
9 | public class Test_HC_SR04 {
10 |
11 | private int triggerPin = 17;
12 | private int echoPin = 18;
13 |
14 | public static void main(String args[]) {
15 | System.out.println("Test HC-SR04");
16 | Test_HC_SR04 app = new Test_HC_SR04();
17 | app.run();
18 | }
19 |
20 | public void run() {
21 | try {
22 | // JPigpio pigpio = new PigpioSocket("raspi", 8888);
23 | JPigpio pigpio = new Pigpio();
24 | pigpio.setDebug(false);
25 | pigpio.gpioInitialize();
26 |
27 |
28 | // Create an instance of the HC_SR04 ultrasonic device
29 | HC_SR04 hcSR04 = new HC_SR04(pigpio, triggerPin, echoPin);
30 | Utils.addShutdown(pigpio);
31 |
32 | // Set the mode of the pins we will be using.
33 | pigpio.gpioSetMode(triggerPin, JPigpio.PI_OUTPUT);
34 | pigpio.gpioSetMode(echoPin, JPigpio.PI_INPUT);
35 | while (true) {
36 | System.out.println("Distance: " + hcSR04.getMetricDistance() * 100 + "cm");
37 | try {
38 | Thread.sleep(250);
39 | } catch (Exception e) {
40 | e.printStackTrace();
41 | return;
42 | }
43 | }
44 | } catch (PigpioException e) {
45 | e.printStackTrace();
46 | }
47 | }
48 | } // End of class
49 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_LCD.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 | import jpigpio.devices.LCD;
8 |
9 | public class Test_LCD {
10 | private int registerSelectGpio = JPigpio.PI_GPIO17;
11 | private int readWriteGpio = JPigpio.PI_GPIO27;
12 | private int enableGpio = JPigpio.PI_GPIO22;
13 | private int db4Gpio = JPigpio.PI_GPIO5;
14 | private int db5Gpio = JPigpio.PI_GPIO6;
15 | private int db6Gpio = JPigpio.PI_GPIO13;
16 | private int db7Gpio = JPigpio.PI_GPIO19;
17 |
18 |
19 | public static void main(String args[]) {
20 | System.out.println("Test_LCD");
21 | Test_LCD app = new Test_LCD();
22 | app.run();
23 | }
24 |
25 | public void run() {
26 |
27 | try {
28 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
29 | JPigpio pigpio = new Pigpio();
30 | pigpio.gpioInitialize();
31 | Utils.addShutdown(pigpio);
32 | pigpio.gpioSetMode(registerSelectGpio, JPigpio.PI_OUTPUT);
33 | pigpio.gpioSetMode(readWriteGpio, JPigpio.PI_OUTPUT);
34 | pigpio.gpioSetMode(enableGpio, JPigpio.PI_OUTPUT);
35 | pigpio.gpioSetMode(db4Gpio, JPigpio.PI_OUTPUT);
36 | pigpio.gpioSetMode(db5Gpio, JPigpio.PI_OUTPUT);
37 | pigpio.gpioSetMode(db6Gpio, JPigpio.PI_OUTPUT);
38 | pigpio.gpioSetMode(db7Gpio, JPigpio.PI_OUTPUT);
39 | LCD lcd = new LCD(pigpio, registerSelectGpio, readWriteGpio, enableGpio, db4Gpio, db5Gpio, db6Gpio, db7Gpio);
40 | //lcd.display(false, false, false);
41 | lcd.clear();
42 | lcd.write("Hi Steph!");
43 |
44 | } catch (PigpioException e) {
45 | e.printStackTrace();
46 | }
47 | }
48 | } // End of class
49 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_LEDs.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.PigpioSocket;
6 | import jpigpio.Utils;
7 |
8 | /**
9 | * Example showing how to operate 16 LEDs using two shift-out registers 74HC595 using Raspberry Pi.
10 | * It can be easily adapted to operate 7 segment LED displays.
11 | *
12 | * Idea has been taken from https://www.arduino.cc/en/Tutorial/ShiftOut
13 | *
14 | * Created by Jozef on 17.06.2016.
15 | */
16 | public class Test_LEDs {
17 |
18 | JPigpio pigpio;
19 |
20 | public static void main(String args[]) {
21 | System.out.println("Test_LEDs");
22 | Test_LEDs app = new Test_LEDs();
23 | app.run();
24 | }
25 |
26 | /**
27 | * Low level function sending data to two 74HC595 shift registers connected in serial
28 | * effectively displaying 16 bits/outputs
29 | * @param dataPin GPIO pin to which 'data' (DS pin of 74HC595) is connected.
30 | * @param clockPin GPIO pin to which 'clock' (SH_CP pin of 74HC595) is connected
31 | * @param data 8 bit data to be displayed
32 | * @throws PigpioException if write is not successful
33 | */
34 | void shiftOut(int dataPin, int clockPin, int data) throws PigpioException{
35 |
36 | boolean pinState;
37 | byte dataOut = (byte)(data & 0xFF);
38 |
39 | pigpio.gpioSetMode(clockPin, JPigpio.PI_OUTPUT);
40 | pigpio.gpioSetMode(dataPin, JPigpio.PI_OUTPUT);
41 |
42 | //clear everything out just in case to
43 | //prepare shift register for bit shifting
44 | pigpio.gpioWrite(dataPin, false);
45 | pigpio.gpioWrite(clockPin, false);
46 |
47 | for (int i = 7; i >= 0; i--) {
48 | pigpio.gpioWrite(clockPin, false);
49 |
50 | pinState = ((dataOut & (1 << i)) > 0);
51 |
52 | //Sets the pin to HIGH or LOW depending on pinState
53 | pigpio.gpioWrite(dataPin, pinState);
54 | //register shifts bits on upstroke of clock pin
55 | pigpio.gpioWrite(clockPin, true);
56 | //zero the data pin after shift to prevent bleed through
57 | pigpio.gpioWrite(dataPin, false);
58 | }
59 |
60 | //stop shifting
61 | pigpio.gpioWrite(clockPin, false);
62 | }
63 |
64 | public void run() {
65 |
66 | String host = "pigpiod-host";
67 |
68 | int latchPin = 23; // gpio connected to ST_CP pin of 74HC595
69 | int clockPin = 24; // gpio connected to SH_CP pin of 74HC595
70 | int dataPin = 25; // gpio connected to DS pin of 74HC595
71 |
72 | byte data[] = new byte[] {1,2}; // data to be sent out
73 |
74 | try {
75 | System.out.println("Opening Pigpio.");
76 |
77 | pigpio = new PigpioSocket(host, 8888); // connect to pigpiod via socket interface
78 | // pigpio = new Pigpio(); // connect to pigpiod directly/locally
79 |
80 | pigpio.gpioInitialize();
81 | Utils.addShutdown(pigpio);
82 |
83 | // display data stored in array fields
84 | pigpio.gpioWrite(latchPin, false); // set latch => here comes the data
85 | shiftOut(dataPin, clockPin, data[1]); // send next 8 bits, etc.
86 | shiftOut(dataPin, clockPin, data[0]); // send 8 bits
87 | pigpio.gpioWrite(latchPin, true); // release latch => we are done
88 |
89 | pigpio.gpioTerminate();
90 |
91 | } catch (PigpioException e) {
92 | e.printStackTrace();
93 | }
94 |
95 | System.out.println("Test LEDs Completed.");
96 | }
97 |
98 |
99 | }
100 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_NRF24L01.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.*;
4 | import jpigpio.devices.NRF24L01;
5 |
6 | import java.io.BufferedReader;
7 | import java.io.IOException;
8 | import java.io.InputStreamReader;
9 |
10 | public class Test_NRF24L01 {
11 | private NRF24L01 nrf24l01;
12 | int cePin = 22; //GPIO number, e.g. GPIO 22 = PIN 15
13 | int csnPin = 8; //GPIO number, e.g. GPIO 8 = PIN 24
14 |
15 | public static void main(String args[]) throws PigpioException {
16 | System.out.println("Test_NRF24L01");
17 | Test_NRF24L01 app = new Test_NRF24L01();
18 | app.run();
19 | }
20 |
21 | public void run() throws PigpioException {
22 |
23 | JPigpio pigpio = new PigpioSocket("pigpiod-host", 8888);
24 |
25 | //JPigpio pigpio = new Pigpio();
26 |
27 | pigpio.gpioInitialize();
28 |
29 | nrf24l01 = new NRF24L01(pigpio);
30 |
31 | p("Initializing...");
32 | if (!nrf24l01.init(cePin, csnPin)) {
33 | p("Failed to initialize nRF module. Module not present?");
34 | nrf24l01.terminate();
35 | pigpio.gpioTerminate();
36 | return;
37 | }
38 |
39 | // 5 byte address width
40 | nrf24l01.setAddressWidth(5);
41 |
42 | // set remote device address - to which data will be sent and from which data will be received
43 | byte rAddr[] = { 'R', 'C', 'V', '0', '1' };
44 | nrf24l01.setRADDR(rAddr);
45 |
46 | // set transmitter device address - from which data will be sent
47 | byte tAddr[] = { 'S', 'N', 'D', '0', '1' };
48 | nrf24l01.setTADDR(tAddr, true);
49 |
50 | // following params should be configured the same as the other side
51 | nrf24l01.setPayloadSize(32); // 32 bytes payload
52 | nrf24l01.setChannel(76); // RF channel
53 | nrf24l01.setRetries(5,15); // 5 retries, 15x250ms delay between retries
54 | nrf24l01.setCRCSize(2); // 16 bit CRC
55 | nrf24l01.setDataRate(NRF24L01.RF24_1MBPS); // 1Mbit/s data rate
56 | nrf24l01.setAutoACK(false); // expecting automatic acknowledgements from receiver
57 | nrf24l01.setPALevel(NRF24L01.RF24_PA_LOW); // low power - testing devices won't be so far apart
58 |
59 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
60 |
61 | byte role = 0;
62 | String cmd = "R"; // start with sender role
63 |
64 | byte counter = 0;
65 | byte senderData[] = new byte[] {1,2,3,4};
66 | byte receiverReply[] = new byte[] {99,99,0,0,0,0,0};
67 | byte data32[] = new byte[32];
68 |
69 | nrf24l01.clearRegisterBits(NRF24L01.CONFIG_REGISTER,(byte)(1<> 6);
47 | int accelY = (bytes[3] << 2) | ((bytes[5] & 0x30) >> 4);
48 | int accelZ = (bytes[4] << 2) | ((bytes[5] & 0x0c) >> 2);
49 | int c = (bytes[5] & 0x02) >> 1;
50 | int z = bytes[5] & 0x01;
51 |
52 | // printf("data: %x %x %x %x %x %x\n", bytes[0], bytes[1],
53 | // bytes[2],
54 | // bytes[3], bytes[4], bytes[5]);
55 | System.out.println(String.format("data: joyX=%x joyY=%x accelX=%x accelY=%x accelZ=%x c=%x z=%x", joyX, joyY, accelX, accelY, accelZ, c, z));
56 | } // End of while true
57 | } catch (PigpioException e) {
58 | e.printStackTrace();
59 | }
60 | } // End of run
61 | }
62 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Nunchuck2.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.sensors.WiiNunchuck;
7 |
8 | public class Test_Nunchuck2 {
9 |
10 | public static void main(String[] args) {
11 | Test_Nunchuck2 app = new Test_Nunchuck2();
12 | app.run();
13 | }
14 |
15 | public void run() {
16 | try {
17 | JPigpio pigpio = new Pigpio();
18 | pigpio.gpioInitialize();
19 | WiiNunchuck wiiNunchuck = new WiiNunchuck(pigpio);
20 | wiiNunchuck.initialize();
21 |
22 | while (true) {
23 | wiiNunchuck.readValue();
24 | System.out.println("Nunchuck: " + wiiNunchuck.toString());
25 | } // End of while true
26 | } catch (PigpioException e) {
27 | e.printStackTrace();
28 | }
29 | } // End of run
30 | } // End of Test_Nunchuck2
31 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_NunchuckServos.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.devices.Servo;
7 | import jpigpio.sensors.WiiNunchuck;
8 |
9 | public class Test_NunchuckServos {
10 |
11 | private final int yawServoGpio=17;
12 | private final int pitchServoGpio=18;
13 | private int yawValue = 128;
14 | private int pitchValue = 128;
15 | private int delta = 5;
16 |
17 | public static void main(String[] args) {
18 | Test_NunchuckServos app = new Test_NunchuckServos();
19 | app.run();
20 | }
21 |
22 | public void run() {
23 | try {
24 | JPigpio pigpio = new Pigpio();
25 | pigpio.gpioInitialize();
26 | pigpio.gpioSetMode(yawServoGpio, Pigpio.PI_OFF);
27 | WiiNunchuck wiiNunchuck = new WiiNunchuck(pigpio);
28 | wiiNunchuck.initialize();
29 |
30 | Servo yawServo = new Servo(pigpio, yawServoGpio, 0, 255);
31 | Servo pitchServo = new Servo(pigpio, pitchServoGpio, 0, 255);
32 |
33 | while (true) {
34 | wiiNunchuck.readValue();
35 | System.out.println("Nunchuck: " + wiiNunchuck.toString());
36 | int yawChange = Byte.toUnsignedInt(wiiNunchuck.getJoyX());
37 | int pitchChange = Byte.toUnsignedInt(wiiNunchuck.getJoyY());
38 | //System.out.println("Servo val = " + val);
39 | if (yawChange < 64) {
40 | decreateYaw();
41 | }
42 | if (yawChange > 128 + 64) {
43 | increaseYaw();
44 | }
45 | if (pitchChange < 64) {
46 | decreasePitch();
47 | }
48 | if (pitchChange > 128 + 64) {
49 | increasePitch();
50 | }
51 | yawServo.setValue(yawValue);
52 | pitchServo.setValue(pitchValue);
53 | pigpio.gpioDelay(40000);
54 | } // End of while true
55 | } catch (PigpioException e) {
56 | e.printStackTrace();
57 | }
58 | } // End of run
59 |
60 | private void increaseYaw() {
61 | if (yawValue < 255-delta) {
62 | yawValue+=delta;
63 | }
64 | }
65 |
66 | private void decreateYaw() {
67 | if (yawValue > delta) {
68 | yawValue-=delta;
69 | }
70 | }
71 |
72 | private void decreasePitch() {
73 | if (pitchValue < 255 - delta) {
74 | pitchValue+=delta;
75 | }
76 | }
77 |
78 | private void increasePitch() {
79 | if (pitchValue > delta) {
80 | pitchValue-=delta;
81 | }
82 | }
83 | } // End of Test_Nunchuck2
84 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_PCD8544.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 |
8 | public class Test_PCD8544 {
9 |
10 | private final int PIN_SCE =22;
11 | private final int PIN_RESET = 23;
12 | private final int PIN_DC = 27;
13 | private final int PIN_SDIN = 18;
14 | private final int PIN_SCLK = 17;
15 |
16 | private final boolean LCD_COMMAND = false;
17 | private final boolean LCD_DATA = true;
18 |
19 | private final int LCD_X = 84;
20 | private final int LCD_Y = 48;
21 |
22 | private JPigpio pigpio;
23 |
24 | private final int ASCII[][] = { //
25 | { 0x00, 0x00, 0x00, 0x00, 0x00 } // 20
26 | , { 0x00, 0x00, 0x5f, 0x00, 0x00 } // 21 !
27 | , { 0x00, 0x07, 0x00, 0x07, 0x00 } // 22 "
28 | , { 0x14, 0x7f, 0x14, 0x7f, 0x14 } // 23 #
29 | , { 0x24, 0x2a, 0x7f, 0x2a, 0x12 } // 24 $
30 | , { 0x23, 0x13, 0x08, 0x64, 0x62 } // 25 %
31 | , { 0x36, 0x49, 0x55, 0x22, 0x50 } // 26 &
32 | , { 0x00, 0x05, 0x03, 0x00, 0x00 } // 27 '
33 | , { 0x00, 0x1c, 0x22, 0x41, 0x00 } // 28 (
34 | , { 0x00, 0x41, 0x22, 0x1c, 0x00 } // 29 )
35 | , { 0x14, 0x08, 0x3e, 0x08, 0x14 } // 2a *
36 | , { 0x08, 0x08, 0x3e, 0x08, 0x08 } // 2b +
37 | , { 0x00, 0x50, 0x30, 0x00, 0x00 } // 2c ,
38 | , { 0x08, 0x08, 0x08, 0x08, 0x08 } // 2d -
39 | , { 0x00, 0x60, 0x60, 0x00, 0x00 } // 2e .
40 | , { 0x20, 0x10, 0x08, 0x04, 0x02 } // 2f /
41 | , { 0x3e, 0x51, 0x49, 0x45, 0x3e } // 30 0
42 | , { 0x00, 0x42, 0x7f, 0x40, 0x00 } // 31 1
43 | , { 0x42, 0x61, 0x51, 0x49, 0x46 } // 32 2
44 | , { 0x21, 0x41, 0x45, 0x4b, 0x31 } // 33 3
45 | , { 0x18, 0x14, 0x12, 0x7f, 0x10 } // 34 4
46 | , { 0x27, 0x45, 0x45, 0x45, 0x39 } // 35 5
47 | , { 0x3c, 0x4a, 0x49, 0x49, 0x30 } // 36 6
48 | , { 0x01, 0x71, 0x09, 0x05, 0x03 } // 37 7
49 | , { 0x36, 0x49, 0x49, 0x49, 0x36 } // 38 8
50 | , { 0x06, 0x49, 0x49, 0x29, 0x1e } // 39 9
51 | , { 0x00, 0x36, 0x36, 0x00, 0x00 } // 3a :
52 | , { 0x00, 0x56, 0x36, 0x00, 0x00 } // 3b ;
53 | , { 0x08, 0x14, 0x22, 0x41, 0x00 } // 3c <
54 | , { 0x14, 0x14, 0x14, 0x14, 0x14 } // 3d =
55 | , { 0x00, 0x41, 0x22, 0x14, 0x08 } // 3e >
56 | , { 0x02, 0x01, 0x51, 0x09, 0x06 } // 3f ?
57 | , { 0x32, 0x49, 0x79, 0x41, 0x3e } // 40 @
58 | , { 0x7e, 0x11, 0x11, 0x11, 0x7e } // 41 A
59 | , { 0x7f, 0x49, 0x49, 0x49, 0x36 } // 42 B
60 | , { 0x3e, 0x41, 0x41, 0x41, 0x22 } // 43 C
61 | , { 0x7f, 0x41, 0x41, 0x22, 0x1c } // 44 D
62 | , { 0x7f, 0x49, 0x49, 0x49, 0x41 } // 45 E
63 | , { 0x7f, 0x09, 0x09, 0x09, 0x01 } // 46 F
64 | , { 0x3e, 0x41, 0x49, 0x49, 0x7a } // 47 G
65 | , { 0x7f, 0x08, 0x08, 0x08, 0x7f } // 48 H
66 | , { 0x00, 0x41, 0x7f, 0x41, 0x00 } // 49 I
67 | , { 0x20, 0x40, 0x41, 0x3f, 0x01 } // 4a J
68 | , { 0x7f, 0x08, 0x14, 0x22, 0x41 } // 4b K
69 | , { 0x7f, 0x40, 0x40, 0x40, 0x40 } // 4c L
70 | , { 0x7f, 0x02, 0x0c, 0x02, 0x7f } // 4d M
71 | , { 0x7f, 0x04, 0x08, 0x10, 0x7f } // 4e N
72 | , { 0x3e, 0x41, 0x41, 0x41, 0x3e } // 4f O
73 | , { 0x7f, 0x09, 0x09, 0x09, 0x06 } // 50 P
74 | , { 0x3e, 0x41, 0x51, 0x21, 0x5e } // 51 Q
75 | , { 0x7f, 0x09, 0x19, 0x29, 0x46 } // 52 R
76 | , { 0x46, 0x49, 0x49, 0x49, 0x31 } // 53 S
77 | , { 0x01, 0x01, 0x7f, 0x01, 0x01 } // 54 T
78 | , { 0x3f, 0x40, 0x40, 0x40, 0x3f } // 55 U
79 | , { 0x1f, 0x20, 0x40, 0x20, 0x1f } // 56 V
80 | , { 0x3f, 0x40, 0x38, 0x40, 0x3f } // 57 W
81 | , { 0x63, 0x14, 0x08, 0x14, 0x63 } // 58 X
82 | , { 0x07, 0x08, 0x70, 0x08, 0x07 } // 59 Y
83 | , { 0x61, 0x51, 0x49, 0x45, 0x43 } // 5a Z
84 | , { 0x00, 0x7f, 0x41, 0x41, 0x00 } // 5b [
85 | , { 0x02, 0x04, 0x08, 0x10, 0x20 } // 5c \
86 | , { 0x00, 0x41, 0x41, 0x7f, 0x00 } // 5d ]
87 | , { 0x04, 0x02, 0x01, 0x02, 0x04 } // 5e ^
88 | , { 0x40, 0x40, 0x40, 0x40, 0x40 } // 5f _
89 | , { 0x00, 0x01, 0x02, 0x04, 0x00 } // 60 `
90 | , { 0x20, 0x54, 0x54, 0x54, 0x78 } // 61 a
91 | , { 0x7f, 0x48, 0x44, 0x44, 0x38 } // 62 b
92 | , { 0x38, 0x44, 0x44, 0x44, 0x20 } // 63 c
93 | , { 0x38, 0x44, 0x44, 0x48, 0x7f } // 64 d
94 | , { 0x38, 0x54, 0x54, 0x54, 0x18 } // 65 e
95 | , { 0x08, 0x7e, 0x09, 0x01, 0x02 } // 66 f
96 | , { 0x0c, 0x52, 0x52, 0x52, 0x3e } // 67 g
97 | , { 0x7f, 0x08, 0x04, 0x04, 0x78 } // 68 h
98 | , { 0x00, 0x44, 0x7d, 0x40, 0x00 } // 69 i
99 | , { 0x20, 0x40, 0x44, 0x3d, 0x00 } // 6a j
100 | , { 0x7f, 0x10, 0x28, 0x44, 0x00 } // 6b k
101 | , { 0x00, 0x41, 0x7f, 0x40, 0x00 } // 6c l
102 | , { 0x7c, 0x04, 0x18, 0x04, 0x78 } // 6d m
103 | , { 0x7c, 0x08, 0x04, 0x04, 0x78 } // 6e n
104 | , { 0x38, 0x44, 0x44, 0x44, 0x38 } // 6f o
105 | , { 0x7c, 0x14, 0x14, 0x14, 0x08 } // 70 p
106 | , { 0x08, 0x14, 0x14, 0x18, 0x7c } // 71 q
107 | , { 0x7c, 0x08, 0x04, 0x04, 0x08 } // 72 r
108 | , { 0x48, 0x54, 0x54, 0x54, 0x20 } // 73 s
109 | , { 0x04, 0x3f, 0x44, 0x40, 0x20 } // 74 t
110 | , { 0x3c, 0x40, 0x40, 0x20, 0x7c } // 75 u
111 | , { 0x1c, 0x20, 0x40, 0x20, 0x1c } // 76 v
112 | , { 0x3c, 0x40, 0x30, 0x40, 0x3c } // 77 w
113 | , { 0x44, 0x28, 0x10, 0x28, 0x44 } // 78 x
114 | , { 0x0c, 0x50, 0x50, 0x50, 0x3c } // 79 y
115 | , { 0x44, 0x64, 0x54, 0x4c, 0x44 } // 7a z
116 | , { 0x00, 0x08, 0x36, 0x41, 0x00 } // 7b {
117 | , { 0x00, 0x00, 0x7f, 0x00, 0x00 } // 7c |
118 | , { 0x00, 0x41, 0x36, 0x08, 0x00 } // 7d }
119 | , { 0x10, 0x08, 0x08, 0x10, 0x08 } // 7e
120 | , { 0x78, 0x46, 0x41, 0x46, 0x78 } // 7f
121 | };
122 |
123 | public static void main(String args[]) {
124 | System.out.println("Test_AppName");
125 | Test_PCD8544 app = new Test_PCD8544();
126 | app.run();
127 | }
128 |
129 | public void run() {
130 |
131 | try {
132 | // JPigpio pigpio = new PigpioSocket("raspi", 8888);
133 | pigpio = new Pigpio();
134 | pigpio.gpioInitialize();
135 | Utils.addShutdown(pigpio);
136 | LcdInitialise();
137 | LcdClear();
138 | LcdString("Hello World!");
139 | System.out.println("About to sleep");
140 | Thread.sleep(60 * 1000);
141 | } catch (PigpioException e) {
142 | e.printStackTrace();
143 | } catch (InterruptedException e) {
144 | e.printStackTrace();
145 | }
146 | }
147 |
148 | private void LcdCharacter(char character) throws PigpioException {
149 | LcdWrite(LCD_DATA, 0x00);
150 | for (int index = 0; index < 5; index++) {
151 | LcdWrite(LCD_DATA, ASCII[character - 0x20][index]);
152 | }
153 | LcdWrite(LCD_DATA, 0x00);
154 | }
155 |
156 | private void LcdClear() throws PigpioException {
157 | for (int index = 0; index < LCD_X * LCD_Y / 8; index++) {
158 | LcdWrite(LCD_DATA, 0x00);
159 | }
160 | }
161 |
162 | private void LcdInitialise() throws PigpioException {
163 |
164 | pigpio.gpioSetMode(PIN_SCE, Pigpio.PI_OUTPUT);
165 | pigpio.gpioSetMode(PIN_RESET, Pigpio.PI_OUTPUT);
166 | pigpio.gpioSetMode(PIN_DC, Pigpio.PI_OUTPUT);
167 | pigpio.gpioSetMode(PIN_SDIN, Pigpio.PI_OUTPUT);
168 | pigpio.gpioSetMode(PIN_SCLK, Pigpio.PI_OUTPUT);
169 | pigpio.gpioWrite(PIN_RESET, Pigpio.PI_LOW);
170 | pigpio.gpioWrite(PIN_RESET, Pigpio.PI_HIGH);
171 | // 0x21 = 0010 0001 = Chip active + Horizontal Addressing + Use extended instructions (H=1)
172 | // 0xB1 = 1011 0001 = Set Vop to 1
173 | // 0x04 = 0000 0100 = Set temperature coefficient (0)
174 | // 0x20 = 0010 0000 = Chip active + Horizontal Addressing + Normal instructions (H=0)
175 | // 0x0c = 0000 1100 = Display normal mode (D=1, E=0 -> 10 = Normal mode)
176 | LcdWrite(LCD_COMMAND, 0x21); // LCD Extended Commands.
177 | LcdWrite(LCD_COMMAND, 0xBF); // Set LCD Vop (Contrast).
178 | //LcdWrite(LCD_COMMAND, 0xB1); // Set LCD Vop (Contrast).
179 | LcdWrite(LCD_COMMAND, 0x04); // Set Temp coefficent. //0x04
180 | LcdWrite(LCD_COMMAND, 0x14); // LCD bias mode 1:48. //0x13
181 | LcdWrite(LCD_COMMAND, 0x20); // LCD Basic Commands
182 | LcdWrite(LCD_COMMAND, 0x0C); // LCD in normal mode.
183 |
184 | }
185 |
186 | private void LcdString(String characters) throws PigpioException {
187 | for (int i = 0; i < characters.length(); i++) {
188 | LcdCharacter(characters.charAt(i));
189 | }
190 | } // End of lcdString
191 |
192 | private void LcdWrite(boolean dc, int data) throws PigpioException {
193 | pigpio.gpioWrite(PIN_DC, dc);
194 | pigpio.gpioWrite(PIN_SCE, Pigpio.PI_LOW);
195 | pigpio.gpioShiftOut(PIN_SDIN, PIN_SCLK, Pigpio.PI_MSBFIRST, (byte)data);
196 | pigpio.gpioWrite(PIN_SCE, Pigpio.PI_HIGH);
197 | } // End of lcdWrite
198 | } // End of class
199 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Rf433Rx.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.PigpioSocket;
6 | import jpigpio.Utils;
7 | import jpigpio.packet.*;
8 |
9 |
10 | /**
11 | * Simple example of using 433MHz transmitter (e.g. FS1000A) with Java and Pigpiod.
12 | */
13 | public class Test_Rf433Rx {
14 |
15 | public static void main(String[] args) throws PigpioException, InterruptedException {
16 |
17 | int GPIO_RX = 17; // GPIO for receiving
18 |
19 | // pigpiod host & port
20 | String host = "pigpiod-host";
21 | int port = 8888;
22 |
23 | int waitForData = 20000; // milliseconds to wait for packets
24 | int waitStep = 1000;
25 |
26 | // protocol defines message length, repetition of messages, signal levels etc.
27 | Protocol protocol = new Protocol();
28 |
29 | protocol.setRepeatCount(5);
30 | protocol.setRxRepeatCount(1); // setting this to lower than TX repeat count value means duplicates will be reported
31 | protocol.setDataSize(16);
32 |
33 | // connect to gpigpiod instance
34 | JPigpio pigpio = new PigpioSocket(host,port);
35 | //pigpio.gpioInitialize();
36 |
37 | Rf433rx rf433rx = new Rf433rx(pigpio, GPIO_RX, protocol);
38 |
39 | System.out.println("Waiting "+ waitForData+ " ms for data.");
40 |
41 | int w = waitForData;
42 | while (w > 0){
43 | while (rf433rx.available() > 0)
44 | System.out.println("Received "+ Utils.bytesToHex(rf433rx.get()));
45 | Thread.sleep(waitStep);
46 | w -= waitStep;
47 | System.out.println("Waiting "+ w + " ms more.");
48 | }
49 |
50 | System.out.println("RX Byte Errors = "+ rf433rx.byteErrorCount());
51 | System.out.println("RX Datagram Errors = "+ rf433rx.datagramErrorCount());
52 | System.out.println("Terminating receiver.");
53 | rf433rx.terminate();
54 |
55 | System.out.println("Terminating RPi connection.");
56 | pigpio.gpioTerminate();
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Rf433Tx.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.PigpioException;
4 | import jpigpio.PigpioSocket;
5 | import jpigpio.Utils;
6 | import jpigpio.packet.Protocol;
7 | import jpigpio.packet.Rf433tx;
8 |
9 | import java.util.Arrays;
10 |
11 | // Created by Jozef on 26.04.2016.
12 |
13 | /**
14 | * Simple example of using 433MHz transmitter (e.g. XD-RF-5V) with Java and Pigpiod.
15 | */
16 | public class Test_Rf433Tx {
17 |
18 | // GPIO pin for transmitting
19 | static int GPIO_TX = 27;
20 |
21 | // pigpiod host & port
22 | static String host = "pigpiod-host";
23 | static int port = 8888;
24 |
25 | // protocol defines message length, repetition of messages, signal levels etc.
26 | static Protocol protocol = new Protocol();
27 |
28 | static PigpioSocket pi;
29 | static Rf433tx rf433tx;
30 |
31 | public static void main(String[] args) throws PigpioException, InterruptedException {
32 |
33 | // test message
34 | byte[] TX_TEST_MSG = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x11, 0x12, 0x13, 0x14, 0x15};
35 | byte[] TX_TEST_MSG2 = new byte[] {(byte)0xA1, (byte)0xA2, (byte)0xA3, (byte)0xA4, (byte)0xA5, (byte)0xA6, (byte)0xA7,
36 | (byte)0xF1, (byte)0xF2, (byte)0xF3, (byte)0xF4, (byte)0xF5, (byte)0xF6, (byte)0xF7, (byte)0xF8, (byte)0xF7};
37 |
38 | int waitStep = 2000;
39 | int w = 0;
40 |
41 | protocol.setRepeatCount(15);
42 | protocol.setDataSize(16);
43 |
44 | // gpigpiod instance
45 | pi = new PigpioSocket(host,port);
46 | pi.gpioInitialize();
47 |
48 | rf433tx = new Rf433tx(pi, GPIO_TX, protocol);
49 |
50 | System.out.println("Transmit test message sending "+ Utils.bytesToHex(TX_TEST_MSG) + " " + protocol.DGRM_REPEAT_TX + " times");
51 | rf433tx.put(TX_TEST_MSG);
52 |
53 | System.out.println("Transmit test message sending "+ Utils.bytesToHex(TX_TEST_MSG2) + " " + protocol.DGRM_REPEAT_TX + " times");
54 | rf433tx.put(TX_TEST_MSG2);
55 |
56 | while (!rf433tx.ready()) {
57 | System.out.println("Waiting for transmitter to finish its job. "+w+"ms");
58 | Thread.sleep(waitStep);
59 | w += waitStep;
60 | }
61 |
62 | System.out.println("Terminating transmitter.");
63 | rf433tx.terminate();
64 |
65 | System.out.println("Terminating RPi connection.");
66 | pi.gpioTerminate();
67 |
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_SP0256.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.GPIO;
4 | import jpigpio.JPigpio;
5 | import jpigpio.Pigpio;
6 | import jpigpio.PigpioException;
7 | import jpigpio.Utils;
8 | import jpigpio.devices.SP0256;
9 |
10 | public class Test_SP0256 {
11 | private GPIO aldGpio;
12 | private GPIO lrqGpio;
13 | private GPIO a1Gpio;
14 | private GPIO a2Gpio;
15 | private GPIO a3Gpio;
16 | private GPIO a4Gpio;
17 | private GPIO a5Gpio;
18 | private GPIO a6Gpio;
19 |
20 | public static void main(String args[]) {
21 | System.out.println("Test_SP0256");
22 | Test_SP0256 app = new Test_SP0256();
23 | app.run();
24 | }
25 |
26 | public void run() {
27 |
28 | try {
29 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
30 | JPigpio pigpio = new Pigpio();
31 | pigpio.gpioInitialize();
32 | Utils.addShutdown(pigpio);
33 |
34 | a1Gpio = new GPIO(pigpio, JPigpio.PI_GPIO17, JPigpio.PI_OUTPUT);
35 | a2Gpio = new GPIO(pigpio, JPigpio.PI_GPIO27, JPigpio.PI_OUTPUT);
36 | a3Gpio = new GPIO(pigpio, JPigpio.PI_GPIO22, JPigpio.PI_OUTPUT);
37 | a4Gpio = new GPIO(pigpio, JPigpio.PI_GPIO5, JPigpio.PI_OUTPUT);
38 | a5Gpio = new GPIO(pigpio, JPigpio.PI_GPIO6, JPigpio.PI_OUTPUT);
39 | a6Gpio = new GPIO(pigpio, JPigpio.PI_GPIO13, JPigpio.PI_OUTPUT);
40 | aldGpio = new GPIO(pigpio, JPigpio.PI_GPIO18, JPigpio.PI_OUTPUT);
41 | lrqGpio = new GPIO(pigpio, JPigpio.PI_GPIO23, JPigpio.PI_INPUT);
42 | SP0256 sp0256 = new SP0256(pigpio, aldGpio, lrqGpio, a1Gpio, a2Gpio, a3Gpio, a4Gpio, a5Gpio, a6Gpio);
43 | for (int i=0; i<64; i++) {
44 | sp0256.sayAlophone((byte)i);
45 | }
46 | pigpio.gpioTerminate();
47 |
48 | } catch (PigpioException e) {
49 | e.printStackTrace();
50 | }
51 | }
52 | } // End of class
53 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Serial.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.PigpioSocket;
6 | import jpigpio.Utils;
7 |
8 | /**
9 | * Simple test class to echo input to output.
10 | * To allow automated RX-TX testing, then if no input is received, then test sends test message
11 | *
12 | * Created by Jozef on 12.06.2016.
13 | */
14 |
15 | public class Test_Serial {
16 | public static void main(String args[]) {
17 | System.out.println("Test_Serial");
18 | Test_Serial app = new Test_Serial();
19 | app.run();
20 | }
21 |
22 | public void run() {
23 |
24 | String host = "pigpiod-host";
25 | String serialPort = "/dev/ttyAMA0";
26 | int baudRate = 9600;
27 |
28 | int handle;
29 | int avail = 0;
30 | byte[] data;
31 | long startTime = System.currentTimeMillis();
32 | int counter = 0;
33 | int testC = 0;
34 | String rcvd;
35 |
36 | try {
37 | System.out.println("Opening Pigpio.");
38 | JPigpio pigpio = new PigpioSocket(host, 8888);
39 | //JPigpio pigpio = new Pigpio();
40 |
41 | pigpio.gpioInitialize();
42 | Utils.addShutdown(pigpio);
43 |
44 | System.out.println("Opening serial port "+serialPort);
45 | handle = pigpio.serialOpen(serialPort, baudRate, 0);
46 |
47 | System.out.println("Going to echo all input for the next 20 seconds");
48 | while (System.currentTimeMillis() - startTime < 20000){
49 |
50 | Thread.sleep(500);
51 | avail = pigpio.serialDataAvailable(handle);
52 | if (avail > 0){
53 | data = pigpio.serialRead(handle, avail);
54 | rcvd = new String(data);
55 | System.out.println("RECEIVED: "+rcvd );
56 |
57 | // do not echo input starting with ECHO to prevent feedback loop :-)
58 | if (rcvd.indexOf("ECHO") != 0) {
59 | pigpio.serialWrite(handle, "ECHO:".getBytes());
60 | pigpio.serialWrite(handle, data);
61 | System.out.println("ECHO containing same data sent back");
62 | }
63 |
64 | counter = 0;
65 | } else if (++counter > 5) {
66 | pigpio.serialWrite(handle, ("TEST "+(++testC)).getBytes());
67 | }
68 | }
69 |
70 | pigpio.serialClose(handle);
71 | pigpio.gpioTerminate();
72 |
73 | } catch (PigpioException|InterruptedException e) {
74 | e.printStackTrace();
75 | }
76 |
77 | System.out.println("Test Serial Completed.");
78 | }
79 | }
80 |
81 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_ServoSweep.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.PigpioException;
5 | import jpigpio.PigpioSocket;
6 |
7 | public class Test_ServoSweep {
8 | private final int servoPin = 17;
9 | private final int min = 500;
10 | private final int max = 2500;
11 |
12 | public static void main(String args[]) {
13 | System.out.println("Starting Test_ServoSweep");
14 | Test_ServoSweep app = new Test_ServoSweep();
15 | app.run();
16 | }
17 |
18 | public void run() {
19 |
20 | try {
21 | JPigpio pigpio = new PigpioSocket("localhost", 8888);
22 | int servoSweepDuration = 500; // Time in ms
23 | int direction = 0; // 0 = up, 1 = down
24 | while (true) {
25 | long startTime = pigpio.gpioTick();
26 | int sweepTime = servoSweepDuration * 1000 / 2;
27 | long delta = pigpio.gpioTick() - startTime;
28 | while (delta < sweepTime) {
29 | // Position is going to be between 0 and 1 and represents
30 | // how far along the sweep we are.
31 | double position = (double) delta / sweepTime * (max - min);
32 |
33 | int timeToWriteHighUSecs;
34 | if (direction == 0) {
35 | timeToWriteHighUSecs = (int) (min + position);
36 | } else {
37 | timeToWriteHighUSecs = (int) (max - position);
38 | }
39 |
40 | System.out.println(String.format("Setting pulse width %d, delta=%d, startTime=%d\n", timeToWriteHighUSecs, delta, startTime));
41 | pigpio.gpioServo(servoPin, timeToWriteHighUSecs);
42 | System.out.println("A");
43 | pigpio.gpioDelay(30);
44 | System.out.println("B");
45 |
46 | long x = pigpio.gpioTick();
47 | System.out.println("x = " + x);
48 | delta = pigpio.gpioTick() - startTime;
49 | } // End of a sweep in one direction
50 |
51 | // We have ended a sweep, let us now go in the other direction!
52 | System.out.println("End sweep");
53 | // Switch direction
54 | if (direction == 0) {
55 | direction = 1;
56 | } else {
57 | direction = 0;
58 | }
59 | } // End of while true
60 |
61 | } catch (PigpioException e) {
62 | e.printStackTrace();
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_SocketListen.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.*;
4 |
5 | /**
6 | * Simple example showing how to process GPIO alerts/notifications via socket interface
7 | *
8 | * Created by Jozef on 20.04.2016.
9 | */
10 | public class Test_SocketListen {
11 |
12 | /**
13 | * This would be your class implementing alert method processing notifications
14 | * received from pigpiod
15 | */
16 | class MyListener extends GPIOListener {
17 |
18 | public int count = 0;
19 |
20 | MyListener(int userGpio, int edge){
21 | super(userGpio, edge);
22 | }
23 |
24 | @Override
25 | public void alert(int gpio, int level, long tick){
26 | this.count++;
27 | System.out.println("MyListener #"+count+" GPIO="+gpio);
28 | }
29 |
30 | }
31 |
32 | public static void main(String args[]) {
33 | System.out.println("Test_SocketListen");
34 | Test_SocketListen app = new Test_SocketListen();
35 | app.run();
36 | }
37 |
38 | public void run() {
39 |
40 | String host = "pigpiod-host";
41 |
42 | int gpio1 = 23;
43 | int gpio2 = 24;
44 | int gpio3 = 25;
45 |
46 | long startTime = System.currentTimeMillis();
47 |
48 | try {
49 | JPigpio pigpio = new PigpioSocket(host, 8888);
50 | pigpio.gpioInitialize();
51 |
52 | // receive notifications for gpio
53 | pigpio.addCallback(new MyListener(gpio1,JPigpio.PI_RISING_EDGE) );
54 | System.out.println("Listening for changes on GPIO "+gpio1);
55 |
56 | // receive notifications for gpio
57 | pigpio.addCallback(new MyListener(gpio2,JPigpio.PI_FALLING_EDGE) );
58 | System.out.println("Listening for changes on GPIO "+gpio2);
59 |
60 | // alternative approach using lambda expression
61 | pigpio.gpioSetAlertFunc(gpio3, (int gpio, int level, long tick) ->
62 | {
63 | System.out.println("ALERT Received: gpio="+gpio+" level="+Integer.toBinaryString(level)+" tick="+tick);
64 | });
65 |
66 | System.out.println("Waiting 20s for incoming notifications");
67 | while(System.currentTimeMillis() - startTime < 20000) {
68 |
69 | Thread.sleep(100);
70 | }
71 |
72 | System.out.println("Finished.");
73 |
74 | pigpio.gpioTerminate();
75 |
76 | } catch (PigpioException|InterruptedException e) {
77 | e.printStackTrace();
78 | }
79 |
80 | } // End of run
81 | }
82 |
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Stepper.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 | import jpigpio.devices.Stepper;
8 |
9 | public class Test_Stepper {
10 |
11 | private int blueGpio=JPigpio.PI_GPIO5; // IN1
12 | private int pinkGpio=JPigpio.PI_GPIO6; // IN2
13 | private int yellowGpio=JPigpio.PI_GPIO13; // IN3
14 | private int orangeGpio=JPigpio.PI_GPIO19; // IN4
15 | private int delay = 2000; // uSecs
16 |
17 | public static void main(String args[]) {
18 | System.out.println("Test_Stepper");
19 | Test_Stepper app = new Test_Stepper();
20 | app.run();
21 | }
22 |
23 | public void run() {
24 | try {
25 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
26 | JPigpio pigpio = new Pigpio();
27 | pigpio.gpioInitialize();
28 | Utils.addShutdown(pigpio);
29 | pigpio.gpioSetMode(blueGpio, JPigpio.PI_OUTPUT);
30 | pigpio.gpioSetMode(pinkGpio, JPigpio.PI_OUTPUT);
31 | pigpio.gpioSetMode(yellowGpio, JPigpio.PI_OUTPUT);
32 | pigpio.gpioSetMode(orangeGpio, JPigpio.PI_OUTPUT);
33 | Stepper stepper = new Stepper(pigpio, blueGpio, pinkGpio, yellowGpio, orangeGpio);
34 | System.out.println("About to start stepping ...");
35 | while(true) {
36 | stepper.forward();
37 | pigpio.gpioDelay(delay);
38 | }
39 |
40 | } catch (PigpioException e) {
41 | e.printStackTrace();
42 | }
43 | } // End of run
44 | } // End of class
45 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_TM1638.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.GPIO;
4 | import jpigpio.JPigpio;
5 | import jpigpio.Pigpio;
6 | import jpigpio.PigpioException;
7 | import jpigpio.Utils;
8 | import jpigpio.devices.TM1638;
9 |
10 | public class Test_TM1638 {
11 | private int stbPin = 5;
12 | private int clkPin = 6;
13 | private int dioPin = 13;
14 | private GPIO stbGpio, clkGpio, dioGpio;
15 | public static void main(String args[]) {
16 | System.out.println("Test_TM1638");
17 | Test_TM1638 app = new Test_TM1638();
18 | app.run();
19 | }
20 |
21 | public void run() {
22 |
23 | try {
24 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
25 | JPigpio pigpio = new Pigpio();
26 | pigpio.gpioInitialize();
27 | Utils.addShutdown(pigpio);
28 | stbGpio = new GPIO(pigpio, stbPin, JPigpio.PI_OUTPUT);
29 | clkGpio = new GPIO(pigpio, clkPin, JPigpio.PI_OUTPUT);
30 | dioGpio = new GPIO(pigpio, dioPin, JPigpio.PI_OUTPUT);
31 |
32 | TM1638 tm1638 = new TM1638(pigpio, stbGpio, clkGpio, dioGpio);
33 | tm1638.writeNumber(0);
34 |
35 | } catch (PigpioException e) {
36 | e.printStackTrace();
37 | }
38 | }
39 | } // End of class
40 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Template.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 |
8 | public class Test_Template {
9 | public static void main(String args[]) {
10 | System.out.println("Test_AppName");
11 | Test_Template app = new Test_Template();
12 | app.run();
13 | }
14 |
15 | public void run() {
16 |
17 | try {
18 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
19 | JPigpio pigpio = new Pigpio();
20 | pigpio.gpioInitialize();
21 | Utils.addShutdown(pigpio);
22 |
23 | } catch (PigpioException e) {
24 | e.printStackTrace();
25 | }
26 | }
27 | } // End of class
28 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_Timings.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 |
7 | public class Test_Timings {
8 | public static void main(String args[]) {
9 | System.out.println("Test_Timings");
10 | Test_Timings app = new Test_Timings();
11 | app.run();
12 | }
13 |
14 | public void run() {
15 |
16 | try {
17 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
18 | JPigpio pigpio = new Pigpio();
19 | pigpio.gpioInitialize();
20 | long last = pigpio.gpioTick();
21 | while (true) {
22 | long tick = pigpio.gpioTick();
23 | System.out.println(String.format("Tick: %d, delta: %d", tick, tick-last));
24 | last = tick;
25 | }
26 | } catch (PigpioException e) {
27 | e.printStackTrace();
28 | }
29 | }
30 | } // End of class
31 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_VS1053.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import java.io.File;
4 |
5 | import jpigpio.JPigpio;
6 | import jpigpio.Pigpio;
7 | import jpigpio.PigpioException;
8 | import jpigpio.Utils;
9 | import jpigpio.devices.VS1053;
10 |
11 | public class Test_VS1053 {
12 | private int XRESET = JPigpio.PI_GPIO20;
13 | private int DREQ = JPigpio.PI_GPIO21;
14 |
15 | private VS1053 vs1053;
16 |
17 | public static void main(String args[]) {
18 | System.out.println("Test_VS1053");
19 | Test_VS1053 app = new Test_VS1053();
20 | app.run();
21 | }
22 |
23 | public void run() {
24 |
25 | try {
26 | //JPigpio pigpio = new PigpioSocket("raspi", 8888);
27 | JPigpio pigpio = new Pigpio();
28 | pigpio.gpioInitialize();
29 | // pigpio.gpioSetMode(XCS, JPigpio.PI_OUTPUT);
30 | // pigpio.gpioSetMode(XDCS, JPigpio.PI_OUTPUT);
31 | pigpio.gpioSetMode(DREQ, JPigpio.PI_INPUT);
32 | pigpio.gpioSetMode(XRESET, JPigpio.PI_OUTPUT);
33 |
34 | // The XCS and XDCS are used to enable the SPI modes of the device. When XCS is low, the device
35 | // will accept control commands. When XDCS is low, the device will accept data input for playing.
36 | // It isn't known what happens if both should be low so don't try it.
37 | // pigpio.gpioWrite(XDCS, true);
38 | // pigpio.gpioWrite(XCS, false);
39 | pigpio.gpioWrite(XRESET, true);
40 |
41 | Utils.addShutdown(pigpio);
42 |
43 | vs1053 = new VS1053(pigpio, DREQ);
44 | pigpio.gpioWrite(XRESET, false);
45 | pigpio.gpioDelay(5000);
46 | pigpio.gpioWrite(XRESET, true);
47 | vs1053.disableMidi();
48 | vs1053.setClockF(0x8800);
49 | //dump();
50 |
51 | //vs1053.softReset();
52 | vs1053.setVolume(0x30);
53 | // pigpio.gpioWrite(XRESET, false);
54 | // pigpio.gpioDelay(5000);
55 | // pigpio.gpioWrite(XRESET, true);
56 | //vs1053.setVolume(0x00);
57 | //vs1053.setLine(false);
58 |
59 | // vs1053.setTestMode(true);
60 | vs1053.dump();
61 | // pigpio.gpioDelay(5000);
62 | // System.out.println("Sine test starting ...");
63 | // vs1053.startSineTest();
64 | // pigpio.gpioDelay(30, JPigpio.PI_SECONDS);
65 | // System.out.println("Tests ending ...");
66 | //
67 | // //vs1053.memoryTest();
68 | // vs1053.setTestMode(false);
69 | //vs1053.playFile(new File("/mnt/share/Data/Audio/sample1.wav"));
70 | //vs1053.playFile(new File("/mnt/share/Data/Audio/sample1-96k.ogg"));
71 | vs1053.playFile(new File("/mnt/share/Data/Audio/sample.mp3"));
72 | //pigpio.gpioDelay(5000);
73 | pigpio.gpioTerminate();
74 |
75 | } catch (PigpioException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 |
80 | // public void dump() throws PigpioException {
81 | // int mode = vs1053.getMode();
82 | // System.out.println("Mode: " + Utils.int16ToBinary(mode));
83 | // System.out.println("Mode: " + vs1053.format(mode, "MODE"));
84 | // System.out.println("Status: " + Utils.int16ToBinary(vs1053.getStatus()));
85 | //
86 | // int audata = vs1053.getAudata();
87 | // System.out.println("Audata: " + Utils.int16ToBinary(audata));
88 | // System.out.println("Audata: " + vs1053.format(audata, "AUDATA"));
89 | // System.out.println("Volume: " + Utils.int16ToBinary(vs1053.getVolume()));
90 | // System.out.println("Bass: " + Utils.int16ToBinary(vs1053.getBass()));
91 | // System.out.println("---");
92 | // }
93 | } // End of class
94 | // End of file
--------------------------------------------------------------------------------
/JPigpio/src/tests/Test_gpioSetAlertFunc.java:
--------------------------------------------------------------------------------
1 | package tests;
2 |
3 | import jpigpio.JPigpio;
4 | import jpigpio.Pigpio;
5 | import jpigpio.PigpioException;
6 | import jpigpio.Utils;
7 |
8 | /**
9 | * Test the gpioSetAlertFunc capability.
10 | * @author Neil Kolban
11 | *
12 | */
13 | public class Test_gpioSetAlertFunc {
14 |
15 | /**
16 | * The pin to watch for changes in state.
17 | */
18 | private final int TESTPIN = 18;
19 |
20 | public static void main(String args[]) {
21 | System.out.println("Test_gpioSetAlertFunc");
22 | Test_gpioSetAlertFunc app = new Test_gpioSetAlertFunc();
23 | app.run();
24 | }
25 |
26 | /**
27 | * Main entry point to the test in the context of an object instance.
28 | */
29 | public void run() {
30 | try {
31 | // Initialize the environment
32 | JPigpio pigpio = new Pigpio();
33 | pigpio.gpioInitialize();
34 | Utils.addShutdown(pigpio);
35 |
36 | // Set the test pin to input
37 | pigpio.gpioSetMode(TESTPIN, JPigpio.PI_INPUT);
38 |
39 | // Define a callback function
40 | pigpio.gpioSetAlertFunc(TESTPIN, (gpio, level, tick) -> {
41 | System.out.println(String.format("NotificationListener in Java: We received an alert on: %d with %d at %d", gpio, level, tick));
42 | });
43 |
44 | System.out.println(String.format("Watching for changes on pin: %d", TESTPIN));
45 |
46 | // Sleep for a minute
47 | Thread.sleep(60 * 1000);
48 |
49 | // Cleanup
50 | pigpio.gpioTerminate();
51 |
52 | } catch (PigpioException e) {
53 | e.printStackTrace();
54 | } catch (InterruptedException e) {
55 | e.printStackTrace();
56 | }
57 | } // End of run
58 | } // End of class
59 | // End of file
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_Blink.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_Blink
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_DualServoSweep.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_DualServoSweep
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_GY_271.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_GY_271
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_HC_SR04.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_HC_SR04
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_LCD.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | sudo java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_LCD
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_NRF24L01_Client.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_NRF24L01_Client
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_Nunchuck.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_Nunchuck
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_Nunchuck2.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_Nunchuck2
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_NunchuckServos.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_NunchuckServos
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_PCD8544.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_PCD8544
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_SP0256.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | sudo java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_SP0256
4 |
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_Stepper.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | sudo java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_Stepper
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_TM1638.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | sudo java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_TM1638
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_Timings.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_Timings
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_VS1053.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | sudo java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_VS1053
--------------------------------------------------------------------------------
/JPigpio/tests/run_Test_gpioSetAlertFunc.sh:
--------------------------------------------------------------------------------
1 | sudo rm -rf /var/run/pigpio.pid
2 | export LIBPATH="/mnt/share/opt/lib"
3 | java -Djava.library.path=$LIBPATH -cp ../bin tests/Test_gpioSetAlertFunc
--------------------------------------------------------------------------------
/JPigpioC/.cproject:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/JPigpioC/.gitignore:
--------------------------------------------------------------------------------
1 | # exclude object files
2 | *.o
3 | # exclude libraries
4 | *.so
--------------------------------------------------------------------------------
/JPigpioC/JPigpioC.c:
--------------------------------------------------------------------------------
1 | /*
2 | * CommonPigpio.c
3 | *
4 | * Created on: Apr 18, 2015
5 | * Author: kolban
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include "jpigpio_Pigpio.h"
14 | #include "JPigpioC.h"
15 |
16 | #define DEBUG 1
17 |
18 | jthrowable createPigpioException(JNIEnv *env, int rc);
19 | void alertCallback(int gpio, int level, unsigned int tick);
20 | unsigned invert(unsigned level);
21 |
22 | JavaVM *g_vm;
23 | int debug = 0;
24 |
25 | #ifdef DEBUG
26 | int lastTime;
27 | extern void logDebug(char *text);
28 | char debugText[2000];
29 | #endif
30 |
31 | // Define an array of callback functions
32 | jobject alertFunctions[MAXPINS];
33 |
34 | /*
35 | * Class: jpigpio_Pigpio
36 | * Method: gpioInitialize
37 | * Signature: ()V
38 | */
39 | void JNICALL Java_jpigpio_Pigpio_gpioInitialize(JNIEnv *env, jobject obj) {
40 | // Zero out any callbacks
41 |
42 | int i;
43 | for (i = 0; i < MAXPINS; i++) {
44 | alertFunctions[i] = NULL;
45 | }
46 | int rc = gpioInitialise();
47 | if (rc < 0) {
48 | (*env)->Throw(env, createPigpioException(env, rc));
49 | }
50 | (*env)->GetJavaVM(env, &g_vm);
51 | #ifdef DEBUG
52 | lastTime = gpioTick();
53 | #endif
54 | } // End of Java_jpigpio_Pigpio_gpioInitialize
55 |
56 | /*
57 | * Class: jpigpio_Pigpio
58 | * Method: gpioTerminate
59 | * Signature: ()V
60 | */
61 | void JNICALL Java_jpigpio_Pigpio_gpioTerminate(JNIEnv *env, jobject obj) {
62 | return gpioTerminate();
63 | }
64 |
65 | /*
66 | * Class: jpigpio_Pigpio
67 | * Method: gpioSetMode
68 | * Signature: (II)V
69 | */
70 | void JNICALL Java_jpigpio_Pigpio_gpioSetMode(JNIEnv *env, jobject obj, jint gpio, jint mode) {
71 | int rc = gpioSetMode(gpio, mode);
72 | if (rc < 0) {
73 | (*env)->Throw(env, createPigpioException(env, rc));
74 | return;
75 | }
76 | } // End of Java_jpigpio_Pigpio_gpioSetMode
77 |
78 | /*
79 | * Class: jpigpio_Pigpio
80 | * Method: gpioGetMode
81 | * Signature: (I)I
82 | */
83 | jint JNICALL Java_jpigpio_Pigpio_gpioGetMode(JNIEnv *env, jobject obj, jint gpio) {
84 | return gpioGetMode(gpio);
85 | } // End of Java_jpigpio_Pigpio_gpioGetMode
86 |
87 | /*
88 | * Class: jpigpio_Pigpio
89 | * Method: gpioSetPullUpDown
90 | * Signature: (II)V
91 | */
92 | void JNICALL Java_jpigpio_Pigpio_gpioSetPullUpDown(JNIEnv *env, jobject obj, jint pin, jint pud) {
93 | int rc = gpioSetPullUpDown(pin, pud);
94 | if (rc < 0) {
95 | (*env)->Throw(env, createPigpioException(env, rc));
96 | return;
97 | }
98 | } // End of Java_jpigpio_Pigpio_gpioSetPullUpDown
99 |
100 | /*
101 | * Class: jpigpio_Pigpio
102 | * Method: gpioRead
103 | * Signature: (I)Z
104 | */
105 | jboolean JNICALL Java_jpigpio_Pigpio_gpioRead(JNIEnv *env, jobject obj, jint gpio) {
106 | return gpioRead(gpio);
107 | } // End of Java_jpigpio_Pigpio_gpioRead
108 |
109 | /*
110 | * Class: jpigpio_Pigpio
111 | * Method: gpioWrite
112 | * Signature: (IZ)V
113 | */
114 | void JNICALL Java_jpigpio_Pigpio_gpioWrite(JNIEnv *env, jobject obj, jint gpio, jboolean value) {
115 | int rc = gpioWrite(gpio, value);
116 | #ifdef DEBUG
117 | if (debug) {
118 | sprintf(debugText, "gpioWrite: gpio: %d, value: 0x%x", gpio, value);
119 | logDebug(debugText);
120 | }
121 | #endif
122 | if (rc < 0) {
123 | (*env)->Throw(env, createPigpioException(env, rc));
124 | return;
125 | }
126 | } // End of Java_jpigpio_Pigpio_gpioWrite
127 |
128 | /*
129 | * Class: jpigpio_Pigpio
130 | * Method: gpioServo
131 | * Signature: (II)V
132 | */
133 | void JNICALL Java_jpigpio_Pigpio_gpioServo(JNIEnv *env, jobject obj, jint gpio, jint pulseWidth) {
134 | int rc = gpioServo(gpio, pulseWidth);
135 | if (rc < 0) {
136 | (*env)->Throw(env, createPigpioException(env, rc));
137 | return;
138 | }
139 | } // End of Java_jpigpio_Pigpio_gpioServo
140 |
141 | /*
142 | * Class: jpigpio_Pigpio
143 | * Method: gpioTrigger
144 | * Signature: (IJZ)V
145 | */
146 | void JNICALL Java_jpigpio_Pigpio_gpioTrigger(JNIEnv *env, jobject obj, jint gpio, jlong pulseLen, jboolean level) {
147 | int rc = gpioTrigger(gpio, pulseLen, level);
148 | if (rc < 0) {
149 | (*env)->Throw(env, createPigpioException(env, rc));
150 | return;
151 | }
152 | } // End of Java_jpigpio_Pigpio_gpioTrigger
153 |
154 | /*
155 | * Class: jpigpio_Pigpio
156 | * Method: i2cOpen
157 | * Signature: (II)I
158 | */
159 | jint JNICALL Java_jpigpio_Pigpio_i2cOpen(JNIEnv *env, jobject obj, jint i2cBus, jint i2cAddr) {
160 | int rc = i2cOpen(i2cBus, i2cAddr, 0);
161 | if (rc < 0) {
162 | (*env)->Throw(env, createPigpioException(env, rc));
163 | }
164 | return rc;
165 | } // End of Java_jpigpio_Pigpio_i2cOpen
166 |
167 | /*
168 | * Class: jpigpio_Pigpio
169 | * Method: i2cClose
170 | * Signature: (I)V
171 | */
172 | void JNICALL Java_jpigpio_Pigpio_i2cClose(JNIEnv *env, jobject obj, jint handle) {
173 | int rc = i2cClose(handle);
174 | if (rc < 0) {
175 | (*env)->Throw(env, createPigpioException(env, rc));
176 | return;
177 | }
178 | } // End of Java_jpigpio_Pigpio_i2cClose
179 |
180 | /*
181 | * Class: jpigpio_Pigpio
182 | * Method: i2cReadDevice
183 | * Signature: (I[B)I
184 | */
185 | jint JNICALL Java_jpigpio_Pigpio_i2cReadDevice(JNIEnv *env, jobject obj, jint handle, jbyteArray array) {
186 |
187 | unsigned count = (*env)->GetArrayLength(env, array);
188 | jbyte *buf = malloc(count);
189 |
190 | (*env)->GetByteArrayRegion(env, array, 0, count, buf);
191 |
192 | int rc = i2cReadDevice(handle, (char *) buf, count);
193 |
194 | if (rc < 0) {
195 | (*env)->Throw(env, createPigpioException(env, rc));
196 | free(buf);
197 | return rc;
198 | }
199 | (*env)->SetByteArrayRegion(env, array, 0, count, buf);
200 | free(buf);
201 | return rc;
202 | } // End of Java_jpigpio_Pigpio_i2cReadDevice
203 |
204 | /*
205 | * Class: jpigpio_Pigpio
206 | * Method: i2cWriteDevice
207 | * Signature: (I[B)V
208 | */
209 | void JNICALL Java_jpigpio_Pigpio_i2cWriteDevice(JNIEnv *env, jobject obj, jint handle, jbyteArray txDataArray) {
210 | unsigned count = (*env)->GetArrayLength(env, txDataArray);
211 | char *buf = malloc(count);
212 |
213 | (*env)->GetByteArrayRegion(env, txDataArray, 0, count, (jbyte *) buf);
214 |
215 | int rc = i2cWriteDevice(handle, buf, count);
216 |
217 | free(buf);
218 | if (rc < 0) {
219 | (*env)->Throw(env, createPigpioException(env, rc));
220 | return;
221 | }
222 | } // End of Java_jpigpio_Pigpio_i2cWriteDevice
223 |
224 | /*
225 | * Class: jpigpio_Pigpio
226 | * Method: gpioDelay
227 | * Signature: (J)V
228 | */
229 | void JNICALL Java_jpigpio_Pigpio_gpioDelay(JNIEnv *env, jobject obj, jlong delay) {
230 | gpioDelay((unsigned int) delay);
231 | } // End of Java_jpigpio_Pigpio_gpioDelay
232 |
233 | /*
234 | * Class: jpigpio_Pigpio
235 | * Method: gpioTick
236 | * Signature: ()J
237 | */
238 | jlong JNICALL Java_jpigpio_Pigpio_gpioTick(JNIEnv *env, jobject obj) {
239 | return gpioTick();
240 | } // End of Java_jpigpio_Pigpio_gpioTick
241 |
242 | /*
243 | * Class: jpigpio_Pigpio
244 | * Method: gpioSetAlertFunc
245 | * Signature: (ILjpigpio/Alert;)V
246 | */
247 | void JNICALL Java_jpigpio_Pigpio_gpioSetAlertFunc(JNIEnv *env, jobject obj, jint gpio, jobject alert) {
248 | // Register the generic callback
249 | int rc = gpioSetAlertFunc(gpio, alertCallback);
250 | // Handle an error registering the alert function
251 | if (rc < 0) {
252 | (*env)->Throw(env, createPigpioException(env, rc));
253 | return;
254 | }
255 | if (alertFunctions[gpio] != NULL) {
256 | (*env)->DeleteGlobalRef(env, alertFunctions[gpio]);
257 | }
258 | alertFunctions[gpio] = (*env)->NewGlobalRef(env, alert);
259 | } // End of Java_jpigpio_Pigpio_gpioSetAlertFunc
260 |
261 | /*
262 | * Class: jpigpio_Pigpio
263 | * Method: spiOpen
264 | * Signature: (III)I
265 | */
266 | jint JNICALL Java_jpigpio_Pigpio_spiOpen(JNIEnv *env, jobject obj, jint channel, jint baudRate, jint flags) {
267 |
268 | int rc = spiOpen(channel, baudRate, flags);
269 | if (rc < 0) {
270 | (*env)->Throw(env, createPigpioException(env, rc));
271 | }
272 | #ifdef DEBUG
273 | if (debug) {
274 | sprintf(debugText, "spiOpen: channel=%d, baudRate=%d, flags=%x - handle=%d", channel, baudRate, flags, rc);
275 | logDebug(debugText);
276 | }
277 | #endif
278 | return rc;
279 | } // End of Java_jpigpio_Pigpio_spiOpen
280 |
281 | /*
282 | * Class: jpigpio_Pigpio
283 | * Method: spiClose
284 | * Signature: (I)V
285 | */
286 | void JNICALL Java_jpigpio_Pigpio_spiClose(JNIEnv *env, jobject obj, jint handle) {
287 | int rc = spiClose(handle);
288 | if (rc < 0) {
289 | (*env)->Throw(env, createPigpioException(env, rc));
290 | }
291 | } // End of Java_jpigpio_Pigpio_spiClose
292 |
293 | /*
294 | * Class: jpigpio_Pigpio
295 | * Method: spiRead
296 | * Signature: (I[B)I
297 | */
298 | jint JNICALL Java_jpigpio_Pigpio_spiRead(JNIEnv *env, jobject obj, jint handle, jbyteArray rxData) {
299 | unsigned count = (*env)->GetArrayLength(env, rxData);
300 | jbyte *buf = malloc(count);
301 |
302 | int rc = spiRead(handle, (char *) buf, count);
303 |
304 | if (rc < 0) {
305 | (*env)->Throw(env, createPigpioException(env, rc));
306 | free(buf);
307 | return rc;
308 | }
309 | (*env)->SetByteArrayRegion(env, rxData, 0, count, buf);
310 | free(buf);
311 | return rc;
312 | } // End of Java_jpigpio_Pigpio_spiRead
313 |
314 | /*
315 | * Class: jpigpio_Pigpio
316 | * Method: spiWrite
317 | * Signature: (I[B)I
318 | */
319 | jint JNICALL Java_jpigpio_Pigpio_spiWrite(JNIEnv *env, jobject obj, jint handle, jbyteArray txData) {
320 | unsigned count = (*env)->GetArrayLength(env, txData);
321 | char *buf = malloc(count);
322 |
323 | (*env)->GetByteArrayRegion(env, txData, 0, count, (jbyte *) buf);
324 |
325 | int rc = spiWrite(handle, buf, count);
326 |
327 | free(buf);
328 | if (rc < 0) {
329 | (*env)->Throw(env, createPigpioException(env, rc));
330 | return rc;
331 | }
332 | return rc;
333 | } // End of Java_jpigpio_Pigpio_spiWrite
334 |
335 | /*
336 | * Class: jpigpio_Pigpio
337 | * Method: spiXfer
338 | * Signature: (I[B[B)I
339 | */
340 | jint JNICALL Java_jpigpio_Pigpio_spiXfer(JNIEnv *env, jobject obj, jint handle, jbyteArray txData, jbyteArray rxData) {
341 | unsigned count = (*env)->GetArrayLength(env, txData);
342 | char *txBuf = malloc(count);
343 | char *rxBuf = malloc(count);
344 |
345 | (*env)->GetByteArrayRegion(env, txData, 0, count, (jbyte *) txBuf);
346 |
347 | int rc = spiXfer(handle, txBuf, rxBuf, count);
348 |
349 | if (rc < 0) {
350 | (*env)->Throw(env, createPigpioException(env, rc));
351 | free(rxBuf);
352 | return rc;
353 | }
354 | #ifdef DEBUG
355 | if (debug) {
356 | char strTXData[1024];
357 | char strRXData[1024];
358 | strcpy(strTXData, "");
359 | strcpy(strRXData, "");
360 | char strByte[10];
361 | unsigned int i;
362 | for (i = 0; i < count; i++) {
363 | sprintf(strByte, "0x%x ", txBuf[i]);
364 | strcat(strTXData, strByte);
365 | sprintf(strByte, "0x%x ", rxBuf[i]);
366 | strcat(strRXData, strByte);
367 | }
368 | sprintf(debugText, "spiXfer: handle=%d, count=%d, TX Data: %s, RX Data: %s", handle, count, strTXData, strRXData);
369 | logDebug(debugText);
370 | }
371 | #endif
372 | // Verified that parms are env, target array, start index, number of bytes, source buffer
373 | (*env)->SetByteArrayRegion(env, rxData, 0, count, (jbyte *) rxBuf);
374 | free(rxBuf);
375 | free(txBuf);
376 | return rc;
377 | } // End of Java_jpigpio_Pigpio_spiXfer
378 |
379 | void JNICALL Java_jpigpio_Pigpio_setDebug(JNIEnv *env, jobject obj, jboolean state) {
380 | debug = state;
381 | }
382 |
383 | /**
384 | * Pulse a named pin and then wait for a response on a different pin. The output pin should already
385 | * have a PI_OUTPUT mode and the input pin should already have a PI_INPUT mode. The wait duration is in
386 | * microseconds. The pulse hold duration is how long (in microseconds) the pulse should be held for. The
387 | * default is to pulse the output high and then return low however if the pulseLow flag is set the inverse
388 | * will happen (pulse the output low and then return high).
389 | *
390 | * The return is how long we waited for the pulse measured in microseconds. If no response is received, we
391 | * return -1 to indicate a timeout.
392 | * @param outGpio The pin on which the output pulse will occur.
393 | * @param inGpio The pin on which the input pulse will be sought.
394 | * @param waitDuration The maximum time to wait in microseconds.
395 | * @param pulseHoldDuration The time to hold the output pulse in microseconds.
396 | * @param pulseLow True if the pulse should be a low pulse otherwise a high pulse will be sent.
397 | * @return The time in microseconds waiting for a pulse or -1 to signfify a timeout.
398 | */
399 |
400 | /*
401 | * Class: jpigpio_Pigpio
402 | * Method: gpioxPulseAndWait
403 | * Signature: (IIJJZ)J
404 | */
405 | jlong JNICALL Java_jpigpio_Pigpio_gpioxPulseAndWait(JNIEnv *env, jobject obj, //
406 | jint outGpio, jint inGpio, jlong waitDuration, jlong pulseHoldDuration, jboolean pulseLow) {
407 | unsigned outLevel;
408 | long start;
409 |
410 | #ifdef DEBUG
411 | char text[1024];
412 | sprintf(text, "gpioxPulseAndWait(outGpio=%d, inGpio=%d, waitDuration=%ld, pulseHoldDuration=%ld, pulseLow=%d)", //
413 | outGpio, inGpio, (long) waitDuration, (long) pulseHoldDuration, pulseLow);
414 | logDebug(text);
415 | #endif
416 | // Determine if the output pulse should be high or low.
417 | if (pulseLow) {
418 | outLevel = PI_LOW;
419 | } else {
420 | outLevel = PI_HIGH;
421 | }
422 |
423 | // Pulse the output pin for the correct duration
424 | gpioWrite(outGpio, outLevel);
425 | gpioDelay(pulseHoldDuration);
426 | gpioWrite(outGpio, invert(outLevel));
427 |
428 | // Loop until we have waited long enough or the input changes
429 | int state = 1;
430 | // 1 = Looking for high
431 | // 2 = looking for low
432 |
433 | // Loop until high
434 | // Start a timer
435 | // Loop until low
436 | // return now - start timer
437 | long waitStart = gpioTick();
438 | //printf("%ld\n",gpioTick() - waitStart );
439 | while ((gpioTick() - waitStart) < waitDuration) {
440 | //printf("%ld\n",gpioTick() - waitStart );
441 | if (state == 1) {
442 | if (gpioRead(inGpio) == PI_HIGH) {
443 | state = 2;
444 | start = gpioTick();
445 | }
446 | } // End of state == 1
447 | else if (state == 2) {
448 | if (gpioRead(inGpio) == PI_LOW) {
449 | return gpioTick() - start;
450 | }
451 | } // End of state == 2
452 | } // End while loop because we timed out
453 |
454 | // We didn't get a response in time.
455 | return -1;
456 | } // End of Java_jpigpio_Pigpio_gpioxPulseAndWait
457 |
458 | /**
459 | * A callback function that is invoked when a gpioSetAlertFunc() happens.
460 | * We use the gpio pin value as a lookup into a saved set of Java Alert objects that have
461 | * been registered. Once we have the correct Alert object, we setup the environment to
462 | * call back into Java to call the Alert.alert() method.
463 | */
464 | void alertCallback(int gpio, int level, unsigned int tick) {
465 | JNIEnv *env;
466 |
467 | if (alertFunctions[gpio] == NULL) {
468 | printf("JPigpio: alertCallback(gpio=%d, level=%d, tick=%d): Odd ... alert callback but no alert function registered\n", gpio, level, tick);
469 | return;
470 | }
471 | //printf("JPigpio: alertCallback(gpio=%d, level=%d, tick=%d)\n", gpio, level, tick);
472 |
473 | int getEnvStat = (*g_vm)->GetEnv(g_vm, (void **) &env, JNI_VERSION_1_8);
474 |
475 | if (getEnvStat == JNI_EDETACHED) {
476 | (*g_vm)->AttachCurrentThread(g_vm, (void **) &env, NULL);
477 | }
478 |
479 | // We have now attached this C thread to the JVM environment.
480 | // Lookup the class of the Alert, lookup the alert method methodId and
481 | // then call the alert() method with the correct parameters.
482 |
483 | jclass classz = (*env)->GetObjectClass(env, alertFunctions[gpio]);
484 | jmethodID methodId = (*env)->GetMethodID(env, classz, "alert", "(IIJ)V");
485 | (*env)->CallVoidMethod(env, alertFunctions[gpio], methodId, gpio, level, (jlong) tick);
486 |
487 | // Cleanup the environment by detaching the thread.
488 | (*g_vm)->DetachCurrentThread(g_vm);
489 | } // End of alertCallback
490 |
491 | #ifdef DEBUG
492 | void logDebug(char *text) {
493 | if (debug) {
494 | printf("%.6d: %s\n", gpioTick() - lastTime, text);
495 | lastTime = gpioTick();
496 | }
497 | }
498 | #endif
499 |
500 | unsigned invert(unsigned level) {
501 | if (level == PI_HIGH) {
502 | return PI_LOW;
503 | }
504 | return PI_HIGH;
505 | }
506 |
507 | /**
508 | * Create a new Java Exception
509 | */
510 | jthrowable createPigpioException(JNIEnv *env, int rc) {
511 | jclass pigpioExceptionClass = (*env)->FindClass(env, "jpigpio/PigpioException");
512 | jmethodID pigpioExceptionConstructorId = (*env)->GetMethodID(env, pigpioExceptionClass, "", "(I)V");
513 | jthrowable newPigpioException = (*env)->NewObject(env, pigpioExceptionClass, pigpioExceptionConstructorId, rc);
514 | return newPigpioException;
515 | } // End of createNewException
516 |
--------------------------------------------------------------------------------
/JPigpioC/JPigpioC.h:
--------------------------------------------------------------------------------
1 | /*
2 | * JPigpio.h
3 | *
4 | * Created on: Apr 18, 2015
5 | * Author: kolban
6 | */
7 | #define MAXPINS 32
8 |
9 |
--------------------------------------------------------------------------------
/JPigpioC/JPigpioC.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/JPigpioC/JPigpioC.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/JPigpioC.o
--------------------------------------------------------------------------------
/JPigpioC/Makefile:
--------------------------------------------------------------------------------
1 | CC=gcc
2 | CFLAGS=-c -Wall -fPIC -I $(JAVA_HOME)/include -I $(JAVA_HOME)/include/linux
3 | JAVACLASSDIR=../JPigpio/bin
4 | LIBDIR=/mnt/share/opt/lib
5 | TARGETLIB=libJPigpioC.so
6 | OBJECTS=JPigpioC.o
7 |
8 | all: jpigpio_Pigpio.h $(TARGETLIB)
9 | cp $(TARGETLIB) $(LIBDIR)
10 |
11 | $(TARGETLIB): $(OBJECTS)
12 | gcc -shared -Wl,-soname,$@ -o $@ $(OBJECTS) -lpigpio -lpthread -lrt
13 |
14 | jpigpio_Pigpio.h:
15 | javah -cp $(JAVACLASSDIR) jpigpio.Pigpio
16 |
17 | .c.o:
18 | $(CC) $(CFLAGS) $<
19 |
20 | clean:
21 | rm -f *.o $(TARGETLIB) jpigpio_Pigpio.h $(LIBDIR)/$(TARGETLIB)
22 |
23 | install: $(TARGETLIB)
24 | cp $< $(LIBDIR)
25 |
--------------------------------------------------------------------------------
/JPigpioC/jpigpio_Pigpio.h:
--------------------------------------------------------------------------------
1 | /* DO NOT EDIT THIS FILE - it is machine generated */
2 | #include
3 | /* Header for class jpigpio_Pigpio */
4 |
5 | #ifndef _Included_jpigpio_Pigpio
6 | #define _Included_jpigpio_Pigpio
7 | #ifdef __cplusplus
8 | extern "C" {
9 | #endif
10 | /*
11 | * Class: jpigpio_Pigpio
12 | * Method: gpioInitialize
13 | * Signature: ()V
14 | */
15 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioInitialize
16 | (JNIEnv *, jobject);
17 |
18 | /*
19 | * Class: jpigpio_Pigpio
20 | * Method: gpioTerminate
21 | * Signature: ()V
22 | */
23 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioTerminate
24 | (JNIEnv *, jobject);
25 |
26 | /*
27 | * Class: jpigpio_Pigpio
28 | * Method: gpioSetMode
29 | * Signature: (II)V
30 | */
31 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioSetMode
32 | (JNIEnv *, jobject, jint, jint);
33 |
34 | /*
35 | * Class: jpigpio_Pigpio
36 | * Method: gpioGetMode
37 | * Signature: (I)I
38 | */
39 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_gpioGetMode
40 | (JNIEnv *, jobject, jint);
41 |
42 | /*
43 | * Class: jpigpio_Pigpio
44 | * Method: gpioSetPullUpDown
45 | * Signature: (II)V
46 | */
47 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioSetPullUpDown
48 | (JNIEnv *, jobject, jint, jint);
49 |
50 | /*
51 | * Class: jpigpio_Pigpio
52 | * Method: gpioRead
53 | * Signature: (I)Z
54 | */
55 | JNIEXPORT jboolean JNICALL Java_jpigpio_Pigpio_gpioRead
56 | (JNIEnv *, jobject, jint);
57 |
58 | /*
59 | * Class: jpigpio_Pigpio
60 | * Method: gpioWrite
61 | * Signature: (IZ)V
62 | */
63 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioWrite
64 | (JNIEnv *, jobject, jint, jboolean);
65 |
66 | /*
67 | * Class: jpigpio_Pigpio
68 | * Method: i2cOpen
69 | * Signature: (II)I
70 | */
71 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_i2cOpen
72 | (JNIEnv *, jobject, jint, jint);
73 |
74 | /*
75 | * Class: jpigpio_Pigpio
76 | * Method: i2cClose
77 | * Signature: (I)V
78 | */
79 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_i2cClose
80 | (JNIEnv *, jobject, jint);
81 |
82 | /*
83 | * Class: jpigpio_Pigpio
84 | * Method: i2cReadDevice
85 | * Signature: (I[B)I
86 | */
87 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_i2cReadDevice
88 | (JNIEnv *, jobject, jint, jbyteArray);
89 |
90 | /*
91 | * Class: jpigpio_Pigpio
92 | * Method: i2cWriteDevice
93 | * Signature: (I[B)V
94 | */
95 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_i2cWriteDevice
96 | (JNIEnv *, jobject, jint, jbyteArray);
97 |
98 | /*
99 | * Class: jpigpio_Pigpio
100 | * Method: gpioDelay
101 | * Signature: (J)V
102 | */
103 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioDelay
104 | (JNIEnv *, jobject, jlong);
105 |
106 | /*
107 | * Class: jpigpio_Pigpio
108 | * Method: gpioTick
109 | * Signature: ()J
110 | */
111 | JNIEXPORT jlong JNICALL Java_jpigpio_Pigpio_gpioTick
112 | (JNIEnv *, jobject);
113 |
114 | /*
115 | * Class: jpigpio_Pigpio
116 | * Method: gpioServo
117 | * Signature: (II)V
118 | */
119 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioServo
120 | (JNIEnv *, jobject, jint, jint);
121 |
122 | /*
123 | * Class: jpigpio_Pigpio
124 | * Method: gpioSetAlertFunc
125 | * Signature: (ILjpigpio/Alert;)V
126 | */
127 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioSetAlertFunc
128 | (JNIEnv *, jobject, jint, jobject);
129 |
130 | /*
131 | * Class: jpigpio_Pigpio
132 | * Method: gpioTrigger
133 | * Signature: (IJZ)V
134 | */
135 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_gpioTrigger
136 | (JNIEnv *, jobject, jint, jlong, jboolean);
137 |
138 | /*
139 | * Class: jpigpio_Pigpio
140 | * Method: spiOpen
141 | * Signature: (III)I
142 | */
143 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_spiOpen
144 | (JNIEnv *, jobject, jint, jint, jint);
145 |
146 | /*
147 | * Class: jpigpio_Pigpio
148 | * Method: spiClose
149 | * Signature: (I)V
150 | */
151 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_spiClose
152 | (JNIEnv *, jobject, jint);
153 |
154 | /*
155 | * Class: jpigpio_Pigpio
156 | * Method: spiRead
157 | * Signature: (I[B)I
158 | */
159 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_spiRead
160 | (JNIEnv *, jobject, jint, jbyteArray);
161 |
162 | /*
163 | * Class: jpigpio_Pigpio
164 | * Method: spiWrite
165 | * Signature: (I[B)I
166 | */
167 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_spiWrite
168 | (JNIEnv *, jobject, jint, jbyteArray);
169 |
170 | /*
171 | * Class: jpigpio_Pigpio
172 | * Method: spiXfer
173 | * Signature: (I[B[B)I
174 | */
175 | JNIEXPORT jint JNICALL Java_jpigpio_Pigpio_spiXfer
176 | (JNIEnv *, jobject, jint, jbyteArray, jbyteArray);
177 |
178 | /*
179 | * Class: jpigpio_Pigpio
180 | * Method: setDebug
181 | * Signature: (Z)V
182 | */
183 | JNIEXPORT void JNICALL Java_jpigpio_Pigpio_setDebug
184 | (JNIEnv *, jobject, jboolean);
185 |
186 | /*
187 | * Class: jpigpio_Pigpio
188 | * Method: gpioxPulseAndWait
189 | * Signature: (IIJJZ)J
190 | */
191 | JNIEXPORT jlong JNICALL Java_jpigpio_Pigpio_gpioxPulseAndWait
192 | (JNIEnv *, jobject, jint, jint, jlong, jlong, jboolean);
193 |
194 | #ifdef __cplusplus
195 | }
196 | #endif
197 | #endif
198 |
--------------------------------------------------------------------------------
/JPigpioC/libJPigpioC.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/libJPigpioC.so
--------------------------------------------------------------------------------
/JPigpioC/tests/Makefile:
--------------------------------------------------------------------------------
1 | LIBSDIR=/mnt/share/opt/lib
2 | PROGRAMS=test_nunchuck test_servo
3 | all: $(PROGRAMS)
4 |
5 |
6 | test_servo: test_servo.o
7 | gcc -L$(LIBSDIR) -o test_servo test_servo.o -lJPigpioC -lpigpio -lpthread -lrt
8 |
9 | test_nunchuck: test_nunchuck.o
10 | gcc -L$(LIBSDIR) -o test_nunchuck test_nunchuck.o -lJPigpioC -lpigpio -lpthread -lrt
11 |
12 | .c.o:
13 | gcc -Wall -I.. -c $<
14 |
15 | clean:
16 | rm $(PROGRAMS) *.o
--------------------------------------------------------------------------------
/JPigpioC/tests/run_test_nunchuck.sh:
--------------------------------------------------------------------------------
1 | export LD_LIBRARY_PATH=/mnt/share/opt/lib
2 | ./test_nunchuck
3 |
--------------------------------------------------------------------------------
/JPigpioC/tests/run_test_servo.sh:
--------------------------------------------------------------------------------
1 | export LD_LIBRARY_PATH=/mnt/share/opt/lib
2 | ./test_servo
3 |
--------------------------------------------------------------------------------
/JPigpioC/tests/test_nunchuck:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/tests/test_nunchuck
--------------------------------------------------------------------------------
/JPigpioC/tests/test_nunchuck.c:
--------------------------------------------------------------------------------
1 | /*
2 | * ultrasonic.c
3 | * Test the getUltrasonicDistance function.
4 | *
5 | * Created on: Apr 7, 2015
6 | * Author: kolban
7 | */
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 |
15 | int main(void) {
16 | int NUNCHUCK_DEVICE = 0x52;
17 | int PI_I2CBUS = 1;
18 |
19 | printf("Testing the nunchuck through I2C\n");
20 | int rc = gpioInitialise();
21 | printf("rc from gpioInitialise: %d\n", rc);
22 | int handle = i2cOpen(PI_I2CBUS, NUNCHUCK_DEVICE, 0);
23 | if (handle) {
24 | printf("Error setting up I2C: %d\n", errno);
25 | exit(0);
26 | }
27 | char buf[2] = {0x40, 0x00};
28 | i2cWriteDevice(handle, buf, sizeof(buf));
29 | gpioDelay(500);
30 |
31 | while(1) {
32 | char buf[1] = {0x00};
33 | i2cWriteDevice(handle, buf, sizeof(buf));
34 | gpioDelay(500);
35 | char bufResponse[6];
36 | i2cReadDevice(handle, bufResponse, sizeof(bufResponse));
37 |
38 | char *bytes = bufResponse;
39 | // (d) 1 2 4 8 16 32 64 128
40 | // (h) 1 2 4 8 10 20 40 80
41 | int joyX = bytes[0];
42 | int joyY = bytes[1];
43 | int accelX = (bytes[2] << 2) | ((bytes[5] & 0xc0) >> 6);
44 | int accelY = (bytes[3] << 2) | ((bytes[5] & 0x30) >> 4);
45 | int accelZ = (bytes[4] << 2) | ((bytes[5] & 0x0c) >> 2);
46 | int c = (bytes[5] & 0x02) >> 1;
47 | int z = bytes[5] & 0x01;
48 |
49 | //printf("data: %x %x %x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]);
50 | printf("data: joyX=%x joyY=%x accelX=%x accelY=%x accelZ=%x c=%x z=%x\n", joyX, joyY, accelX, accelY, accelZ, c, z);
51 | }
52 | return 0;
53 | }
54 |
--------------------------------------------------------------------------------
/JPigpioC/tests/test_nunchuck.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/tests/test_nunchuck.o
--------------------------------------------------------------------------------
/JPigpioC/tests/test_servo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/tests/test_servo
--------------------------------------------------------------------------------
/JPigpioC/tests/test_servo.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 |
8 | int main(void) {
9 | int rc = gpioInitialise();
10 | if (rc < 0) {
11 | printf("gpioInitialise() failed: %d\n", rc);
12 | exit(-1);
13 | }
14 | int pwmPin = 17;
15 | int servoSweepDuration = 500; // Time in ms
16 |
17 | printf("pwmPin pin = %d\n", pwmPin);
18 | printf("servoSweepDuration = %d seconds\n", servoSweepDuration);
19 |
20 | int direction = 0; // 0 = up, 1 = down
21 | while(1) {
22 | unsigned int startTime = gpioTick();
23 | unsigned int sweepTime = servoSweepDuration * 1000 / 2;
24 | unsigned int delta = gpioTick() - startTime;
25 | while(delta < sweepTime) {
26 | // Position is going to be between 0 and 1 and represents how far along the sweep
27 | // we are.
28 | double position = (double)delta/sweepTime;
29 |
30 | unsigned int timeToWriteHighUSecs;
31 | position = -0.4;
32 | if (direction == 0) {
33 | timeToWriteHighUSecs = (position + 1.0) * 1000;
34 | } else {
35 | timeToWriteHighUSecs = (2.0 - position) * 1000;
36 | }
37 |
38 | printf("Setting pulse width %d, %d, %d\n", timeToWriteHighUSecs, delta, startTime);
39 | gpioServo(pwmPin, timeToWriteHighUSecs);
40 | gpioDelay(20 * 1000);
41 |
42 | delta = gpioTick() - startTime;
43 | } // End of a sweep in one direction
44 |
45 | // Switch direction
46 | if (direction == 0) {
47 | direction = 1;
48 | } else {
49 | direction = 0;
50 | }
51 | } // End of while true
52 | return 0;
53 | }
54 |
--------------------------------------------------------------------------------
/JPigpioC/tests/test_servo.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/JPigpioC/tests/test_servo.o
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all:
2 | ./build.sh
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # jpigpio
2 | A Java interface to the Raspberry Pi pigpio library
3 |
4 | [Pigpio](http://abyz.co.uk/rpi/pigpio/index.html) is a great library for accessing the GPIO pins and other inputs and outputs of a Raspberry Pi. Pigpio provides interfaces for C and Python. However, if what you want to do is use the functions of the library from a Java application, you are stuck. The purpose of this project is to provide a Java interface to the pigpio library.
5 |
6 | The core of the solution is a Java interface called `jpigpio.JPigpio`. It is this interface that provides the exposed functions that perform the pigpio requests. Currently, the following pigpio operations are supported:
7 |
8 | * gpioInitialize
9 | * gpioTerminate
10 | * gpioGetMode
11 | * gpioSetMode
12 | * gpioRead
13 | * gpioWrite
14 | * gpioTrigger
15 | * gpioSetAlertFunc (Not available for sockets)
16 | * gpioSetPullUpDown
17 | * gpioDelay
18 | * gpioTick
19 | * gpioShiftOut (Extra)
20 |
21 | * gpioServo
22 |
23 | * i2cOpen
24 | * i2cClose
25 | * i2cReadDevice
26 | * i2cWriteDevice
27 |
28 | * spiOpen
29 | * spiClose
30 | * spiRead
31 | * spiWrite
32 | * spiXfer
33 |
34 | Obviously, this is only a subset of the full and rich capabilities of C and Python pigpio. However, the subset is the starter set we chose to create. If you find you need a pigpio function that is not provided by Java, simply let us know and we will turn it around very quickly. We simply don't want to spend time porting if there is no demand.
35 |
36 | Since `jpigpio.JPigpio` is a Java interface, something must implement it. Two separate implementations are provided. One called `jpigpio.Pigpio` and one called `jpigpio.PigpioSocket`. Both of them implement the `jpigpio.JPigpio` interface. The difference between them is how the calls from Java to pigpio are achieved.
37 |
38 | ## jpigpio.Pigpio
39 | Using this class, your custom Java code **must** be executed on the Raspberry Pi. The method calls made in Java are passed as quickly as possible to the underlying pigpio C library for execution. This provides the fastest capability to call pigpio with as little Java overhead as possible. Of course, the Java classes must execute on the Pi.
40 |
41 | 
42 |
43 | ## jpigpio.PigpioSocket
44 | Using this class, your custom Java code can run either on the Raspberry Pi or on a separate machine as long as there is a network connection (TCP/IP). The pigpio function requests are transmitted via sockets to the pigpio supplied demon which is called `pigpiod` which can listen for incoming requests and service them when they arrive.
45 |
46 | 
47 |
48 | ## Exception handling
49 | The pigpio library returns code values which indicate the outcome of a function call. In Java, we have the ability to throw exceptions. As such, if an error is detected when making a jpigpio method call, an exception of type `PigpioException` is thrown. This makes our logic for error handling much cleaner as we do not have to explicitly check the response values for each of the calls.
50 |
51 | Upon catching a PigpioException, we can ask for the error code value with the `getErrorCode()` method.
52 |
53 | Symbolic definitions for each of the potential errors are supplied as statics on the PigpioException class. For example:
54 |
55 | PigpioException.PI_BAD_GPIO
56 |
57 | will have a value of `-3` which is the underlying code for the corresponding pigpio error.
58 |
59 | try {
60 | // Perform a pigpio function
61 | }
62 | catch(PigpioException e) {
63 | e.printStackTrace();
64 | if (e.getErrorCode() == PigpioException.PI_BAD_GPIO) {
65 | System.out.println("You supplied a bad pin!");
66 | }
67 | }
68 |
69 | ## Alert callbacks
70 | The `gpioSetAlertFunc` method takes a gpio pin and an instance of an `Alert` class. The `Alert` is a Java interface that has the following signature:
71 |
72 | public interface Alert {
73 | public void alert(int gpio, int level, long tick);
74 | }
75 |
76 | This is a callback class. When the state of the gpio pin changes, the `alert` method is invoked to indicate that a state change event has occurred. Because the `Alert` interface only has a single member function, it is eligible to be used as a Java 8 lambda function which makes it very convenient to use:
77 |
78 | pigpio.gpioSetAlertFunc(TESTPIN, (gpio, level, tick) -> {
79 | System.out.println(
80 | String.format("Callback in Java: We received an alert on: %d with %d at %d",
81 | gpio, level, tick));
82 | });
83 |
84 | ## Utilities
85 | A class called `Utils` provides some Java utilities that can be used in conjunction with JPigpio.
86 |
87 | * `static void addShutdown(JPigpio pigpio)` - Register a JVM shutdown handler that automatically gets called when the JVM ends. This shutdown handler cleans up (terminates) any resources allocated on behalf of pigpio.
88 |
89 | ## Constant definitions
90 |
91 | The JPigpio interface defines a set of constants for use with the library:
92 |
93 | * PI_HIGH - A high value
94 | * PI_LOW - A low value
95 | * PI_ON - A high value
96 | * PI_OFF - A low value
97 | * PI_INPUT - The mode of a gpio for input
98 | * PI_OUTPUT - The mode of a gpio for output
99 | * PI\_PUD_OFF - No pull-up associated with the gpio
100 | * PI\_PUD_UP - Pull-up the gpio to high
101 | * PI\_PUD_DOWN - Pull-down the gpio to low
102 |
103 | ----
104 |
105 | # Running an application
106 | JPigpio is built against Java version 8 and hence requires a Java 8 environment in order to run. This is the current level of Java supplied with Raspbian. An application that only uses the `PigpioSocket` class needs no additional special environment. However, an application that uses the `Pigpio` class needs to be able to find the JPigpio shared library written in C. This is specified by adding the path to the directory which contains the file `libJPigpioC.so`.
107 |
108 | java -Djava.library.path= tests/Test_Blink
109 |
110 | If the library can not be found, you will get an exception that looks similar to:
111 |
112 | Exception in thread "main" java.lang.UnsatisfiedLinkError: no JPigpioC in java.library.path
113 | at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857)
114 | at java.lang.Runtime.loadLibrary0(Runtime.java:870)
115 | at java.lang.System.loadLibrary(System.java:1119)
116 | at jpigpio.Pigpio.(Pigpio.java:5)
117 | at tests.Test_Blink.run(Test_Blink.java:30)
118 | at tests.Test_Blink.main(Test_Blink.java:24)
119 |
120 | Check that the java.library.path is supplied and that its value points to a directory which contains the `libJPigpioC.so` library file.
121 |
122 | ----
123 |
124 | # Installation
125 | A prerequisite of this package is the correct installation of pigpio on the Raspberry Pi by itself. Please see the Pigpio [Download & Install](http://abyz.co.uk/rpi/pigpio/download.html) page for details. A quick way to check that a version of pigpio is present is to look for the following files:
126 |
127 | * `/usr/local/lib/libpigpio.a`
128 | * `/usr/local/bin/pigpiod`
129 | * `/usr/local/include/pigpio.h`
130 |
131 | Details of the installation techniques for this project to be provided here ...
132 |
133 | ----
134 | # Mapping
135 | On occasion, you may find existing code written for either an Arduino (a sketch) or for alternate Raspberry Pi libraries such as Wiring Pi. Here we provide a mapping from similar capabilities to those found in the JPigpio package.
136 |
137 | ## Arduino
138 |
139 | * digitalWrite - gpioWrite
140 | * digitalRead - gpioRead
141 | * shiftOut - gpioShiftOut
142 | * pinMode - gpioSetMode
143 |
144 | ## Wiring Pi
145 |
146 | * digitalWrite - gpioWrite
147 | * digitalRead - gpioRead
148 | * pinMode - gpioSetMode
149 |
150 | ----
151 |
152 | # Future of the project
153 | I will be delighted to accept change requests and bug reports (if any can be found) and turn those around as quickly as possible. I have been an IT hobbyist/coder for decades and am not planning on going anywhere soon so feel free to believe that this will be a maintained project as long as needed.
154 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | cd JPigpio
2 | make clean
3 | make
4 | cd ..
5 | cd JPigpioC
6 | make clean
7 | make
8 |
--------------------------------------------------------------------------------
/examples.md:
--------------------------------------------------------------------------------
1 | # JPigpio Examples
2 |
3 | ## Basics
4 |
5 | ### Blink
6 | Pulse a gpio on high and low. Typically, you would connect an LED to the pin and watch it blink.
--------------------------------------------------------------------------------
/images/NoSockets.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/images/NoSockets.png
--------------------------------------------------------------------------------
/images/Sockets.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nkolban/jpigpio/05b8c6f8795d7f81324f0a0022fd2d530ea5229d/images/Sockets.png
--------------------------------------------------------------------------------