I'm implementing the counter from chap. 3. Here is my code:
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/03/a/PC.hdl
/**
* A 16-bit counter with load and reset control bits.
* if (reset[t] == 1) out[t+1] = 0
* else if (load[t] == 1) out[t+1] = in[t]
* else if (inc[t] == 1) out[t+1] = out[t] + 1 (integer addition)
* else out[t+1] = out[t]
*/
CHIP PC {
IN in[16], load, inc, reset;
OUT out[16];
//sel=0; a;sel=1;b
PARTS:
//reset
Not16(in=true, out=resetted);
//inc
Inc16(in=t, out=incremented);
//Choose input between reset and out[t]
Mux16(a=t,b=resetted,sel=reset,out=o1);
//Choose input between o1 and in[t](load)
Mux16(a=o1, b=in,sel=load,out=o2);
//Choose input between o2 and inc
Mux16(a=o2,b=incremented, sel=inc, out=o3);
Register(in=o3, load=load, out=t, out=out);
}
It's seems to fail at this test:
set in -32123,
tick,
output
This is line 5, I can't find my mistake(s). Any help is appreciated
Hint (because this is a learning exercise, after all):
You are doing a cascade of muxes to generate your new value, but under what circumstances are you updating the Register?
Suggestions:
Go back to Chapter 2 and notice that they had you implement a Mux4Way16 component. Using it will make your life a lot easier.
Also, you can use false as an input and it will automatically become as wide as needed. So you don't need to run true through a Not16 to get false[16].
Related
EDIT: After playing around a bit in main(), it seems like the program is choosing whichever function is being called in the if/elif block regardless of input. I have no idea why it started doing this after working fine
I've gone over and over my code, and I can't figure out what I'm not seeing.
It's a number sequence game, and it asks the user to choose a difficulty between easy and hard. It was working just fine at one point, but now no matter what is selected, it goes to easy mode each time. Even you hit enter without any input at all.
#main program function and difficulty selection
def main():
print('-----------------------------------------------')
print('Please choose a difficulty.')
difficulty = str(input('(e)asy|(h)ard: '))
print('-----------------------------------------------')
if difficulty == 'easy'or'e':
easy()
elif difficulty == 'hard'or'h':
hard()
Then I have a function for easy and one for hard.
Hard is just the easy function, with only a change to the size of the sequence generated and nothing else. I've gone over each block and nothing is changed that would affect which function is called.
It happens regardless of how many times the game is played, so it has to be something wrong with my main() function
The rest of the code is here if that helps, maybe I'm missing something obvious.
import random
def easy():
print ('Easy Mode','\n')
#Generates inital number, step value, and upper limit
num_sequence = 5
numbers = random.randint(1,101)
step = random.randint(1,20)
#Accumulates and prints all but last number in sequence
for num_generated in range (1, num_sequence):
print(numbers)
numbers = numbers + step
#Sets tries allowed and subtracts wrong attempts
guesses = 3
while guesses > 0:
user_num = int(input('Next Number: '))
guesses = guesses - 1
if user_num != numbers:
if guesses == 0:
break
else:
print('Try Again (Attempts Remaining:', guesses,')')
if user_num == numbers:
break
#Prints appropriate message based on game results
if user_num == numbers:
print ('Correct','\n')
if user_num != numbers:
print ('Attempts Exceeded: The answer was',numbers,'\n')
#block for hard difficulty (same as above, sequence size changed to 4)
def hard():
print ('Hard Mode','\n')
num_sequence = 4
#main program function and difficulty selection
def main():
print('-----------------------------------------------')
print('Please choose a difficulty.')
difficulty = str(input('(e)asy|(h)ard: '))
print('-----------------------------------------------')
if difficulty == 'easy'or'e':
easy()
elif difficulty == 'hard'or'h':
hard()
#block for replay selection
replay = 'y'
while replay == 'y':
main()
replay = input('Play again? (y)|(n): ',)
print ('\n')
if replay == 'n':
print('-----------------------------------------------')
print('Goodbye!')
print('-----------------------------------------------')
break
hard() is the same code as easy() line for line after those first few
When you are making a compound comparison (using the or) both sides of the condition must be complete. In other words,
if difficulty == 'easy'or difficulty == 'e':
easy()
elif difficulty == 'hard'or difficulty == 'h':
hard()
Otherwise you are saying "if difficulty == 'easy' >> which is false, then assign difficulty to 'e'" which was not the intent.
So I'm just getting to grips with node-red and I need to create a conditional global function.
I have two separate global.payloads set to a number value of either 0 or 1.
What I need to happen now is, if global.payload is equal to value 1 then follow this flow, if it is equal to value 0 then follow this one.
I'm just a little confused with the syntax for the function statement. Any help gratefully appreciated.
Since you haven't accepted the current answer, thought I'd give this a try.
I think this is what you need to handle inputs from two separate global contexts. I'm simulating them here with two separate inject nodes to demonstrate:
The checkconf inject node emits a 1 or a 0. Same for the meshstatus node. Substitute your real inputs for those inject nodes. The real work is done inside the function:
var c = context.get('c') || 0; // initialize variables
var m = context.get('m') || 0;
if (msg.topic == "checkconf") // update context based on topic of input
{
c = {payload: msg.payload};
context.set("c", c); // save last value in local context
}
if (msg.topic == 'meshstatus') // same here
{
m = {payload: msg.payload};
context.set('m', m); // save last value in local context
}
// now do the test to see if both inputs are triggered...
if (m.payload == 1) // check last value of meshstatus first
{
if (c.payload == 1) // now check last value of checkconf
return {topic:'value', payload: "YES"};
}
else
return {topic:'value', payload: "NO"};
Be sure to set the "topic" property of whatever you use as inputs so the if statements can discriminate between the two input. Good luck!
You can use the Switch node to do this, rather than a Function node.
SKAction has waiting for duration abilities, for a period of time on a node. And seems to perform actions on nodes. Like moveTo, etc.
If I don't want that, rather I'd prefer to call functions within GameScene after a period of time, how do I do that with SpriteKit in the GameScene, not on a Sprite or other Node?
Are SKActions the way to do this? The only way to do this?
Yes. This question IS that ridiculously simple. I lack the heuristics and terminology to find an answer. Just keep looping around on how SKAction waits are calls on SKSprites for things like scale, rotation, etc, after time. Which isn't want I want/need.
Update:
Desired outcome, inside GameScene
doSetupStuff() // does some stuff...
waitForAWhile() // somehow wait, perhaps do somethings in here, while waiting
doSomethingElse() // does this after the waitForAWhile has waited
UPDATE 2:
What I think happens, again, inside didMove(to view...)
func wait(){
let timeToPause = SKAction.wait(forDuration: 3)
run(timeToPause)
}
let wontwait = SKAction.wait(forDuration: 3)
run(wontwait)
thisFunction(willnot: WAIT"it starts immediately")
wait()
thisFunction(forcedToWait: "for wait()'s nested action to complete")
UPDATE 3:
Found a way to get the delay without using SKActions. It's a little crude and brutal, but makes more sense to me than SKActions, so far:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
print("I waited ten seconds before printing this!")
}
An option, as you cited, is to manage this externally. The way I typically manage this sort of thing is to have an externally run update cycle. One that
To drive this updater, you could use either CADisplayLink (which is what I use right now with my OpenGL renderer) or a dispatch source timer (which I have used with my SpriteKit engine). When you use an updated, you want to calculate the delta time. The tick handler could look something like:
func tickHandler() {
let currTime = NSDate().timeIntervalSince1970
let dt = lastTime - currTime // lastTime is a data member of the class
// Call all updaters here, pretend "updater" is a known updater class
updater.update(dt)
}
And updater's update method would look something like:
func update(deltaTime:NSTimeInterval) {
// Do your magic
}
I typically have a main overall updater running independent of what people are calling scenes. Example usage would be something like having an attract mode like in old school arcade games. There they show title screen, sample game play, high scores, rinse and repeat. Scenes would be title, game play, high score. Here you can your main updater manage the time and coordinate the construction/destruction/switching of the scenes. Note this implies having an overall scene manager (which is actually quite handy to have).
For your case, you could use this updater to drive the GameScene updater. It's updater could look something like:
func update(deltaTime:NSTimeInterval) {
switch state {
case .SetupState:
// noop?
println("I'm in setup") // Shown just so you can see there is a setup state
case .WaitState:
waitTime += deltaTime
if waitTime >= kWaitTime {
// Do whats you gots to do
doSomethingElse()
state = .NextState
}
case .NextState:
// blah blah blah blah
}
}
So the flow to do this call path from your driver (CADisplayLink or dispatch source) would be something like:
tickHandler -> master updater -> game scene updater
Some will def find this is perhaps a little heavy handed. I, on the other hand, find this very helpful. While there is obviously some time management and the loss of being able to fire and forget, it can help provide more control for orchestrating pieces, as well as arbitrarily changing state without having to worry about killing already queued actions. There is also nothing that says you still cannot mix SKAction. When I did use SpriteKit, I did all my updating this way along with some dispatched items. I only used SKAction to update hierarchy. Keep in mind that I used my own animation and physics system. So at least for me I had a lot less dependency on SpriteKit (it effectively was just a renderer for me).
Note you have to have your own means to handle pause and coming to foreground where your timer will need to be resynced (you only need to worry about tickHandler). Breakpoints also will cause time jumps.
You can use below function
#define ANIM_TIME 2
SKAction *customACtion = [SKAction customActionWithDuration: ANIM_TIME actionBlock:^(SKNode *node, CGFloat elapsedTime) {
// Do Something Here
}];
Another way to make something happen after a certain period of time is to make use of the 'current time' parm passed to update(). The following code will spawn a boss at intervals ranging from 20 to 30 seconds.
In your property definitions:
var timeOfLastBoss: CFTimeInterval = -1 //Indicate no boss yet
var timePerBoss = CFTimeInterval()
.
.
.
didMoveToView() {
...
timePerBoss = CFTimeInterval(Int.random(20...30))
'''
}
.
.
.
func update(currentTime: CFTimeInterval) {
...
spawnBossForUpdate(currentTime)
...
}
'
'
'
func spawnBossForUpdate(currentTime : CFTimeInterval) {
if ( timeOfLastBoss == -1 ) {timeOfLastBoss = currentTime}
if (currentTime - timeOfLastBoss < timePerBoss) {return}
// Rest of 'spawnBoss code
self.timePerBoss = CFTimeInterval(Int.random(20...30))
self.timeOfLastBoss = currentTime
}
One way, using SKActions, in Swift 3.0, looks like this:
DEFINE: aPatientlyWaitingFunction() at the top level of
GameScene class.
To cause a delay to happen before calling the above function, inside
didMove(to view...)
three ways I've found to do this using Actions:
All three ways seem to accomplish the exact same thing:
let timeToWait: TimeInterval = 3 // is seconds in SKAction thinking time
let waitSomeTime = SKAction.wait(forDuration: timeToWait)
// 1st way __________________________________________
// with a completion handler, the function can be called after Action
run(waitSomeTime) {self.aPatientlyWaitingFunction()}
// 2nd way __________________________________________
// as a completion to be done after action, in the run invocation:
run(waitSomeTime, completion: aPatientlyWaitingFunction)
// 3rd way __________________________________________
// alternatively, as part of a sequence of actions...
// Create a sequence, by making a run action from waitSomeTime and...
let thenDoThis = SKAction.run(aPatientlyWaitingFunction)
// then activate sequence, which does one action, then the next
run(SKAction.sequence([waitSomeTime, thenDoThis]))
// OR... for something different ____________________
////////////////////////////////////////////////////////
DispatchQueue.main.asyncAfter(deadline: .now() + timeToWait) {
self.aPatientlyWaitingFunction()
print("DispatchQueue waited for 3 seconds")
}
I'm trying to code a simple PWM servo control that uses pin 11 on the Arduino Mega 2560. This servo should turn CW (clockwise) or CCW (counterclockwise) depending on pressing and holding one of the two buttons (L and R). The problem I seem to be running into is that the variable I have set to change the OCR1A(i) is incrementing even when the 'if' statements are not true. The buttons work as I've tested using the Serial.println(PINA) to make sure. I'm really not sure where I've gone wrong. I would appreciate any help.
void setup() {
// put your setup code here, to run once:
TCCR1A |= (1<<COM1A1)|(1<<WGM11)|(1<<WGM10);
TCCR1B = 0B00001100; // set mode 7 and prescale to 256
DDRB |= (1<<PB5); // data direction register for PORTB(pwm output pin 11)
DDRA = (1<<2)|(1<<3); // Last 2 digits of PORTA are inputs
Serial.begin(9600); //initialize the serial
}
void loop() {
int i = 63;
// This value controls the duty cycle, duty(%) = OCR1A/255*100
// 63 is just a random start position
OCR1A = i;
int swL;
int swR;
swL = PINA & 0b00000001;
swR = PINA & 0b00000010;
while(i<160) {
if (swR != 0b00000001) {
i++; // increments OCR1A when button R is pressed
Serial.println(PINA); // For testing button is pressed
Serial.println(OCR1A); // debugging use
Serial.println(i); // debugging use
delay(100);
}
if(swL != 0b00000010) {
i--; // negative increments when button L is pressed
Serial.println(PINA);
Serial.println(OCR1A);
Serial.println(i);
delay(100);
}
}
}
It seems like PINA & 0b00000001 provides some value to swL. Now I am not able to find the initial value of PINA but I assume that it is another variable having binary value and so when the two values perform a Bit-wise AND they provide a different value to swL.
I suppose this is the reason why the if condition
if (swL != 0b00000001) evaluates to TRUE and it then enters the if statement.
The same happens to the other variable swR and so it also enters the if statement.
I may be wrong but have a look at the lines:
swL = PINA & 0b00000001;
swR = PINA & 0b00000010;
Thanks, it turns out I just needed an extra set of eyes. My swR and swL were swapped. with a few other changes it now works as intended. Thank you all.
As a homework assignment, I'm writing a code that uses the bisection method to calculate the root of a function with one variable within a range. I created a user function that does the calculations, but one of the inputs of the function is supposed to be "fun" which is supposed to be set equal to the function.
Here is my code, before I go on:
function [ Ts ] = BisectionRoot( fun,a,b,TolMax )
%This function finds the value of Ts by finding the root of a given function within a given range to a given
%tolerance, using the Bisection Method.
Fa = fun(a);
Fb = fun(b);
if Fa * Fb > 0
disp('Error: The function has no roots in between the given bounds')
else
xNS = (a + b)/2;
toli = abs((b-a)/2);
FxNS = fun(xns);
if FxNS == 0
Ts = xNS;
break
end
if toli , TolMax
Ts = xNS;
break
end
if fun(a) * FxNS < 0
b = xNS;
else
a = xNS;
end
end
Ts
end
The input arguments are defined by our teacher, so I can't mess with them. We're supposed to set those variables in the command window before running the function. That way, we can use the program later on for other things. (Even though I think fzero() can be used to do this)
My problem is that I'm not sure how to set fun to something, and then use that in a way that I can do fun(a) or fun(b). In our book they do something they call defining f(x) as an anonymous function. They do this for an example problem:
F = # (x) 8-4.5*(x-sin(x))
But when I try doing that, I get the error, Error: Unexpected MATLAB operator.
If you guys want to try running the program to test your solutions before posting (hopefully my program works!) you can use these variables from an example in the book:
fun = 8 - 4.5*(x - sin(x))
a = 2
b = 3
TolMax = .001
The answer the get in the book for using those is 2.430664.
I'm sure the answer to this is incredibly easy and straightforward, but for some reason, I can't find a way to do it! Thank you for your help.
To get you going, it looks like your example is missing some syntax. Instead of either of these (from your question):
fun = 8 - 4.5*(x - sin(x)) % Missing function handle declaration symbol "#"
F = # (x) 8-4.5*(x-sin9(x)) %Unless you have defined it, there is no function "sin9"
Use
fun = #(x) 8 - 4.5*(x - sin(x))
Then you would call your function like this:
fun = #(x) 8 - 4.5*(x - sin(x));
a = 2;
b = 3;
TolMax = .001;
root = BisectionRoot( fun,a,b,TolMax );
To debug (which you will need to do), use the debugger.
The command dbstop if error stops execution and opens the file at the point of the problem, letting you examine the variable values and function stack.
Clicking on the "-" marks in the editor creates a break point, forcing the function to pause execution at that point, again so that you can examine the contents. Note that you can step through the code line by line using the debug buttons at the top of the editor.
dbquit quits debug mode
dbclear all clears all break points