Hardware 33
Hardware
>AutoFormat to make your code look nicer.
• Use comments Start by writing comments after every line of code. As you gain more experience,
use comments for anything weird, potentially confusing, or a problem area.
• Don’t write your program all at once Break your program into smaller, testable blocks.
Make sure you can tell if a part of it is working. If you know each part is working, the only type of errors
will be found while putting them together, which is a lot less.
• Test often - Not sure how a part of your code should work? Make a separate program to test it.
Look at similar examples using the internet, or the built-in examples (le->examples).
• Write it out - Write out, by hand, how the program is supposed to work. Put each part in a box, and
connect the parts with arrows.
Diagnosing - Logical errors are hard to nd. If your program just doesn’t work right, even if it uploads ne.
Some approaches to nd logical errors:
• Write it out again - Go through how it’s supposed to work again, does it make sense? Does the
program look the same?
• Comment out a problem line - Try to see if a specic line is causing a problem. What hap-
pens, when you remove some line?
• Print out program information - The word ‘print’ in computer programming is to output text
information, not print it out on paper. A microcontroller can print variable names, or text to the console
in the following way:
voidsetup{
Serial.begin(9600);//tellsthemicrocontrollerthatyou
wanttousetheserialport
}
voidloop{
intmyNumber=0;
Serial.println(“Iamlooping!!”);//printaline
Serial.print(“Mynumberis:”);//Thesetwothingswill
beonthesameline
Serial.print(myNumber);
myNumber++;//AddonetomyNumber
delay(500);//Includeadelayofatleast10mswhenus-
ingSerial.print,topreventbackup
}