Of course you want working code, but
make your code readable so:- Can tell if code doing what you want now.
- Understand your code in a year.
Best Coding Practices
- Use variable names that are meaningful.
- Abbreviations are ok.
- Makes code understandable with minimum of comments
- Avoid hard-coding values in code
- By using setting a constant variable
- use const before declaring the variable
- const int photoresistorPin = 3; //blue
- const int tooClose = 40; // 40 cm is too close
- const int launchCata = 180; // degrees to move to launch catapult
- In code: if (distance < tooClose) cata.write(launchCata);
- Then you can change the value in 1 place
- Move sensor to a different pin on Arduino
- Maybe better if 20 or 60 cm is too close
- Maybe 90 degrees is enough to launch catapult
- Declare variable at top of code, so easy to find
- Group related variables together
- Use functions rather than repeating (similar) code via cut/paste
- shortens code so easier to understand and type in
- give function name so easy to know what it does
- int sonicBat() - returns distance measures from ultrasonic sensor
- void moveMotor(int speed) - move motor at speed requested
- always put helper functions in same place in code.
- in blog helper functions come before loop function that uses these functions
- Comment code to include background info
- distance = (duration/2)/29.1;
- // speed of sound is: ~29.1 microsecs/cm or 1/29.1 cm/microsec
- For Arduino the wiring info in words and color of jumper wire using can help
- // L9110S pins
- const int B1B = 9; // red to pin 9
- const int B1A = 3; // blue to pin 3
- // GND // purple to GND by 5V on Arduino
- // VCC signal // red to 5V by GND on Arduino
- const int A1B = 11; // gray to pin 11
- const int A1A = 10; // white to pin 10
No comments:
Post a Comment