Is there a way to have a gpio output 1 when two nodes are outputting 1 into it? - raspberry-pi3

I'm working on a security system with my raspberry pi and node-red. I have an infrared sensor outputting 1 when motion is detected, 0 when no motion is detected. I also have a switch with the pallete node-red-dashboard that outputs 1 when it is "open" and 0 when "closed". I want to make a function that would output 1 when both of the inputs are 1, kind of like an and gate. Any help?

There are a number of ways to achieve what you want. Import the flow below and see if it behaves like you want.
Credits to Cory Guyyn
[{"id":"326ee761.191508","type":"tab","label":"Flow 6","disabled":false,"info":""},{"id":"aa420627.bdb3e8","type":"function","z":"326ee761.191508","name":"Flow On/Off","func":"var state = context.get(\"state\") || \"on\";\n\n// Display initial state status\nif(state ==\"on\"){\n node.status({fill:\"green\",shape:\"dot\",text:state});\n}else{\n node.status({fill:\"red\",shape:\"ring\",text:state});\n}\n\nif(msg.topic == \"state\"){\n context.set(\"state\",msg.payload);\n state = msg.payload;\n // update status\n if(state == \"on\"){\n node.status({fill:\"green\",shape:\"dot\",text:state});\n }else{\n node.status({fill:\"red\",shape:\"ring\",text:state});\n }\n}else{\n if(state == \"on\"){\n return msg;\n }\n}\n","outputs":1,"noerr":0,"x":570,"y":340,"wires":[["6968506.c5da8b"]]},{"id":"d1c0dabc.ff33f8","type":"ui_switch","z":"326ee761.191508","name":"","label":"Dynamic Input","group":"efb0cd04.2f1fe","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"state","style":"","onvalue":"on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"off","offvalueType":"str","officon":"","offcolor":"","x":500,"y":240,"wires":[["aa420627.bdb3e8"]]},{"id":"fb35a101.734b3","type":"inject","z":"326ee761.191508","name":"","topic":"state","payload":"on","payloadType":"str","repeat":"","crontab":"","once":true,"x":280,"y":220,"wires":[["d1c0dabc.ff33f8"]]},{"id":"7f455eab.e11b4","type":"inject","z":"326ee761.191508","name":"","topic":"state","payload":"off","payloadType":"str","repeat":"","crontab":"","once":false,"x":270,"y":260,"wires":[["d1c0dabc.ff33f8"]]},{"id":"6968506.c5da8b","type":"debug","z":"326ee761.191508","name":"","active":true,"console":"false","complete":"false","x":750,"y":340,"wires":[]},{"id":"38c4ee82.f54e92","type":"comment","z":"326ee761.191508","name":"Sample Flow Toggle with UI and Link input","info":"","x":300,"y":120,"wires":[]},{"id":"5fb3fc9b.523764","type":"inject","z":"326ee761.191508","name":"PIR - 0","topic":"","payload":"0","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":340,"wires":[["aa420627.bdb3e8"]]},{"id":"a1e5b421.b65e08","type":"inject","z":"326ee761.191508","name":"PIR - 1","topic":"","payload":"1","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":270,"y":380,"wires":[["aa420627.bdb3e8"]]},{"id":"efb0cd04.2f1fe","type":"ui_group","z":"","name":"Flow Toggle","tab":"6dfbaaa8.8cfbb4","disp":true,"width":"6"},{"id":"6dfbaaa8.8cfbb4","type":"ui_tab","z":"","name":"Sandbox","icon":"dashboard"}]

Related

Display images on Tensorboard to have the input, the ground truth and the prediction side by side

I'm working on a deep learning model and I would like to be able to display images on Tensorboard to have the input, the ground truth and the prediction side by side.
Currently, the display look like this :
current display
But this visualization is not convenient, because it's not easy to compare the ground truth with the prediction if images are not side by side, and we have to scroll to pass from the ground truth to the prediction (because images are too big and we display more than 6 images).
The current code :
for epoch in range(EPOCHS):
for step, (x_train, y_train) in enumerate(train_ds):
y_, gloss, dloss = pix2pix.train_step(x_train, y_train, epoch)
if step%PRINT_STEP == 0:
template = 'Epoch {} {}%, G-Loss: {}, D-Loss: {}'
print (template.format(epoch+1,int(100*step/max_steps),gloss, dloss))
with train_writer.as_default():
tf.summary.image('GT', y_train+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.image('pred', y_+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.image('input', x_train+0.5, step=epoch*max_steps+step, max_outputs=3, description=None)
tf.summary.scalar('generator loss', gloss, step = epoch*max_steps+step)
tf.summary.scalar('discriminator loss', dloss, step = epoch*max_steps+step)
tf.summary.flush()
So here is an example that what I would like to have :
desired display
I thought about an other solution : save all triples images(input/truth/pred) in local folders (folders 1 : input 1 /truth 1 /pred 1, folders 2 : input 2 /truth 2 /pred 2 ...) and display them with a python library (cv2, matplotlib ...) but same problem, I don't know how to do that if it's possible.
Thanks for your help

Pinescript duplicate alerts

I have created a very basic script in pinescript.
study(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
rc = close
buy_entry = rc[0] > rc[2]
sell_entry = rc[0] < rc[2]
alertcondition(buy_entry, title='BUY')
alertcondition(sell_entry, title='SELL')
plot(buy_entry/10)
The problem is that I get a lot of duplicate alerts. I want to edit this script so that I only get a 'Buy' alert when the previous alert was a 'Sell' alert and visa versa. It seems like such a simple problem, but I have a hard time finding good sources to learn pinescript. So, any help would be appreciated. :)
One way to solve duplicate alters within the candle is by using "Once Per Bar Close" alert. But for alternative alerts (Buy - Sell) you have to code it with different logic.
I Suggest to use Version 3 (version shown above the study line) than version 1 and 2 and you can accomplish the result by using this logic:
buy_entry = 0.0
sell_entry = 0.0
buy_entry := rc[0] > rc[2] and sell_entry[1] == 0? 2.0 : sell_entry[1] > 0 ? 0.0 : buy_entry[1]
sell_entry := rc[0] < rc[2] and buy_entry[1] == 0 ? 2.0 : buy_entry[1] > 0 ? 0.0 : sell_entry[1]
alertcondition(crossover(buy_entry ,1) , title='BUY' )
alertcondition(crossover(sell_entry ,1), title='SELL')
You'll have to do it this way
if("Your buy condition here")
strategy.entry("Buy Alert",true,1)
if("Your sell condition here")
strategy.entry("Sell Alert",false,1)
This is a very basic form of it but it works.
You were getting duplicate alerts because the conditions were fulfulling more often. But with strategy.entry(), this won't happen
When the sell is triggered, as per paper trading, the quantity sold will be double (one to cut the long position and one to create a short position)
PS :You will have to add code to create alerts and enter this not in study() but strategy()
The simplest solution to this problem is to use the built-in crossover and crossunder functions.
They consider the entire series of in-this-case close values, only returning true the moment they cross rather than every single time a close is lower than the close two candles ago.
//#version=5
indicator(title='Renko Strat w/ Alerts', shorttitle='S_EURUSD_5_[MakisMooz]', overlay=true)
c = close
bool buy_entry = false
bool sell_entry = false
if ta.crossover(c[1], c[3])
buy_entry := true
alert('BUY')
if ta.crossunder(c[1], c[3])
sell_entry := true
alert('SELL')
plotchar(buy_entry, title='BUY', char='B', location=location.belowbar, color=color.green, offset=-1)
plotchar(sell_entry, title='SELL', char='S', location=location.abovebar, color=color.red, offset=-1)
It's important to note why I have changed to the indices to 1 and 3 with an offset of -1 in the plotchar function. This will give the exact same signals as 0 and 2 with no offset.
The difference is that you will only see the character print on the chart when the candle actually closes rather than watch it flicker on and off the chart as the close price of the incomplete candle moves.

Send and Receive operations between communicators in MPI

Following my previous question : Unable to implement MPI_Intercomm_create
The problem of MPI_INTERCOMM_CREATE has been solved. But when I try to implement a basic send receive operations between process 0 of color 0 (globally rank = 0) and process 0 of color 1 (ie globally rank = 2), the code just hangs up after printing received buffer.
the code:
program hello
include 'mpif.h'
implicit none
integer tag,ierr,rank,numtasks,color,new_comm,inter1,inter2
integer sendbuf,recvbuf,tag,stat(MPI_STATUS_SIZE)
tag = 22
sendbuf = 222
call MPI_Init(ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD,rank,ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD,numtasks,ierr)
if (rank < 2) then
color = 0
else
color = 1
end if
call MPI_COMM_SPLIT(MPI_COMM_WORLD,color,rank,new_comm,ierr)
if (color .eq. 0) then
if (rank == 0) print*,' 0 here'
call MPI_INTERCOMM_CREATE(new_comm,0,MPI_Comm_world,2,tag,inter1,ierr)
call mpi_send(sendbuf,1,MPI_INT,2,tag,inter1,ierr)
!local_comm,local leader,peer_comm,remote leader,tag,new,ierr
else if(color .eq. 1) then
if(rank ==2) print*,' 2 here'
call MPI_INTERCOMM_CREATE(new_comm,2,MPI_COMM_WORLD,0,tag,inter2,ierr)
call mpi_recv(recvbuf,1,MPI_INT,0,tag,inter2,stat,ierr)
print*,recvbuf
end if
end
The communication with intercommunication is not well understood by most users, and examples are not as many as examples for other MPI operations. You can find a good explanation by following this link.
Now, there are two things to remember:
1) Communication in an inter communicator always go from one group to the other group. When sending, the rank of the destination is its the local rank in the remote group communicator. When receiving, the rank of the sender is its local rank in the remote group communicator.
2) Point to point communication (MPI_send and MPI_recv family) is between one sender and one receiver. In your case, everyone in color 0 is sending and everyone in color 1 is receiving, however, if I understood your problem, you want the process 0 of color 0 to send something to the process 0 of color 1.
The sending code should be something like this:
call MPI_COMM_RANK(inter1,irank,ierr)
if(irank==0)then
call mpi_send(sendbuf,1,MPI_INT,0,tag,inter1,ierr)
end if
The receiving code should look like:
call MPI_COMM_RANK(inter2,irank,ierr)
if(irank==0)then
call mpi_recv(recvbuf,1,MPI_INT,0,tag,inter2,stat,ierr)
print*,'rec buff = ', recvbuf
end if
In the sample code, there is a new variable irank that I use to query the rank of each process in the inter-communicator; that is the rank of the process in his local communicator. So you will have two process of rank 0, one for each group, and so on.
It is important to emphasize what other commentators of your post are saying: when building a program in those modern days, use moderns constructs like use mpi instead of include 'mpif.h' see comment from Vladimir F. Another advise from your previous question was yo use rank 0 as remote leader in both case. If I combine those 2 ideas, your program can look like:
program hello
use mpi !instead of include 'mpif.h'
implicit none
integer :: tag,ierr,rank,numtasks,color,new_comm,inter1,inter2
integer :: sendbuf,recvbuf,stat(MPI_STATUS_SIZE)
integer :: irank
!
tag = 22
sendbuf = 222
!
call MPI_Init(ierr)
call MPI_COMM_RANK(MPI_COMM_WORLD,rank,ierr)
call MPI_COMM_SIZE(MPI_COMM_WORLD,numtasks,ierr)
!
if (rank < 2) then
color = 0
else
color = 1
end if
!
call MPI_COMM_SPLIT(MPI_COMM_WORLD,color,rank,new_comm,ierr)
!
if (color .eq. 0) then
call MPI_INTERCOMM_CREATE(new_comm,0,MPI_Comm_world,2,tag,inter1,ierr)
!
call MPI_COMM_RANK(inter1,irank,ierr)
if(irank==0)then
call mpi_send(sendbuf,1,MPI_INT,0,tag,inter1,ierr)
end if
!
else if(color .eq. 1) then
call MPI_INTERCOMM_CREATE(new_comm,0,MPI_COMM_WORLD,0,tag,inter2,ierr)
call MPI_COMM_RANK(inter2,irank,ierr)
if(irank==0)then
call mpi_recv(recvbuf,1,MPI_INT,0,tag,inter2,stat,ierr)
if(ierr/=MPI_SUCCESS)print*,'Error in rec '
print*,'rec buff = ', recvbuf
end if
end if
!
call MPI_finalize(ierr)
end program h

Fields and Events in Elm 0.13

This question somehow relates to How to use Fields in Elm 0.13 (and we are working on the same assignment).
In my case, everything that changes in the game should generate a Event:
data Event = NewGame
| PauseGame
| Turn [KeyCode]
| PlayerActive [Bool]
| PlayerChanged [PlayerSettings]
| Tick Time
The PlayerChanged event, for example, is generated as follows:
settingsSignal : Signal Event
settingsSignal =
lift PlayerChanged <|
combine [ pOneSettingsSignal, pTwoSettingsSignal
, pThreeSettingsSignal, pFourSettingsSignal]
pOneSettingsSignal : Signal PlayerSettings
pOneSettingsSignal =
PlayerSettings <~ (Controls <~ lift toCode pOneUp.signal
~ lift toCode pOneDown.signal
~ lift toCode pOneLeft.signal
~ lift toCode pOneRight.signal)
~ (pOneColor.signal)
~ (lift contentToString pOneName.signal)
where pOne<Direction> and pOneColor are inputs for dropDowns and pOneName is an Input for a Input.Field:
pOneName : Input Content
pOneName = input (Content nameOne (Selection 0 0 Forward))
I hereby assume that when I update the text field (or a dropdown), a PlayerChanged [PlayerSettings] event will be generated. All event get combined as follows:
eventSignal : Signal Event
eventSignal = merges [ clockSignal
, newGameSignal
, pauseGameSignal
, turnSignal
, activeSignal
, settingsSignal ]
and finally the event signal is lifted onto an update function:
gameState : Signal Game
gameState =
foldp update initialGame eventSignal
main = lift2 view gameState Window.dimensions
However, when the game is paused, it seems that all input is blocked and no signals propagate anymore. Also, the text fields are uneditable. Each Input.Field for the player names is defined as follows:
playerOneName : String -> Element
playerOneName name =
field defaultStyle pOneName.handle identity nameOne
(Content name (Selection 0 0 Forward))
and then, in the view function
pOneNameField = playerOneName playerOne.settings.name
To me it seems like everything is correct. When editing the displayed field, pOneName.signal is changed, which causes (trough a series of liftings) a PlayerChanged event to be generated, which causes the model to be redrawn, which should show the new update. Somehow the Input.Field is still uneditable, however. Worse: even a simple NewGame event isn't generated anymore and events from the dropdowns are also not propagated: nothing changes.
newGameSignal : Signal Event
newGameSignal =
always NewGame <~ (keepIf identity False <| space)
If I start the game in playing mode (thus no input forms are shown), this works fine and I can reset the game. It seems like the inputs are blocking the event stream, but I can't figure out where its going wrong.
So, I fixed it.
Appearantly the
case (event, game.state) of
(NewGame, _) ->
...
(Tick t, Playing) ->
statement is blocking, so it didn't match Tick Time signals sent in the Paused and Ended states and blocked there. A simple
(_, _) -> game
case fixed everything, so my 960 lines of Elm don't go to waste!

PID control - value of process parameter based on PID result

I'm trying to implement a PID controller following http://en.wikipedia.org/wiki/PID_controller
The mechanism I try to control works as follows:
1. I have an input variable which I can control. Typical values would be 0.5...10.
2. I have an output value which I measure daily. My goal for the output is roughly at the same range.
The two variables have strong correlation - when the process parameter goes up, the output generally goes up, but there's quite a bit of noise.
I'm following the implementation here:
http://code.activestate.com/recipes/577231-discrete-pid-controller/
Now the PID seems like it is correlated with the error term, not the measured level of output. So my guess is that I am not supposed to use it as-is for the process variable, but rather as some correction to the current value? How is that supposed to work exactly?
For example, if we take Kp=1, Ki=Kd=0, The process (input) variable is 4, the current output level is 3 and my target is a value of 2, I get the following:
error = 2-3 = -1
PID = -1
Then I should set the process variable to -1? or 4-1=3?
You need to think in terms of the PID controller correcting a manipulated variable (MV) for errors, and that you need to use an I term to get to an on-target steady-state result. The I term is how the PID retains and applies memory of the prior behavior of the system.
If you are thinking in terms of the output of the controller being changes in the MV, it is more of a 'velocity form' PID, and the memory of prior errors and behavior is integrated and accumulated in the prior MV setting.
From your example, it seems like a manipulated value of -1 is not feasible and that you would like the controller to suggest a value like 3 to get a process output (PV) of 2. For a PID controller to make use of "The process (input) variable is 4,..." (MV in my terms) Ki must be non-zero, and if the system was at steady-state, whatever was accumulated in the integral (sum_e=sum(e)) would precisely equal 4/Ki, so:
Kp= Ki = 1 ; Kd =0
error = SV - PV = 2 - 3 = -1
sum_e = sum_e + error = 4/Ki -1
MV = PID = -1(Kp) + (4/Ki -1)Ki = -1Kp + 4 - 1*Ki = -1 +4 -1 = 2
If you used a slower Ki than 1, it would smooth out the noise more and not adjust the MV so quickly:
Ki = 0.1 ;
MV = PID = -1(Kp) + (4/Ki -1)Ki = -1Kp + 4 - 1*Ki = -1 +4 -0.1 = 2.9
At steady state at target (PV = SV), sum_e * Ki should produce the steady-state MV:
PV = SV
error = SV - PV = 0
Kp * error = 0
MV = 3 = PID = 0 * Kp + Ki * sum_e
A nice way to understand the PID controller is to put units on everything and think of Kp, Ki, Kd as conversions of the process error, accumulated error*timeUnit, and rate-of-change of error/timeUnit into terms of the manipulated variable, and that the controlled system converts the controller's manipulated variable into units of output.

Resources