On branch main

Your branch is up to date with 'origin/main'.
Changes to be committed:
	modified:   README.md
	new file:   examples/SIK_Circuit_1A-Blink/SIK_Circuit_1A-Blink.ino
	new file:   examples/SIK_Circuit_1B-Potentiometer/SIK_Circuit_1B-Potentiometer.ino
	new file:   examples/SIK_Circuit_1C-Photoresistor/SIK_Circuit_1C-Photoresistor.ino
	new file:   examples/SIK_Circuit_1D-RGBNightlight/SIK_Circuit_1D-RGBNightlight.ino
	new file:   examples/SIK_Circuit_2A-Buzzer/SIK_Circuit_2A-Buzzer.ino
	new file:   examples/SIK_Circuit_2B-DigitalTrumpet/SIK_Circuit_2B-DigitalTrumpet.ino
	new file:   examples/SIK_Circuit_2C-SimonSays/SIK_Circuit_2C-SimonSays.ino
	new file:   examples/SIK_Circuit_3A-Servo/SIK_Circuit_3A-Servo.ino
	new file:   examples/SIK_Circuit_3B-DistanceSensor/SIK_Circuit_3B-DistanceSensor.ino
	new file:   examples/SIK_Circuit_3C-MotionAlarm/SIK_Circuit_3C-MotionAlarm.ino
	new file:   examples/SIK_Circuit_4A-LCDHelloWorld/SIK_Circuit_4A-LCDHelloWorld.ino
	new file:   examples/SIK_Circuit_4B-TemperatureSensor/SIK_Circuit_4B-TemperatureSensor.ino
	new file:   examples/SIK_Circuit_4C-DIYWhoAmI/SIK_Circuit_4C-DIYWhoAmI.ino
	new file:   examples/SIK_Circuit_5A-MotorBasics/SIK_Circuit_5A-MotorBasics.ino
	new file:   examples/SIK_Circuit_5B-RemoteControlRobot/SIK_Circuit_5B-RemoteControlRobot.ino
	new file:   examples/SIK_Circuit_5C-AutonomousRobot/SIK_Circuit_5C-AutonomousRobot.ino
	new file:   library.properties
	new file:   src/SIK.h
This commit is contained in:
Nicholas Bishop 2025-08-13 14:49:56 -04:00
parent 35e1115a5c
commit 0cf48bdc8d
19 changed files with 1654 additions and 2 deletions

View file

@ -0,0 +1,32 @@
/*
SparkFun Inventors Kit
Circuit 1A-Blink
Turns an LED connected to pin 13 on and off. Repeats forever.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download code at: https://github.com/sparkfun/SIK-Guide-Code
*/
void setup() {
pinMode(13, OUTPUT); // Set pin 13 to output
}
void loop() {
digitalWrite(13, HIGH); // Turn on the LED
delay(2000); // Wait for two seconds
digitalWrite(13, LOW); // Turn off the LED
delay(2000); // Wait for two seconds
}

View file

@ -0,0 +1,36 @@
/*
SparkFun Inventors Kit
Circuit 1B-Potentiometer
Changes how fast an LED connected to pin 13 blinks, based on a potentiometer connected to pin A0
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download code at: https://github.com/sparkfun/SIK-Guide-Code
*/
int potPosition; //this variable will hold a value based on the position of the potentiometer
void setup()
{
Serial.begin(9600); //start a serial connection with the computer
pinMode(13, OUTPUT); //set pin 13 as an output that can be set to HIGH or LOW
}
void loop()
{
//read the position of the pot
potPosition = analogRead(A0); //set potPosition to a number between 0 and 1023 based on how far the knob is turned
Serial.println(potPosition); //print the value of potPosition in the serial monitor on the computer
//change the LED blink speed based on the pot value
digitalWrite(13, HIGH); // Turn on the LED
delay(potPosition); // delay for as many milliseconds as potPosition (0-1023)
digitalWrite(13, LOW); // Turn off the LED
delay(potPosition); // delay for as many milliseconds as potPosition (0-1023)
}

View file

@ -0,0 +1,39 @@
/*
SparkFun Inventors Kit
Circuit 1C-Photoresistor
Use a photoresistor to monitor how bright a room is, and turn an LED on when it gets dark.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
int photoresistor = 0; //this variable will hold a value based on the brightness of the ambient light
int threshold = 750; //if the photoresistor reading is below this value the the light will turn on
void setup()
{
Serial.begin(9600); //start a serial connection with the computer
pinMode(13, OUTPUT); //set pin 13 as an output that can be set to HIGH or LOW
}
void loop()
{
//read the brightness of the ambient light
photoresistor = analogRead(A0); //set photoresistor to a number between 0 and 1023 based on how bright the ambient light is
Serial.println(photoresistor); //print the value of photoresistor in the serial monitor on the computer
//if the photoresistor value is below the threshold turn the light on, otherwise turn it off
if (photoresistor < threshold) {
digitalWrite(13, HIGH); // Turn on the LED
} else {
digitalWrite(13, LOW); // Turn off the LED
}
delay(100); //short delay to make the printout easier to read
}

View file

@ -0,0 +1,127 @@
/*
SparkFun Inventors Kit
Circuit 1D-RGB Nightlight
Turns an RGB LED on or off based on the light level read by a photoresistor.
Change colors by turning the potentiometer.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
int photoresistor = A0; //variable for storing the photoresistor value
int potentiometer = A1; //this variable will hold a value based on the position of the knob
int threshold = 700; //if the photoresistor reading is lower than this value the light will turn on
//LEDs are connected to these pins
int RedPin = 9;
int GreenPin = 10;
int BluePin = 11;
void setup() {
Serial.begin(9600); //start a serial connection with the computer
//set the LED pins to output
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}
void loop() {
photoresistor = analogRead(A0); //read the value of the photoresistor
potentiometer = analogRead(A1);
Serial.print("Photoresistor value:");
Serial.print(photoresistor); //print the photoresistor value to the serial monitor
Serial.print(" Potentiometer value:");
Serial.println(potentiometer); //print the potentiometer value to the serial monitor
if (photoresistor < threshold) { //if it's dark (the photoresistor value is below the threshold) turn the LED on
//These nested if statements check for a variety of ranges and
//call different functions based on the current potentiometer value.
//Those functions are found at the bottom of the sketch.
if (potentiometer > 0 && potentiometer <= 150)
red();
if (potentiometer > 150 && potentiometer <= 300)
orange();
if (potentiometer > 300 && potentiometer <= 450)
yellow();
if (potentiometer > 450 && potentiometer <= 600)
green();
if (potentiometer > 600 && potentiometer <= 750)
cyan();
if (potentiometer > 750 && potentiometer <= 900)
blue();
if (potentiometer > 900)
magenta();
}
else { //if it isn't dark turn the LED off
turnOff(); //call the turn off function
}
delay(100); //short delay so that the printout is easier to read
}
void red () {
//set the LED pins to values that make red
analogWrite(RedPin, 100);
analogWrite(GreenPin, 0);
analogWrite(BluePin, 0);
}
void orange () {
//set the LED pins to values that make orange
analogWrite(RedPin, 100);
analogWrite(GreenPin, 50);
analogWrite(BluePin, 0);
}
void yellow () {
//set the LED pins to values that make yellow
analogWrite(RedPin, 100);
analogWrite(GreenPin, 100);
analogWrite(BluePin, 0);
}
void green () {
//set the LED pins to values that make green
analogWrite(RedPin, 0);
analogWrite(GreenPin, 100);
analogWrite(BluePin, 0);
}
void cyan () {
//set the LED pins to values that make cyan
analogWrite(RedPin, 0);
analogWrite(GreenPin, 100);
analogWrite(BluePin, 100);
}
void blue () {
//set the LED pins to values that make blue
analogWrite(RedPin, 0);
analogWrite(GreenPin, 0);
analogWrite(BluePin, 100);
}
void magenta () {
//set the LED pins to values that make magenta
analogWrite(RedPin, 100);
analogWrite(GreenPin, 0);
analogWrite(BluePin, 100);
}
void turnOff () {
//set all three LED pins to 0 or OFF
analogWrite(RedPin, 0);
analogWrite(GreenPin, 0);
analogWrite(BluePin, 0);
}

View file

@ -0,0 +1,109 @@
/*
SparkFun Inventors Kit
Circuit 2A - Buzzer
Play notes using a buzzer connected to pin 10
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
int speakerPin = 10; //the pin that buzzer is connected to
void setup()
{
pinMode(speakerPin, OUTPUT); //set the output pin for the speaker
}
void loop()
{
play('g', 2); //ha
play('g', 1); //ppy
play('a', 4); //birth
play('g', 4); //day
play('C', 4); //to
play('b', 4); //you
play(' ', 2); //pause for 2 beats
play('g', 2); //ha
play('g', 1); //ppy
play('a', 4); //birth
play('g', 4); //day
play('D', 4); //to
play('C', 4); //you
play(' ', 2); //pause for 2 beats
play('g', 2); //ha
play('g', 1); //ppy
play('G', 4); //birth
play('E', 4); //day
play('C', 4); //dear
play('b', 4); //your
play('a', 6); //name
play(' ', 2); //pause for 2 beats
play('F', 2); //ha
play('F', 1); //ppy
play('E', 4); //birth
play('C', 4); //day
play('D', 4); //to
play('C', 6); //you
while (true) {} //get stuck in this loop forever so that the song only plays once
}
void play( char note, int beats)
{
int numNotes = 14; // number of notes in our note and frequency array (there are 15 values, but arrays start at 0)
//Note: these notes are C major (there are no sharps or flats)
//this array is used to look up the notes
char notes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', ' '};
//this array matches frequencies with each letter (e.g. the 4th note is 'f', the 4th frequency is 175)
int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494, 0};
int currentFrequency = 0; //the frequency that we find when we look up a frequency in the arrays
int beatLength = 150; //the length of one beat (changing this will speed up or slow down the tempo of the song)
//look up the frequency that corresponds to the note
for (int i = 0; i < numNotes; i++) // check each value in notes from 0 to 14
{
if (notes[i] == note) // does the letter passed to the play function match the letter in the array?
{
currentFrequency = frequencies[i]; // Yes! Set the current frequency to match that note
}
}
//play the frequency that matched our letter for the number of beats passed to the play function
tone(speakerPin, currentFrequency, beats * beatLength);
delay(beats * beatLength); //wait for the length of the tone so that it has time to play
delay(50); //a little delay between the notes makes the song sound more natural
}
/* CHART OF FREQUENCIES FOR NOTES IN C MAJOR
Note Frequency (Hz)
c 131
d 147
e 165
f 175
g 196
a 220
b 247
C 262
D 294
E 330
F 349
G 392
A 440
B 494
*/

View file

@ -0,0 +1,59 @@
/*
SparkFun Inventors Kit
Circuit 2B-ButtonTrumpet
Use 3 buttons plugged to play musical notes on a buzzer.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
//set the pins for the button and buzzer
int firstKeyPin = 2;
int secondKeyPin = 3;
int thirdKeyPin = 4;
int buzzerPin = 10;
void setup() {
//set the button pins as inputs
pinMode(firstKeyPin, INPUT_PULLUP);
pinMode(secondKeyPin, INPUT_PULLUP);
pinMode(thirdKeyPin, INPUT_PULLUP);
//set the buzzer pin as an output
pinMode(buzzerPin, OUTPUT);
}
void loop() {
if (digitalRead(firstKeyPin) == LOW) { //if the first key is pressed
tone(buzzerPin, 262); //play the frequency for c
}
else if (digitalRead(secondKeyPin) == LOW) { //if the second key is pressed
tone(buzzerPin, 330); //play the frequency for e
}
else if (digitalRead(thirdKeyPin) == LOW) { //if the third key is pressed
tone(buzzerPin, 392); //play the frequency for g
}
else {
noTone(buzzerPin); //if no key is pressed turn the buzzer off
}
}
/*
note frequency
c 262 Hz
d 294 Hz
e 330 Hz
f 349 Hz
g 392 Hz
a 440 Hz
b 494 Hz
C 523 Hz
*/

View file

@ -0,0 +1,240 @@
/*
SparkFun Inventors Kit
Circuit 2C-Simon Says
The Simon Says game flashes a pattern using LED lights, then the player must repeat the pattern.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
//set the pins where the buttons, LEDs and buzzer connect
int button[] = {2, 4, 6, 8}; //red is button[0], yellow is button[1], green is button[2], blue is button[3]
int led[] = {3, 5, 7, 9}; //red is led[0], yellow is led[1], green is led[2], blue is led[3]
int tones[] = {262, 330, 392, 494}; //tones to play with each button (c, e, g, b)
int roundsToWin = 10; //number of rounds the player has to play before they win the game (the array can only hold up to 16 rounds)
int buttonSequence[16]; //make an array of numbers that will be the sequence that the player needs to remember
int buzzerPin = 10; //pin that the buzzer is connected to
int pressedButton = 4; //a variable to remember which button is being pressed. 4 is the value if no button is being pressed.
int roundCounter = 1; //keeps track of what round the player is on
long startTime = 0; //timer variable for time limit on button press
long timeLimit = 2000; //time limit to hit a button
boolean gameStarted = false; //variable to tell the game whether or not to play the start sequence
void setup() {
//set all of the button pins to input_pullup (use the built-in pull-up resistors)
pinMode(button[0], INPUT_PULLUP);
pinMode(button[1], INPUT_PULLUP);
pinMode(button[2], INPUT_PULLUP);
pinMode(button[3], INPUT_PULLUP);
//set all of the LED pins to output
pinMode(led[0], OUTPUT);
pinMode(led[1], OUTPUT);
pinMode(led[2], OUTPUT);
pinMode(led[3], OUTPUT);
pinMode(buzzerPin, OUTPUT); //set the buzzer pin to output
}
void loop() {
if (gameStarted == false) { //if the game hasn't started yet
startSequence(); //flash the start sequence
roundCounter = 0; //reset the round counter
delay(1500); //wait a second and a half
gameStarted = true; //set gameStarted to true so that this sequence doesn't start again
}
//each round, start by flashing out the sequence to be repeated
for (int i = 0; i <= roundCounter; i++) { //go through the array up to the current round number
flashLED(buttonSequence[i]); //turn on the LED for that array position and play the sound
delay(200); //wait
allLEDoff(); //turn all of the LEDs off
delay(200);
}
//then start going through the sequence one at a time and see if the user presses the correct button
for (int i = 0; i <= roundCounter; i++) { //for each button to be pressed in the sequence
startTime = millis(); //record the start time
while (gameStarted == true) { //loop until the player presses a button or the time limit is up (the time limit check is in an if statement)
pressedButton = buttonCheck(); //every loop check to see which button is pressed
if (pressedButton < 4) { //if a button is pressed... (4 means that no button is pressed)
flashLED(pressedButton); //flash the LED for the button that was pressed
if (pressedButton == buttonSequence[i]) { //if the button matches the button in the sequence
delay(250); //leave the LED light on for a moment
allLEDoff(); //then turn off all of the lights and
break; //end the while loop (this will go to the next number in the for loop)
} else { //if the button doesn't match the button in the sequence
loseSequence(); //play the lose sequence (the loose sequence stops the program)
break; //when the program gets back from the lose sequence, break the while loop so that the game can start over
}
} else { //if no button is pressed
allLEDoff(); //turn all the LEDs off
}
//check to see if the time limit is up
if (millis() - startTime > timeLimit) { //if the time limit is up
loseSequence(); //play the lose sequence
break; //when the program gets back from the lose sequence, break the while loop so that the game can start over
}
}
}
if (gameStarted == true) {
roundCounter = roundCounter + 1; //increase the round number by 1
if (roundCounter >= roundsToWin) { //if the player has gotten to the 16th round
winSequence(); //play the winning song
}
delay(500); //wait for half a second between rounds
}
}
//----------FUNCTIONS------------
//FLASH LED
void flashLED (int ledNumber) {
digitalWrite(led[ledNumber], HIGH);
tone(buzzerPin, tones[ledNumber]);
}
//TURN ALL LEDS OFF
void allLEDoff () {
//turn all the LEDs off
digitalWrite(led[0], LOW);
digitalWrite(led[1], LOW);
digitalWrite(led[2], LOW);
digitalWrite(led[3], LOW);
//turn the buzzer off
noTone(buzzerPin);
}
//CHECK WHICH BUTTON IS PRESSED
int buttonCheck() {
//check if any buttons are being pressed
if (digitalRead(button[0]) == LOW) {
return 0;
} else if (digitalRead(button[1]) == LOW) {
return 1;
} else if (digitalRead(button[2]) == LOW) {
return 2;
} else if (digitalRead(button[3]) == LOW) {
return 3;
} else {
return 4; //this will be the value for no button being pressed
}
}
//START SEQUENCE
void startSequence() {
randomSeed(analogRead(A0)); //make sure the random numbers are really random
//populate the buttonSequence array with random numbers from 0 to 3
for (int i = 0; i <= roundsToWin; i++) {
buttonSequence[i] = round(random(0, 4));
}
//flash all of the LEDs when the game starts
for (int i = 0; i <= 3; i++) {
tone(buzzerPin, tones[i], 200); //play one of the 4 tones
//turn all of the leds on
digitalWrite(led[0], HIGH);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], HIGH);
digitalWrite(led[3], HIGH);
delay(100); //wait for a moment
//turn all of the leds off
digitalWrite(led[0], LOW);
digitalWrite(led[1], LOW);
digitalWrite(led[2], LOW);
digitalWrite(led[3], LOW);
delay(100); //wait for a moment
} //this will repeat 4 times
}
//WIN SEQUENCE
void winSequence() {
//turn all the LEDs on
for (int j = 0; j <= 3; j++) {
digitalWrite(led[j], HIGH);
}
//play the 1Up noise
tone(buzzerPin, 1318, 150); //E6
delay(175);
tone(buzzerPin, 1567, 150); //G6
delay(175);
tone(buzzerPin, 2637, 150); //E7
delay(175);
tone(buzzerPin, 2093, 150); //C7
delay(175);
tone(buzzerPin, 2349, 150); //D7
delay(175);
tone(buzzerPin, 3135, 500); //G7
delay(500);
//wait until a button is pressed
do {
pressedButton = buttonCheck();
} while (pressedButton > 3);
delay(100);
gameStarted = false; //reset the game so that the start sequence will play again.
}
//LOSE SEQUENCE
void loseSequence() {
//turn all the LEDs on
for (int j = 0; j <= 3; j++) {
digitalWrite(led[j], HIGH);
}
//play the 1Up noise
tone(buzzerPin, 130, 250); //E6
delay(275);
tone(buzzerPin, 73, 250); //G6
delay(275);
tone(buzzerPin, 65, 150); //E7
delay(175);
tone(buzzerPin, 98, 500); //C7
delay(500);
//wait until a button is pressed
do {
pressedButton = buttonCheck();
} while (pressedButton > 3);
delay(200);
gameStarted = false; //reset the game so that the start sequence will play again.
}

View file

@ -0,0 +1,38 @@
/*
SparkFun Inventors Kit
Circuit 3A-Servo
Move a servo attached to pin 9 so that it's angle matches a potentiometer attached to A0.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
#include <Servo.h> //include the servo library
int potPosition; //this variable will store the position of the potentiometer
int servoPosition; //the servo will move to this position
Servo myservo; //create a servo object
void setup() {
myservo.attach(9); //tell the servo object that its servo is plugged into pin 9
}
void loop() {
potPosition = analogRead(A0); //use analog read to measure the position of the potentiometer (0-1023)
servoPosition = map(potPosition, 0, 1023, 20, 160); //convert the potentiometer number to a servo position from 20-160
//Note: its best to avoid driving the little SIK servos all the
//way to 0 or 180 degrees it can cause the motor to jitter, which is bad for the servo.
myservo.write(servoPosition); //move the servo to the 10 degree position
}

View file

@ -0,0 +1,87 @@
/*
SparkFun Inventors Kit
Circuit 3B-Distance Sensor
Control the color of an RGB LED using an ultrasonic distance sensor.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
const int trigPin = 11; //connects to the trigger pin on the distance sensor
const int echoPin = 12; //connects to the echo pin on the distance sensor
const int redPin = 3; //pin to control the red LED inside the RGB LED
const int greenPin = 5; //pin to control the green LED inside the RGB LED
const int bluePin = 6; //pin to control the blue LED inside the RGB LED
float distance = 0; //stores the distance measured by the distance sensor
void setup()
{
Serial.begin (9600); //set up a serial connection with the computer
pinMode(trigPin, OUTPUT); //the trigger pin will output pulses of electricity
pinMode(echoPin, INPUT); //the echo pin will measure the duration of pulses coming back from the distance sensor
//set the RGB LED pins to output
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
distance = getDistance(); //variable to store the distance measured by the sensor
Serial.print(distance); //print the distance that was measured
Serial.println(" in"); //print units after the distance
if (distance <= 10) { //if the object is close
//make the RGB LED red
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
} else if (10 < distance && distance < 20) { //if the object is a medium distance
//make the RGB LED yellow
analogWrite(redPin, 255);
analogWrite(greenPin, 50);
analogWrite(bluePin, 0);
} else { //if the object is far away
//make the RGB LED green
analogWrite(redPin, 0);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
}
delay(50); //delay 50ms between each reading
}
//------------------FUNCTIONS-------------------------------
//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
float echoTime; //variable to store the time it takes for a ping to bounce off an object
float calculatedDistance; //variable to store the distance calculated from the echo time
//send out an ultrasonic pulse that's 10ms long
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the
//pulse to bounce back to the sensor
calculatedDistance = echoTime / 148.0; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)
return calculatedDistance; //send back the distance that was calculated
}

View file

@ -0,0 +1,108 @@
/*
SparkFun Inventors Kit
Circuit 3C-Motion Alarm
Control the color of an RGB LED using an ultrasonic distance sensor. When an object is close to the sensor, buzz the buzzer and wiggle the servo motor.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
#include <Servo.h> //include the servo library
const int trigPin = 11; //connects to the trigger pin on the distance sensor
const int echoPin = 12; //connects to the echo pin on the distance sensor
const int redPin = 3; //pin to control the red LED inside the RGB LED
const int greenPin = 5; //pin to control the green LED inside the RGB LED
const int bluePin = 6; //pin to control the blue LED inside the RGB LED
const int buzzerPin = 10; //pin that will drive the buzzer
float distance = 0; //stores the distance measured by the distance sensor
Servo myservo; //create a servo object
void setup()
{
Serial.begin (9600); //set up a serial connection with the computer
pinMode(trigPin, OUTPUT); //the trigger pin will output pulses of electricity
pinMode(echoPin, INPUT); //the echo pin will measure the duration of pulses coming back from the distance sensor
//set the RGB LED pins to output
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buzzerPin, OUTPUT); //set the buzzer pin to output
myservo.attach(9); //use pin 9 to control the servo
}
void loop() {
distance = getDistance(); //variable to store the distance measured by the sensor
Serial.print(distance); //print the distance that was measured
Serial.println(" in"); //print units after the distance
if (distance <= 10) { //if the object is close
//make the RGB LED red
analogWrite(redPin, 255);
analogWrite(greenPin, 0);
analogWrite(bluePin, 0);
//this code wiggles the servo and beeps the buzzer
tone(buzzerPin, 272); //buzz the buzzer pin
myservo.write(10); //move the servo to 45 degrees
delay(100); //wait 100 milliseconds
noTone(buzzerPin); //turn the buzzer off
myservo.write(150); //move the servo to 135 degrees
delay(100); //wait 100 milliseconds
} else if (10 < distance && distance < 20) { //if the object is a medium distance
//make the RGB LED yellow
analogWrite(redPin, 255);
analogWrite(greenPin, 50);
analogWrite(bluePin, 0);
} else { //if the object is far away
//make the RGB LED green
analogWrite(redPin, 0);
analogWrite(greenPin, 255);
analogWrite(bluePin, 0);
}
delay(50); //delay 50ms between each reading
}
//------------------FUNCTIONS-------------------------------
//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
float echoTime; //variable to store the time it takes for a ping to bounce off an object
float calculatedDistance; //variable to store the distance calculated from the echo time
//send out an ultrasonic pulse that's 10ms long
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the
//pulse to bounce back to the sensor
calculatedDistance = echoTime / 148.0; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)
return calculatedDistance; //send back the distance that was calculated
}

View file

@ -0,0 +1,32 @@
/*
SparkFun Inventors Kit
Circuit 4A-HelloWorld
The LCD will display the words "Hello World" and show how many seconds have passed since
the RedBoard was last reset.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
#include <LiquidCrystal.h> //the liquid crystal library contains commands for printing to the display
LiquidCrystal lcd(13, 12, 11, 10, 9, 8); // tell the RedBoard what pins are connected to the display
void setup() {
lcd.begin(16, 2); //tell the lcd library that we are using a display that is 16 characters wide and 2 characters high
lcd.clear(); //clear the display
}
void loop() {
lcd.setCursor(0, 0); //set the cursor to the 0,0 position (top left corner)
lcd.print("Hello, world!"); //print hello, world! starting at that position
lcd.setCursor(0, 1); //move the cursor to the first space of the bottom row
lcd.print(millis() / 1000); //print the number of seconds that have passed since the last reset
}

View file

@ -0,0 +1,45 @@
/*
SparkFun Inventors Kit
Circuit 4B - Temperature Sensor
The LCD will display readings from a temperature sensor in degrees Celsius and Fahrenheit.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
#include <LiquidCrystal.h> //the liquid crystal library contains commands for printing to the display
LiquidCrystal lcd(13, 12, 11, 10, 9, 8); // tell the RedBoard what pins are connected to the display
float voltage = 0; //the voltage measured from the TMP36
float degreesC = 0; //the temperature in Celsius, calculated from the voltage
float degreesF = 0; //the temperature in Fahrenheit, calculated from the voltage
void setup() {
lcd.begin(16, 2); //tell the lcd library that we are using a display that is 16 characters wide and 2 characters high
lcd.clear(); //clear the display
}
void loop() {
voltage = analogRead(A0) * 0.004882813; //convert the analog reading, which varies from 0 to 1023, back to a voltage value from 0-5 volts
degreesC = (voltage - 0.5) * 100.0; //convert the voltage to a temperature in degrees Celsius
degreesF = degreesC * (9.0 / 5.0) + 32.0; //convert the voltage to a temperature in degrees Fahrenheit
lcd.clear(); //clear the LCD
lcd.setCursor(0, 0); //set the cursor to the top left position
lcd.print("Degrees C: "); //print a label for the data
lcd.print(degreesC); //print the degrees Celsius
lcd.setCursor(0, 1); //set the cursor to the lower left position
lcd.print("Degrees F: "); //Print a label for the data
lcd.print(degreesF); //print the degrees Fahrenheit
delay(1000); //delay for 1 second between each reading (this makes the display less noisy)
}

View file

@ -0,0 +1,197 @@
/*
SparkFun Inventors Kit
Circuit 4C - Heads Up Game
This is a DIY version of the popular Heads Up party game. To play, one person resets the RedBoard and holds the LCD
facing away from them so that they cannot see it (usually on their forehead). The display will show a short countdown
then display random words. The other player(s) who can see the screen must yell out clues until time runs out or the player
guesses what word is on the screen. If they guess correctly, they can press the button on the breadboard and another word
will be displayed.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
#include <LiquidCrystal.h> //the liquid crystal library contains commands for printing to the display
LiquidCrystal lcd(13, 12, 11, 10, 9, 8); // tell the RedBoard what pins are connected to the display
int buttonPin = 2; //pin that the button is connected to
int buzzerPin = 6; //pin for driving the buzzer
int buttonPressTime = 0; //variable to show how much time the player has left to guess the word (and press the button)
long timeLimit = 15000; //time limit for the player to guess each word
long startTime = 0; //used to measure time that has passed for each word
int roundNumber = 0; //keeps track of the roundNumber so that it can be displayed at the end of the game
const int arraySize = 25;
const char* words[arraySize] = {"moose", "beaver", "bear", "goose", "dog", "cat", "squirrel", "bird", "elephant", "horse",
"bull", "giraffe", "seal", "bat", "skunk", "turtle", "whale", "rhino", "lion", "monkey",
"frog", "alligator", "kangaroo", "hippo", "rabbit"
};
// the start value in the sequence array must have a value that could never be an index of an array
// or at least a value outside the range of 0 to the size of the words array - 1; in this case, it can't be between 0 to 24
int sequence[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; //start with an array full of -1's
void setup() {
pinMode(buttonPin, INPUT_PULLUP); //set the button pin as an input
lcd.begin(16, 2); //tell the LCD library the size of the screen
generateRandomOrder(); //generate an array of random numbers from 0 to 24 that will determine which order the words are shown in
showStartSequence(); //print the start sequence text
}
void loop() {
for (int i = 0; i < arraySize; i++) { //for each of the 25 words in the sequence
lcd.clear(); //clear off the array
roundNumber = i + 1; //the array starts at 0, but the roundNumber will start counting from 1
lcd.print(roundNumber); //print the roundNumber (this is the current round number)
lcd.print(": "); //spacer between the number and the word
lcd.print(words[sequence[i]]); //print a random word from the word array
startTime = millis(); //record the time that this round started
while (digitalRead(buttonPin) == HIGH) { //do this until the button is pressed...
int roundedTime = round((timeLimit - (millis() - startTime)) / 1000); //calculate the time left in the round (dividing by 1000 converts the number to seconds
lcd.setCursor(14, 1); //set the cursor in the lower right corner of the screen
lcd.print(" ");
lcd.setCursor(14, 1); //set the cursor in the lower right corner of the screen
lcd.print(roundedTime); //print the time left in the time limit
delay(15);
if (millis() - startTime > timeLimit) { //if the time limit is up before the button is pressed
gameOver(); //end the game
}
if (digitalRead(buttonPin) == LOW) {
tone(buzzerPin, 272, 10); //emit a short beep when the button is pressed
}
} //exit this loop when the button is pressed
delay(500); //delay for a moment before going onto the next round, so that the button press doesn't get registered twice
}
//if you finish all 25 words
winner(); //show the you win message
}
//--------------FUNCTIONS------------------------------
//DISPLAYS A COUNTDOWN TO START THE GAME
void showStartSequence() {
lcd.clear(); //clear the screen
lcd.setCursor(0, 0); //move the cursor to the top left corner
lcd.print("Category:"); //print "Category:"
lcd.setCursor(0, 1); //move the cursor to the bottom left corner
lcd.print("Animals"); //print "Animals:"
delay(2000); //Wait 2 seconds
lcd.clear(); //clear the screen
lcd.print("Get ready!"); //print "Get ready!"
delay(1000); //wait 1 second
lcd.clear(); //clear the screen
lcd.print("3"); //print "3"
delay(1000); //wait 1 second
lcd.clear(); //clear the screen
lcd.print("2"); //print "3"
delay(1000); //wait 1 second
lcd.clear(); //clear the screen
lcd.print("1"); //print "3"
delay(1000); //wait 1 second
}
//GENERATES A RANDOM ORDER FOR THE WORDS TO BE DISPLAYED
void generateRandomOrder() {
randomSeed(analogRead(0)); //reset the random seed (Arduino needs this to generate truly random numbers
for (int i = 0; i < arraySize; i++) { //do this until all 25 positions are filled
int currentNumber = 0; //variable to hold the current number
boolean match = false; //does the currentNumber match any of the previous numbers?
//generate random numbers until you've generated one that doesn't match any of the other numbers in the array
do {
currentNumber = random(0, arraySize); //generate a random number from 0 to 24
match = false; //we haven't checked for matches yet, so start by assuming that it doesn't match
for (int i = 0; i < arraySize; i++) { //for all 25 numbers in the array
if (currentNumber == sequence[i]) { //does the currentNumber match any of the numbers?
match = true; //if so, set the match variable to true
}
}
} while (match == true); //if the match variable is true, generate another random number and try again
sequence[i] = currentNumber; //if the match variable is false (the new number is unique) then add it to the sequence
}
}
//GAME OVER
void gameOver() {
lcd.clear(); //clear the screen
lcd.setCursor(0, 0); //move the cursor the top left corner
lcd.print("Game Over"); //print "Game Over"
lcd.setCursor(0, 1); //move to the bottom row
lcd.print("Score: "); //print a label for the score
lcd.print(roundNumber-1); //print the score (the score is equal to the previous level/round number)
//play the losing fog horn
tone(buzzerPin, 130, 250); //E6
delay(275);
tone(buzzerPin, 73, 250); //G6
delay(275);
tone(buzzerPin, 65, 150); //E7
delay(175);
tone(buzzerPin, 98, 500); //C7
delay(500);
while (true) {} //get stuck in this loop forever
}
//WINNER
void winner() {
lcd.clear(); //clear the screen
lcd.setCursor(7, 0); //move the cursor to the top center of the screen
lcd.print("YOU"); //print "You"
lcd.setCursor(7, 1); //move the cursor to the bottom center of the screen
lcd.print("WIN!"); //print "WIN!"
//play the 1Up noise
tone(buzzerPin, 1318, 150); //E6
delay(175);
tone(buzzerPin, 1567, 150); //G6
delay(175);
tone(buzzerPin, 2637, 150); //E7
delay(175);
tone(buzzerPin, 2093, 150); //C7
delay(175);
tone(buzzerPin, 2349, 150); //D7
delay(175);
tone(buzzerPin, 3135, 500); //G7
delay(500);
while (true) {} //get stuck in this loop forever
}

View file

@ -0,0 +1,79 @@
/*
SparkFun Inventors Kit
Circuit 5A - Motor Basics
Learn how to control one motor with the motor driver.
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
//PIN VARIABLES
//the motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13; //control pin 1 on the motor driver for the right motor
const int AIN2 = 12; //control pin 2 on the motor driver for the right motor
const int PWMA = 11; //speed control pin on the motor driver for the right motor
int switchPin = 7; //switch to turn the robot on and off
//VARIABLES
int motorSpeed = 0; //starting speed for the motor
void setup() {
pinMode(switchPin, INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped
//set the motor control pins as outputs
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(PWMA, OUTPUT);
Serial.begin(9600); //begin serial communication with the computer
Serial.println("Enter motor speed (0-255)... "); //Prompt to get input in the serial monitor.
}
void loop() {
if (Serial.available() > 0) { //if the user has entered something in the serial monitor
motorSpeed = Serial.parseInt(); //set the motor speed equal to the number in the serial message
Serial.print("Motor Speed: "); //print the speed that the motor is set to run at
Serial.println(motorSpeed);
}
if (digitalRead(7) == LOW) { //if the switch is on...
spinMotor(motorSpeed);
} else { //if the switch is off...
spinMotor(0); //turn the motor off
}
}
/********************************************************************************/
void spinMotor(int motorSpeed) //function for driving the right motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(AIN1, HIGH); //set pin 1 to high
digitalWrite(AIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, LOW); //set pin 2 to low
}
analogWrite(PWMA, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}

View file

@ -0,0 +1,161 @@
/*
SparkFun Inventors Kit
Circuit 5B - Remote Control Robot
Control a two wheeled robot by sending direction commands through the serial monitor.
This sketch was adapted from one of the activities in the SparkFun Guide to Arduino.
Check out the rest of the book at
https://www.sparkfun.com/products/14326
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
//the right motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13; //control pin 1 on the motor driver for the right motor
const int AIN2 = 12; //control pin 2 on the motor driver for the right motor
const int PWMA = 11; //speed control pin on the motor driver for the right motor
//the left motor will be controlled by the motor B pins on the motor driver
const int PWMB = 10; //speed control pin on the motor driver for the left motor
const int BIN2 = 9; //control pin 2 on the motor driver for the left motor
const int BIN1 = 8; //control pin 1 on the motor driver for the left motor
int switchPin = 7; //switch to turn the robot on and off
const int driveTime = 20; //this is the number of milliseconds that it takes the robot to drive 1 inch
//it is set so that if you tell the robot to drive forward 25 units, the robot drives about 25 inches
const int turnTime = 8; //this is the number of milliseconds that it takes to turn the robot 1 degree
//it is set so that if you tell the robot to turn right 90 units, the robot turns about 90 degrees
//Note: these numbers will vary a little bit based on how you mount your motors, the friction of the
//surface that your driving on, and fluctuations in the power to the motors.
//You can change the driveTime and turnTime to make them more accurate
String botDirection; //the direction that the robot will drive in (this change which direction the two motors spin in)
String distance; //the distance to travel in each direction
/********************************************************************************/
void setup()
{
pinMode(switchPin, INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped
//set the motor control pins as outputs
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(PWMA, OUTPUT);
pinMode(BIN1, OUTPUT);
pinMode(BIN2, OUTPUT);
pinMode(PWMB, OUTPUT);
Serial.begin(9600); //begin serial communication with the computer
//prompt the user to enter a command
Serial.println("Enter a direction followed by a distance.");
Serial.println("f = forward, b = backward, r = turn right, l = turn left");
Serial.println("Example command: f 50");
}
/********************************************************************************/
void loop()
{
if (digitalRead(7) == LOW)
{ //if the switch is in the ON position
if (Serial.available() > 0) //if the user has sent a command to the RedBoard
{
botDirection = Serial.readStringUntil(' '); //read the characters in the command until you reach the first space
distance = Serial.readStringUntil(' '); //read the characters in the command until you reach the second space
//print the command that was just received in the serial monitor
Serial.print(botDirection);
Serial.print(" ");
Serial.println(distance.toInt());
if (botDirection == "f") //if the entered direction is forward
{
rightMotor(200); //drive the right wheel forward
leftMotor(200); //drive the left wheel forward
delay(driveTime * distance.toInt()); //drive the motors long enough travel the entered distance
rightMotor(0); //turn the right motor off
leftMotor(0); //turn the left motor off
}
else if (botDirection == "b") //if the entered direction is backward
{
rightMotor(-200); //drive the right wheel forward
leftMotor(-200); //drive the left wheel forward
delay(driveTime * distance.toInt()); //drive the motors long enough travel the entered distance
rightMotor(0); //turn the right motor off
leftMotor(0); //turn the left motor off
}
else if (botDirection == "r") //if the entered direction is right
{
rightMotor(-200); //drive the right wheel forward
leftMotor(255); //drive the left wheel forward
delay(turnTime * distance.toInt()); //drive the motors long enough turn the entered distance
rightMotor(0); //turn the right motor off
leftMotor(0); //turn the left motor off
}
else if (botDirection == "l") //if the entered direction is left
{
rightMotor(255); //drive the right wheel forward
leftMotor(-200); //drive the left wheel forward
delay(turnTime * distance.toInt()); //drive the motors long enough turn the entered distance
rightMotor(0); //turn the right motor off
leftMotor(0); //turn the left motor off
}
}
}
else
{
rightMotor(0); //turn the right motor off
leftMotor(0); //turn the left motor off
}
}
/********************************************************************************/
void rightMotor(int motorSpeed) //function for driving the right motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(AIN1, HIGH); //set pin 1 to high
digitalWrite(AIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, LOW); //set pin 2 to low
}
analogWrite(PWMA, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}
/********************************************************************************/
void leftMotor(int motorSpeed) //function for driving the left motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(BIN1, HIGH); //set pin 1 to high
digitalWrite(BIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(BIN1, LOW); //set pin 1 to low
digitalWrite(BIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(BIN1, LOW); //set pin 1 to low
digitalWrite(BIN2, LOW); //set pin 2 to low
}
analogWrite(PWMB, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}

View file

@ -0,0 +1,175 @@
/*
SparkFun Inventors Kit
Circuit 5C - Autonomous Robot
This robot will drive around on its own and react to obstacles by backing up and turning to a new direction.
This sketch was adapted from one of the activities in the SparkFun Guide to Arduino.
Check out the rest of the book at
https://www.sparkfun.com/products/14326
This sketch was written by SparkFun Electronics, with lots of help from the Arduino community.
This code is completely free for any use.
View circuit diagram and instructions at: https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41
Download drawings and code at: https://github.com/sparkfun/SIK-Guide-Code
*/
//the right motor will be controlled by the motor A pins on the motor driver
const int AIN1 = 13; //control pin 1 on the motor driver for the right motor
const int AIN2 = 12; //control pin 2 on the motor driver for the right motor
const int PWMA = 11; //speed control pin on the motor driver for the right motor
//the left motor will be controlled by the motor B pins on the motor driver
const int PWMB = 10; //speed control pin on the motor driver for the left motor
const int BIN2 = 9; //control pin 2 on the motor driver for the left motor
const int BIN1 = 8; //control pin 1 on the motor driver for the left motor
//distance variables
const int trigPin = 6;
const int echoPin = 5;
int switchPin = 7; //switch to turn the robot on and off
float distance = 0; //variable to store the distance measured by the distance sensor
//robot behaviour variables
int backupTime = 300; //amount of time that the robot will back up when it senses an object
int turnTime = 200; //amount that the robot will turn once it has backed up
/********************************************************************************/
void setup()
{
pinMode(trigPin, OUTPUT); //this pin will send ultrasonic pulses out from the distance sensor
pinMode(echoPin, INPUT); //this pin will sense when the pulses reflect back to the distance sensor
pinMode(switchPin, INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped
//set the motor control pins as outputs
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(PWMA, OUTPUT);
pinMode(BIN1, OUTPUT);
pinMode(BIN2, OUTPUT);
pinMode(PWMB, OUTPUT);
Serial.begin(9600); //begin serial communication with the computer
Serial.print("To infinity and beyond!"); //test the serial connection
}
/********************************************************************************/
void loop()
{
//DETECT THE DISTANCE READ BY THE DISTANCE SENSOR
distance = getDistance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" in"); // print the units
if (digitalRead(switchPin) == LOW) { //if the on switch is flipped
if (distance < 10) { //if an object is detected
//back up and turn
Serial.print(" ");
Serial.print("BACK!");
//stop for a moment
rightMotor(0);
leftMotor(0);
delay(200);
//back up
rightMotor(-255);
leftMotor(-255);
delay(backupTime);
//turn away from obstacle
rightMotor(255);
leftMotor(-255);
delay(turnTime);
} else { //if no obstacle is detected drive forward
Serial.print(" ");
Serial.print("Moving...");
rightMotor(255);
leftMotor(255);
}
} else { //if the switch is off then stop
//stop the motors
rightMotor(0);
leftMotor(0);
}
delay(50); //wait 50 milliseconds between readings
}
/********************************************************************************/
void rightMotor(int motorSpeed) //function for driving the right motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(AIN1, HIGH); //set pin 1 to high
digitalWrite(AIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(AIN1, LOW); //set pin 1 to low
digitalWrite(AIN2, LOW); //set pin 2 to low
}
analogWrite(PWMA, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}
/********************************************************************************/
void leftMotor(int motorSpeed) //function for driving the left motor
{
if (motorSpeed > 0) //if the motor should drive forward (positive speed)
{
digitalWrite(BIN1, HIGH); //set pin 1 to high
digitalWrite(BIN2, LOW); //set pin 2 to low
}
else if (motorSpeed < 0) //if the motor should drive backward (negative speed)
{
digitalWrite(BIN1, LOW); //set pin 1 to low
digitalWrite(BIN2, HIGH); //set pin 2 to high
}
else //if the motor should stop
{
digitalWrite(BIN1, LOW); //set pin 1 to low
digitalWrite(BIN2, LOW); //set pin 2 to low
}
analogWrite(PWMB, abs(motorSpeed)); //now that the motor direction is set, drive it at the entered speed
}
/********************************************************************************/
//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR
float getDistance()
{
float echoTime; //variable to store the time it takes for a ping to bounce off an object
float calculatedDistance; //variable to store the distance calculated from the echo time
//send out an ultrasonic pulse that's 10ms long
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the
//pulse to bounce back to the sensor
calculatedDistance = echoTime / 148.0; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)
return calculatedDistance; //send back the distance that was calculated
}