Friday, January 13, 2017

Design Patterns - Java

Derek Banas created a great simple video quickly describing Design Patterns. Here is the link - https://youtu.be/vNHpsC5ng_E

I am going to text type out the principles discussed below.

What is inheritance?

  • What do the classes have in common?
  • Abstract out the features
  • Override or extend methods that don't work
  •  "is a" relationship


class Animal{
    private String name;
    private double height;
    private int weight;
   
    public void setName(String newName){
        name = newName;
    }
}

class Dog extends Animal{
    public void digHole(String newName){
        System.out.println("Hole dug");
    }
}

  • Fields and methods are already defined when you extend the super class (aka "parent class")
  • You define only the changes

What is main for?

  • main creates the objects and then they interact
 public static void main(String[] args){
    Dog grover = new Dog();
   grover.setName("Grover");
   grover.name = "Grover"; //do not do this!!! (this gets rid of encapsulation)
}

What is encapsulation?

  • Allows you do to data hiding
  • This is done through getters / setters

 

class Dog extends Animal{
     String name;
    double height;
    int weight;

     public void setWeight(int newWeight){
        if(newWeight > 0){
            weight= newWeight;
        }
        else{
           //throw error
        }  
    }}

How to hide the data?

  • Fields (Instance variables) are private
  • Getters / setters are public

class Dog extends Animal{
     private String name;
     private double height;
     private int weight;

     public void setName(String newName){
        name = newName;
    }
    public String getName(String newName){
        return name;
    }
}

Instance & Local Variables?

  • Fields (Instance variables) are private
    • Declared in the class
  • Local variables are declared in a method
class Dog extends Animal{
     private int weight;   // field

     public double getGrams(){
       double gramMult = 453.59; // local variable
       return gramMult * weight;
    }
}

Is A?Versus has A?

  • Is A? Helps you decide if a class should extend another
    • Is a Dog an Animal?
    • Is a Dog a Cat? 
  • Has A? Helps you decide if something is a field
    • Dog has a height

When to use Inheritance?

  • The subclass 'is a' superclass; ex) dog 'is an' animal
  • When a sublcass needs moth of the methods in the superclass
    • Almost every method in Animal is used in Dog
  • Don't: Use inheritance just to reuse code, or they dont have a is a relationship 

 -------------------------------------
 Code: (also found here - http://www.newthinktank.com/2012/08/design-patterns-video-tutorial/)
 
Animal.java 
public class Animal {
 
 private String name;
 private double height;
 private int weight;
 private String favFood;
 private double speed;
 private String sound;
 
 public void setName(String newName){ name = newName; }
 public String getName(){ return name; }
 
 public void setHeight(double newHeight){ height = newHeight; }
 public double getHeight(){ return height; }
 
 public void setWeight(int newWeight){ 
  if (newWeight > 0){
   weight = newWeight; 
  } else {
   System.out.println("Weight must be bigger than 0");
  }
 }
 public double getWeight(){ return weight; }
 
 public void setFavFood(String newFavFood){ favFood = newFavFood; }
 public String getFavFood(){ return favFood; }
 
 public void setSpeed(double newSpeed){ speed = newSpeed; }
 public double getSpeed(){ return speed; }
 
 public void setSound(String newSound){ sound = newSound; }
 public String getSound(){ return sound; }
 
 // A private method can only be accessed by other public methods
 // that are in the same class
 
 private void bePrivate(){
  System.out.println("I'm a private method");
 }
 
 public static void main(String[] args){
  
  Animal dog = new Animal();
  
  dog.setName("Grover");
  
  System.out.println(dog.getName());
  
 }
 
}
Dog.java 
public class Dog extends Animal{
 
 public void digHole(){
  
  System.out.println("Dug a hole");
  
 }
 
 public void changeVar(int randNum){
  
  randNum = 12;
  
  System.out.println("randNum in method value: " + randNum);
  
 }
 
 
 /* This private method can only be accessed through using other 
  * methods in the class */
 
 private void bePrivate(){
  System.out.println("In a private method");
 } 
 
 public void accessPrivate(){
  bePrivate();
 }
 
 // The constructor initializes all objects
 
 public Dog(){
  
  // Executes the parents constructor
  // Every class has a constructor whether you make it or not
  
  super();
  
  // Sets bark for all Dog objects by default
  
  setSound("Bark");
  
 }
 
}

Cat.java  
public class Cat extends Animal{
 
 // The constructor initializes all objects
 
 public Cat(){
  
  // Executes the parents constructor
  // Every class has a constructor whether you make it or not
  
  super();
  
  // Sets bark for all Dog objects by default
  
  setSound("Meow");
  
 }
 
 // If you want to make sure a method isn't overridden mark it as Final
 
 final void attack(){
  // Do stuff that can never change
 }
 
 // A field marked with final can't be changed
 
 public static final double FAVNUMBER = 3.14;
 
 // A class labeled as final can't be extended
 
}
 
WorkWithAnimals.java 

public class WorkWithAnimals{
 
 int justANum = 10;
 
 public static void main(String[] args){
  
  Dog fido = new Dog();
  
  fido.setName("Fido");
  System.out.println(fido.getName());
  
  fido.digHole();
  
  fido.setWeight(-1);
  
  // Everything is pass by value
  // The original is not effected by changes in methods
  
  int randNum = 10;
  fido.changeVar(randNum);
  
  System.out.println("randNum after method call: " + randNum);
  
  // Objects are passed by reference to the original object
  // Changes in methods do effect the object
  
  changeObjectName(fido);
  
  System.out.println("Dog name after method call: " + fido.getName());
  
  System.out.println("Animal Sound: " + fido.getSound());
  
  // Create a Dog and Cat object with the super class
  // but the Dog and Cat reference type
  
  Animal doggy = new Dog();
  Animal kitty = new Cat();
  
  System.out.println("Doggy says: " + doggy.getSound());
  System.out.println("Kitty says: " + kitty.getSound() + "\n");
  
  // Now you can make arrays of Animals and everything just works
  
  Animal[] animals = new Animal[4];
  animals[0] = doggy;
  animals[1] = kitty;
  
  System.out.println("Doggy says: " +animals[0].getSound());
  System.out.println("Kitty says: " +animals[1].getSound() + "\n");
  
  // Sends Animal objects for processing in a method
  
  speakAnimal(doggy);
  
  // Polymorphism allows you to write methods that don't need to 
  // change if new subclasses are created.
  
  // You can't reference methods, or fields that aren't in Animal
  // if you do, you'll have to cast to the required object
  
  ((Dog) doggy).digHole();
  
  // You can't use non-static variables or methods in a static function
  
  // System.out.println(justANum);
  
  // sayHello();
  
  // You can't call a private method even if you define it in
  // the subclass
  
  // fido.bePrivate();
  
  // You can execute a private method by using another public
  // method in the class
  
  fido.accessPrivate();
  
  // Creating a Giraffe from an abstract class
  
  Giraffe giraffe = new Giraffe();
  
  giraffe.setName("Frank");
  
  System.out.println(giraffe.getName());
  
 }
 
 // Any methods that are in a class and not tied to an object must
 // be labeled static. Every object created by this class will
 // share just one static method
 
 public static void changeObjectName(Dog fido){
  
  fido.setName("Marcus");
  
 }
 
 // Receives Animal objects and makes them speak
 
 public static void speakAnimal(Animal randAnimal){
  
  System.out.println("Animal says: " + randAnimal.getSound());
  
 }
 
 // This is a non-static method used to demonstrate that you can't
 // call a non-static method inside a static method
 
 public void sayHello(){
  
  System.out.println("Hello");
  
 }
 
}

Tuesday, March 22, 2016

Best Java Interview Review I've found yet! And SOAP vs REST.

http://www.tutorialspoint.com/java/java_interview_questions.htm

------------

SOAP vs REST - http://spf13.com/post/soap-vs-rest

Someone asked me a question today “Why would anyone choose SOAP (Simple Object Access Protocol) instead of REST (Representational State Transfer)?” My response: “The general rule of thumb I’ve always heard is ‘Unless you have a definitive reason to use SOAP use REST’”. He asked “what’s one reason?” I thought about it for a minute and honestly answered that I haven’t ever come across a reason. My background is building great internet companies.
While he seemed satisfied, I wasn’t very happy with that answer, I did some homework and here’s my summary on REST versus SOAP, the difference between SOAP and REST and why anyone would choose SOAP. As usual, with competing technologies both have value, the challenge is to know when to use each one (spoiler: luckily the answer is almost always REST).
I’m clearly boiling down a somewhat so please don’t flame me for simplifying things, but feel free to provide any corrections you feel are necessary.

Definitions

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.
By way of illustration here are few calls and their appropriate home with commentary.
getUser(User);
This is a rest operation as you are accessing a resource (data).
switchCategory(User, OldCategory, NewCategory)
This is a SOAP operation as you are performing an operation.
Yes, either could be done in either SOAP or REST. The purpose is to illustrate the conceptual difference.

Why REST?

Here are a few reasons why REST is almost always the right answer.
Since REST uses standard HTTP it is much simpler in just about ever way. Creating clients, developing APIs, the documentation is much easier to understand and there aren’t very many things that REST doesn’t do easier/better than SOAP.
REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.
REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
It’s a bad argument (by authority), but it’s worth mentioning that Yahoo uses REST for all their services including Flickr and del.ici.ous. Amazon and Ebay provide both though Amazon’s internal usage is nearly all REST source. Google used to provide only SOAP for all their services, but in 2006 they deprecated in favor of REST source. It’s interesting how there has been an internal battle between rest vs soap at amazon. For the most part REST dominates their architecture for web services.

Why SOAP?

Here are a few reasons you may want to use SOAP.

WS-Security

While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features. Supports identity through intermediaries, not just point to point (SSL). It also provides a standard implementation of data integrity and data privacy. Calling it “Enterprise” isn’t to say it’s more secure, it simply supports some security tools that typical internet services have no need for, in fact they are really only needed in a few “enterprise” scenarios.

WS-AtomicTransaction

Need ACID Transactions over a service, you’re going to need SOAP. While REST supports transactions, it isn’t as comprehensive and isn’t ACID compliant. Fortunately ACID transactions almost never make sense over the internet. REST is limited by HTTP itself which can’t provide two-phase commit across distributed transactional resources, but SOAP can. Internet apps generally don’t need this level of transactional reliability, enterprise apps sometimes do.

WS-ReliableMessaging

Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

Summary

In Summary, SOAP is clearly useful, and important. For instance, if I was writing an iPhone application to interface with my bank I would definitely need to use SOAP. All three features above are required for banking transactions. For example, if I was transferring money from one account to the other, I would need to be certain that it completed. Retrying it could be catastrophic if it succeed the first time, but the response failed.

Friday, March 11, 2016

Embedded / Firmware Interview Review

Today I have an embedded / firmware interview so gathering resources to review. Here are a few websites that I found:


Below I'll put some information I found useful.

Preprocessor

1. Using the #define statement, how would you declare a manifest constant that returns the number of seconds in a year? Disregard leap years in your answer.
#define SECONDS_PER_YEAR (60UL * 60UL * 24UL * 365UL)

I’m looking for several things here:
(a)    Basic knowledge of the #define syntax (i.e. no semi-colon at the end, the need to parenthesize etc.).
(b)    A good choice of name, with capitalization and underscores.
(c)    An understanding that the pre-processor will evaluate constant expressions for you. Thus, it is clearer, and penalty free to spell out how you are calculating the number of seconds in a year, rather than actually doing the calculation yourself.
(d)    A realization that the expression will overflow an integer argument on a 16 bit machine – hence the need for the L, telling the compiler to treat the expression as a Long.
(e)    As a bonus, if you modified the expression with a UL (indicating unsigned long), then you are off to a great start because you are showing that you are mindful of the perils of signed and unsigned types – and remember, first impressions count!

2. Write the ‘standard’ MIN macro. That is, a macro that takes two arguments and returns the smaller of the two arguments.
#define MIN(A,B)       ((A) <=  (B) ? (A) : (B))

The purpose of this question is to test the following:
(a)    Basic knowledge of the #define directive as used in macros. This is important, because until the inline operator becomes part of standard C, macros are the only portable way of generating inline code. Inline code is often necessary in embedded systems in order to achieve the required performance level.
(b)    Knowledge of the ternary conditional operator.  This exists in C because it allows the compiler to potentially produce more optimal code than an if-then-else sequence. Given that performance is normally an issue in embedded systems, knowledge and use of this construct is important.
(c)    Understanding of the need to very carefully parenthesize arguments to macros.
(d)    I also use this question to start a discussion on the side effects of macros, e.g. what happens when you write code such as :
least = MIN(*p++, b);
3. What is the purpose of the preprocessor directive #error?
Either you know the answer to this, or you don’t. If you don’t, then see reference 1. This question is very useful for differentiating between normal folks and the nerds. It’s only the nerds that actually read the appendices of C textbooks that find out about such things.  Of course, if you aren’t looking for a nerd, the candidate better hope she doesn’t know the answer.

Infinite Loops

4. Infinite loops often arise in embedded systems. How does one code an infinite loop in C?
There are several solutions to this question. My preferred solution is:
while(1)
{

}
Another common construct is:
for(;;)
{

}
Personally, I dislike this construct because the syntax doesn’t exactly spell out what is going on.  Thus, if a candidate gives this as a solution, I’ll use it as an opportunity to explore their rationale for doing so.  If their answer is basically – ‘I was taught to do it this way and I have never thought about it since’ – then it tells me something (bad) about them. Conversely, if they state that it’s the K&R preferred method and the only way to get an infinite loop passed Lint, then they score bonus points.
A third solution is to use a goto:
Loop:

goto Loop;
Candidates that propose this are either assembly language programmers (which is probably good), or else they are closet BASIC / FORTRAN programmers looking to get into a new field.

Data declarations

5. Using the variable a, write down definitions for the following:
(a) An integer
(b) A pointer to an integer
(c) A pointer to a pointer to an integer
(d) An array of ten integers
(e) An array of ten pointers to integers
(f) A pointer to an array of ten integers
(g) A pointer to a function that takes an integer as an argument and returns an integer
(h)    An array of ten pointers to functions that take an integer argument and return an integer.
The answers are:
(a)    int a;                 // An integer
(b)    int *a;               // A pointer to an integer
(c)    int **a;             // A pointer to a pointer to an integer
(d)    int a[10];          // An array of 10 integers
(e)    int *a[10];        // An array of 10 pointers to integers
(f)     int (*a)[10];     // A pointer to an array of 10 integers
(g)    int (*a)(int);     // A pointer to a function a that takes an integer argument and returns an integer
(h)    int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer
People often claim that a couple of these are the sorts of thing that one looks up in textbooks – and I agree. While writing this article, I consulted textbooks to ensure the syntax was correct. However, I expect to be asked this question (or something close to it) when in an interview situation. Consequently, I make sure I know the answers – at least for the few hours of the interview.  Candidates that don’t know the answers (or at least most of them) are simply unprepared for the interview.  If they can’t be prepared for the interview, what will they be prepared for?

Static

6. What are the uses of the keyword static?
This simple question is rarely answered completely.  Static has three distinct uses in C:
(a)    A variable declared static within the body of a function maintains its value between function invocations.
(b)    A variable declared static within a module[1], (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module.  That is, it is a localized global.
(c)    Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared.
Most candidates get the first part correct.  A reasonable number get the second part correct, while a pitiful number understand answer (c).  This is a serious weakness in a candidate, since they obviously do not understand the importance and benefits of localizing the scope of both data and code.

Const

7. What does the keyword const mean?
As soon as the interviewee says ‘const means constant’, I know I’m dealing with an amateur. Dan Saks has exhaustively covered const in the last year, such that every reader of ESP should be extremely familiar with what const can and cannot do for you. If you haven’t been reading that column, suffice it to say that const means “read-only”.  Although this answer doesn’t really do the subject justice, I’d accept it as a correct answer. (If you want the detailed answer, then read Saks’ columns – carefully!).
If the candidate gets the answer correct, then I’ll ask him these supplemental questions:
What do the following incomplete[2] declarations mean?
const int a;
int const a;
const int *a;
int * const a;
int const * a const;
The first two mean the same thing, namely a is a const (read-only) integer.  The third means a is a pointer to a const integer (i.e., the integer isn’t modifiable, but the pointer is). The fourth declares a to be a const pointer to an integer (i.e., the integer pointed to by a is modifiable, but the pointer is not). The final declaration declares a to be a const pointer to a const integer (i.e., neither the integer pointed to by a, nor the pointer itself may be modified).
If the candidate correctly answers these questions, I’ll be impressed.
Incidentally, one might wonder why I put so much emphasis on const, since it is very easy to write a correctly functioning program without ever using it.  There are several reasons:
(a)    The use of const conveys some very useful information to someone reading your code. In effect, declaring a parameter const tells the user about its intended usage.  If you spend a lot of time cleaning up the mess left by other people, then you’ll quickly learn to appreciate this extra piece of information. (Of course, programmers that use const, rarely leave a mess for others to clean up…)
(b)    const has the potential for generating tighter code by giving the optimizer some additional information.
(c)    Code that uses const liberally is inherently protected by the compiler against inadvertent coding constructs that result in parameters being changed that should not be.  In short, they tend to have fewer bugs.

Volatile
8. What does the keyword volatile mean? Give three different examples of its use.
A volatile variable is one that can change unexpectedly.  Consequently, the compiler can make no assumptions about the value of the variable.  In particular, the optimizer must be careful to reload the variable every time it is used instead of holding a copy in a register.  Examples of volatile variables are:
(a)    Hardware registers in peripherals (e.g., status registers)
(b)    Non-stack variables referenced within an interrupt service routine.
(c)    Variables shared by multiple tasks in a multi-threaded application.
If a candidate does not know the answer to this question, they aren’t hired.  I consider this the most fundamental question that distinguishes between a ‘C programmer’ and an ‘embedded systems programmer’.  Embedded folks deal with hardware, interrupts, RTOSes, and the like. All of these require volatile variables. Failure to understand the concept of volatile will lead to disaster.
On the (dubious) assumption that the interviewee gets this question correct, I like to probe a little deeper, to see if they really understand the full significance of volatile. In particular, I’ll ask them the following:
(a) Can a parameter be both const and volatile? Explain your answer.
(b) Can a pointer be volatile? Explain your answer.
(c) What is wrong with the following function?:
int square(volatile int *ptr)
{
return *ptr * *ptr;
}

The answers are as follows:
(a)    Yes. An example is a read only status register. It is volatile because it can change unexpectedly. It is const because the program should not attempt to modify it.
(b)    Yes. Although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer.
(c)    This one is wicked.  The intent of the code is to return the square of the value pointed to by *ptr. However, since *ptr points to a volatile parameter, the compiler will generate code that looks something like this:
int square(volatile int *ptr)
{
int a,b;
a = *ptr;
b = *ptr;
return a * b;
}
Since it is possible for the value of *ptr to change unexpectedly, it is possible for a and b to be different. Consequently, this code could return a number that is not a square!  The correct way to code this is:
long square(volatile int *ptr)
{
int a;
a = *ptr;
return a * a;
}

Bit Manipulation

9. Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified.
These are the three basic responses to this question:
(a) No idea. The interviewee cannot have done any embedded systems work.
(b) Use bit fields.  Bit fields are right up there with trigraphs as the most brain-dead portion of C.  Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable.  I recently had the misfortune to look at a driver written by Infineon for one of their more complex communications chip.  It used bit fields, and was completely useless because my compiler implemented the bit fields the other way around. The moral – never let a non-embedded person anywhere near a real piece of hardware![3]
(c) Use #defines and bit masks.  This is a highly portable method, and is the one that should be used.  My optimal solution to this problem would be:
#define BIT3       (0x1 << 3)
static int a;
void set_bit3(void) {
a |= BIT3;
}
void clear_bit3(void) {
a &= ~BIT3;
}
Some people prefer to define a mask, together with manifest constants for the set & clear values.  This is also acceptable.  The important elements that I’m looking for are the use of manifest constants, together with the |= and &= ~ constructs.

Accessing fixed memory locations

10. Embedded systems are often characterized by requiring the programmer to access a specific memory location. On a certain project it is required to set an integer variable at the absolute address 0x67a9 to the value 0xaa55. The compiler is a pure ANSI compiler. Write code to accomplish this task.
This problem tests whether you know that it is legal to typecast an integer to a pointer in order to access an absolute location.  The exact syntax varies depending upon one’s style. However, I would typically be looking for something like this:
int *ptr;
ptr = (int *)0x67a9;
*ptr = 0xaa55;
A more obfuscated approach is:
*(int * const)(0x67a9) = 0xaa55;
Even if your taste runs more to the second solution, I suggest the first solution when you are in an interview situation.

Interrupts

11. Interrupts are an important part of embedded systems. Consequently, many compiler vendors offer an extension to standard C to support interrupts. Typically, this new key word is __interrupt. The following code uses __interrupt to define an interrupt service routine. Comment on the code.
__interrupt double compute_area(double radius) {
{
double area = PI * radius * radius;
printf(“\nArea = %f”, area);
return area;
}
This function has so much wrong with it, it’s almost tough to know where to start.
(a)    Interrupt service routines cannot return a value. If you don’t understand this, then you aren’t hired.
(b)    ISR’s cannot be passed parameters. See item (a) for your employment prospects if you missed this.
(c)    On many processors / compilers, floating point operations are not necessarily re-entrant. In some cases one needs to stack additional registers, in other cases, one simply cannot do floating point in an ISR. Furthermore, given that a general rule of thumb is that ISRs should be short and sweet, one wonders about the wisdom of doing floating point math here.
(d)    In a similar vein to point (c), printf() often has problems with reentrancy and performance.  If you missed points (c) & (d) then I wouldn’t be too hard on you.  Needless to say, if you got these two points, then your employment prospects are looking better and better.

Code Examples

12. What does the following code output and why?
void foo(void)
{
unsigned int a = 6;
int b = -20;
(a+b > 6) ? puts(“> 6”) : puts(“<= 6”);
}
This question tests whether you understand the integer promotion rules in C – an area that I find is very poorly understood by many developers.  Anyway, the answer is that this outputs “> 6”.  The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus –20 becomes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently (see reference 2).  If you get this one wrong, then you are perilously close to not being hired.
13. Comment on the following code fragment?
unsigned int zero = 0;
unsigned int compzero = 0xFFFF;       /*1’s complement of zero */
On machines where an int is not 16 bits, this will be incorrect. It should be coded:
unsigned int compzero = ~0;
This question really gets to whether the candidate understands the importance of word length on a computer.  In my experience, good embedded programmers are critically aware of the underlying hardware and its limitations, whereas computer programmers tend to dismiss the hardware as a necessary annoyance.
By this stage, candidates are either completely demoralized – or they are on a roll and having a good time.  If it is obvious that the candidate isn’t very good, then the test is terminated at this point. However, if the candidate is doing well, then I throw in these supplemental questions.  These questions are hard, and I expect that only the very best candidates will do well on them. In posing these questions, I’m looking more at the way the candidate tackles the problems, rather than the answers. Anyway, have fun…

Dynamic memory allocation.
14. Although not as common as in non-embedded computers, embedded systems still do dynamically allocate memory from the heap.  What are the problems with dynamic memory allocation in embedded systems?
Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, etc. This topic has been covered extensively in ESP, mainly by Plauger.  His explanations are far more insightful than anything I could offer here, so go and read those back issues! Having lulled the candidate into a sense of false security, I then offer up this tidbit:
What does the following code fragment output and why?
char *ptr;
if ((ptr = (char *)malloc(0)) == NULL) {
puts(“Got a null pointer”);
}
else {
puts(“Got a valid pointer”);
}
This is a fun question.  I stumbled across this only recently, when a colleague of mine inadvertently passed a value of 0 to malloc, and got back a valid pointer! After doing some digging, I discovered that the result of malloc(0) is implementation defined, so that the correct answer is ‘it depends’. I use this to start a discussion on what the interviewee thinks is the correct thing for malloc to do.  Getting the right answer here is nowhere near as important as the way you approach the problem and the rationale for your decision.

Typedef

15. Typedef is frequently used in C to declare synonyms for pre-existing data types.  It is also possible to use the preprocessor to do something similar. For instance, consider the following code fragment:

#define dPS  struct s *
typedef  struct s * tPS;

The intent in both cases is to define dPS and tPS to be pointers to structure s.  Which method (if any) is preferred and why?
This is a very subtle question, and anyone that gets it right (for the right reason) is to be congratulated or condemned (“get a life” springs to mind). The answer is the typedef is preferred. Consider the declarations:
dPS p1,p2;
tPS p3,p4;
The first expands to
struct s * p1, p2;
which defines p1 to be a pointer to the structure and p2 to be an actual structure, which is probably not what you wanted. The second example correctly defines p3 & p4 to be pointers.

Obfuscated syntax

16. C allows some appalling constructs.  Is this construct legal, and if so what does this code do?
int a = 5, b = 7, c;
c = a+++b;
This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax.  The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the “maximum munch” rule, which stipulates that the compiler should bite off as big a (legal) chunk as it can.  Hence, this code is treated as:
c = a++ + b;
Thus, after this code is executed, a = 6, b = 7 & c = 12;
If you knew the answer, or guessed correctly – then well done.  If you didn’t know the answer then I would not consider this to be a problem.  I find the biggest benefit of this question is that it is very good for stimulating questions on coding styles, the value of code reviews and the benefits of using lint.
Well folks, there you have it.  That was my version of the C test.  I hope you had as much fun doing it as I had writing it.  If you think the test is a good test, then by all means use it in your recruitment.  Who knows, I may get lucky in a year or two and end up being on the receiving end of my own work.

--------------------------------------------------------------------------------------------------

What is the need for an infinite loop in Embedded systems?

- Infinite Loops are those program constructs where in there is no break statement so as to get out of the loop, it just keeps looping over the statements within the block defined.
Example:
While(Boolean True) OR for(;;);
{
//Code
}
- Embedded systems need infinite loops for repeatedly processing/monitoring the state of the program. One example could be the case of a program state continuously being checked for any exceptional errors that might just occur during run time such as memory outage or divide by zero etc.,
- For e.g. Customer care Telephone systems where in a pre-recorded audio file is played in case the dialer is put on hold..
- Also circuits being responsible for indicating that a particular component is active/alive during its operation by means of LED's.

How does combination of functions reduce memory requirements in embedded systems?

- The amount of code that has to be dealt with is reduced thus easing the overhead and redundancy is eliminated in case if there is anything common among the functions.

- Memory allocation is another aspect that is optimized and it also makes sense to group a set of functions related in some way as one single unit rather than having them to be dispersed in the whole program.

- In case of interactive systems display of menu list and reading in the choices of user's could be encapsulated as a single unit.

A vast majority of High Performance Embedded systems today use RISC architecture why?

- According to the instruction sets used, computers are normally classified into RISC and CISC. RISC stands for 'Reduced Instruction Set Computing' . The design philosophy of RISC architecture is such that only one instruction is performed on each machine cycle thus taking very less time and speeding up when compared to their CISC counterparts.

- Here the use of registers is optimised as most of the memory access operations are limited to store and load operations.

- Fewer and simple addressing modes, and simple instruction formats leads to greater efficiency, optimisation of compilers, re-organisation of code for better throughput in terms of space and time complexities. All these features make it the choice of architecture in majority of the Embedded systems.

- CISC again have their own advantages and they are preferred whenever the performance and compiler simplification are the issues to be taken care of.

Why do we need virtual device drivers when we have physical device drivers?

Device drivers are basically a set of modules/routines so as to handle a device for which a direct way of communication is not possible through the user's application program and these can be thought of as an interface thus keeping the system small providing for minimalistic of additions of code, if any.
Physical device drivers can’t perform all the logical operations needed in a system in cases like IPC, Signals and so on...

The main reason for having virtual device drivers is to mimic the behaviour of certain hardware devices without it actually being present and these could be attributed to the high cost of the devices or the unavailability of such devices.

These basically create an illusion for the users as if they are using the actual hardware and enable them to carryout their simulation results.
Examples could be the use of virtual drivers in case of Network simulators,also the support of virtual device drivers in case a user runs an additional OS in a virtual box kind of a software.

What is the need for DMAC in ES?

- Direct memory access is mainly used to overcome the disadvantages of interrupt and progam controlled I/O.
- DMA modules usually take the control over from the processor and perform the memory operations and this is mainly because to counteract the mismatch in the processing speeds of I/O units and the procesor. This is comparatively faster.
- It is an important part of any embedded systems,and the reason for their use is that they can be used for bursty data transfers instead of single byte approaches.
- It has to wait for the systems resources such as the system bus in case it is already in control of it.

What is Endianness of a system and how do different systems communicate with each other?

- Endianness basically refers to the ordering of the bytes within words or larger bytes of data treated as a single entity.

- When we consider a several bytes of data say for instance 4 bytes of data,XYZQ the lower byte if stored in a Higher address and others in successively decreasing addresses, then it refers to the Big Endian and the vice versa of this refers to Little Endian architecture.

- Intel 80x86 usually follows Little Endian and others like IBM systems follow Big Endian formats.

- If the data is being transmitted care has to be taken so as to know as to which byte,whether the higher or the lower byte is being transmitted.

- Hence a common format prior to communication has to be agreed upon to avoid wrong interpretation/calculations.
- Usually layer modules are written so as to automate these conversion in Operating systems.

How are macros different from inline functions?

- Macros are normally used whenever a set of instructions/tasks have to be repeatedly performed. They are small programs to carryout some predefined actions.

- We normally use the #define directive in case we need to define the values of some constants so in case a change is needed only the value can be changed and is reflected throughout.
#define mul(a,b) (a*b)

- The major disadvantage of macros is that they are not really functions and the usual error checking and stepping through of the code does not occur.

- Inline functions are expanded whenever it is invoked rather than the control going to the place where the function is defined and avoids all the activities such as saving the return address when a jump is performed. Saves time in case of short codes.
inline float add(float a,float b)
{
    return a+b;
}

- Inline is just a request to the compiler and it is upto to the compiler whether to substitute the code at the place of invocation or perform a jump based on its performance algorithms.

What could be the reasons for a System to have gone blank and how would you Debug it?

Possible reasons could be:

- PC being overheated.
- Dust having being accumulated all around.
- CPU fans not working properly .
- Faulty power connections.
- Faulty circuit board from where the power is being drawn.
- Support Drivers not having being installed.

Debugging steps which can be taken are:

- Cleaning the system thoroughly and maintaining it in a dust-free environment. Environment that is cool enough and facilitates for easy passage of air should be ideal enough.

- By locating the appropriate support drivers for the system in consideration and having them installed.

Explain interrupt latency and how can we decrease it?

1. Interrupt latency basically refers to the time span an interrupt is generated and it being serviced by an appropriate routine defined, usually the interrupt handler.
2. External signals, some condition in the program or by the occurrence of some event, these could be the reasons for generation of an interrupt.
3. Interrupts can also be masked so as to ignore them even if an event occurs for which a routine has to be executed.
4. Following steps could be followed to reduce the latency
- ISRs being simple and short.
- Interrupts being serviced immediately
- Avoiding those instructions that increase the latency period.
- Also by prioritizing interrupts over threads.
- Avoiding use of inappropriate APIs.

How to create a child process in linux?

- Prototype of the function used to create a child process is pid_t fork(void);
- Fork is the system call that is used to create a child process. It takes no arguments and returns a value of type pid_t.
- If the function succeeds it returns the pid of the child process created to its parent and child receives a zero value indicating its successful creation.
- On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set.
- The child process normally performs all its operations in its parents context but each process independently of one nother and also inherits some of the important attributes from it such as UID, current directory, root directory and so on.

Sunday, October 20, 2013

EG Chance's Quake Bible

Introduction


Practice, Practice, Practice. The famous words of Champion Johnathan "Fatal1ty"
Wendel. We've all heard it before, and we all know how important it is to reaching
the highest levels of play, but what about those guys who practice all day every
day and seem to never improve? I'm sure you know who I'm talking about. That
guy who's been playing for the last 4 years and in the 240 hours of game time
he's logged, since the Quake Live beta opened, has barely managed to etch out a
positive record. Well, this article intends to help those players - and any player
ready to patch up holes in their game that prevent them from reaching higher
levels of play. Unlike other articles, you won't find play by play instructions here.
Quake is about choices. From the second you spawn in, every single thing you do
matters. As we'll see more into this guide, even every single thing you think
about doing matters.

This article is structured around insight. Insights are the foundation for your
improvement; the building blocks of your game. They enable you to make the
right choices at the right times. Without them, you can't build a structure strong
enough to carry you into the next level. Remember that in every step forward
there is an often hidden insight holding it in place that you must find in order to
further establish it as your strength. Meaning, if you're playing great - there's a
reason why. You have to find that reason to retain that level of play. If you're
playing miserably, there's a reason why. You have find that reason and stamp it
out.

The following sections primarily contain insights to help you improve your game
on your own, this is the most important thing you can learn. You won't always
have someone to tell you how to play. Irregardless I cover a few key subjects that
should be your primary focus every time you play. Those two subjects are enemy
status and timing. We'll get to them a little later. For now, we need to understand
some principles to keep your head together.

Discipline. (Willing forward the strongest formula)


Create no waste. Discipline is probably the most difficult and synonymously
important strength of a competitor. Discipline is often what separates the
aforementioned soft practice junkies from the hardened veteran masters. The
practice junkie plays, and plays, and plays, but while he does so he'll be thinking
about doing his laundry. Or what about that new episode of Lost? A thousand
superfluous thoughts are floating through his head while he's drunkenly dropping
into the void like a bewildered klutz or missing the easy jump pad rail. Players like
Fatal1ty will tell you, even when you practice you need to focus 100 percent on
every game, the entire game. If you can keep this up for 8 hours a day you're
going to come out with some serious results. If you can do that, by the way, you
may have some kind of gift ;p. There are few people I know that can play more
than a couple hours without reaching "burn out." Don't concern yourself too much
with the quantity however, because the quality is what counts.

So discipline is largely about staying focused, and staying focused has a lot to do
with your emotional state. You can't be getting too angry, excited, or relaxed
when you need to be completing a crucial task like timing red armor or dodging
behind a pillar. An example of the kind of excitement that creates problems is
when that energetic excited feeling takes your mind out of the game. i.e. "I'm
doing so good! That shot was amazing! Wait.. what was the armor time again?"
Herein lies the difference between an amateur and an expert. The expert player
will simply move onto the next frag, perhaps increasing or maintaining the same
level of energy and readiness whenever necessary.

All that matters is that at the very least you're ready to accept and deal with the
current situation, rather than acting on your emotions regarding the current
situation. On the whole, emotional features like excitement will, by nature, lead
to what are called "leaks." Unintentional holes in your game that, despite knowing
what you should have done in a situation, you went ahead and did something
else. Leaks commonly arise from emotion, but they may also come in a more
dangerously subtle package; thoughts. Anytime you have thoughts floating
around that don't pertain to the game at hand you generate leaks. Disciplined
athletes have little to no leaks.

In order to prevent leaks you have to be aware of your current state of mind.
Keeping your mind clear of fog will allow you to take on any and all information
presented to you, and process it in an unbiased, no-nonsense fashion. With a
clear mind, you stay out of your own way and focus on the critical information
you need to make your next move. That is what strong discipline is about and
that is the core purpose of discipline.

Don't think of discipline as a strenuous exercise. A large part of it is making
yourself comfortable with giving it your all and ensuring you're ready to play
irregardless of what might have or could happen inside and outside of the game.
There is an "easy way" to attain a leak-free strong discipline without breaking
your routine down into thousands of meticulous details and then making yourself
remember them all when you need them. This leads us to our next insight.


Presence. (Remaining in the moment to maximize mental efficiency)



Presence is the state of mind (or no-mind) that has no past or future. Without
past and future, you are not wasting your brain cells/neurons on things that do
not currently exist and therefore hold no bearing on you as a player. You are
focused entirely on what is happening, and since what is happening is all there is,
it is therefore all that matters. This is an easy way "cut down" or lean up your
thoughts and become all killer, no filler. In my experience, you are may only
compete at your peak performance when you are committed fully to the present
moment. The ideal way to look at this is; there is no seperation between you and
what is. This "oneness" is commonly referred to by sports analysts as, "the zone."
Disciplined presence means we should be playing the entire game in the moment
as it emerges unto itself.

You don't need to "think" to strafe jump. You just do it, and the more you can
clear up the mental noise in your head while you play - the more your mind will
wrap around the task you're trying to accomplish. The task of discipline is greatly
simplified by just maintaining continual conscious presence. How is this achieved?
Focus on the task at hand, nothing more, nothing less - and not so much on the
task, but the totality of the moment.

Your mind should be like water, ready to adapt perfectly to fit any container.
Concentrate on what is happening, what the situation needs from you, don't think
it out in long-drawn inner dialogue - just be aware of it and allow it to come
through you. Give your mind the space and freedom to gather all the information
you need. Allow yourself to respond to the situation with relentless indifference,
clarity. Through this comes power. This is natural for a lot of athletes but will take
some practice in itself if you're not used to it. It seems like focusing on the "Now"
is common sense, but that all depends on how aware you are of your straying
thoughts and emotions. There's not much more that I can say about this, you
either get it or you don't. If you don't, just keep playing with a clear head and
always focus. Eventually you'll figure out how to find your "zone." When you do,
recognize the Presence and understand that it is an enormously beneficial ability
which can become absolutely pivitol to your success as a player.

Alright, so. Now we know we need discipline to continually bring our best forward
so we can call on our abilities at will, and we know how to stay in the moment so
we can be efficient with our mental resources. The line between beast and newbie
doesn't stop at staying focused and cognatively present the entire time, you have
to be focused on the right things. Now, what exactly are these "right things" I
keep mentioning, the "important stuff"? What should I concentrate on while I
play?


Opponent Awareness/Enemy Status. (Mastering the raw data.)


Whether you're playing Duel, Team Deathmatch, Clan Arena, Free for All, or even
Counter-Strike for that matter - your awareness of the enemies status is huge.
This is the part of the game that provides you with the information to make
almost all of your decisions useful. I come from a Duel background, so for the
most part I will explain this from a singular, one-player perspective rather than
the plural, team-oriented perspective, but the same nonetheless applies to either
mode.

Your opponent has XXX health and armor (at maximum totalling up to 400), he is
standing X,Y,Z on the map, with X weapons, and X ammo. The opponent is also
moving at XXX units per second. These variables are life and death in the arena.
The ability to contain this information accurately within your consciousness is the
apex of your game. I can't stress this enough because when it comes down to
winning or losing a frag - the most common thing a player does is --misread the
situation and--- mistake some other feature for the reason it happened.

For example: Player B goes through a doorway expecting Player A to have 25
health, when really Player A has 125 because he just got the mega health. When
Player B gets killed after landing a few beads of shaft he gets mad and blames his
aim for not doing enough damage. The anger itself is an issue, but we'll get to
that later. The misjudgment of enemy status is by a landslide the most common
mistake players make, and if not immediately corrected here it has the potential
to just domino.

Any time a gap occurs in our intellect we immediately fill it with the most easily
accessibly and most seemingly obvious reason, and if there is no obvious
reason... we invent one! Creating a solution to fill the gap works well on a short
term scale to alleviate a problem with the best solution we can come up with off
hand, but eventually if the player leaves it unchecked his game's foundation is
liable to become almost superstitious. Many times rather than filling the gaps with
a logical guess to what may have happened players fill it with any answer that
most conveniently protects their ego. Anger is likely indicative of the player trying
to defend his sense of strength that he feels he is losing by being punished.
Players that get stuck in ego will perpetually blame some inauspicious aspect of
the game, continue letting problems chain together by answering them
baselessly, and thus continue to be on the receiving end of the next fragger.

The only way out of this is being honest with yourself and accepting the reality of
the situation, which, I will tell you on the bright side is that you simply did not
accurately read the information you were given. Why is that on the bright side?
Because you no longer have your superstitions like "I just suck" to blame, you
have real, tangible reasoning to tell you what went wrong, and how exactly to
deal with it. We are all human, we all make mistakes. We need to remind
ourselves that these mistakes can either bear fruit, or drag us to hell, depending
on whether we accept our equality and subsequent mortality, or cling to ego and
think somehow we deserve better or worse without first understanding more. It's
the questions we can not answer that cause our suffering should we find
ourselves in a situation where we are struggling.

Once you have accurate awareness of the enemy's status, this is where the Art of
War comes in. (<3 Sun Tzu) Now you can constantly balance your status against
the enemy status, and move accordingly. If you have the advantage, you attack.
At the disadvantage, you wait for your opponent to make a mistake or you retreat
in order to gain more resources than your opponent.

What about when your back is against the wall and you can't retreat? You're out
of luck. The best way out of any sticky situation is to not get stuck there in the
first place. If you're already in this situation you're forced rely on a miracle shot,
opponent choke, luck, or some insight into your opponents fallibility to survive.
This is the last thing you want to do. Good players will attempt to force you into
this situation all game long. There's never a time when they want you to be
prepared.

You always hear about successful athletes and gamers "visualizing" their success.
I promise you they aren't visualizing having 2 health and hitting 5 consecutive
grenades for the win. They're seeing kills unfold realistically and effortlessly in
their minds eye. Studies have shown visualization helps immensely in improving
task completion. In fact, it's been shown that you can actually gain muscle by
merely thinking about lifting weights. Try and keep your opponent contained in
your minds eye throughout the game. And you don't just want to think about
where they are, you want to literally contain them by limiting how they can
expand around the map.

The majority of the learning curve in any game comes from getting yourself into
the right situations. The more experienced you are, the easier it becomes to
make useful choices using the discrepency between your enemies status and your
own, and the more meaningful every move you make becomes. I said it earlier
and I'll say it again. Quake is a game about choices. From the second you spawn
in, every single thing you do or even think about doing matters. Misinformed
decisions lead to death. If you can't figure out immediately why you just lost or
got fragged, go back and examine the replay afterwards. You need to understand
what happened. (Hopefully one day we'll have easy-access demos that display
enemy health, enemies through walls, and item times.)
Enemy status is key, but make sure you're always paying attention to your own
status (and your team if you're in a team mode). You might think you can take on
125 health joe newbie with his spawn shotty - but if you're not healthy enough
and he's in close ducking behind pillars he's gonna drop you like a brick. I'm
always suprising myself how often I go in to attack and look down and realize I've
got 150 armor but only 12 health. It's a given that any time enemy status is
considered, it should be weighed against your and your teammates statuses as
well.

The most difficult thing is gathering this information, and retaining it while
playing. Saying that it's difficult is misleading, however, because this again isn't a
stressful or demanding skill. It can be achieved with ease given time, discipline,
and continual conscious presence. The idea of difficulty is purely psychological
and arises when you resist your current situation or the "time" it takes to
accomplish your desired result.

Other insights reguarding enemy status can include player tendencies. If you've
played a person enough times, or even in your first time playing a guy you can
sometimes pick these up a few minutes in. You can use them to "get inside" your
opponents head, putting damage on them when they're not expecting it - or
taking the RA they always leave up when Mega spawns. Psychology can also play
a role here. If you know your opponent is fatigued, you may be at an advantage.
This isn't something you will want to learn to rely on, but it helps to be aware of it
so when they're feeling peppy next time - you can expect they won't be cutting
you the same slack.

So I know where he is, I know how much health he's got and I'm totally with it.
What else do I need to focus on? We'll discuss just that in the next part.

Resource Timing (Expanding and controlling your advantages)


Resources include items placed around the map that are designed to give you or
your opponent an advantage. In most modes these include weapons, armor,
health, quad, and other powerups. In Quake, it is essential that you time items to
the second. First and foremost you'll be weighing enemy status with your status,
but the ultimate goal of resource management is to effectively eliminate your
opponents ability to gain any significant advantage.

This means timing the most important items while simultaneously preventing
your opponent from getting them. This also means what items you can not time
you need to be mindful of as well. If you know they don't have the Lightning Gun
(LG) but you do, not only will you try to force mid-range fights where you have
the damage advantage, you will also want to prevent them from getting the LG so
you can continue control area's of the map that are best suited for its use. The
same goes for rockets (close range) and rail (long range). As you can see, enemy
status falls in to effect resource status, and vice versa.

In duel, the advantage of the Megahealth and Red Armor are so great that you
want to have each of them timed all game, every game. This is an area where a
lot of players faulter. You can play mindlessly all day long and garner enough
experience to eventually have a pretty solid lock on enemy status, but item
timing is a whole other beast. It takes planning, forethought, careful execution
and extreme intelligence. Experts say you need an IQ somewhere in the 140's at
least. Wait... really? No. Again - this isn't something that requires a lot of stress
or effort. Like everything else it just requires conscious present awareness.
Forethought itself only happens in the present moment. The future holds no
significance. Just because you're timing something does not mean you are
focusing on the future. All timing requires is presence and the ability to add. The
important thing to remember here is to time to the second.

What I often do is simply repeat ":16, :16, :16" in my head and if I have Mega
and RA timed I repeat the RA time too, ":16, :23, :16, :23..." Keep in mind that
its not necessary to time like this if you are good at remembering when it spawns
without it. I generally have trouble timing without repeating the numbers if I
haven't been playing in awhile or I'm distracted (either by physical external things
or just mental noise).

It may also help you to time them out loud. I recall sitting behind Paul "CZM"
Nelson and hearing him chant the spawn times for RA and MH like a quake item
conjurer after he said in the game prior he was having trouble timing. Sometimes
I'll get confused and mix up which items are spawning in which order, especially
when mega is spawning before RA (because mega usually spawns after RA). For
example I'll be repeating ":26, :30, :26, :30" in my head but the item I think is
going to spawn at :26 is actually spawning at :30 and vice versa, so it may be
helpful to remember to emphasise the next coming item in your head first and
foremost.
As we said before, in order to maximize any advantage you gain from picking up
a resource you must time it. Of course this will not be possible with every item,
not only because some items spawn in less than 5 seconds effectively rendering
timing them meaningless, but also because there are often 20+ items per map
and the average human being can only remember around 8 digits at a time.
So why is timing a weakness for so many? Well for starters, many players
experience heavy mental resistance to it, most often labeling it as a "less fun"
aspect of the game. Other people are trapped in the illusion that its too effortful,
and requires too much of their concentration or is beyond their intelligence.
General lack of discipline is, however, the biggest problem. Mental wandering
anyone? Too frustrated or impatient to remember the time? There's your lacking
discipline.

Item status, enemy status, and team status are an interconnected power struggle
where the exact respawn times play a critical role. Megahealth respawns at :XX,
red armor at :XX. You have XXX health+armor... You get the picture. Accuracy
within these categories takes time and determination to master. Along the way,
its a lot of fun. Brilliant plays start to emerge when both players become fully
aware of the enemy status and item times. It's a game with RTS style resource
management and Fighting game reflexes. The overlay of deception and
punctuality unfolds a dynamic and eternally interesting genre of E-Sport. Every
map has a unique architecture, powerup layout and weapon scheme. This sets
the stage for a vast set of gameplay meta-memes and personal meme's just
waiting to be uncovered.

Perhaps in the future I'll write an article laying out the specific meta-strategies
encountered on individual maps, but for now this marks the conclusion of the
"what to do/think about in-game" section. From here, there's a few other things
to consider pre-game and post-game.


Aim (The most overthought skill in Quake.)


If you were to ask the best aimer in the world how he aims so good he would
probably explain the process in a way that would leave you just as well off as if
he told you to tap your heals together and wish for good aim. Indeed, the concept
of "aiming well" is one place where things get a little foggy for us humans to
describe =]. We tend to try to quantify things in order to understand them and
aim is such a dynamic category we are stuck with a lack of general insight here.
But there are a few things that I think play a crucial role in aim.

1. Comfortablility. Firstly, you need to be comfortable with your environment. If
you're not used the height of your chair, size of the monitor, shape of your mouse
etc. you may have trouble aiming just because you'll be encumbered with
discomfort the whole game. Simple ^_^. Next you need a sensitivity you can
stand behind 100 percent. To do this, you need it to meet the demands of the
arena with absolute ease and comfort. This means setting it high enough for
those quick yet important placement shots, and having it low enough to maintain
a steady track.

Warmup is there purely to get a good comfortable feel for your setup and make
your mind comfortable with your sensitivity and the general handling of your
mouse again.

2. Concentration. I've said enough on this already. Presence directly equates to
amazing aim =]

3. Movement. Great movement kills two birds with one stone. You stand where
you need to be to simplify the shot(s) while synonymously avoiding enemy
attacks.

These are really the only three factors of any relevance that I can offer you when
it comes to aiming. A lot of people get borderline superstitious with their aim.
Some will nervously tweak mouse settings, sensitivities, visual configs like they
have obsessive compulsive disorder. Don't be that guy ;p.

Here's a few more tips to make sure you're on the right track.

Stop trying to predict the future. There's a lot of hype in being able to "read" your
opponent. Thats fine, but don't mistake "reading" them for predicting them. You
can not predict what a person will do. Trying to predict player movement in battle
will only lead to poor accuracy and frustration. What you can do is merely read
their movements and this'll be all you need to match them perfectly. So stop
spamming that corner for 10 seconds cause he's already behind you :p. In a
straight up shaft fight you want your crosshair to track the opponent with the
immediacy of a shadow (<3 Bruce Lee), and you can only achieve this through
total presence.

Just like we discussed earlier with enemy status, putting yourself in the right
situation with aim also has an enormous value. You're not going to miss that
jump pad shot when you're 200/200 and have every item in the map on lock. The
reason? Comfortability and simplicity. You're comfortable because you're in the
exact situation you need to be, add that to the fact that the shot is the simplest
shot in the game and probably doesn't even require you to move - and you have
yourself a winner :)

Motivation, Attitude (Pushing the limits)


It's important to keep a healthy morale when you go to play a game. Sometimes
you just aren't motivated. If you're not feeling up to a game, don't play. It takes
discipline just to take a break sometimes. A lot of players think, "Man, I keep
losing because I'm playing bad... I'm playing badly because I don't feel like
playing... but I need to get better so I have to keep playing." This is a vicious
cycle that traps almost every aspiring pro*** at some point. If you find yourself
in that situation you just need to remind yourself that it's the quality that counts.
Taking into account the stress of tournaments, it may all be a bit overwhelming at
times. If you're new to the scene, you might be freaking out months before the
tournament even starts. If you take my previous advice, you know its not smart
to practice when you're stressed because you'll be too emotional to concentrate
or play your best. So how will you get practice if you're purposely not playing
because the pressure is too high? The answer is simple. Do what you can with
what you have, and, you receive what you give.

"Do what you can with what you have." What I mean by this is, you do as much
as you can with what you're given. Whatever that means, whatever situation you
are in. If you're stressed out and you can't seem to calm down, you have may
have no choice but to play through it. You gotta accept that you're just going to
suck while you play. If you can't practice for a solid week before an event, what
can you do about it? Do everything you can but don't resist it psychologically. You
have to bring peace into the game in order to maintain functionality because....
"You receive what you give." Give it nothing, you can expect to receive nothing.
Give it your all, every, single, time-- you're going to get something back. If it's
not enough for you, too bad - give it some more. How is there a choice in the
matter? And don't just give it more- give it better, brighter. Give it lightness,
freedom, joy, enthusiasm. See what you get back. Life is the journey, a beautiful
means through uncertainty. So you start with what you have, and you do what
you can with it. Give it your all, Good luck.


Resolve. (Conscious adaptation)


Alright, so I'm practicing really hard and I'm paying acute attention to everything
thats happening - but I still having troubles with such-and-such problem(s). This
is where resolve comes in. Resolve is my favorite word, it just means so much
(seriously, it has 18 definitions on dictionary.com.) I said at the beginning of this
article that discipline may be the most important aspect of an individuals ability,
to me resolve plays a key just above that. Resolve gives you the ability to take a
step back, and tackle the problem again from a different angle. Or maybe just
tackle it harder this time. Or maybe lets try diving in on it from above. What if we
dug a hole and trapped the problem in a pit of spikes? No, I've got it... we'll use
magnets!... haha

A brilliant player (you know who you are) once told me repeatedly to think
outside the box. I kept thinking to myself, "What does that even mean?" I think
the answer to that question, or any question, is the fruit of resolve. With your
resolve you have ability to adapt, rework, recreate, restore, regenerate, renew.
Resolve is the forge by which the blade of your will is tempered. And like any
great sword, it must be shaped, heated, cooled, and folded thousands of times
before it is perfect - but who is ever perfect?
The end.

I want to remind you that while all these insights are important, and though its
important to gather new knowledge - the core of your concentration while playing
should be on enemy status, and timing. These two components are the basis for
all in-game decision making.

Hopefully this article has given you some knew knowledge or at least a fresh
perspective on things. If you still find yourself getting stuck, try writing stuff
down, you can build a journal or progress report of sorts this way.
It's been fun sharing with you all! Keep at it and together we will improve the
meta game! See you on the interwebs =]

Sunday, May 12, 2013

Sound 101

So today I wanted to purchase new head phones. Just when I got back I was just wanting to confirm the specifications that I used to purchase. Which by the way, I purchased the JVC HA-S600-B from Fry's. 

I specifically liked the frequency range of the sound - 8Hz-25KHz. So it had a nice range of bass as well as treble.

Here is a cool website that explained everything that goes on behind sound engineering. - http://www.tech-forums.net/forums/f12/sound-101-a-169733/
-------------

So... you're lookin fer some bumpin speakers eh? Well, heres some tips for you. Headphones can also follow these guidelines!

First of all, wattage isn't everything. Wattage is only the power your feeding to it. Also, especially when looking at 5.1 or 7.1 systems, when the box says "A WHOPPING 100w!", you have to remember... that 100watts is divided 6 ways (5.1) or even 8 ways (7.1). Usually, the sub will get most of the power and the satellites will get a miniscule amount. Higher wattage is good, but not always better. As this is just basic information, I'm not going to get into RMS and Peak power ratings, but researching these two forms of power is DEFINITELY a must when looking at speakers/amps. Also, resistance (ohms) is another thing you may want to dabble into.

------------------

Since wattage isn't everything, what is? Sensitivity!!! Ok... so you spent your hard earned cash on some awesome speakers with 500 watts of power. Freakin sweet eh? You open the box, get everything all set up and you go to press PLAY anxiously waiting for your heart to be resuscitated by the massive 500watts flowing through them speakers. You press play and what you hear is good. Then you take the dive and turn the volume up. "WTF?! I've got these things all the way up and they aren't loud whatsoever!! WHAT BS!!!" Sensitivity my good friend. So what is sensitivity? Well, in most specifications you will see a section called Signal to noise ratio (SNR) or sensitivity. Then you will get a number followed by dB (decibels). Say this number is 50dB (which is horrendous), that means for every one watt of power going in, 50 decibels of sound will come out (if playing white noise at nominal level). Most consumer quality stuff ranges from 70-80's. You really want at least 89dB. Anything above 90 will give you plenty of volume and will use its wattage more efficiently.

------------------

Anything else? DUH! We haven't even scratched the surface! Frequency range!! Frequency range is that weird section of numbers that no one ever understands. (100-20,000hz). What the heck does that mean? Well, hz (hertz) is a measurement of how many times a sound wave cycles in one second. So, the lower the number, the slower the wave. Thusly, the slower the wave, the lower it sounds. The human hearing range is technically 20hz-20,000hz (or 20khz). I consider the USABLE range to be 30hz-18khz Although I can hear 20-20k, people above 25 years old(ranges) can't hear much above 17k due to hearing damage (no matter what you do, it happens when you get older).

A GOOD frequency range is having the first number as low as possible and the second number as high as possible. So, if your speakers have a 75hz-16,000hz (which is not so great) range, if you play anything below or above those numbers, you wont hear it as your speakers can't play it. Chest thumping is normally found around 30-60hz. A good range I like to follow is to keep the first number below 50hz and the high number at least at 18khz (or 18,000hz).

------------------

Digital versus analog! WHAT?! THERE ARE NO SUCH THINGS AS DIGITAL SPEAKERS! NEVER! Speakers are purely an analog mechanism. A speaker consists of a magnet, a voice coil, a spider and a cone (with a dust cap in the middle, which really serves no purpose). Essentially, the speaker vibrates (in AND out) to move molecules which form sound waves. When a description says DIGITAL SPEAKERS, that means it has a digital to analog converter (AD/DA) OR it has a digital decoder built in. Digital connections only transmit information. No audio whatsoever. Just a bunch of ones and zeros.

So now you should have a basic understanding about speakers and headphones. Now, go out and get yourself some GOOD speakers (excluding Bose).

Whats next? Wiring!

Let's say you've got some sweet speakers and a really sweet amp. Rock on eh? Car install, home theater, whatever... wiring it all up goes here! There are a few different ways to wire things up, but first we gotta understand the basics:
  • Ohms (impedence or resistance)
  • Wattage
  • Load
  • Phase
Let's start with resistance! This can be quite the challenge, but its quite simple. Every speaker has a level of resistance, called impedence. Impedence is measured in what's called Ohm's. Now, we could get crazy and go into Ohm's Law, but theres really no point without going into some advanced stuff. Just so you can see it, here is the Ohm's Law chart:



This is used for figuring Impedence (resistance), wattage, voltage, and current. Simple math as long as you know the information. Anyways, back to resistance. You know how on your amplifier it says it can handle X amount of ohms? Well, thats what is called Load. 8ohms and 4ohms are the most common, but there are components that run even lower than that. How do we figure out load? Well, that all depends on how things are wired up. There are three ways to wire: Series, Parallel, and Series Parallel (I know, scary... don't worry). When hooking up more than one speaker, you have to use one of these wiring methods. Though it may seem obvious, but "black goes to black and red goes to red". These are the positive and negative leads. This gets into phase, which we'll learn a bit later.

Series:



As you can see, there are two 8ohm speakers hooked up. When you wire them in series method, you add the resistance of all of the speakers, and you get your load. In this case, 8+8= 16ohm load. REMEMBER! The higher the resistance, the lower the output. Why? Most amplifiers can handle high loads. The less resistance there is, the more power the speakers will draw from the amp, the more output (and we all know what that means... LOUDER!). The smaller load rating on the amp, the better. If the amp can handle 2 ohms, you better be sure it can give you more than enough power for any application. In the case of the picture above, it won't be very hard at all for the amp to drive those two speakers, but keep in mind that it sure isn't going to get that loud. It may be better to wire it in a different method, such as parallel!


Parallel:



Here we have the same to speakers, but wired differently. When wiring in parallel, you multiply the resistance of all of the speakers, and divide it by the sum of all the resistance of the speakers. This will give you your load rating. Here we have two 8ohm speakers wired in parallel. So, we take 8 * 8 = 64 ---- 64 / 16 = 4 ---- This gives us a load of 4ohms. If we were to hook up this to the same amplifier as we did with series, we would get a much high output since it is drawing much more power from the amp.

Series Parallel

Friday, March 22, 2013

Embedded Systems Interview Review

Today, I have a few interviews lined up. I want to do well of course, so I thought I would lay out some interview review.

Let's begin!

A really awesome review is linked here- http://www.sanjayahuja.com/Interview%20questions.pdf
--------------
This information came from- http://careerride.com/embedded-systems-interview-questions.aspx

What is the need for an infinite loop in Embedded systems?

Infinite Loops are those program constructs where in there is no break statement so as to get out of the loop, it just keeps looping over the statements within the block defined.
Example:
While(1) {}

OR

for(;;);
{
//Code
}
Embedded systems need infinite loops for repeatedly processing/monitoring the state of the program. One example could be the case of a program state continuously being checked for any exceptional errors that might just occur during run time such as memory outage or divide by zero etc.,

For e.g. Customer care Telephone systems where in a per-recorded audio file is played in case the dialer is put on hold..

Also circuits being responsible for indicating that a particular component is active/alive during its operation by means of LED's.

How does combination of functions reduce memory requirements in embedded systems?

The amount of code that has to be dealt with is reduced thus easing the overhead and redundancy is eliminated in case if there is anything common among the functions.

Memory allocation is another aspect that is optimized and it also makes sense to group a set of functions related in some way as one single unit rather than having them to be dispersed in the whole program.

In case of interactive systems display of menu list and reading in the choices of user's could be encapsulated as a single unit.

A vast majority of High Performance Embedded systems today use RISC architecture why?

According to the instruction sets used, computers are normally classified into RISC and CISC. RISC stands for 'Reduced Instruction Set Computing' .The design philosophy of RISC architecture is such that only one instruction is performed on each machine cycle thus taking very less time and speeding up when compared to their CISC counterparts.

Here the use of registers is optimized as most of the memory access operations are limited to store and load operations.

Fewer and simple addressing modes, and simple instruction formats leads to greater efficiency, optimization of compilers, re-organisation of code for better throughput in terms of space and time complexities. All these features make it the choice of architecture in majority of the Embedded systems.

CISC again have their own advantages and they are preferred whenever the performance and compiler simplification are the issues to be taken care of.

CISC RISC
Emphasis on hardware Emphasis on software
Includes multi-clock
complex instructions
Single-clock,
reduced instruction only
Memory-to-memory:
"LOAD" and "STORE"
incorporated in instructions
Register to register:
"LOAD" and "STORE"
are independent instructions
Small code sizes,
high cycles per second
Low cycles per second,
large code sizes
Transistors used for storing
complex instructions
Spends more transistors
on memory registers
 
However, the RISC strategy also brings some very important advantages. Because each instruction requires only one clock cycle to execute, the entire program will execute in approximately the same amount of time as the multi-cycle "MULT" command. These RISC "reduced instructions" require less transistors of hardware space than the complex instructions, leaving more room



The Performance Equation
The following equation is commonly used for expressing a computer's performance ability:


The CISC approach attempts to minimize the number of instructions per program, sacrificing the number of cycles per instruction. RISC does the opposite, reducing the cycles per instruction at the cost of the number of instructions per program. 

 

Why do we need virtual device drivers when we have physical device drivers?

Device drivers are basically a set of modules/routines so as to handle a device for which a direct way of communication is not possible through the user's application program and these can be thought of as an interface thus keeping the system small providing for minimalistic of additions of code, if any.
Physical device drivers can’t perform all the logical operations needed in a system in cases like IPC, Signals and so on...
The main reason for having virtual device drivers is to mimic the behaviour of certain hardware devices without it actually being present and these could be attributed to the high cost of the devices or the unavailability of such devices.
These basically create an illusion for the users as if they are using the actual hardware and enable them to carryout their simulation results.
Examples could be the use of virtual drivers in case of Network simulators,also the support of virtual device drivers in case a user runs an additional OS in a virtual box kind of a software.

What is the need for DMAC in ES?

Direct memory access is mainly used to overcome the disadvantages of interrupt and progam controlled I/O.
DMA modules usually take the control over from the processor and perform the memory operations and this is mainly because to counteract the mismatch in the processing speeds of I/O units and the procesor.This is comparatively faster.

It is an important part of any embedded systems,and the reason for their use is that they can be used for bursty data transfers instead of single byte approaches.
It has to wait for the systems resources such as the system bus in case it is already in control of it.

What is Endianness of a system and how do different systems communicate with each other?

Endianness basically refers to the ordering of the bytes within words or larger bytes of data treated as a single entity.
When we consider a several bytes of data say for instance 4 bytes of data,XYZQ the lower byte if stored in a Higher address and others in successively decreasing addresses ,then it refers to the Big Endian and the vice versa of this refers to Little Endian architecture.
Intel 80x86 usually follows Little Endian and others like IBM systems follow Big Endian formats.
If the data is being transmitted care has to be taken so as to know as to which byte,whether the higher or the lower byte is being transmitted.
Hence a common format prior to communication has to be agreed upon to avoid wrong interpretation/calculations.
Usually layer modules are written so as to automate these conversion in Operating systems.


"Little Endian" means that the low-order byte of the number is stored in memory at the lowest address, and the high-order byte at the highest address. (The little end comes first.) For example, a 4 byte LongInt
    Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:
    Base Address+0   Byte0
    Base Address+1   Byte1
    Base Address+2   Byte2
    Base Address+3   Byte3
Intel processors (those used in PC's) use "Little Endian" byte order. "Big Endian" means that the high-order byte of the number is stored in memory at the lowest address, and the low-order byte at the highest address. (The big end comes first.) Our LongInt, would then be stored as:
    Base Address+0   Byte3
    Base Address+1   Byte2
    Base Address+2   Byte1
    Base Address+3   Byte0
Motorola processors (those used in Mac's) use "Big Endian" byte order.
^Found from http://people.cs.umass.edu/~verts/cs32/endian.html

How are macros different from inline functions?

Macros are normally used whenever a set of instructions/tasks have to be repeatedly performed. They are small programs to carryout some predefined actions.
We normally use the #define directive in case we need to define the values of some constants so in case a change is needed only the value can be changed and is reflected throughout.
#define mul(a,b) (a*b)
The major disadvantage of macros is that they are not really functions and the usual error checking and stepping through of the code does not occur.
Inline functions are expanded whenever it is invoked rather than the control going to the place where the function is defined and avoids all the activities such as saving the return address when a jump is performed. Saves time in case of short codes.
inline float add(float a,float b)
{
return a+b;
}
Inline is just a request to the compiler and it is upto to the compiler whether to substitute the code at the place of invocation or perform a jump based on its performance algorithms.

What could be the reasons for a System to have gone blank and how would you Debug it?

Possible reasons could be,
- PC being overheated.
- Dust having being accumulated all around.
- CPU fans not working properly .
- Faulty power connections.
- Faulty circuit board from where the power is being drawn.
- Support Drivers not having being installed.

Debugging steps which can be taken are:

- Cleaning the system thoroughly and maintaining it in a dust-free environment.
Environment that is cool enough and facilitates for easy passage of air should be ideal enough.

- By locating the appropriate support drivers for the system in consideration and having them installed.

Explain interrupt latency and how can we decrease it?

Interrupt latency basically refers to the time span an interrupt is generated and it being serviced by an appropriate routine defined.,usually the interrupt handler.
External signals,some condition in the program or by the occurrence of some event,these could be the reasons for generation of an interrupt.
Interrupts can also be masked so as to ignore them even if an event occurs for which a routine has to be executed.
Following steps could be followed to reduce the latency
- isrs being simple and short.
- Interrupts being serviced immediately
- Avoiding those instructions that increase the latency period.
- Also by prioritizing interrupts over threads.
- Avoiding use of inappropriate APIs.

How to create a child process in linux?

Prototype of the function used to create a child process is pid_t fork(void);
Fork is the system call that is used to create a child process. It takes no arguments and returns a value of type pid_t.
If the function succeeds it returns the pid of the child process created to its parent and child receives a zero value indicating its successful creation.
On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set
The child process normally performs all its operations in its parents context but each process independently of one another and also inherits some of the important attributes from it such as UID, current directory, root directory and so on.

Significance of watchdog timer in Embedded Systems

Watchdog timer is basically a timing device that is set for predefined time interval and some event should occur during that time interval else the device generates a time out signal.
One application where it is most widely used is when the mobile phone hangs and no activity takes place,in those cases watchdog timer performs a restart of the system and comes to the rescue of the users.
It is used to reset to the original state whenever some inappropriate events take place such as too many commands being given at the same time or other activities that result in malfunctioning of the GUI.It is usually operated by counter devices.

If you buy some RTOS, what are the features you look for in ?

-Deterministic operating system having guaranteed worst-case interrupt latency and context-switch times.
-Documentation providing for the minimum, average, and maximum number of clock cycles required by each system call
-Interrupt response times should be very minute.
-Context switch time should be very low.
-Compatibility with several plugin devices.
- Overall it should be very reliable.

Why is java mostly used in embedded systems?

Java was mainly designed and conceputalised for code that can work on different platforms without any hassles and also for being secure enough so as to not harm or corrupt other modules of code.
Features like exception handling,simple syntax and Automatic Garbage collection all work in its favour as the language for use in ES's.
Also that it is widely used in the form of Java applets makes it very popular confining it to the limits of JVM.It is Dynamic in nature.
Its use is also being exploited in enterprise systems in the form of J2EE ,J2SE
J2ME in case of mobile applications.

Differentiate between mutexes vs semaphores

-Semaphores is a synchronisation tool to overcome the critical section problem.
- A semaphore S is basically an integer variable that apart from initialisation is accesses only through atomic operations such as wait() and signal().
- Semaphore object basically acts as a counter to monitor the number of threads accessing a resource.
- Mutex is also a tool that is used to provide deadlock free mutual exclusion.It protects access to every critical data item.if the data is locked and is in use,it either waits for the thread to finish or awakened to release the lock from its inactive state.

What are the commonly found errors in Embedded Systems?

- Damage of memory devices due to transient current and static discharges.
- Malfunctioning of address lines due to a short in the circuit
- Malfunctioning of Data lines.
- Some memory locations being inaccessible in storage due to garbage or errors.
- Improper insertion of Memory devices into the memory slots
- Faulty control signals.

What is the need for having multibyte data input and output buffers in case of device ports?

It’s normally the case that some devices transfer the output either in a bursty or a sequential manner and also during input entry. If we take the example of keyboards, all the data entered is stored in a buffer and given at a time or one character at a time.
In case of networking there may be several requests to access the same resource and all these are queued in a buffer and serviced in the order they are received
Hence to avoid the input/output units from getting overloaded with requests, we use multibyte buffers.

--------------
The following are basic interview questions for embedded systems - found http://careerride.com/embedded-systems-interview-for-freshers.aspx

What is lst file?

• This file is also called as list file.
• It lists the opcodes ,addresses and errors detected by the assembler.
• List file is produced only when indicated by the user.
• It can be accessed by an editor and displayedon monitor screen or printed.
• Progammer uses this file to find the syntax errors and later fix them.

How is a program executed’ bit by bit’ or’ byte by byte’?

EXAMPLE

ADDRESS OPCODE PROGRAM
1   0000
ORG 0H
2   0000 7D25 MOV R5,#25H
3   0002 7F34 MOV R7,#34H
4   0004 2D ADD A, R5
5   0005
END
• A program is always executed byte by byte.
• Firstly,1st opcode 7D is fetched from location 0000 and then the value 25 is fetched from 0001 .
• 25 is then placed in the register R5 and program counter is incremented to point 0002.
• On execution of opcode 7F, value 34 is copied to register R7.
• Then addition of contents of R5 and accumulater takes place.
• Here all the opcodes are 8 bit forming a byte.

Explain DB.

• DB is called as define byte used as a directive in the assembler.
• It is used to define the 8 bit data in binary ,hexadecimal or decimal formats.
• It is the only directive that can be used to define ASCII strings larger than two characters.
• DB is also used to allocate memory in byte sized chunks.
• The assembler always converts the numbers lnto hexadecimal.

What is EQU?

• EQU is the equate assmbler directive used to define a constant without occupying a memory location.
• It associates a constant value with data label .
• Whenever the label appears in the program ,constant value is subsituted for label.
• Advantage: The constant value occuring at various positions in a program can be changed at once using this directive.
• Syntax: label EQU constant value

How are labels named in assembly language?

• Label name should be unique and must contain alphabetic letters in both uppercase and lowercase.
• 1st letter should always be an alphabetic letter.
• It can also use digits and special characters ?,.,@,_,$.
• Label should not be one of the reserved words in assembly language.
• These labels make the progam much easier to read and maintain.

Are all the bits of flag register used in 8051?

• The flag register also called as the program status word uses only 6 bits.
• The two unused bits are user defineable flags.
• Carry ,auxillary carry ,parity and overflow flags are the conditional flags used in it.
• PSW.1 is a user definable bit and PSW.5 can be used as general purpose bit.
• Rest all flags indicate some or the other condition of an arithematic operation.

Which bit of the flag register is set when output overflows to the sign bit?

• The 2nd bit of the flag register is set when output flows to the sign bit.
• This flag is also called as the overflow flag.
• Here the output of the signed number operation is too large to be accomodated in 7 bits.
• For signed numbers the MSB is used to indicate the whether the number is positive or negative.
• It is only used to detect errors in signed number operations. 

Which register bank is used if we use the following instructions
SETB  PSW.3      A
SETB  PSW.4       B

• Statement A sets 3rd bit of flag register.
• Statement B sets 4th bit of flag register.
• Therefore register bank 3 is initiated .
• It uses memory location 18H to 1FH.
• The register bank is also called as R3.

Issues related to stack and bank 1.

• Bank 1 uses the same RAM space as the stack.
• Stack pointer is incremented or decremented according to the push or pop instruction.
• If the stack pointer is decremented it uses locations 7,6,5… which belongs to register bank 0.
• If a given program uses R1 then stack is provided new memory location.
• The push instruction may also take stack to location 0 i.e.it will run out of space.

Explain JNC.

• It is a command used to jump if no carry occurs after an arithematic operation.
• It is called as jump if no carry( conditional jump instruction).
• Here the carry flag bit in PSW register is used to make decision.
• The processor looks at the carry flag to see if it is raised or not.
• If carry flag is 0 ,CPU fetches instructions from the address of the label.

Write a program to toggle all bits of P1 every 200ms.


                    MOV              A,#55H
AGAIN:       MOV              P1,A
                    ACALL          DELAY
                    CPL               A
                    SJMP            AGAIN

DELAY:
                    MOV              R5,#9
HERE1:     MOV              R4,#242
HERE2:     MOV              R3,#255
HERE3:     DJNZ            R3,HERE3
                    DJNZ            R4,HERE2
                    DJNZ            R5,HERE1
                    RET
• Here the delay produced is 9*255*4MC*90=199,940 micro seconds.
• CPL is used to toggle the bits of P1.
• Short jump is jusd to produce a continuous loop.

Can port 0 be used as input output port?

• Yes, port 0 can be used as input output port.
• Port 0 is an open drain unlike ports 2,3,4.
• To use it as input or output the 10k ohm pull-up resisters are connected to it externally.
• To make port 0 as input port it must be programmed by writing 1 to all bits.
• Example:

MOV  A,#0FFH
MOV  P0,A

Which 2 ports combine to form the 16 bit address for external memory access?

• Port0 and port2 together form the 16 bit address for external memory.
• Port0 uses pins 32 to 39 of 8051 to give the lower address bits(AD0-AD7)
• Port2 uses pins 21 to 28 of 8051 to give the higher address bits(A8-A15)
• This 16 bit address is used to access external memory if attached.
• When connected to external memory they cannot be used as input output ports.

Can single bit of a port be accessed in 8051?

• Yes,8051 has the capability of accessing only single bit of a port.
• Here only single bit is accessed and rest are unaltered.
• SYNTAX: “SETB X. Y”.
• Here X is the port number and y is the desired bit.
• Example: SETB P1.2

Here the second bit of port 1 is set to 1.

Other than SETB ,CLR are there any single bit instructions ?

• There are total 6 single-bit instructions.
• CPL bit : complement the bit (bit= NOT bit).
• JB bit,target: Jump to target if bit equal to 1.
• JNB bit,target: Jump to target if bit is equal to 0.
• JCB bit,target: Jump to target if bit is equal to 1 and then clear bit.