Week 9: Analog and Digital Sensor

Concept

For this idea, I decided to develop a prototype of ambient light. The project makes use of a photoresistor that collects data from the ambiance and lights up an appropriate LED. Initially, I was planning on using a few other tools, in addition to the one already used, but the use of a photoresistor prevented the use of additional tools. Since the resistance of the circuit increases or decreases based on the lighting, adding a few other tools further increased the resistance in the total circuit, as a result, LEDs were not lighting up. Thus, I resorted to a simple design using two LEDs, four resistors (all 330 Ω), two switches, one photoresistor and a few lines of Arduino code. 

The idea of the project is straightforward in terms of functionality. The photoresistor detects the amount of light falling on the sensor, which then alters the resistance of the entire circuit. As a consequence of the altered resistance, the potential difference differs under varying conditions. Thus, if the potential difference falls under a particular threshold, one LED lights up and so on. 

Code

At the beginning of the program, different parameters of the project are controlled by a bunch of global variables declared at the very beginning of the file. Inside the loop() function, the readings from the photo sensor are stored in a variable called ‘volt_reading’ – the value is a range of (1-1023). However, to replicate the actual configuration, I converted this value to an equivalent volt. 

// Reading data from the photoresistor and storing it in volt_read
volt_read = analogRead(lightSensorPin);

// Mapping to a range of (0.0 V to 5.0 V)
float volt_converted = volt_read * (5.0/ 1023);

Here, the idea is similar to that of the map() function of p5.js. The value to be converted is mapped to a range of 1.0 V to 5.0 V since 5.0 V is the electromotive force (emf) of the circuit. This value is used in the latter section.

The LED controlling phase involves the use of conditional loops. The code that regulates which LED to light up is placed inside a function titled whichSensor() that takes the converted voltage reading as a parameter. The function is called recursively inside the loop() function. 

// Function that determines which LED to light up - takes converted volt reading as input
int whichSensor(int volt)
{
  int value_to_be_returned;

  if (volt >= 0 && volt < 1.8)
  {
    value_to_be_returned = 13;
  }
  else if (volt >= 1.5 && volt < 4.0)
  {
    value_to_be_returned = 12;
  }

  return value_to_be_returned;
}

Inside this function, two if-conditions run continuously and check the value stored in the argument — if the value is a range of [0, 1.8) V, digital pin “13” is used to light up a yellow LED; similarly, if the value is a range of [1.8, 5.0] V, digital pin “12” is used to light up the blue LED. 

View the entire project on GitHub.

 

Reflection 

The project involves the use of a photoresistor (an analog sensor). In order to make it more realistic, I added two switches to the circuit. Thus, if the yellow switch is pressed and the sensor is giving a certain reading, the yellow LED lights up and vice versa. 

Similarly, at first, the yellow LED was less fluorescent, so I added one 330 Ω resistor parallel to the already present resistor. This decreased the resistance of the circuit and the yellow LED was brighter. 

Overall, I am happy with the results. I wanted to include a total of three LEDs, but I could not because there are just ground terminals in the circuit — at present, all of them have been used. Moreover, my initial thought was to induce a flickering effect on the second LED when the first LED is emitting light, but the use of switches prevented this idea. Thus, one improvement could be to devise a mechanism that facilitates the implementation of the aforementioned idea. 

A partition has been placed between the LEDs and the photosensor for better visibility. Watch the completed demonstration on YouTube.

 

Analog & Digital

DESIGN

Because I am still unfamiliar with circuit building, what I created for this project is rather simple. Two elements on the board, a digital switch and a light sensor control two LED’s. When the program starts, the lights flicker in an alternating pattern with a starting interval of 500 milliseconds. However, the frequency at which the LED’s flicker is dependent on the light sensor: low levels of light cause the lights to flicker on a larger interval, and high levels of light cause the lights to flicker on a shorter interval. Finally, the switch changes the LED’s from flickering in an alternating pattern to a simultaneous pattern.

MATERIALS 

The materials I used for this project are listed below:

  • 2 LED’s
  • 3 10k Ohm resistors
  • wires
  • switch
  • light sensor

BUILDING THE CIRCUIT 

I began by building a simple 2 LED circuit like we had practiced in class. I then incorporated the switch, and finally I extended it to include the light sensor. A photo of the board is shown below:

CODE 

The most challenging part of this project was getting the button to toggle. In class, we had only worked with buttons that do something once when clicked; however, what I wanted was for the LED’s to maintain a certain pattern from the time the button was pressed to the time it was pressed again. To achieve this, I referenced the Arduino website. Ooutside of the setup() and loop() function, I define variables currentButtonState, previousButtonState, and ledState. The currentButtonState is obtained by reading the input at pin 8, which is where the switch on the board is connected. The ledState is initially set to LOW and is the variable that defines what the LED’s do. In the loop() function, the state of the button is defined by the following if statement:

if (previousButtonState == HIGH && currentButtonState == LOW) { 
  ledState = !ledState; 
  digitalRead(ledState); 
}

This statement essentially says that when the button is pressed, flip the ledState  from HIGH to LOW and vice versa. In separate if statements, I define the behavior of the LED’s, which has to options: flash simultaneously when the ledState is HIGH or flash alternating when the ledState is LOW. The code is shown below:

if (ledState) { 
  digitalWrite(LED1, LOW); 
  delay(interval); 
  digitalWrite(LED1, HIGH); 
  digitalWrite(LED2, HIGH); 
  delay(interval); 
  digitalWrite(LED2, LOW); 
}

if (!ledState) { 
  digitalWrite(LED1, HIGH); 
  delay(interval); 
  digitalWrite(LED1, LOW); 
  digitalWrite(LED2, HIGH); 
  delay(interval); 
  digitalWrite(LED2, LOW); 
}

FINAL PRODUCT

REFLECTIONS

As mentioned above, I find building circuits very challenging, while the coding portion comes more naturally to me. I am relatively comfortable coding in C, so making the transition to using C++ was not too difficult, and I actually had a lot of fun experimenting with the code. I do wish that this project could have been more creative and visually appealing, but I don’t think time allowed. I spent a lot of time taking apart the board and rebuilding the board several times so that I could better understand how the circuit was working.

 

Week 9: Analog & Digital

For this week’s assignment, I initially thought of doing a stoplight or a guessing game, but when I searched around on this website, I saw that many people have already done those concepts. I therefore decided to put a little spin on things by making a stoplight-esque guessing game. Since the potentiometer reminded me of a shower temperature dial, I made a temperature guessing game called “Swampy’s Shower”, where you help a little bathing crocodile get his desired water temperature.

I started out by assembling the basics: a blue, yellow, and red LED connected to three different pins, a digital switch to start and restart the game, and an analog potentiometer to serve as our shower dial. This was fairly straightforward, but it took so many wires. For the “interface” of the game, I used a piece of cardboard that I would slot into the breadboard to label the controls / signals. The one in the picture below is an initial version that I revised in order to also have instructions for the switch and knob.

No description available.

I had the greatest difficulty with making the digital switch because I plugged some things wrong, so I kept getting random values. Thankfully, Google and Youtube saved the day, and I got it working.

From there, writing the code was also fairly straightforward because I built my program off the Analog Switch program from class. I used a simple if else statement to compare the dial entry vs a randomly generated temperature. The switch, when pressed, starts the game. The game ends when the yellow pin flashes (when the temperature is just right!) and you can restart it again with the switch.

  if (sensorValue == randNumber) {
    Serial.println("JUST RIGHT");
    digitalWrite(yellowPin, HIGH); //just right
    digitalWrite(bluePin, LOW);
    digitalWrite(redPin, LOW);
    delay(2000);
    start = false;
  } else if (sensorValue > randNumber) {
    digitalWrite(yellowPin, LOW);
    digitalWrite(bluePin, LOW);
    digitalWrite(redPin, HIGH); //too hot
  } else if (sensorValue < randNumber) {
    digitalWrite(yellowPin, LOW);
    digitalWrite(bluePin, HIGH); //too cold
    digitalWrite(redPin, LOW);
  }

} else { //turn everything off
    digitalWrite(yellowPin, LOW);
    digitalWrite(bluePin, LOW);
    digitalWrite(redPin, LOW);
}

I tried having the LEDs flash (e.g. if the temperature is closer, the light would flash faster) but it was more distracting and annoying (and kind of made the game too easy too), so I decided to keep things simple and have the blue light be on if it was too cold and the red light be on if it was too hot. The only things I might improve would be more shower functionality (a way to turn water on? drain or fill the tub?) or maybe making the brightness of the bulb an indicator of the closeness of the answer.

No description available.

I’m very happy with my final product. Watch it here:

 

[Assignment 9] Police Light

Concept

For this assignment, I made a police light using two LEDs, a button, and a potentiometer. When the button is pressed once, the blue LED turns on; when the button is pressed twice, the blue LED turns off and the red LED turns on; when the button is pressed three times, the two LEDs turn on and off alternatively. Using the potentiometer, the user can also control how fast the two LEDs will turn on and off.

Codes

As mentioned above, this police light has 3 modes: two single-light modes and alternating lights modes. This mode (0, 1, and 2) will change whenever the user presses the button. Since Arduino will read a single button press as a series of multiple “1s,” I used millis() to make sure Arduino reads only a single 1 for every 200ms. This means Arduino will ignore any 1s that come after the first 1 within 200ms. When 1 is read, the mode will increase by 1 and back to 0 after 2. Variable blueLED is a boolean that is used to keep track of which single LED to turn on and off.

if (currentTime == 0 || millis() - currentTime > 200) {
    if (switchVal) {
      mode = ++mode % 3;
      if (mode != 2) blueLED = !blueLED; 
    }
    currentTime = millis();
  }

Then, the program will turn LEDs on and off according to the current mode. For mode 0 and 1:

if (mode != 2) {
  if (blueLED) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  } else {
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }
}

For mode 2, two LEDs turns on and off alternatively. I could have used delay() to achieve this effect, but I decided to not use such function because Arduino cannot read any other sensor data at the same time. Instead, I used millis() to do this.  pVal is a analog reading of potentiometer and the input was mapped to a value between 0 and 800. LEDs will turn on and off for every pVal ms.

int pVal = map(analogRead(A0), 1023, 0, 0, 800);

else {
  if (millis() - ledTime > pVal) {
    if (ledOnOff) {
      digitalWrite(13, HIGH);
      digitalWrite(12, LOW);
    } else {
      digitalWrite(13, LOW);
      digitalWrite(12, HIGH);
    }

    ledTime = millis();
    ledOnOff = !ledOnOff;
  }
}

Future Improvements

This project turned out to be better than I first expected. I am very satisfied about the fact that the button is functional even when LEDs are alternatively lighting up by not using delay(). For future improvements, I may be able to add more complex patterns to the LEDs, which seems challenging because no delay()s can be used. Additionally, adding piezo speaker included in the kit will make this police light more interesting and realistic.

Light Sensitive Switch

This switch uses the photodiode to create a circuit that lights the LED. When the photodiode receives enough photons, it allows current to flow and vice versa.

The switch:

A picture of the closed circuit:

Reflections:

It was fun to play with the various ways to construct a circuit for current to flow. I had a lot of options but using light to close the circuit was my favorite.

Muscle flexing switch

Concept:

For this project, I took brainstorming to another level. I actually did multiple projects but since I like gyming (although results not showing) so I decided to do the flexing the way our fathers and grandfathers did it: bicep flexing. Something that bothered me in this is that while connecting the circuit it burned my skin so much that my hands began shaking. However, I liked the project so I just went on with it.

Circuit:

a simple circuit and attach two pieces of aluminum foil on both ends of the wire where the switch would normally go. Attach one piece of foil on the bicep and the other on the forearm. When I begin flexing – the circuit is completed.

Result:

 

Reflection:

It felt really good engaging gyming in any way in an academic course. Looking forward to engaging more with circuits and Arduino.

Hands-free switch:Mini-football

Concept:

When the task stated that we can’t use hands, I immediately though about legs and thought it would fun to recreate the soccer game. The led-light goes on when the person strikes a goal(battery) with a small ball. Then the battery falls and  connects two cables, which turns on the switch. This kinda resembles the football game where you have to kick the ball on the field.

Process:

First, I made a basic circuit to turn on my led-light with a resistor 0hm 330. Then, I prolonged the circuit and added more cables and taped two cables to allow myself broader area to work. I spent a lot of time figuring out how to make the switch stay on, not light it once when the ball and cable have a collision, because ball bounces back. That’s why I added a battery as a target, which will fall and stay in the same place, so the two cables could be connected and stay on.

Reflection

It was really fun and super brain-stormin process to figure out how to make the switch on without hands, as connecting cables with hands seemed so easy and most efficient. I wish I had flat surface like domino cards, because I had a lot of trouble of the battery’s round surface, as it would roll around and won’t stay on the cables. However, this also added difficulty level to my soccer game, as scoring a goal is never easy in the real life too.

Unusual Switch

Concept

The main functionality of this unusual switch is to create a night lamp of sorts which goes into action as soon as the window blinds are closed.

Method

The method is simple: create a simple circuit and attach two pieces of aluminium foil on both ends of wire where the switch would normally go. Attach foil on the window blind. When the blinds go down – the circuit is completed.

Result

Reflections

Although there is little functionality, the design is really flimsy and it looks very unappealing. This is my first time working with Arduino and I am enjoying it so far.

Unusual Switch – Daniel Basurto

concept

For this project I was lost as to what to do until I remembered my guitar having metal strings. I gave it a test to see if the signal would go through and it did. Something that bothered me when learning guitar was how seemingly play many notes at once and not pluck the strings, my circuit makes it so that when the string is plucked the LED will light up.

circuit

My circuit is based on this one we did in class to demonstrate how switches work:

The difference being that where the button would be the 5V cable is connected to my guitar, specifically positioned to not affect the sound. And the blue cable is serving as a pick to pluck the string.  It ended up looking like this:

Circuit in action

(I couldn’t get the video to upload on the media tab, there were errors when I tried, here is a google drive link to it)

https://drive.google.com/file/d/1YEtHQ7wPWW2iyJYIZq_hYwD8EEd6IBIJ/view?usp=sharing

As you can see by the video, whenever I touch the string, the LED lights up, and when I pluck it it turns off. Due to where I put the 5V cable the sound is not altered and it can sound fully.

My only difficulty was working with the short length of the cables and the size 0f the guitar.

further improvements

Personally this is the best I can make with my limited knowledge of Arduino, however, I’d like to make another circuit like this where each string is connected to a different LED light. This could be very useful for beginner guitarists if they’d like to see what string is being plucked.

Data Visualization

Concept

For this task I decided to generate some sort of imagery based upon the music being played. There isn’t a particular reason why  wanted to implement this other than the fact that it seems pretty cool and fun to make.

Implementation

let song, buttton, fft;


function toggleSong() {
  if(song.isPlaying()) {
    song.pause();
  } else {
    song.play();
  }
}

function preload() {
  song = loadSound('bgmusic.mp3'); 
}

function setup() {
  createCanvas(600, 600);
  colorMode(HSB);
  angleMode(DEGREES); // Change the mode to DEGREES
  

  song.play();  
  fft = new p5.FFT(0.9, 128);
}

function draw() {
  background(0);
  space = width / 128;
  
  let spectrum = fft.analyze();
  //console.log(spectrum);
  for (let i = 0; i < (spectrum.length/2)+1; i++) {
    stroke(255);
    let amp = spectrum[i];
    let y = map(amp, 0, 256, height, 0);
    fill(i,125,125); //remove stroke(255);
    noStroke();
    rect(i * space, y, space, height - y);
    rect(width - (i * space), y, space, height);
    //rect(space, height ,width - (i * space), y);
  }
}


function touchStarted() {
  getAudioContext().resume();
}

Sketch (you might have to click the canvas to start)

 

Reflections

I would love to explore creating 3d visuals for the background and improving the aesthetics in general for this sketch. However, this was a lot of fun to make and I enjoyed the process.