Project 2 – Flex-It

If for some reason you and a friend ever wondered who was better at flexing a flex sensor just right you can now settle it with Flex-it. Flex-it is a my second original project working with the SparkFun RedBoard.
CS111 Project2 -1
Flex-It is a small game in which two players each has a flex sensor which corresponds to each players’ own LED, either red or blue. The LEDs begin light and as you flex the sensor you either make the LED brighter or dimmer. The object of the game is to dim your light below a certain point. Whoever succeeds at this first wins the game and locks the sensors and LEDS. To make sure the players know who has won the RGB LED will light up with the appropriate winning color, i.e. if the blue player wins the RGB LED will light up blue and if the red player wins it will light up red. After that if you push the button the RGB LED will flash green and the game will reset. If the players want to keep track of their score they can open up the Serial display for this. However, make sure to open it before you begin playing, because it will reset if you open it up after a few rounds and you will not have records of who won those.

(My apologizes about the difficulty to read the computer screen. It simply displays the score after each light has been lit up.)

The assignment called for us to use analog inputs and outputs. After playing around with a flex sensor in class for a while and using it with a motor, I found the device was rather interesting to use and figured I should explore it more. After some thought I decided I liked the idea of having two players compete to turn off LEDs. I started sketching this idea and then decided I should add the RGB LED so that it was more clear who was the winner. Shortly after I decided that it would be good idea to add a button to the set up so that it would be easy to reset the game. This idea appeared even better when I began coding and found that originally I would have to reset the whole Redboard to get the game up and running and that was more of a hassle than it should be.

Some of my biggest challenges came with the wiring, I made a few dumb mistakes hooking up resistors and wires to appropriate parts. For example I accidentally hooked up the push button wrong and had the five volts running in the same row as the wire attached to the pin, thus making it read wrong. I also had some trouble setting up the appropriate range for the flex sensors and LED brightness. This range may be able to be adjusted slightly more accurately with more skilled and practiced hands, but I feel I got it as close as I could. It also took me a while to get the code for the push button worked out. I had to get the help of my instructor to figure out to use the return() function correctly. Finally, I had the idea to keep track of the score and have it be posted to the Serial display using Serial.println();. After that I had the finished product seen below.

CS111 Project2-2

CS111 Project2-3

If you’d like to build your own Flex-It then read below for schematics, parts, and the code.

Parts:
(1) SparkFun Redboard or Arduino Uno
(1) Blue LED
(1) Red LED
(1) RGB LED
(2) Flex Sensor
(5) 330 Ohm resistor
(3) 10K Ohm resistor
(1) push button
(Approx. 19) Wires

The basic schematic and sketch can be seen below
Project 2_bb

Project 2 skematic_schem

You want to hook up the a wire attached to 5 volts to one end of the flex sensor, it should be to the side that leads to the thin line of the flex sensor. From the other side you want to run a 10K Ohm resistor to ground and then have a wire hooking it up to one of the analog output pins, I used A0 and A1. You want the negative end of the blue and red LEDs and the ground pin of the RGB LED to run to ground. Then run a wire from pin 11 through a resistor and into the positive side of the blue LED. Do the same with the red LED to pin 10. You can use any pin you desire, as long as it has pulse width moderation – marked by a tilde (~) – since we will be using analog output for these LEDs. Then hook up the red, green, and blue pins of the RGB LED to any digital output pin, I used 9, 8, and 7 respectively. Run 5 volts into one row of the button and run wire out of it to a digital pin and through a resistor to ground.

The code I used is listed below, feel free to make any modifications deemed necessary.


/* Flex-it
The game should work that two players flex the sensors
with the intent of dimming the light to a certain point.
Whoever succeeds first the RGB LED will light up that color, i.e.
if blue wins then the RGB LED will light up blue.
If the push button is pressed it should reset the circuit so
it can be played again. And if the Serial screen is opened it will keep
track of the score, though it must be started before the two players begin.
*/
//Set up variables
const int blue = 11;
const int red = 10;
const int RGBred = 9;
const int RGBgreen = 8;
const int RGBblue = 7;
const int pushButton = 2;
const int minRed = 15;
const int maxRed = 330;
const int minBlue = 15;
const int maxBlue = 345;
int counterRed = 0;
int counterBlue = 0;

void setup() {
  // set up our inputs
  pinMode(pushButton, INPUT);
  //set up our outputs
  pinMode(RGBred, OUTPUT);
  pinMode(RGBgreen, OUTPUT);
  pinMode(RGBblue, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  
  digitalWrite(RGBgreen, LOW);
  int redSensor; // define a variable for the red light's sensor
  int blueSensor; // define a variable for the blue light's sensor
  int redMap; // map the range of the red sensor to fit analog values better
  int blueMap; // map the range of the blue sensor to fit analog values better

  redSensor = analogRead(A1);
  blueSensor = analogRead(A0);



  //have the values of the sensors sent to our computer
  //so that we can set our output to the most appropriate values
  //Serial.println("redsensor:");
  //Serial.println(redSensor);
  //Serial.println("redmapping");
  //Serial.println("bluesensor:");
  //Serial.println(blueSensor);
  //delay(1000);
  //These were used for debugging and are limited to comments
  // so the final score can be displayed with less clutter.

  //constrain the results of our sensor to the sweet
  //spot of the flex senors
  redSensor = constrain(redSensor, minRed, maxRed);
  blueSensor = constrain(blueSensor, minBlue, maxBlue);
  //map the values of the sensor to be more accurate
  //with analogWrite
  redSensor = map(redSensor, minRed, maxRed, 0, 255);
  blueSensor = map(blueSensor, minBlue, maxBlue, 0, 255);

  analogWrite(red, redSensor);
  analogWrite(blue, blueSensor);
  int buttonState; // set up a variable to use for our reset button


  while ((redSensor < minRed)) { //indicates that red won
    digitalWrite(RGBred, HIGH);
    analogWrite(blue, 255);

    buttonState = digitalRead(pushButton); //check the value of the push button
    if (buttonState == HIGH) { //resets the game
      analogWrite(red, 0);
      digitalWrite(RGBred, LOW);
      analogWrite(blue, 0);
      digitalWrite(RGBblue, LOW);
      digitalWrite(RGBgreen, HIGH);
      counterRed++; // keeps track of how many times red has won.
      Serial.println("Red Wins:");
      Serial.println(counterRed);
      Serial.println("Blue Wins:");
      Serial.println(counterBlue);
      delay(1000);
      return (loop());
      Serial.println("it works"); // message to ensure the switch work

    }
  }

  while ((blueSensor < minBlue)) { //indicates that blue won
    digitalWrite(RGBblue, HIGH);
    analogWrite(red, 255);

    buttonState = digitalRead(pushButton); //check the value of the button
    if (buttonState == HIGH) { //resets the game
      analogWrite(red, 0);
      digitalWrite(RGBred, LOW);
      analogWrite(blue, 0);
      digitalWrite(RGBblue, LOW);
      digitalWrite(RGBgreen, HIGH);
      counterBlue++; // keeps track of how many times blue has won.
      Serial.println("Red Wins:");
      Serial.println(counterRed);
      Serial.println("Blue Wins:");
      Serial.println(counterBlue);
      delay(1000);
      return (loop());
      Serial.println("it works"); // message to ensure the switch worked
    }
  }
}

The code is rather simplistic. The comments clarify most of the points, but I will go over the main points here as well. Basically the code starts out setting up our variables and then we tell it to read the input value of the analog pins (we do not need to specify these as inputs at the top since they are analog). We then read these values and found a range to use. We use this value to constrain the values we read and then to map it to a relative range for our analog outputs. The code then continues to check these until either the red or the blue analog out reads as less than the minimum, in which case it will light up the RGB LED and stop calculating the analog values. It also adds one to the appropriate scorer’s points. Then the code checks for the status of the push button and if it reads as high it returns to the beginning of the loop and the code repeats as long as it has power.

The project could be extended to any form of analog input, such as a potentiometer. It would also help to use a larger breadboard to avoid as much clutter. The larger breadboard would also allow for using a LCD display for the score rather than the computer Serial monitor. If I had had room I would have incorporated this, but I thought of it too late to update the size of the breadboard. As I said earlier the values for the maximums and minimums could probably be altered to give more precision as well. Also I occasionally have issues where the flex sensors will come out of their pins while being flexed. This may be a user error, but it would still help if there was a way to get them to stay put better.

Thanks for reading and I hope you enjoyed!

Topic Plan

Looking over the list of topics I believe I want to put a focus on the following list of topics:
LED matrix, Ethernet, Piezo buzzer or possibly speakers, triple-axis accelerometer or possibly an ultrasonic range finder, shift registers, servo motor, position GPS, temperature sensor, and time GPS.

I am not fully sure exactly what I want to do with all of these just yet, but I have a few rough ideas worked out. One idea I had worked out is to use the Ethernet, position and time GPS, and the temperature sensor to create a device that reads the temperature where some one is and posts it online. It could include some notes as well with the temperature, such as what to wear maybe. This is just a rough idea, but I know I want to use the Ethernet at some point in the semester. This could be one of the first independent projects I work on. I also thought perhaps I could use either the triple-axis accelerometer or the ultra sonic range finder – whichever I decide – with the servo motor to create another device, I will have to put more thought into it to decide exactly what I would want it to do. Perhaps I could include the shift register with it. Also being a large fan of video games if I could I would like to use the LED matrix and Piezo buzzer/speakers to make some form of simple game, much like this girl did with Super Mario Bros. https://vimeo.com/9928343. If the game had a scoring system I could use the Ethernet cable to post scores onto the internet. If I could make it advanced enough this would be one idea for my final project. I would also use as many of these skills and parts as possible in my numbered projects as well, such as using the Piezo buzzer in Project 1.

Project 1 – Mini Singing Light

My first simple little project working with the SparkFun Redboard. Since it’s primary purpose is to light up a RGB LED and to play a song it has creatively been named the Mini Singing Light.
CS111 Project 1-2
The device has an impromptu switch made from a small key taped to a post-it note. When the wire is not connected, and thus the switch is open, the RBG LED cycles through several different colors. When the switch is closed the LED turns red and and the buzzer begins to play a tune. While the switch is closed the LED remains red and flashes green along with the tune. It will continue to play for the entire time the switch is closed and then will replay as many times as possible until the switch is opened.

The assignment called for me to use a RBG LED, a switch, and whatever else I desired. After a little thought I decided that I wanted to try and use the Piezo buzzer and have the LED flash colors along with it. After a little thought I decided to try and make the device sing “Daisy Bell” as a homage to the wonderful HAL 9000. I broke this song down to its notes – as much as I could at least given that I have no musical talent at all – and entered it into code using a code from the SparkFun Inventor’s Kit as a guideline. I originally had the intention of having the LED be just red while the switch was off and then have it cycle through colors while the switch was on and the tune playing. I ran into difficulties while trying to code this so I ended up changing it to the final result.

The largest challenge came with getting the switch to work properly. Once I got the base code down for the tune and lights I noticed I had the issue that once the switch was turned on I had to listen to the entire tune play, even if I turned the switch off in the middle of the process. I tried several different methods, including trying while, for, do, and switch statements, but I was still stuck on the same issue. After seeking help I found that while I was saying I wanted the code to do a specific action if the value of switchState() changed, my code was missing the important comand to actually check if these changes were occurring, and thus was not acting correctly. After this and making the code a little cleaner I arrived at the final product seen here.
CS111 Project 1- 1

If you are interested in building your own little singing light keep reading to find parts, schematics, and code. This is a very simple project and, since I am a beginner, it is very easy for beginners to construct.

Required Parts:

(1) SparkFun Redboard/ Arduino Uno
(1) RGB LED
(1) Piezo buzzer
(1) 10k Ohm resistor
(3) 330 Ohm resistors
(11) wires
(1) switch (the assignment called for us to make our own switch, you can use a button switch or any other that you desire)

The basic schematic and sketch can be seen below.

Project 1 skematic_schem
Project 1 sketch_bb
You want to hook up the switch to the 5V pin and have it run to pin 2 if closed and through the 10k Ohm resistor to ground. Make sure to run the positive end of the buzzer to pin 13 on the redboard/ Arduino and the negative to the ground if open. Then make sure to hook up the LED to the appropriate pins, red to 12, green to 11, and blue to 10. Make any necessary corrections if your LED differs the order of the colors.

The code I used is found below, copy and paste it to achieve the desired result.


/* Mini Singing Light
Uses a RBG LED, switch, and Piezo buzzer to create a small device that plays 
a song and lights up red and green when the switch is closed and cycles through 
colors while the switch is off.
*/

// Set up the variables
const int buzzer = 13;
const int red = 12;
const int green = 11;
const int blue = 10;
const int switch1 = 2;
int time = 1000;
int multiple = 2;
int previous = LOW;
  // set up variables to hold the state of our switch
int switchState = digitalRead(switch1);

void setup() {
  //set up our switch to be a digital input
  pinMode(switch1, INPUT);
  // set up our LED and buzzer to act as a digital output
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {


//set up variables for the tune of our song
const int songLength = 54;

char notes[] = "dbgdefgegd adbgefgaba bcbadbagabgeged dgba gbabcdbgadg"; 
//a space represents a rest

float beats[] = {0.75,0.75,0.75,0.75,0.25,0.25,0.25,0.50,0.25,
1.25,0.25,0.75,0.75,0.75,0.75,0.25,0.25,0.25,0.5,0.25,1,0.25, //second rest
0.25,0.25,0.25,0.25,0.5,0.25,0.25,1,0.25,0.5,0.25,0.5,0.25,
0.25,0.75,0.25,0.25,0.5,0.25,0.5,0.25,0.5,0.25,0.25,0.25,0.25,0.25,
0.25,0.25,0.5,0.25,1};

int tempo = 250;

int i,  duration;

/* 
if the switch is on it should light up the light and play a song
if the switch is not on the LED should cycle through different colors.
*/
switch (switchState) {
  case 0:
blink();
  case 1:
{
  digitalWrite(blue, LOW);
  digitalWrite(green, LOW); 
   for (i = 0; i < songLength; i++)
  {
      switchState = digitalRead(switch1);
      if (switchState == LOW) break;
    duration = beats[i] * (4 * tempo);
    if (notes[i] == ' ')
    {
      delay(duration);
    }
    else
    {
     
      tone(buzzer, frequency(notes[i]), duration);
      digitalWrite(green, LOW);
      digitalWrite(red, HIGH);
      delay(duration);
      digitalWrite(green, HIGH);
      digitalWrite(red, LOW);
      
    }
  delay(tempo/40);  
  }
}
  break;
}
  
}

// this function sets up the cycle of colors for when the switch is turned off

int blink() {
    digitalWrite(green, LOW);
  digitalWrite(blue, HIGH);  //blue
  switchState = digitalRead(switch1); 
   if (switchState == HIGH) return(0);
   delay(time);
   digitalWrite(green, HIGH); //cyan
    switchState = digitalRead(switch1); 
   if (switchState == HIGH) return(0);
   delay(time);
   digitalWrite(blue, LOW); //green
    switchState = digitalRead(switch1); 
   if (switchState == HIGH) return(0);
   delay(time);
   digitalWrite(red, HIGH); //yellow
    switchState = digitalRead(switch1); 
   if (switchState == HIGH) return(0);
   delay(time);
   digitalWrite(blue, HIGH); //white
    switchState = digitalRead(switch1); 
   if (switchState == HIGH) return(0);
   delay(time*multiple);
   digitalWrite(green, LOW);
    switchState = digitalRead(switch1); 
   if (switchState == HIGH) return (0);
   delay(time);
   digitalWrite(red, LOW);
  return (1);
}
//This function takes the note character and returns the necessary frequency in Hz
//This code was adapted from example Circuit_11 of the 
//SparkFun Inventor's Guide: Verson 3.2 <sparkfun.com/sikcode>
int frequency(char note) {
  int i;
  const int numNotes = 8;
  
  char names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};
  
  for (i = 0; i < numNotes; i++)
  {
    if (names[i] == note)
    {
      return(frequencies[i]);
    }
  }
  return(0);
}
// song adaption from "Daisy Bell" composed by Harry Darce. 1892. 
//Copyright: Creative Commons Attribute 3.0 
//<http://www.8notes.com/scores/4117.asp>
  

The code is relatively straight forward and if you read the comments it should explain any confusion.
Being new to writing code it is more than likely that the code could be simplified. As I talked about earlier, the process of getting the code to recognize when the switch was on or off was the largest challenge.

The code and set up should work with any song as well, though you will have to break down the notes and beats to fit it correctly. Also you may need to play around with the tempo. It may also be more interesting to include more LEDs so that the light show is more fancy.

Thanks for reading my friend. And may the force be with you 🙂

 
“Daisy Bell” composed by Harry Dacre. 1892 Copyright: Creative Commons Attribute 3.0 http://www.8notes.com/scores/4117.asp#info