RaspberryPi@WiringPi

Hier könnt Ihr gute, von Euch geschriebene Codes posten. Sie müssen auf jeden Fall funktionieren und sollten möglichst effizient, elegant und beispielhaft oder einfach nur cool sein.
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

RaspberryPi@WiringPi

Beitrag von ccode_new »

@RaspberryPi
Hier ist ein Test der "wiringpi"-Bibliothek: (PureBasic-Include)
(;update)

Code: Alles auswählen

;@ccode_new

;PureBasic-Test: wiringPi-Lib
;pinout:
#GPIO_0 = 8 ;rev1
#GPIO_1 = 9 ;rev1
#GPIO_2 = 8
#GPIO_3 = 9
#GPIO_4 = 7
#GPIO_7 = 11
#GPIO_8 = 10
#GPIO_9 = 13
#GPIO_10 = 12
#GPIO_11 = 14
#GPIO_14 = 15
#GPIO_15 = 16
#GPIO_17 = 0
#GPIO_18 = 1
#GPIO_21 = 2 ;rev1
#GPIO_22 = 3
#GPIO_23 = 4
#GPIO_24 = 5
#GPIO_25 = 6
#GPIO_27 = 2
#GPIO_28 = 17
#GPIO_29 = 18
#GPIO_30 = 19
#GPIO_31 = 20

;gpio readall (helpful for pinout "wiringPi")

;wget https://project-downloads.drogon.net/wiringpi-latest.deb
;sudo dpkg -i wiringpi-latest.deb

;Compile-Example:
;export PUREBASIC_HOME=/home/pi/purebasic/
;export pbc=/home/pi/purebasic/compilers/pbcompiler
;$pbc -d -t -z -e wire wire.pb

;Persistent environment variables:
;edit: (insert the "export" commands)
;sudo nano /.bash_profile

;Edit-Example:
;touch wire.pb
;nano wire.pb
;edit-commands:
;jump to line: nano +1900 wire.pb (strg And shift And -)
;strg AND o = Save
;strg AND x = Close

;Cancel-Program:
;strg AND c
;Cancel-Debugger:
;insert "exit" (without quotes)

;-Pinbelegung (Pi400)

;Standard: 
;Terminal: pinout

;  | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
;  +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
;  |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |
;  |   2 |   8 |   SDA.1 |  OUT | 0 |  3 || 4  |   |      | 5v      |     |     |
;  |   3 |   9 |   SCL.1 |   IN | 1 |  5 || 6  |   |      | 0v      |     |     |
;  |   4 |   7 | GPIO. 7 |   IN | 0 |  7 || 8  | 1 | IN   | TxD     | 15  | 14  |
;  |     |     |      0v |      |   |  9 || 10 | 1 | IN   | RxD     | 16  | 15  |
;  |  17 |   0 | GPIO. 0 |  OUT | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |
;  |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |
;  |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |
;  |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |
;  |  10 |  12 |    MOSI |   IN | 0 | 19 || 20 |   |      | 0v      |     |     |
;  |   9 |  13 |    MISO |   IN | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |
;  |  11 |  14 |    SCLK |   IN | 0 | 23 || 24 | 1 | IN   | CE0     | 10  | 8   |
;  |     |     |      0v |      |   | 25 || 26 | 1 | IN   | CE1     | 11  | 7   |
;  |   0 |  30 |   SDA.0 |   IN | 1 | 27 || 28 | 1 | IN   | SCL.0   | 31  | 1   |
;  |   5 |  21 | GPIO.21 |   IN | 0 | 29 || 30 |   |      | 0v      |     |     |
;  |   6 |  22 | GPIO.22 |   IN | 0 | 31 || 32 | 0 | IN   | GPIO.26 | 26  | 12  |
;  |  13 |  23 | GPIO.23 |   IN | 0 | 33 || 34 |   |      | 0v      |     |     |
;  |  19 |  24 | GPIO.24 |   IN | 0 | 35 || 36 | 0 | IN   | GPIO.27 | 27  | 16  |
;  |  26 |  25 | GPIO.25 |   IN | 0 | 37 || 38 | 0 | IN   | GPIO.28 | 28  | 20  |
;  |     |     |      0v |      |   | 39 || 40 | 1 | IN   | GPIO.29 | 29  | 21  |
;  +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
;  | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |


#PI_GPIO_MASK = $FFFFFFC0

;wiringPi modes

#WPI_MODE_PINS = 0
#WPI_MODE_GPIO = 1
#WPI_MODE_GPIO_SYS = 2
#WPI_MODE_PHYS = 3
#WPI_MODE_PIFACE = 4
#WPI_MODE_UNINITIALISED = -1

;Pin modes

#INPUT = 0
#OUTPUT = 1
#PWM_OUTPUT = 2
#GPIO_CLOCK = 3
#SOFT_PWM_OUTPUT = 4
#SOFT_TONE_OUTPUT = 5
#PWM_TONE_OUTPUT = 6

#LOW = 0
#HIGH = 1

;Pull up/down/none

#PUD_OFF = 0
#PUD_DOWN = 1
#PUD_UP = 2

;PWM

#PWM_MODE_MS = 0
#PWM_MODE_BAL = 1

;Interrupt levels

#INT_EDGE_SETUP = 0
#INT_EDGE_FALLING	= 1
#INT_EDGE_RISING = 2
#INT_EDGE_BOTH = 3

;Pi model types And version numbers
;Intended For the GPIO program Use at your own risk.
;https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#new-style-revision-codes

#PI_MODEL_A = 0
#PI_MODEL_B = 1
#PI_MODEL_AP = 2
#PI_MODEL_BP = 3
#PI_MODEL_2 = 4
#PI_ALPHA = 5
#PI_MODEL_CM = 6
#PI_MODEL_07 = 7
#PI_MODEL_3B = 8
#PI_MODEL_ZERO = 9
#PI_MODEL_CM3 = 10
#PI_MODEL_ZERO_W = 12
#PI_MODEL_3BP = 13
#PI_MODEL_3AP = 14
#PI_MODEL_CM3P = 16
#PI_MODEL_4B = 17
#PI_MODEL_ZERO_2W	= 18
#PI_MODEL_400	= 19
#PI_MODEL_CM4	= 20

#PI_VERSION_1	= 0
#PI_VERSION_1_1	= 1
#PI_VERSION_1_2	= 2
#PI_VERSION_2	= 3

#PI_MAKER_SONY = 0
#PI_MAKER_EGOMAN = 1
#PI_MAKER_EMBEST = 2
#PI_MAKER_UNKNOWN	= 3

Global Dim piModelNames.s(21)
Global Dim piRevisionNames.s(16)
Global Dim piMakerNames.s(16)
Global Dim piMemorySize.i(8)

;Failure modes
#WPI_FATAL = 1
#WPI_ALMOST	= 2

;wiringShift.h
#LSBFIRST	= 0
#MSBFIRST	= 1

;unistd.h
#STDIN_FILENO = 0
#STDOUT_FILENO = 1
#STDERR_FILENO = 2

;mcp3422.h
#MCP3422_SR_240 = 0
#MCP3422_SR_60 = 1
#MCP3422_SR_15 = 2
#MCP3422_SR_3_75 = 3

#MCP3422_GAIN_1	= 0
#MCP3422_GAIN_2	= 1
#MCP3422_GAIN_4	= 2
#MCP3422_GAIN_8	= 3


Import "-lwiringPi"
  wiringPiFailure.i(fatal.i, *message)
  
  wiringPiFindNode(pin.i)
  wiringPiNewNode(pinBase.i, numPins.i)
  
  wiringPiVersion(*major, *minor)
  wiringPiSetup.i()
  wiringPiSetupSys.i()
  wiringPiSetupGpio.i()
  wiringPiSetupPhys.i()
  
  pinModeAlt(pin.i, mode.i)
  pinMode(pin.i, mode.i)
  pullUpDnControl(pin.i, pud.i)
  digitalRead.i(pin.i)
  digitalWrite(pin.i, value.i)
  digitalRead8.i(pin.i)
  digitalWrite8(pin.i, value.i)
  pwmWrite(pin.i, value.i)
  analogRead.i(pin.i)
  analogWrite(pin.i, value.i)
  
  wiringPiSetupPiFace.i()
  wiringPiSetupPiFaceForGpioProg.i() ;Don't use this - for gpio program only
  
  ;On-Board Raspberry Pi hardware specific stuff
  piGpioLayout.i()
  piBoardRev.i() ;	// Deprecated
  piBoardId(*model, *rev, *mem, *maker, *overVolted)
  wpiPinToGpio.i(wpiPin.i)
  physPinToGpio.i(physPin.i)
  setPadDrive(group.i, value.i)
  getAlt(pin.i)
  pwmToneWrite(pin.i, freq.i)
  pwmSetMode(mode.i)
  pwmSetRange(range.i)
  pwmSetClock(divisor.i)
  gpioClockSet(pin.i, freq.i)
  digitalReadByte.i()
  digitalReadByte2.i()
  digitalWriteByte(value.i)
  digitalWriteByte2(value.i)
  
  ;Interrupts
  ;(Also Pi hardware specific)
  waitForInterrupt.i(pin.i, ms.i)
  
  ;Schedulling priority
  piHiPri.i(pri.i)
  
  ;Extras from arduino land
  delayMicroseconds(howLong.i)
  millis.i()
  micros.i()
  
  ;softPwm.h
  softPwmCreate.i(pin.i, value.i, range.i)
  softPwmWrite(pin.i, value.i)
  softPwmStop(pin.i)
  
  ;softTone.h
  softToneCreate.i(pin.i)
  softToneStop(pin.i)
  softToneWrite(pin.i, freq.i)
  
  ;wiringShift.h
  shiftIn.i(dPin.i, cPin.i, order.i)
  shiftOut(dPin.i, cPin.i, order.i, val.i)
  
  ;wiringPiI2C.h
  wiringPiI2CRead.i(fd.i)
  wiringPiI2CReadReg8.i(fd.i, reg.i)
  wiringPiI2CReadReg16.i(fd.i, reg.i)
  
  wiringPiI2CWrite.i(fd.i, cData.i)
  wiringPiI2CWriteReg8.i(fd.i, reg.i, cData.i)
  wiringPiI2CWriteReg16.i(fd.i, reg.i, cData.i)
  
  wiringPiI2CSetupInterface.i(*device, devId.i)
  wiringPiI2CSetup.i(devId.i)
  
  ;pcf8574.h
  pcf8574Setup.i(pinBase.i, i2cAddress.i)
  
  ;mcp23008.h
  mcp23008Setup.i(pinBase.i, i2cAddress.i)
  
  ;ds18b20.h
  ds18b20Setup.i(pinBase.i, *serialNum)
  
  ;mcp3422.h
  mcp3422Setup.i(pinBase.i, i2cAddress.i, sampleRate.i, gain.i)
  
EndImport

;lcd.h (lwiringPiDev)
#MAX_LCDS =	8

Import "-lwiringPiDev"
  ;ds1302.h (RTC = Real Time clock)
  ds1302rtcRead.i(reg.i)
  ds1302rtcWrite(reg.i, cData.i)
  ds1302ramRead.i(addr.i)
  ds1302ramWrite(addr.i, cData.i)
  ds1302clockRead(Array clockData.i(1))
  ds1302clockWrite(Array clockData.i(1))
  ds1302trickleCharge(diodes.i, resistors.i)
  ds1302setup(clockPin.i, dataPin.i, csPin.i)
  
  ;lcd.h
  lcdHome(fd.i)
  lcdClear(fd.i)
  lcdDisplay(fd.i, state.i)
  lcdCursor(fd.i, state.i)
  lcdCursorBlink(fd.i, state.i)
  lcdSendCommand(fd.i, command.i)
  lcdPosition(fd.i, x.i, y.i)
  lcdCharDef(fd.i, index.i, Array cData.i(1))
  lcdPutchar(fd.i, cData.i)
  lcdPuts(fd.i, *string)
  lcdPrintf(fd.i, *message)
  lcdInit.i(rows.i, cols.i, bits.i, rs.i, strb.i, d0.i, d1.i, d2.i, d3.i, d4.i, d5.i, d6.i, d7.i)
  
  ;lcd128x64.h
  lcd128x64setOrigin(x.i, y.i)
  lcd128x64setOrientation(orientation.i)
  lcd128x64orientCoordinates(*x, *y)
  lcd128x64getScreenSize(*x, *y)
  lcd128x64point(x.i, y.i, colour.i)
  lcd128x64line(x0.i, y0.i, x1.i, y1.i, colour.i)
  lcd128x64lineTo(x.i, y.i, colour.i)
  lcd128x64rectangle(x1.i, y1.i, x2.i, y2.i, colour.i, filled.i)
  lcd128x64circle(x.i, y.i, r.i, colour.i, filled.i)
  lcd128x64ellipse(cx.i, cy.i, xRadius.i, yRadius.i, colour.i, filled.i)
  lcd128x64putchar(x.i, y.i, c.i, bgCol.i, fgCol.i)
  lcd128x64puts(x.i, y.i, *str, bgCol.i, fgCol.i)
  lcd128x64update()
  lcd128x64clear(colour.i)
  lcd128x64setup.i()
  
EndImport


;-Test1 (Blink)
; #ledPin = 0
; 
; wiringPiSetup() ;Initialize wiringPi
; pinMode(#ledPin, #OUTPUT) ;Set the pin mode
; 
; While(1)
;   digitalWrite(#ledPin, #HIGH)
;   Delay(3000)
;   digitalWrite(#ledPin, #LOW)
;   Delay(3000)
; Wend


;-Test2 (Button)
; #ledPin = 0
; #buttonPin = 29
; 
; wiringPiSetup()
; 
; pinMode(#ledPin, #OUTPUT)
; pinMode(#buttonPin, #INPUT)
; 
; pullUpDnControl(#buttonPin, #PUD_UP)
; 
; While(1)
;   If(digitalRead(#buttonPin) = #LOW)
;     digitalWrite(#ledPin, #HIGH)
;   Else
;     digitalWrite(#ledPin, #LOW)
;   EndIf
; Wend


;-Test3 (Thread-Test)
; #LED = 0
; 
; Procedure PI_THREAD(blinky)
;   Repeat
;     digitalWrite(#LED, #HIGH) ;On
;     Delay(1000)
;     digitalWrite(#LED, #LOW) ;Off
;     Delay(1000)
;   ForEver
; EndProcedure
;   
; wiringPiSetup()
; 
; pinMode(#LED, #OUTPUT)
; 
; CreateThread(@PI_THREAD(), 0)
; 
; Repeat
;   Debug("Blink!")
; ForEver


;-Test4 (RGB-LED)
; #ledPinRed = 21
; #ledPinGreen = 22
; #ledPinBlue = 23
; 
; #MaxV = 100
; 
; Procedure setupLedPin()
;   softPwmCreate(#ledPinRed, 0, #MaxV) ;Creat SoftPWM pin for red
;   softPwmCreate(#ledPinGreen, 0, #MaxV) ;Creat SoftPWM pin for green
;   softPwmCreate(#ledPinBlue, 0, #MaxV) ;Creat SoftPWM pin for blue
; EndProcedure
; 
; ;VCC or GND - HIGH or LOW ?
; Procedure setLedColor(r.i, g.i, b.i)
;   softPwmWrite(#ledPinRed, (r*-1)+#MaxV) ;Set the duty cycle
;   softPwmWrite(#ledPinGreen, (g*-1)+#MaxV) ;Set the duty cycle 
;   softPwmWrite(#ledPinBlue, (b*-1)+#MaxV) ;Set the duty cycle
; EndProcedure
; 
; 
; Define.i r,g,b
; 
; wiringPiSetup() ;Initialize wiringPi.
; 
; setupLedPin();
; ;While(1)
;   ;r=Random(#MaxV) ;get a random in (0,100)
;   ;g=Random(#MaxV) ;get a random in (0,100)
;   ;b=Random(#MaxV) ;get a random in (0,100)
;   
;   ;setLedColor(r,g,b) ;set random as the duty cycle value 
;   ;Debug("r="+r+" g="+g+" b="+b)
;   
;   setLedColor(#MaxV,0,0) ;red
;   Delay(3000)
;   setLedColor(0,0,0)
;   Delay(1000)
; ;Wend


;-Test5 (Buzzer-Sound)
; #buzzerPin = 7 ;Define the buzzerPin
; #buttonPin = 28 ;Define the buttonPin
; 
; Procedure alertor(pin.i)
; 	Protected.i x
; 	Protected.d sinVal, toneVal
; 	For x=0 To 360 ;frequency of the alertor is consistent With the sine wave 
; 		sinVal = Sin(x * (#PI / 180)) ;Calculate the sine value
; 		toneVal = 2000 + sinVal * 500 ;Add the resonant frequency and weighted sine value 
; 		softToneWrite(pin,toneVal) ;output corresponding PWM
; 		Delay(1)
; 	Next
; EndProcedure
; 	
; Procedure stopAlertor(pin.i)
; 	softToneWrite(pin, 0)
; EndProcedure
; 
; 
; wiringPiSetup();
; 	
; pinMode(#buzzerPin, #OUTPUT) 
; pinMode(#buttonPin, #INPUT)
; softToneCreate(#buzzerPin) ;set buzzerPin
; pullUpDnControl(#buttonPin, #PUD_UP) ;pull up to HIGH level
; 
; While(1)
;   If(digitalRead(#buttonPin) = #LOW) ;button is pressed
; 	  alertor(#buzzerPin) ;turn on buzzer
; 		Debug("alertor turned on")
; 	Else ;button is released 
; 	  stopAlertor(#buzzerPin) ;turn off buzzer
; 		Debug("alertor turned off")
; 	EndIf
; Wend


;-Test6 (Relay)
; #relayPin = 26 ;Define the relayPin
; #buttonPin =	27 ;Define the buttonPin
; relayState.i = #LOW ;store the State of relay
; buttonState.i = #HIGH ;store the State of button
; lastbuttonState = #HIGH ;store the lastState of button
; lastChangeTime.i ;store the change time of button state
; captureTime.i = 50 ;set the button state stable time
; reading.i
; 
; wiringPiSetup()	
; 	
; pinMode(#relayPin, #OUTPUT) 
; pinMode(#buttonPin, #INPUT)
; pullUpDnControl(#buttonPin, #PUD_UP) ;pull up to high level
; While(1)
;   reading = digitalRead(#buttonPin) ;read the current state of button
; 	If(reading <> lastbuttonState) ;If the button state changed ,record the time point
; 	  lastChangeTime = millis()
; 	  Debug lastChangeTime
; 	EndIf
; 	;If changing-state of the button last beyond the time we set,we considered that 
; 	;the current button state is an effective change rather than a buffeting
; 	If(millis() - lastChangeTime > captureTime)
; 	  ;If button state is changed, update the Data.
; 		If(reading <> buttonState)
; 		  buttonState = reading
; 			;If the state is low, the action is pressing.
; 			If(buttonState = #LOW)
; 			  Debug("Button is pressed!")
; 				If Not(relayState)
; 				  Debug("turn on relay")
; 				  relayState = #HIGH
; 				Else
; 				  Debug("turn off relay")
; 				  relayState = #LOW
; 				EndIf
; 				;If the state is high, the action is releasing.
; 		  Else
; 			  Debug("Button is released!")
; 			EndIf 
; 		EndIf
; 	EndIf
; 	digitalWrite(#relayPin, relayState)
; 	lastbuttonState = reading
; Wend


;-Test7 (Servo)
; #OFFSET_MS = 3 ;Define the unit of servo pulse offset: 0.1ms
; #SERVO_MIN_MS = 5+#OFFSET_MS ;Define the pulse duration For minimum angle of servo
; #SERVO_MAX_MS = 25+#OFFSET_MS ;Define the pulse duration For maximum angle of servo
; 
; #servoPin = 1 ;Define the GPIO number connected To servo
; Procedure.i CMap(value.i, fromLow.i, fromHigh.i, toLow.i, toHigh.i)
;   ProcedureReturn (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
; EndProcedure
;     
; Procedure servoInit(pin.i) ;initialization function For servo PWM pin
;     softPwmCreate(pin, 0, 200)
; EndProcedure
;     
; Procedure servoWrite(pin.i, angle.i)  ;Specific a certain rotation angle (0-180) For the servo
;     If(angle > 180)
;       angle = 180
;     ElseIf(angle < 0)
;       angle = 0
;     EndIf
;     softPwmWrite(pin, CMap(angle,0,180,#SERVO_MIN_MS,#SERVO_MAX_MS));   
; EndProcedure
;     
; Procedure servoWriteMS(pin.i, ms.i) ;specific the unit For pulse(5-25ms) With specific duration output by servo pin: 0.1ms
;   If(ms > #SERVO_MAX_MS)
;     ms = #SERVO_MAX_MS
;   ElseIf(ms < #SERVO_MIN_MS)
;     ms = #SERVO_MIN_MS
;   EndIf
;   softPwmWrite(pin, ms)
; EndProcedure
; 
; 
; Define.i i
; 
; wiringPiSetup()    
; servoInit(#servoPin) ;initialize PWM pin of servo
; 
; While(1)
;   For i = #SERVO_MIN_MS To #SERVO_MAX_MS ;make servo rotate from minimum angle to maximum angle
;     servoWriteMS(#servoPin, i)
;     Delay(10)
;   Next
;   Delay(500)
;   For i = #SERVO_MAX_MS To #SERVO_MIN_MS Step -1;make servo rotate from maximum angle to minimum angle
;     servoWriteMS(#servoPin, i)
;     Delay(10)
;   Next
;   Delay(500)
; Wend


;-Test8 (Stepper)
; Global Dim motorPins.i(3) ;define pins connected to four phase ABCD of stepper motor 
; motorPins(0) = 21
; motorPins(1) = 22
; motorPins(2) = 23
; motorPins(3) = 24
; 
; Global Dim CCWStep.i(3) ;Define power supply order For coil For rotating anticlockwise
; CCWStep(0) = $01
; CCWStep(1) = $02
; CCWStep(2) = $04
; CCWStep(3) = $08
; 
; Global Dim CWStep.i(3) ;define power supply order for coil for rotating clockwise
; CCWStep(0) = $08
; CCWStep(1) = $04
; CCWStep(2) = $02
; CCWStep(3) = $01
; 
; ;As For four phase stepping motor, four steps is a cycle. the function is used To drive the stepping motor clockwise Or anticlockwise To take four steps
; Procedure moveOnePeriod(dir.i, ms.i)
;   Protected.i i=0,j=0
;   For j = 0 To 3 ;cycle according To power supply order 
;     For i = 0 To 3 ;assign To each pin, a total of 4 pins
;       If(dir = 1)  ;power supply order clockwise
;         digitalWrite(motorPins(i), Bool(CCWStep(j) = (1<<i)))
;       Else ;power supply order anticlockwise
;         digitalWrite(motorPins(i), Bool(CWStep(j) = (1<<i)))
;       EndIf
;       Debug("motorPin "+Str(motorPins(i))+": "+Str(digitalRead(motorPins(i))))
;     Next
;     Debug("Step cycle!")
;     If(ms < 3) ;the delay can Not be less than 3ms, otherwise it will exceed speed limit of the motor
;       ms = 3
;     EndIf
;     Delay(ms)
;   Next
; EndProcedure
; 
; ;continuous rotation function, the parameter steps specifies the rotation cycles, every four steps is a cycle
; Procedure moveSteps(dir.i, ms.i, steps.i)
;   Protected.i i
;   For i = 0 To steps
;     moveOnePeriod(dir, ms)
;   Next
; EndProcedure
; 
; Procedure motorStop() ;function used To stop rotating
;   Protected.i i
;   For i = 0 To 3
;     digitalWrite(motorPins(i), #LOW)
;   Next   
; EndProcedure
;   
; 
; Define.i c
; 
; wiringPiSetup();
;     
; For c = 0 To 3
;   pinMode(motorPins(c), #OUTPUT)
; Next
; 
; While(1)
;   moveSteps(1, 3, 512) ;rotating 360° clockwise, a total of 2048 steps in a circle, namely, 512 cycles.
;   Delay(500)
;   moveSteps(0, 3, 512) ;rotating 360° anticlockwise
;   Delay(500)
; Wend


;-Test9 (FlowingLight)
; #dataPin = 3 ;DS Pin of 74HC595(Pin14)
; #latchPin = 2 ;ST_CP Pin of 74HC595(Pin12)
; #clockPin = 0 ;CH_CP Pin of 74HC595(Pin11)
; 
; Procedure _shiftOut(dPin.i, cPin.i, order.i, val.i)   
;   Protected.i i  
;   For i = 0 To 9
;     digitalWrite(cPin, #LOW);
;     If(order = #LSBFIRST)
;       digitalWrite(dPin, Bool(($01 & (val>>i)) = $01))
;       delayMicroseconds(10)
; 		Else
;       digitalWrite(dPin, Bool(($80 & (val<<i)) = $80))
;       delayMicroseconds(10)
; 		EndIf
;     digitalWrite(cPin, #HIGH)
;     delayMicroseconds(10)
; 	Next
; EndProcedure
; 
; 
; Define.i c, x
; 
; wiringPiSetup();
; 	
; pinMode(#dataPin, #OUTPUT)
; pinMode(#latchPin, #OUTPUT)
; pinMode(clockPin, #OUTPUT)
; While(1)
;   x = $0001
; 	For c = 0 To 9
; 	  digitalWrite(#latchPin, #LOW) ;Output low level to latchPin
; 		_shiftOut(#dataPin, #clockPin, #LSBFIRST, x) ;Send serial data to 74HC595
; 		digitalWrite(#latchPin, #HIGH) ;Output high level to latchPin, and 74HC595 will update the data to the parallel output port.
; 		x<<1 ;make the variable move one bit to left once, then the bright LED move one step to the left once.
; 		Delay(100)
; 	Next
; 	x = $0200
; 	For c = 0 To 9
; 	  digitalWrite(#latchPin, #LOW)
; 		_shiftOut(#dataPin, #clockPin, #LSBFIRST, x)
; 		digitalWrite(#latchPin, #HIGH)
; 		x>>1
; 		Delay(100)
; 	Next
; Wend


;-Test10 (StopWatch)
; #dataPin = 3 ;DS Pin of 74HC595(Pin14)
; #latchPin = 2 ;ST_CP Pin of 74HC595(Pin12)
; #clockPin = 0 ;CH_CP Pin of 74HC595(Pin11)
; 
; Global quit.i = #False
; Global CounterThread.i
; 
; ;character 0-9 code of common anode 7-segment display 
; Global Dim num.i(9)
; num(0) = $c0
; num(1) = $f9
; num(2) = $a4
; num(3) = $b0
; num(4) = $99
; num(5) = $92
; num(6) = $82
; num(7) = $f8
; num(8) = $80
; num(9) = $90
; 
; Global counter.i = 10 ;variable counter,the number will be displayed by 7-segment display
; 
; ;Open one of the 7-segment display And close the remaining three, the parameter digit is optional For 1,2,4,8
; Procedure.i selectDigit(digit.i)  
;   If(digit = $01)
;     ProcedureReturn ($08<<8) 
;   ElseIf(digit = $02)
;     ProcedureReturn ($04<<8) 
;   ElseIf(digit = $04)
;     ProcedureReturn ($02<<8)
;   ElseIf(digit = $08)
;     ProcedureReturn ($01<<8) 
;   Else
;     ProcedureReturn ($f0<<8)
;   EndIf
; EndProcedure
;       
; Procedure _shiftOut(dPin.i, cPin.i, order.i, val.i)   
;   Protected.i i  
;   For i = 0 To 15
;     digitalWrite(cPin, #LOW)
;     If(order = #LSBFIRST)
;       digitalWrite(dPin, Bool(($01 & (val>>i)) = $01))
;       delayMicroseconds(1)
; 		Else ;If(order = #MSBFIRST)
;       digitalWrite(dPin, Bool(($8000 & (val<<i)) = $8000))
;       delayMicroseconds(1)
; 		EndIf
;       digitalWrite(cPin, #HIGH)
;       delayMicroseconds(1)
; 	Next
; EndProcedure
; 	
; Procedure outData(cData.i) ;function used To output Data For 74HC595
;   digitalWrite(#latchPin, #LOW)
;   _shiftOut(#dataPin, #clockPin, #MSBFIRST, cData)
;   digitalWrite(#latchPin, #HIGH)
; EndProcedure
;     
; Procedure display(dec.i) ;display function For 7-segment display
;   Protected.i delays = 1, digit
; 	outData($ffff)	
;   digit = selectDigit($01) ;select the first, and display the single digit
;   outData(num(dec%10)|digit)   
;   Delay(delays) ;display duration
;     
;   outData($ffff)    
;   digit = selectDigit($02) ;select the second, and display the tens digit
;   outData(num(dec%100/10)|digit)
;   Delay(delays)
;     
;   outData($ffff)    
;   digit = selectDigit($04) ;select the third, and display the hundreds digit
;   outData(num(dec%1000/100)|digit)
;   Delay(delays)
;     
;   outData($ffff);    
;   digit = selectDigit($08) ;select the fourth, and display the thousands digit
;   outData(num(dec%10000/1000)|digit)
;   Delay(delays)
; EndProcedure
;   
; Procedure Timer(*val)
;   Repeat
;     Delay(1000)
;     counter-1
;   Until counter = 0
;   quit = #True
;   ProcedureReturn
; EndProcedure
;     
; wiringPiSetup();
;     
; pinMode(#dataPin, #OUTPUT) ;set the pin connected to74HC595 for output mode
; pinMode(#latchPin, #OUTPUT)
; pinMode(#clockPin, #OUTPUT)
; 
; CounterThread = CreateThread(@Timer(), 0)
; 
; Repeat
;   display(counter) ;display the number counter
; Until quit
; If IsThread(CounterThread)
;   KillThread(CounterThread)
; EndIf
; End


;-Test11 (LED-Matrix)
; #dataPin = 3 ;DS Pin of 74HC595(Pin14)
; #latchPin = 2;ST_CP Pin of 74HC595(Pin12)
; #clockPin = 0;SH_CP Pin of 74HC595(Pin11)
; 
; ;Data of smile face
; DataSection
;   smile_start:    
;   Data.i $1c,$22,$51,$45,$45,$51,$22,$1c
;   smile_end:
;   pictures_start:
;   Data.i $00, $00, $00, $00, $00, $00, $00, $00 ;" "
;   Data.i $00, $00, $3E, $41, $41, $3E, $00, $00 ;"0"
;   Data.i $00, $00, $21, $7F, $01, $00, $00, $00 ;"1"
;   Data.i $00, $00, $23, $45, $49, $31, $00, $00 ;"2"
;   Data.i $00, $00, $22, $49, $49, $36, $00, $00 ;"3"
;   Data.i $00, $00, $0E, $32, $7F, $02, $00, $00 ;"4"
;   Data.i $00, $00, $79, $49, $49, $46, $00, $00 ;"5"
;   Data.i $00, $00, $3E, $49, $49, $26, $00, $00 ;"6"
;   Data.i $00, $00, $60, $47, $48, $70, $00, $00 ;"7"
;   Data.i $00, $00, $36, $49, $49, $36, $00, $00 ;"8"
;   Data.i $00, $00, $32, $49, $49, $3E, $00, $00 ;"9"  
;   Data.i $00, $00, $3F, $44, $44, $3F, $00, $00 ;"A"
;   Data.i $00, $00, $7F, $49, $49, $36, $00, $00 ;"B"
;   Data.i $00, $00, $3E, $41, $41, $22, $00, $00 ;"C"
;   Data.i $00, $00, $7F, $41, $41, $3E, $00, $00 ;"D"
;   Data.i $00, $00, $7F, $49, $49, $41, $00, $00 ;"E"
;   Data.i $00, $00, $7F, $48, $48, $40, $00, $00 ;"F"
;   Data.i $00, $00, $00, $00, $00, $00, $00, $00 ;" "
;   pictures_end:
; EndDataSection
; 
; 
; Procedure LoadArray(Array this.i(1), *addr_start, *addr_end)
;   *start.integer = *addr_start
;   i=0
;   While *start < *addr_end
;     this(i) = *start\i
;     *start+SizeOf(integer)
;     i+1
;   Wend
; EndProcedure
; 
; 
; Global Dim smile.i(7)
; Global Dim pictures.i(143)
; 
; LoadArray(smile(), ?smile_start, ?smile_end)
; LoadArray(pictures(), ?pictures_start, ?pictures_end)
; 
; 
; Procedure _shiftOut(dPin.i, cPin.i, order.i, val.i)   
;   Protected.i i  
;   For i = 0 To 7
;     digitalWrite(cPin, #LOW)
;     If(order = #LSBFIRST)
;       digitalWrite(dPin, Bool(($01 & (val>>i)) = $01))
;       delayMicroseconds(10)
;     Else ;If(order == MSBFIRST)
;       digitalWrite(dPin, Bool(($80 & (val<<i)) = $80))
;       delayMicroseconds(10)
;     EndIf
;     digitalWrite(cPin, #HIGH)
;     delayMicroseconds(10)
;   Next
; EndProcedure
; 
; 
; Global.i i, j, k, x
; 
; wiringPiSetup();
; 
; pinMode(#dataPin, #OUTPUT)
; pinMode(#latchPin, #OUTPUT)
; pinMode(#clockPin, #OUTPUT)
; While(1)
;   For j = 0 To 499 ;Repeat enough times To display the smiling face a period of time
;     x = $80
;     For i = 0 To 7
;       digitalWrite(#latchPin, #LOW);
;       _shiftOut(#dataPin, #clockPin, #MSBFIRST, smile(i)) ;first shift data of line information to the first stage 74HC959
;       _shiftOut(#dataPin, #clockPin, #MSBFIRST, ~x)       ;then shift data of column information to the second stage 74HC959
;       
;       digitalWrite(#latchPin, #HIGH) ;Output data of two stage 74HC595 at the same time
;       x>>1                           ;display the next column
;       Delay(1)
;     Next
;   Next
;   For k = 0 To (ArraySize(pictures())-8) ;sizeof(data) total number of "0-F" columns 
;     For j = 0 To 19                      ;times of repeated displaying LEDMatrix in every frame, the bigger the “j”, the longer the display time 
;       x = $80                            ;Set the column information to start from the first column
;       For i = k To (7+k)
;         digitalWrite(#latchPin, #LOW)
;         _shiftOut(#dataPin, #clockPin, #MSBFIRST, pictures(i))
;         _shiftOut(#dataPin, #clockPin, #MSBFIRST, ~x)
;         digitalWrite(#latchPin, #HIGH)
;         x>>1
;         Delay(1)
;       Next
;     Next
;   Next
; Wend


;-Test12 (LCD-Display)

;Enable i2c-Bus:

;sudo raspi-config
;lsmod | grep i2c
;sudo apt-get install i2c-tools
;i2cdetect -y 1


; Global.i pcf8574_address = $27 ;PCF8574T:0x27, PCF8574AT:0x3F
; #BASE = 64                     ;BASE any number above 64
;                                ;Define the output pins of the PCF8574, which are directly connected To the LCD1602 pin.
; #_RS = #BASE+0
; #_RW = #BASE+1
; #_EN = #BASE+2
; #LED = #BASE+3
; #D4 = #BASE+4
; #D5 = #BASE+5
; #D6 = #BASE+6
; #D7 = #BASE+7
; 
; Global.i lcdhd ;used to handle LCD
; 
; Procedure printCPUTemperature() ;sub function used To print CPU temperature
;                                 ;Protected.i fp = 0
;   Protected str_temp.s{15}
;   Protected.f CPU_temp
;   ;CPU temperature Data is stored in this directory.
;   If ReadFile(0, "/sys/class/thermal/thermal_zone0/temp")
;     str_temp = ReadString(0, #PB_UTF8, 15)
;     CPU_temp = ValF(str_temp)/1000.0 ;convert to Celsius degrees
;     Debug("CPU's temperature: "+StrF(CPU_temp,2)+"^C")
;     lcdPosition(lcdhd, 0, 0) ;set the LCD cursor position to (0,0) 
;     lcdPrintf(lcdhd, UTF8("CPU: "+StrF(CPU_temp,2)+"^C")) ;Display CPU temperature on LCD
;     CloseFile(0)
;   EndIf
; EndProcedure
; 
; Procedure printDataTime() ;used To print system time 
;   lcdPosition(lcdhd, 0, 1);set the LCD cursor position to (0,1) 
;   lcdPrintf(lcdhd, UTF8(Str(Hour(Date()))+":"+Str(Minute(Date()))+":"+Str(Second(Date()))+" clock")) ;Display system time on LCD
; EndProcedure
; 
; Procedure.i detectI2C(addr.i)
;   Protected.i _fd
;   _fd = wiringPiI2CSetup(addr)   
;   If(_fd < 0)		
;     Debug("Error address: "+Str(addr))
;     ProcedureReturn 0 
;   Else	
;     If(wiringPiI2CWrite(_fd, 0) < 0)
;       Debug("Not found device in address: "+Str(addr))
;       ProcedureReturn 0
;     Else
;       Debug("Found device in address: "+Str(addr))
;       ProcedureReturn 1
;     EndIf
;   EndIf
; EndProcedure
; 
; Global.i c
; 
; wiringPiSetup()
; 
; If(detectI2C($27))
;   pcf8574_address = $27
; ElseIf(detectI2C($3F))
;   pcf8574_address = $3F
; Else
;   Debug(~"No correct I2C address found, \nPlease use command 'i2cdetect -y 1' To check the I2C address! \nProgram Exit. \n")
;   End
; EndIf
; pcf8574Setup(#BASE, pcf8574_address) ;initialize PCF8574
; For c = 0 To 7
;   pinMode(#BASE+c, #OUTPUT) ;set PCF8574 port to output mode
; Next 
; digitalWrite(#LED, #HIGH) ;turn on LCD backlight
; digitalWrite(#_RW, #LOW)  ;allow writing to LCD
; lcdhd = lcdInit(2,16,4,#_RS,#_EN,#D4,#D5,#D6,#D7,0,0,0,0) ;initialize LCD and return “handle” used to handle LCD
; If(lcdhd = -1)
;   Debug("lcdInit failed !")
;   End
; EndIf 
; While(1)
;   printCPUTemperature() ;print CPU temperature
;   printDataTime()       ;print system time
;   Delay(1000)
; Wend


;-Test13 (Analog-Read)

; Global.i address = 0
; Global.i cmd = $40
; Global.i _fd
; 
; ;wiringPiSetup() ;Initialize wiringPi.
; 
; Procedure.i detectI2C(addr.i)
;   _fd = wiringPiI2CSetup(addr)   
;   If (_fd < 0)	
;     Debug("Error address: "+Str(addr))
;     ProcedureReturn 0 
;   Else
;     If(wiringPiI2CWrite(_fd, 0) < 0)
;       Debug("Not found device in address: "+Str(addr))
;       ProcedureReturn 0
;     Else
;       Debug("Found device in address: "+Str(addr))
;       ProcedureReturn 1
;     EndIf
;   EndIf 
; EndProcedure
; 
; Procedure PCF8591_init(addr.i)
;   address = addr
;   cmd = $40 ;The default command for PCF8591 is 0x40.
;   wiringPiSetup()
;   detectI2C(address);
;   Debug("PCF8591 setup successful!")
; EndProcedure
; 
; Procedure.i PCF8591_analogRead(chn.i)
;   wiringPiI2CWrite(_fd, cmd+chn)
;   wiringPiI2CRead(_fd)
;   wiringPiI2CWrite(_fd, cmd+chn)
;   ProcedureReturn wiringPiI2CRead(_fd)
; EndProcedure
; 
; Procedure.i PCF8591_analogWrite(value.i)
;   ProcedureReturn wiringPiI2CWriteReg8(_fd, cmd, value)
; EndProcedure
; 
; Procedure ADS7830_init(addr.i)
;   address = addr
;   cmd = $84
;   wiringPiSetup()
;   detectI2C(address)
;   Debug("ADS7830 setup successful!")
; EndProcedure
; 
; Procedure.i ADS7830_analogRead(chn.i)
;   wiringPiI2CWrite(_fd, cmd|(((chn<<2 | chn>>1) & $07)<<4))
;   ProcedureReturn wiringPiI2CRead(_fd)
; EndProcedure
; 
; ;Testing: (Read Temperature)
; ;Debug detectI2C($48)
; 
; If(detectI2C($48)) ;Detect the ads7830
;   ADS7830_init($48);If detected, create an instance of ADS7830.
; Else
;   Debug(~"No correct I2C address found\nPlease use command 'i2cdetect -y 1' To check the I2C address! \nProgram Exit. \n")
;   End
; EndIf
; 
; Global.i adcValue
; Global.f voltage, Rt, tempK, tempC
; 
; While(1)
;   adcValue = ADS7830_analogRead(0) ;read analog value A0 pin
;   voltage = adcValue / 255.0 * 5.0 ;calculate voltage    
;   Rt = 10 * voltage / (5.0 - voltage) ;calculate resistance value of thermistor
;   tempK = 1/(1/(273.15 + 25) + Log(Rt/10)/3950.0) ;calculate temperature (Kelvin)
;   tempC = tempK -273.15                           ;calculate temperature (Celsius)
;   Debug("ADC value: "+Str(adcValue)+~"\nVoltage: "+StrF(voltage, 2)+~"V\nTemperature: "+StrF(tempC, 2)+"^C")
;   Delay(100)
; Wend

;-Test14 (UniPi-Relais-Test -'Running light')
;mcp23008.h (UniPi,..)
; #_PIN_BASE = 100
; #_ADDRESS = $20
; 
; Global.i count = #_PIN_BASE
; 
; wiringPiSetup()
; mcp23008Setup(#_PIN_BASE, #_ADDRESS)
;   
; For i = 0 To 7
;   pinMode(count, #OUTPUT)
;   count = count + 1
; Next
; 
; count = #_PIN_BASE
; 
; For i = 0 To 7
;   digitalWrite(count, 1)
;   count = count + 1
;   Delay(1000)
; Next
; 
; Delay(2000)
; 
; count = #_PIN_BASE
; 
; For i = 0 To 7
;   digitalWrite(count, 0)
;   count = count + 1
;   Delay(1000)
; Next
; 
; Delay(1000)
; End


;-Test15 (UltrasonicRanging)

; #TRIG = 15
; #ECHO = 16
; 
; Procedure setup()
;   wiringPiSetup()
;   pinMode(#TRIG, #OUTPUT)
;   pinMode(#ECHO, #INPUT)
;   
;   ;TRIG pin must start LOW
;   digitalWrite(#TRIG, #LOW)
;   Delay(30)
; EndProcedure
; 
; Procedure.d getCM()
;   Protected.i startTime, travelTime
;   ;Protected.d distance
;   ;Send trig pulse
;   digitalWrite(#TRIG, #HIGH)
;   Delay(20)
;   digitalWrite(#TRIG, #LOW)
;   
;   ;Wait For echo start
;   While(digitalRead(#ECHO) = #LOW):Wend
;   ;Wait For echo End
;   startTime = micros()
;   While(digitalRead(#ECHO) = #HIGH):Wend
;   travelTime = micros() - startTime
;   
;   ;Get distance in cm
;   ProcedureReturn travelTime / 58
; EndProcedure
; 
; ;main
; setup()
; 
; Debug("Distance: " + StrD(getCM(), 2) + "cm")


;-Test16 (lcd128x64) ;no tested

; Global.d clockRadius, thickness, barLen
; Global.i maxX, maxY
; 
; Procedure rads.d(degs.d)
;   ProcedureReturn degs * #PI / 180.0
; EndProcedure
; 
; Procedure drawClockHands()
;   Protected.i now = Date()
;   Protected.d angle, p, x0, y0, x1, y1
;   Protected.i h24, h, m, s
;   Protected text.s{20}
; 
;   h24 = Hour(now)
;   m   = Minute(now)
;   s   = Second(now)
; 
;   h = h24
;   If(h > 12)
;     h - 12
;   EndIf
;   
;   ;Hour hand
; 
;   angle = h * 30 + m * 0.5
;   x0 = Sin(rads(angle)) * (clockRadius * 0.75)
;   y0 = Cos(rads(angle)) * (clockRadius * 0.75)
;   For p = -3.0 To 3.0 Step 0.2
;     x1 = Sin(rads(angle + p)) * (clockRadius * 0.7)
;     y1 = Cos(rads(angle + p)) * (clockRadius * 0.7)
;     lcd128x64line(0, 0, x1, y1, 1)
;     lcd128x64lineTo(x0, y0, 1)
;   Next
; 
;   ;Minute hand
; 
;   angle = m * 6
;   x0 = Sin(rads(angle)) * (clockRadius * 0.9)
;   y0 = Cos(rads(angle)) * (clockRadius * 0.9)
;   For p = -1.0 To 1.0 Step 0.2
;     x1 = Sin(rads(angle + p)) * (clockRadius * 0.85)
;     y1 = Cos(rads(angle + p)) * (clockRadius * 0.85)
;     lcd128x64line(0, 0, x1, y1, 1)
;     lcd128x64lineTo(x0, y0, 1)
;   Next
; 
;   ;Second hand
; 
;   angle = s * 6
;   x0 = Sin(rads (angle)) * (clockRadius * 0.2)
;   y0 = Cos(rads (angle)) * (clockRadius * 0.2)
;   x1 = Sin(rads (angle)) * (clockRadius * 0.95)
;   y1 = Cos(rads (angle)) * (clockRadius * 0.95)
;   lcd128x64line(0 - x0, 0 - y0, x1, y1, 1)
;   lcd128x64circle(0, 0, clockRadius * 0.1,  0, 1)
;   lcd128x64circle(0, 0, clockRadius * 0.05, 1, 1)
; 
;   ;Text:
; 
;   text = Str(h24) +":"+ Str(m) +":"+ Str(s))
;   lcd128x64puts(32, 24, text, 0, 1)
; 
;   text = Str(Day(now))+"."+Str(Month(now+1))+"."+Str(Year(now-100))
;   lcd128x64puts(32, -23, text, 0, 1)
; EndProcedure
; 
; Procedure drawClockFace()
;   Protected.i m
;   Protected.d d, px1, py1, px2, py2
; 
;   lcd128x64clear(0)
;   lcd128x64circle(0,0, clockRadius, 1, #True)
;   lcd128x64circle(0,0, clockRadius - thickness, 0, #True)
; 
;   ;The four big indicators For 12,15,30 And 45
; 
;   lcd128x64rectangle(- 3,  clockRadius - barLen, 3,  clockRadius, 1, #True) ;12
;   lcd128x64rectangle(clockRadius - barLen, 3,  clockRadius, -3, 1, #True) ;3
;   lcd128x64rectangle(- 3, -clockRadius + barLen, 3, -clockRadius, 1, #True) ;6
;   lcd128x64rectangle(-clockRadius + barLen, 3, -clockRadius, -3, 1, #True) ;9
; 
;   ;Smaller 5 And 1 minute ticks
;   
;   For m = 0 To 59
;     px1 = Sin(rads(m * 6)) * clockRadius
;     py1 = Cos(rads(m * 6)) * clockRadius
;     If ((m % 5) = 0)
;       d = barLen
;     Else 
;       d = barLen / 2.0
;     EndIf
;     px2 = Sin(rads(m * 6)) * (clockRadius - d)
;     py2 = Cos(rads(m * 6)) * (clockRadius - d)
;     lcd128x64line(px1, py1, px2, py2, 1)
;   Next
; EndProcedure
; 
; Procedure setup()
;   lcd128x64getScreenSize(@maxX, @maxY)
;   clockRadius = maxY / 2 - 1
;   thickness = maxX / 48
;   barLen = thickness * 4
;   lcd128x64setOrigin(32, 32)
; EndProcedure
; 
; ;***********************************************************************
; ;The main program
; ;***********************************************************************
; 
; Global.i now = Date() 
; 
; wiringPiSetup()
; 
; lcd128x64setup()
; 
; setup()
; 
; Repeat
;   drawClockFace()
;   drawClockHands()
;   lcd128x64update()
; Until Date() = now


;-Test17 (Keypad)

;MatrixKeypad
; #ROWS = 3 ;rows
; #COLS = 3 ;columns
; 
; Global.b pressedKey = 0
; 
; DataSection
;   keys:
;   keys_start: 
;   Data.b '1','2','3','A'
;   Data.b '4','5','6','B'
;   Data.b '7','8','9','C'
;   Data.b '*','0','#','D'
;   keys_end:
;   rowPins:
;   rowPins_start:
;   Data.b 27,28,29,25
;   rowPins_end:
;   colPins:
;   colPins_start:
;   Data.b 24,23,22,21
;   colPins_end:
; EndDataSection
; 
; Global Dim keys.b(#ROWS, #COLS)
; CopyMemory(?keys, @keys(), ?keys_end - ?keys_start)
; 
; Global Dim rowPins.b(#ROWS) ;define the row pins for the keypad
; CopyMemory(?rowPins, @rowPins(), ?rowPins_end - ?rowPins_start)
; 
; Global Dim colPins.b(#COLS) ;define the column pins for the keypad
; CopyMemory(?colPins, @colPins(), ?colPins_end - ?colPins_start)
; 
; 
; Procedure init_keypad()
;   Protected.i c, r
;   For c = 0 To #COLS
;     pinMode(colPins(c), #OUTPUT)   
;     digitalWrite(colPins(c), #HIGH)
;   Next
;   
;   For r = 0 To #ROWS
;     pinMode(rowPins(0), #INPUT)   
;     pullUpDnControl(rowPins(r), #PUD_UP)
;   Next
; EndProcedure
; 
; Procedure.i findLowRow()
;   Protected.i r
;   For r = 0 To #ROWS
;     If (digitalRead(rowPins(r)) = #LOW)
;       ProcedureReturn r
;     EndIf
;   Next
;   
;   ProcedureReturn -1
; EndProcedure
; 
; Procedure.i get_key()
;   Protected.i rowIndex
;   
;   For c = 0 To #COLS
;     digitalWrite(colPins(c), #LOW)
;     
;     rowIndex = findLowRow();
;     If (rowIndex > -1)
;       If Not pressedKey
;         pressedKey = keys(rowIndex, c)
;         ProcedureReturn pressedKey
;       EndIf
;     EndIf
;     digitalWrite(colPins(c), #HIGH)
;   Next
;   
;   pressedKey = 0
;   
;   ProcedureReturn pressedKey
; EndProcedure
; 
; ;main
; Global.b k
; 
; wiringPiSetup()
; 
; init_keypad()
; 
; While(1)
;   k = get_key()
;   
;   If k <> 0
;     Debug("pressed: "+Chr(k))
;   Else
;     ;Debug("no key pressed")
;   EndIf
;   Delay(100)
; Wend


;-Test18 (Speed-Test)
; #FAST_COUNT = 10000000
; #SLOW_COUNT = 100000000
; #PASSES = 5
; 
; OpenConsole()
; 
; Procedure speedTest(pin.i, maxCount.i)
;   Protected.i count, sum = 0, perSec, i, start, quit
; 
;   For i = 0 To #PASSES-1
;     start = millis()
;     For count = 0 To maxCount
;       digitalWrite(pin, 1) 
;     Next
;     quit = millis()
;     PrintN(Str(quit - start))
;     sum = sum + (quit - start)
;   Next
; 
;   digitalWrite(pin, 0)
; EndProcedure
; 
; PrintN("Raspberry Pi wiringPi GPIO speed test program")
; PrintN("=============================================")
; 
; ;Start the standard way
; 
; PrintN("Native wiringPi method: "+Str(#FAST_COUNT)+" iterations")
; wiringPiSetup()
; pinMode(0, #OUTPUT)
; speedTest(0, #FAST_COUNT)
; 
; ;GPIO
; 
; PrintN("Native GPIO method: "+Str(#FAST_COUNT)+" iterations")
; wiringPiSetupGpio()
; pinMode(17, #OUTPUT)
; speedTest(17, #FAST_COUNT)
; 
; ;Phys
; 
; PrintN("Physical pin GPIO method: "+Str(#FAST_COUNT)+" iterations")
; wiringPiSetupPhys()
; pinMode(11, #OUTPUT)
; speedTest(11, #FAST_COUNT)
; 
; ;Switch To SYS mode:
; 
; ;system("/usr/local/bin/gpio export 17 out")
; RunProgram("/usr/local/bin/gpio", "export 17 out", "", #PB_Program_Open | #PB_Program_Read)
; PrintN("/sys/class/gpio method: "+Str(#FAST_COUNT)+" iterations (SLOW?)")
; wiringPiSetupSys()
; speedTest(17, #FAST_COUNT)
; 
; CloseConsole()
; End


;-Test19 (1-Wire Digital Temperature Sensor)
; ;ds18b20
; 
; ;sudo modprobe wire 
; ;sudo modprobe w1-gpio 
; ;sudo modprobe w1-therm
; 
; ;sudo nano "/etc/modules
; 
; ;add "w1-gpio" (without quotes)
; ;add "w1-therm" (without quotes)
; 
; ;sudo nano /etc/modprobe.d/1-wire.conf
; ;options wire max_slave_count=20
;
; ;UniPi: (4 wire ds18b20)
; ;edit (above the "exit 0" line):
; ;sudo nano /etc/rc.local
; ;modprobe ds2482
; ;sh -c "echo ds2482 0x18 > /sys/bus/i2c/devices/i2c-1/new_device "
; ;modprobe wire
; ;save(ctrl + o / ctrl + x)
; ;sudo reboot
; 
; wiringPiSetup()
; 
; ;ds18b20Setup(const int pinBase, const char *serialNum)
; 
; #BUFSIZE = 128
; 
; Procedure.f tempRead()
;   Protected.f temp
;   Protected.i i, j, fd, ret
;   Protected.i buf, tempBuf
;   
;   *buf = AllocateMemory(#BUFSIZE)
;   *tempBuf = AllocateMemory(5)
; 
;   If ReadFile(0, "/sys/bus/w1/devices/28-031590bf4aff/w1_slave") ;replace id
;     While Eof(0) = 0
;       ret = ReadData(0, Array *buf, #BUFSIZE)
;     Wend
;     CloseFile(0)
;   Else
;     ProcedureReturn -1
;   EndIf
; 
;   For i=0 To SizeOf(buf)
;     If(PeekC(*buf+i) = 't')
;       For j=0 To SizeOf(tempBuf)
;         ;tempBuf[j] = buf[i+2+j];
;         PokeC(*tempBuf, @buf+(i+2+j))
;       Next
;     EndIf
;    Next
; 
;   temp = PeekF(tempBuf) / 1000
; 
;   ProcedureReturn temp
; EndProcedure
; 
; ;main
; If(wiringPiSetup() = -1)
;   Debug("setup wiringPi failed !")
;   End -1
; EndIf
; 
; Global.f temp
; 
; ;While(1)
; temp = tempRead();
; Debug("Current temperature: " + StrF(temp, 2))
; ;Wend


;-Test20 (Joystick)

; Global.i address = 0
; Global.i cmd = $40
; Global.i _fd
; 
; #Z_Pin = 11 ;Define pin For axis Z
; 
; Procedure.i detectI2C(addr.i)
;   _fd = wiringPiI2CSetup(addr)   
;   If (_fd < 0)	
;     Debug("Error address: "+Str(addr))
;     ProcedureReturn 0 
;   Else
;     If(wiringPiI2CWrite(_fd, 0) < 0)
;       Debug("Not found device in address: "+Str(addr))
;       ProcedureReturn 0
;     Else
;       Debug("Found device in address: "+Str(addr))
;       ProcedureReturn 1
;     EndIf
;   EndIf 
; EndProcedure
; 
; Procedure ADS7830_init(addr.i)
;   address = addr
;   cmd = $84
;   wiringPiSetup()
;   detectI2C(address)
;   Debug("ADS7830 setup successful!")
; EndProcedure
; 
; Procedure.i ADS7830_analogRead(chn.i)
;   wiringPiI2CWrite(_fd, cmd|(((chn<<2 | chn>>1) & $07)<<4))
;   ProcedureReturn wiringPiI2CRead(_fd)
; EndProcedure
; 
; 
; If(detectI2C($48)) ;Detect the ads7830
;   ADS7830_init($48)
; Else
;   Debug(~"No correct I2C address found,\n Please use command 'i2cdetect -y 1' To check the I2C address! \nProgram Exit. \n")
;   End -1
; EndIf
; 
; wiringPiSetup();    
; 
; pinMode(#Z_Pin, #INPUT) ;set Z_Pin as input pin and pull-up mode
; pullUpDnControl(#Z_Pin, #PUD_UP)
; 
; Global.d val_X, val_Y, val_Z
; 
; While(1)
;   val_Z = digitalRead(#Z_Pin) ;read digital value of axis Z
;   val_Y = ADS7830_analogRead(5) ;Read analog value of axis Y
;   val_X = ADS7830_analogRead(6) ;Read analog value of axis X
;   Debug("val_X: "+StrD(val_X))
;   Debug("val_Y: "+StrD(val_Y))
;   Debug("val_Z: "+StrD(val_Z))
;   Delay(100)
; Wend
; 
; End


;-Test21 (Mini DC Motor)

; Global.i address = 0
; Global.i cmd = $40
; Global.i _fd
; 
; #motorPin1 = 16 ;Define the pin connected To L293D
; #motorPin2 = 15
; #enablePin = 3
; 
; ;Map function: Map the value from a range To another range.
; Procedure.i CMap(value.i, fromLow.i, fromHigh.i,toLow.i, toHigh.i)
;   ProcedureReturn (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
; EndProcedure
;   
; ;motor function: determine the direction And speed of the motor according To the ADC 
; Procedure motor(ADC.i)
;   Protected.i value = ADC - 128
;   If(value > 0)
;     Debug CMap(Abs(value), 0, 128, 0, 100)
;     softPwmWrite(#motorPin2, 0)
;     softPwmWrite(#motorPin1, CMap(Abs(value), 0, 128, 0, 100))
;     Debug("turn Forward...")
;   ElseIf(value < 0)
;     softPwmWrite(#motorPin1, 0)
;     softPwmWrite(#motorPin2, CMap(-value, 0, 128, 0, 100))
;     Debug("turn Back...")
;   Else
;     digitalWrite(#motorPin1, #LOW) 
;     digitalWrite(#motorPin2, #LOW)
;     Debug("Motor Stop...")
;   EndIf
;     
;   Debug("The PWM duty cycle is "+StrD(Abs(value)*100/127, 2)) ;print the PWM duty cycle
; EndProcedure
; 
; Procedure.i detectI2C(addr.i)
;   _fd = wiringPiI2CSetup(addr)   
;   If (_fd < 0)	
;     Debug("Error address: "+Str(addr))
;     ProcedureReturn 0 
;   Else
;     If(wiringPiI2CWrite(_fd, 0) < 0)
;       Debug("Not found device in address: "+Str(addr))
;       ProcedureReturn 0
;     Else
;       Debug("Found device in address: "+Str(addr))
;       ProcedureReturn 1
;     EndIf
;   EndIf 
; EndProcedure
; 
; Procedure ADS7830_init(addr.i)
;   address = addr
;   cmd = $84
;   wiringPiSetup()
;   detectI2C(address)
;   Debug("ADS7830 setup successful!")
; EndProcedure
; 
; Procedure.i ADS7830_analogRead(chn.i)
;   wiringPiI2CWrite(_fd, cmd|(((chn<<2 | chn>>1) & $07)<<4))
;   ProcedureReturn wiringPiI2CRead(_fd)
; EndProcedure
;     
; ;main
; If(detectI2C($48)) ;Detect the ads7830
;   ADS7830_init($48)
; Else
;   Debug(~"No correct I2C address found,\nPlease use command 'i2cdetect -y 1' To check the I2C address! \nProgram Exit. \n")
;   End -1
; EndIf
; 
; wiringPiSetup()
; 
; pinMode(#motorPin1, #OUTPUT)
; pinMode(#motorPin2, #OUTPUT)
;     
; softPwmCreate(#motorPin1, 0, 100) ;define PWM pin
; softPwmCreate(#motorPin2, 0, 100) ;define PWM pin
; 
; Global.i value
;     
; While(1)
;   value = ADS7830_analogRead(2) ;read analog value of A0 pin
;   Debug("ADC value: "+Str(value))
;   motor(value) ;make the motor rotate with speed(analog value of A0 pin)
;   Delay(100)
; Wend
; 
; End


;-Test22 (DHT (11)/22 - Digital Temperature Sensor)
  
; ;Read Return flag of sensor
; #DHTLIB_OK = 0
; #DHTLIB_ERROR_CHECKSUM = -1
; #DHTLIB_ERROR_TIMEOUT = -2
; #DHTLIB_INVALID_VALUE = -999
; 
; #DHTLIB_DHT11_WAKEUP = 18
; #DHTLIB_DHT_WAKEUP = 1
; 
; #DHTLIB_TIMEOUT = 100
; 
; Global.d humidity, temperature ;use to store temperature and humidity data read
; Global Dim bits.b(5)  ;Buffer to receiver data
; 
; ;Function: Read DHT sensor, store the original Data in bits[]
; ;Return values:DHTLIB_OK   DHTLIB_ERROR_CHECKSUM  DHTLIB_ERROR_TIMEOUT
; 
; Procedure.i DHT_readSensor(pin.i, wakeupDelay.i)
;   Protected mask = $80, idx = 0, i, t, loopCnt
;   
;   For i = 0 To 4
; 		bits(i) = 0
; 	Next
; 	
; 	pinMode(pin, #OUTPUT)
; 	digitalWrite(pin, #LOW)
; 	Delay(wakeupDelay)
; 	digitalWrite(pin, #HIGH)
; 	delayMicroseconds(40)
; 	pinMode(pin, #INPUT)
; 	
; 	loopCnt = #DHTLIB_TIMEOUT
; 	t = micros()
; 	While(digitalRead(pin) = #LOW)
; 		If((micros() - t) > loopCnt)
; 			ProcedureReturn #DHTLIB_ERROR_TIMEOUT
; 		EndIf
; 	Wend
; 	loopCnt = #DHTLIB_TIMEOUT
; 	t = micros()
; 	While(digitalRead(pin) = #HIGH)
; 		If((micros() - t) > loopCnt)
; 			ProcedureReturn #DHTLIB_ERROR_TIMEOUT
; 		EndIf
; 	Wend
; 	For i = 0 To 39
; 		loopCnt = #DHTLIB_TIMEOUT
; 		t = micros()
; 		While(digitalRead(pin) = #LOW)
; 			If((micros() - t) > loopCnt)
; 			  ProcedureReturn #DHTLIB_ERROR_TIMEOUT
; 			EndIf
; 		Wend
; 		t = micros()
; 		loopCnt = #DHTLIB_TIMEOUT
; 		While(digitalRead(pin) = #HIGH)
; 			If((micros() - t) > loopCnt)
; 				ProcedureReturn #DHTLIB_ERROR_TIMEOUT
; 			EndIf
; 		Wend
; 		If((micros() - t ) > 60)
; 			bits(idx) | mask
; 		EndIf
; 		mask >> 1
; 		If(mask = 0)
; 			mask = $80
; 			idx+1
; 		EndIf
; 	Next
; 	pinMode(pin, #OUTPUT)
; 	digitalWrite(pin, #HIGH)
; 	;printf("bits:\t%d,\t%d,\t%d,\t%d,\t%d\n",bits[0],bits[1],bits[2],bits[3],bits[4]);
; 	ProcedureReturn #DHTLIB_OK;
; EndProcedure
; 
; 
; ;Function:Read DHT sensor, analyze the Data of temperature And humidity
; ;Return:DHTLIB_OK, DHTLIB_ERROR_CHECKSUM, DHTLIB_ERROR_TIMEOUT
; Procedure.i DHT_readDHT11(pin.i)
;   Protected.i rv
; 	Protected.b sum
; 	
; 	rv = DHT_readSensor(pin, #DHTLIB_DHT11_WAKEUP)
; 	If(rv <> #DHTLIB_OK)
; 		humidity = #DHTLIB_INVALID_VALUE
; 		temperature = #DHTLIB_INVALID_VALUE
; 		ProcedureReturn rv
; 	EndIf
; 	humidity = bits(0)
; 	temperature = bits(2) + bits(3) * 0.1
; 	sum = bits(0) + bits(1) + bits(2) + bits(3)
; 	If(bits(4) <> sum)
; 	  ProcedureReturn #DHTLIB_ERROR_CHECKSUM
; 	EndIf
; 	ProcedureReturn #DHTLIB_OK
; EndProcedure
; 	
; ;main
; #DHT11_Pin = 4 ;Define the pin of sensor 
; 
; Global.i chk,sumCnt ;chk:read the return value of sensor; sumCnt:times of reading sensor
;     
; wiringPiSetup()
;     
; While(1)
;   chk = DHT_readDHT11(#DHT11_Pin) ;read DHT11 and get a return value. Then determine whether data read is normal according to the return value.
;   sumCnt+1 ;counting number of reading times
;   Debug("The sumCnt is: "+Str(sumCnt))
;   Select(chk)
;     Case #DHTLIB_OK ;If the Return value is DHTLIB_OK, the Data is normal.
;       Debug("DHT11,OK!") 
;     Case #DHTLIB_ERROR_CHECKSUM ;Data check has errors
;       Debug("DHTLIB_ERROR_CHECKSUM!")
;     Case #DHTLIB_ERROR_TIMEOUT ;reading DHT times out
;       Debug("DHTLIB_ERROR_TIMEOUT!")
;     Case #DHTLIB_INVALID_VALUE ;other errors
;       Debug("DHTLIB_INVALID_VALUE!")
;   EndSelect
;   Debug("Humidity is: "+StrD(humidity,2)+"%, Temperature is: "+StrD(temperature,2)+"*C")
;   Delay(3000)
; Wend


;-Test23 (PT1000 - Analog Resistance thermometer (with UniPi) )

;gpio -x mcp3422:100:0x68:0:0 aread 101

Global.i address = $68
Global.i cmd = $64 ;100

Global.i samplerate = #MCP3422_SR_15
Global.i gain = #MCP3422_GAIN_1

Global.i MaxDigit = 32767 ;16 Bit

;Testing:

;Based on:
;"https://kb.unipi.technology/en:hw:03-unipi11:description-of-io:04-description-of-ai#resistance_measurement"

If Not (mcp3422Setup(cmd, address, samplerate, gain))
  Debug(~"No correct I2C address found\nPlease use command 'i2cdetect -y 1' To check the I2C address! \nProgram Exit. \n")
  End -1
EndIf

#Platin = 0.00391 ;average temperature coefficient

Global.i adcValue, norm_adc
Global.i R_ref = 1200
Global.f voltage, Rt, tempC
Global.f v = 12.0 ;V_max

Select samplerate
  Case #MCP3422_SR_15
    MaxDigit = 32767 ;16 Bit
  Case #MCP3422_SR_60
    MaxDigit = 8191 ;14 Bit
  Case #MCP3422_SR_240
    MaxDigit = 2047 ;12 Bit
EndSelect

;minimum accuracy
Repeat
  adcValue = analogRead(cmd + 1) ;A2-Pin (That's working!)
  norm_adc = (adcValue * -1) + MaxDigit ;analog value correction
  voltage = norm_adc / MaxDigit * v ;calculate the voltage value
  Rt = R_ref * voltage / (v - voltage) ;calculate the resistance value
  tempC = (Rt - 1000) / (1000 * #Platin) ;calculate the temperature value
  Debug("ADC value: "+Str(norm_adc)+~"\nVoltage: "+StrF(voltage, 2)+~"V\nTemperature: "+StrF(tempC, 2)+"^C")
  Delay(3000)
Until tempC >= 30.0


;-Test24 (Button-Events/Interrupt)
;coming soon
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
Benutzeravatar
mpz
Beiträge: 497
Registriert: 14.06.2005 15:53
Computerausstattung: Win 10 Pro, 16 GB Ram, Intel I5 CPU und TI1070 Grafikkarte, PB 5.73 / 6.00 beta4
Wohnort: Berlin, Tempelhof

Re: RaspberryPi@WiringPi

Beitrag von mpz »

Hallo,

ich habe mir vor ein paar Tagen den Pi400 zugelegt und deine Bibliothek ist einfach super! Ich werde ein paar von Deinen Testroutinen am Wochenende mal ausprobieren.

Ich habe aber davor noch eine Frage z.B zu dem ersten Test;

Hier steht:
#ledPin = 0

Ist mit der 0 eine interne LED des Raspi gemeint oder doch ein Pin des GPIO Ports? Wenn ja welcher?
Oder müsste man z.b. den GPIO Port 11 z.B. statt der 0 wählen wenn man den GPIO Port verwenden will?

Gruss Michael
Working on - MP3D Engine -
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: RaspberryPi@WiringPi

Beitrag von ccode_new »

#ledPin = #GPIO_17 ;= 0

Du kannst aber auch einen anderen GPIO-Pin benutzen.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
Benutzeravatar
mk-soft
Beiträge: 3691
Registriert: 24.11.2004 13:12
Wohnort: Germany

Re: RaspberryPi@WiringPi

Beitrag von mk-soft »

Da kann man sehen das es viele verschiedene Libraries für die GPIO gibt.

Nicht vergessen das es auch eine mitgelieferte Standard Library für die GPIO gibt, die nicht erst installiert werden muss.
Mal ins Englische Forum schauen. ;)
Alles ist möglich, fragt sich nur wie...
Projekte ThreadToGUI / EventDesigner V3 / OOP-BaseClass-Modul
Downloads auf MyWebspace / OneDrive
Benutzeravatar
mpz
Beiträge: 497
Registriert: 14.06.2005 15:53
Computerausstattung: Win 10 Pro, 16 GB Ram, Intel I5 CPU und TI1070 Grafikkarte, PB 5.73 / 6.00 beta4
Wohnort: Berlin, Tempelhof

Re: RaspberryPi@WiringPi

Beitrag von mpz »

Hi mk-soft,

welche genau meinst du den, bzw, welcher link?!? Meinst Du PIGPIOD ?

Gruss Michael
Working on - MP3D Engine -
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: RaspberryPi@WiringPi

Beitrag von ccode_new »

Du kannst auch Bash direkt nutzen, aber die wiringPi-Lib ist viel cooler.
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
ccode_new
Beiträge: 1214
Registriert: 27.11.2016 18:13
Wohnort: Erzgebirge

Re: RaspberryPi@WiringPi

Beitrag von ccode_new »

Hinweis für 64bit Raspian:

git clone https://github.com/guation/WiringPi-arm64.git
cd WiringPi-arm64/
./build

oder:

sudo apt install -y gcc-arm-linux-gnueabihf
./build debian
sudo apt install -fy ./debian-template/wiringpi-`cat VERSION`.deb

->Die ursprüngliche Lib ist nur für 32bit !!!
Betriebssysteme: div. Windows, Linux, Unix - Systeme

no Keyboard, press any key
no mouse, you need a cat
Antworten