Arduino Basic Code Primer
By: Cam Wohlfeil
Published: 2018-02-01 0000 EST
Modified: 2019-03-01 1115 EST
Category: Programming
Tags:
arduino
A basic code explanation I made for my physics class based on Arduino Lesson 13.
/*
Arduino Lesson 13: DC Motors
Parts required:
- 270 ohm resistor
- half size breadboard
- Small 6v motor
- Arduino Uno R3
- PN2222 Transistor
- 1N4001 diode
- Jumper wire pack
Licensed under the WTFPL 2.0
*/
/*
Define an integer variable with the name "motorPin" and assign it a value of "3"
An integer is a whole number, and their maximum and minimum size depends on the language.
A variable is a named piece of information stored in code. You can define them, change them, and call them in your code.
Since this variable is declared at this level, it is available to all of our following functions.
*/
int motorPin = 3;
/*
Define a function with the name of "setup" that takes no parameters and returns nothing.
A function is a way of putting together code to perform a single thing and use it multiple times by calling its name.
setup() is a built in function, meaning it comes with the language and has a special purpose, to set up the Arduino before it does anything else.
A return type of void means the function does not return any values back to the program, however this does not mean it doesn't do anything.
No parameters are defined in between the parentheses so no data is expected by the function for it to work.
*/
void setup() {
// Tell the pin number assigned to motorPin that it should behave as output.
pinMode(motorPin, OUTPUT);
// Begin communication over the serial port with a transfer (baud) rate of 9600.
Serial.begin(9600);
// A loop to check if a serial connection is running. If it is, continue the program, otherwise quit.
while (! Serial);
// Print a line of text to the serial connection.
Serial.println("Speed 0 to 255");
}
// Function to run a loop continuously until the program is ended. Takes no parameters and returns nothing.
void loop() {
// Conditional statement to continue if the serial connection is available for data to be transfered.
if (Serial.available()) {
/*
An integer variable with the name speed.
Reads from text sent on the serial connection, converts it to an integer, and assigns it to the variable.
*/
int speed = Serial.parseInt();
/*
Conditional statement to ensure speed is within acceptable limits.
Must be greater than or equal to 0, and less than or equal to 255.
*/
if (speed >= 0 && speed <= 255) {
/*
Send the speed value we accepted from input to the pin number we assigned to motorPin.
Accepts values from 0 (always off) to 255 (always on). 127 would be on half of the time.
This functions uses Pulse Width Modulation to take make a digital signal (either on or off) to appear like an analog signal.
*/
analogWrite(motorPin, speed);
// Print out last speed value sent on serial port.
Serial.println(speed);
}
}
}