Assignment 2: State Machines, switch/case, for() loops

The second assignment is about state machines, switch/case and for() statements.

As before, go through the process of coming up with an idea, planning it, implementing it, then documenting your project. If you are going to post your project to google docs, please make sure the link is sharable with other people.

This assignment can be done using your Arduino circuit for Assignment 1. The requirements are to implement a state machine with at least four states and transition paths between those states. The transition path can be a switch, a photoresistor, a pot, or some other form of input you’ve learned outside of class.  You’re free to use other outputs or make your own switches, there’s also the collection of components in A10.

Your state machine should use switch/case to change state and for() loops to create output.

Document your entire process, from your first idea, the circuits that didn’t work, the changes you made, and what was the final result. In your documentation, ask yourself what you learned, what went wrong, what you’d do differently if you did it a second time.

To submit your project, post a reply with the documentation. Attach a zip file to that post containing your Arduino sketch, a photo of your finished breadboard circuit, and anything else you think is relevant. I’m working on how we can post video to the blog, but for now you could post it to your AFS account and link to that from your submission.

Due 23:59, Monday, 18 September. Let me know ASAP if you have a conflict and will be submitting late, if you talked to me after class please send me email as a reminder.

26 thoughts on “Assignment 2: State Machines, switch/case, for() loops”

  1. My idea for this project was to have four states of servo combinations, similar to a door opening. By clicking on the same switch, you would add to a counter that changes the case and combination of the servos. After all four combinations have been passed through, the counter is reset. In addition, I wanted to keep a series of lights that notated which combination was in use.

    zip file with process, movs, and reflections: https://cmu.box.com/s/nl98dmv8kgxaif3c7jd4to533qrhqpnr

  2. My idea was to take the concept of finite state machines from 15-251 and combine that with Arduino to demonstrate the concept of DFAs. This was a pretty successful project and I got everything working in the end.

    The Arduino circuit and program allow for you to iteratively enter bitstrings through button clicks and check which ones belong to the regular language 0^n1^m. The blue led lights up if the strings is in the language, red led lights up otherwise.

    The program is basically a DFA that runs the string through the deterministic finite state machine and decides whether the entered bitstring is in the 0^n1^m language or not.

    The issues I ran into was not introducing an artificial delay for the button press. Before, even a slight button press was entering too many digits at a single time. After the artificial delay, a single click corresponds to a single digit added to the bitstring you want to check.

    Also, I made a comprehensive video demonstration of DFAs, working and demoing the project here:
    https://drive.google.com/a/andrew.cmu.edu/file/d/0B-XYwe_ldmF9SUxUckYwMlJXZUU/view?usp=sharing

    The zip file of the code and circuit diagram is given here: https://drive.google.com/a/andrew.cmu.edu/file/d/0B-XYwe_ldmF9bC1Yc2xBRzE4YTQ/view?usp=sharing

  3. I started with the idea of using distance sensor to change the state of my system, particularly the motion of a servo. So I first had an infrared sensor because I didn’t need a wide range of distance. But I couldn’t figure out the hardware bug in the infrared sensor system I built, so I replaced the infrared sensor with an ultrasonic distance sensor. The ultrasonic sensor also had some flaws; it was acting oddly to distances that were supposed to be far but it did not register. It took me a while to find a good range and angle to place the ultrasonic sensor. In the end, I added a fun feature in which I turned the servo into an arm of a man so that the man dabs as the servo moves.

    The code and demo of my project is here: https://drive.google.com/drive/folders/0B0lS0mmjvCWPamtxOXUwbElsSVk?usp=sharing

  4. My idea for the project came from my prior assignment. I adapted my first assignment to use a potentiometer to control different states of my circuit. First, I needed to find the analogRead range of the potentiometer on the Arduino and then I used that to create 4 different states of LED flashes. As I change the potentiometer’s knob, the LEDs would flash in different sequences. The problem I ran into was trying to use a digital pin with PWM to read the analog input of the potentiometer. It did not work well probably because it was not designed for that. Using an analog pin, it worked well and the coding went smoothly.

    https://cmu.box.com/s/rl6xvekki56759kuc0rw914lz07rizsz
    https://youtu.be/8wO9_W6Jvp0

  5. My idea for this project was built upon my last project. I wanted to have states involving flashing the 10 LEDs on the LED bar in different combinations. There would also be a switch, to control the transition from one state to another.
    The states were as follows:
    1) alternate lights flash in turns
    2) alternate groups of 2 and 3 lights flash in turns
    3) alternate groups of 5 lights flash in turns
    4) all lights flash on and off.
    Moving the switch left or right triggers a change in state; therefore the state of the switch must also be kept track off. Additionally, since the groups of lights have to flash on or off, the state of the leds must also be kept track off. For loops were used to toggle groups of LEDs, and case switch statements were used to transition between different states.
    I did not experience much difficulty while making the project, but given a second chance, I think it would be a better idea to use a push button instead of a switch from a design perspective.
    https://drive.google.com/file/d/0BxDLW7cgDfWoaHpPaHI2QV81aFU/view?usp=sharing

  6. My idea for this circuit was to create a set of switches which would control the channels of an RGB LED. Specifically, there would be three switches (R, G, B appropriately) such that when you would press one switch the LED would gradually turn on (from 0 to 255) of the appropriate color. The next color pressed would cause the second channel to be turned on during the next cycle, and the final switch pressed would cause the LED to eventually glow bright white. For example, if the switches were pressed in the order of red then blue then green, the LED on the first cycle would eventually light up to red, then purple (a combination of red and blue), and then finally white. I also added a reset switch, such that when turned “on” would reset the LED so it would be off once again.

    In the last assignment, I had ran into a lot of bugs because I hadn’t planned the circuit and the code properly ahead of time. Therefore, this time, I made sure that before I constructed the circuit, I individually tested the components used in the circuit and carefully planned out the states in my state machine and what the states would consist of. I decided to have 8 states in my system: nolight, redonly, greenonly, blueonly, redgreen, bluegreen, redblue, redgreenblue. These eight states allowed me to be able to press the three switches in any possible order for the light mixing to still work. Each state would have the appropriate colors cycle from value 0 to value 255 using a for loop.

    With my components tested and circuit planned out, I started wiring the circuit. Something odd had happened to me immediately though; my Arduino wasn’t getting powered properly and required me to plug it in and out a few times before it got power again. Therefore, I made a simple test circuit (with an LED and a resistor that would just connect to 5 volts and ground) which I kept on for the rest of my circuit building. The rest of the circuit was constructed without any issue.

    I then wrote my Arduino code following my state diagram plan. I had a few issues with semicolons and parentheses, but I was able to get the code compiling fast enough. However, then I downloaded the code onto my Arduino, and weirdly enough only the Red LED was cycling through the states and the other states were responding erratically. I went back to the code again and added System print statements in every one of my case statements, so I could track which state the code had managed to get to. After seeing the output on the Serial monitor, I realized that my first state “nolight” was getting immediately bypassed to “redonly,” my second defined state. Confused, I went back to the code and realized I had forgotten a “break” statement after my first state. The circuit then worked perfectly, except I realized in my initial planning I did not see the need for a “reset” button. Therefore, I added a toggle switch in my circuit and code to serve as a reset trigger, and my circuit was working perfectly quite quickly.

    As mentioned before, my main issues caused by my previous circuit were because of a lack of planning. Therefore, this time I wanted to attack the problem with a lot of planning and see if that helped me have less bugs. My main takeaway from this circuit was that the planning in fact saved tremendous time; my debugging process for a circuit that involved 8 dependent states was substantially quicker than my previous circuit. In terms of general learning, I also realized that this was my first time really implementing a finite state machine with real physical parts (my previous experience had been in class and only created operations that worked on a specific FPGA board), so that was a good learning experience for me. If I were to redo my process, I would try to improve my pre-circuit work a little bit more, just because the main mistake I made was not realizing I would need a reset switch. If I could get more practice with honing my circuit planning, then I think I would be able to avoid that rather simple mistake.

    YouTube Link of the project: https://youtu.be/QLH9u9R9czU
    Google Drive link of the project: https://drive.google.com/drive/folders/0B6_H_AUOVi–X0x0c2NNT19aTkk?usp=sharing

  7. Idea: I wanted to play with the idea of being able to interact with light in some physical way, and so I figured it might be interesting to treat light as a fragile, spill-able liquid.

    Hardware: In order to get feedback on physical motions preformed to the breadboard, I knew I’d want to use an IMU to track rotations. Initially I planned to use a row of standard LEDs, but I found an LED bar and decided to use that instead. While I may have wanted to use more LEDs, I didn’t pick up enough resistors and wires, so while multiplexing would have saved inputs on the arduino, I still needed enough wires for each individual LED to consistently power them.

    Software: I pulled up I2C and MPU6050 (the IMU I was using) libraries so that I could quickly read information from the IMU. While the sample code I was using provided some calibration/filtering, the sensor still had pretty significant drift, making it not very reliable. I then wrote some code to control the LED bar in response to the IMU.
    I broke the states up into the following:
    1. Calibration and boot-up state (started through Serial monitor, light up LEDs)
    2. No rotation state (Light up the full bar)
    3. Slide bars to left state (When a positive rotation is detected, slide bars off left-wise)
    4. Slide bars to right state (When a negative rotation is detected, slide bars off right-wise)
    However, I ran into an issue with the example IMU code where slowing down readings would cause the sensor’s data buffers to overflow. While this didn’t have a significant effect on the project (as anti-overflow measures were in place), I would ideally only call the IMU when I want to check if it’s had a significant change in motion, keeping it in an inactive state the rest of the time.

    Images and Code with IMU and I2C Libraries:
    https://drive.google.com/file/d/0BxEy1_Wr9TRpZ0VHSDNUeDc0czQ/view?usp=sharing
    IMU test Demo:
    https://drive.google.com/file/d/0BxEy1_Wr9TRpbkU0ZVVlZXdWdm8/view?usp=sharing
    Finished Demo:
    https://drive.google.com/file/d/0BxEy1_Wr9TRpY1B4OVVFbmNnSWc/view?usp=sharing

  8. The switch/case seemed perfectly suited to my previous circuit, and the demo code from Arduino was also used with an ambient light sensor, so I just changed all my if statements to switch case statements. It worked great with the circuit, and since the code is really similar, I didn’t run into any issues with converting my if statements to switch cases.

    https://drive.google.com/drive/folders/0B0yMpI_ZOcoYNlItTzMwcUloVW8?usp=sharing

  9. I started this project by challenging myself to learn a new component: shift registers. Basically, a shift register takes two inputs, places the input into an 8-bit memory, and can illuminate multiple LEDs from that information. I am fascinated by shift registers because theoretically a computer can control hundreds (or thousands) of LEDs with only two inputs (is that how computer displays work?). I started this by watching a couple youtube videos to help me figure them out… one awesome one is this: https://www.youtube.com/watch?v=6fVbJbNPrEU&t=.

    I sketched a quick schematic of the desired circuit (before I implemented the shift register). I then rewired it to use the SR integrated circuit. Surprisingly, I didn’t have too many problems setting up the SR with the LEDs correctly, but i forgot basic steps….like connecting the ground rail to ground on the arduino. I discovered if the chip is not grounded, current flows through each of the LED pins, and they are always illuminated. During this project, I used color coordinated jumper cables, and it was a fun challenge.

    The state machine I made has four states: first state illuminates alternating LEDs, state two illuminates one after another, each second. State three illuminates the same pattern, but four-times as fast, and the fourth state does the same thing, but really quickly.

    These chips are neat because you send in a 1 or a 0, tick a clock, and that number is applied to the first slot of memory. The next time the clock ticks, a 1 or 0 is sent into the first slot, and the other slot is pushed to the second slot. This can be repeated to display a lot of information (only 8 bits on this chip). I plan to use this chip in other projects!

    Video: https://youtu.be/xZRSvtp6Jko

    Folder: https://drive.google.com/drive/folders/0B6FN8R0MrzCKU2pkWEhWU21jMVE?usp=sharing

  10. For my project I knew I wanted there to be 4 LEDs, one for each state. In order to get from one state to the other, I used a button. I added a delay to the way the button worked so that the interaction was more natural. I had the button increment the variable that the switch case was based on, and then modulo that to cycle through the modes. I then added a final mode, that used a for loop to iterate a variable from 0 to 15. I then had the 4 LEDs count up to 15 with a delay, representing the numbers in binary. After the cycle completes, it goes back to the first single LED mode.

    zip: https://drive.google.com/open?id=0B60n0Wdv4KcIOUZrd1M1VnV1ems

  11. I decided to make something that used more functionality than last time, without starting to get particularly complicated. I made a three button controller that selects menu items on a 2×16 lcd, as well as an ultrasonic distance sensor that doesn’t seem to work that well but the number kinda make sense on occasion.
    The project has seven states, with four stable ones. The way that I’m counting is slightly inflated, but the first one is a start screen that says BEEP. The next three are for each of the menu items being selected, and then the final three are the results of the selections, with the third switching to a state were it reads out the distance sensed.
    Video – https://drive.google.com/open?id=0B6bFUuOZ0DHJajdEYjF6eWdXckU
    Code – https://drive.google.com/file/d/0B6bFUuOZ0DHJa0dmakpGeVA1amM/

  12. For this project I utilized my previous configuration and implemented for () loops, switch/case, and a state machine to meet the requirements of this project. My previous code was all about 5 inputs that would turn on a light if pressed in the right order as well as an analog reading from the photo resistor. I proceeded to remove one of the 5 buttons as well as the photo resistor and work from the left over 4 inputs A-D. Since I am new to Arduino coding I did a very simple configuration in which each of the 4 buttons would make the LED behave differently. InputA would make the LED flash rapidly, InputB would make the LED pulse slower, InputC would make the LED fade from off to on, and InputC would make the LED fade to off. I practiced by trying to figure out the statement to fade on and once figured out reversed that to have it fade off and then copy pasted that into my for()loop. The rest of the commands were pretty simple.

    youtube video link- https://youtu.be/lUm5E2ytEoQ
    link to code- https://drive.google.com/drive/folders/0B_JEXda9ZXwvem9yRks3LUlrcXM?usp=sharing

  13. For this assignment, I controlled different patterns of lighting of 5 colored LEDs, -red, yellow, green, blue and white- using a button and a potentiometer. With the use of switch cases and for() loops, the button will work as the switch that chooses which light to be brightened up for the amount of times it has been pressed so far. So for instance, when pressed once, the red LED will light up and blink for once; when pressed the second time, the red LED light will turn off and instead, the yellow LED will light up and blink twice, and so on. The potentiometer would be the controller of the brightness of the LED currently lit.

    Drive Link: https://drive.google.com/drive/folders/0B70fyRiHk85qWUtYcjNxUFlTYk0

  14. In my opinion, it is possible to find ways to describe any system as a state machine. That’s what makes them so interesting to me. When given this project, one of my first ideas was to create a simple device that can detect when a person is being followed at night. The motivation for this was because of the way I feel when people close to walk places alone late at night.
    To do this, I decided to use the following components: Switch, Resistors, Photoresistors, PIR(Passive Infrared) Sensor, LED Matrix on an Adafruit LED Backpack, and a vibration motor. The concept of this project was to design a potentially wearable device that would warn someone of when they are followed. The photoresistor is placed on the face of the watch near the lED matrix. The PIR sensor can be worn as an addition to a person’s backpack. This device has 4 major operating states. There is a switch, when turned off the system is idle. That is, the device is not in the active mode for safety. It displays a graphic of an open switch on the LED matrix indicating that the device is not engaged. The second state occurs when the switch is turned on and the photoresistor detects that there is still light out. In this state, the LED matrix displays a smiley face indicating that all is good. However, when the photoresistor reads a value below the threshold, it switches into the third state. In this state, the LED matrix displays an eye indicating that the system is engaged and the PIR sensor is working. The 4th state is when the PIR sensor detects an object and this fires of the alarm. In this state there is a flashing screen and the vibration motor goes off.

    In doing this project, I was stuck for a long time because no matter what I did the photoresistor and PIR sensor were always reading high values. I tried different values of resistors for “pull-down” and nothing was seeming to work. On getting a second pair of eyes on the circuit, I found that the lead that was meant to be connected to ground was actually connected to a different pin. This was a big lesson: when something is not working, check the simplest parts of the circuit. It is easy to not connect leads in the pin you were not intending to. I also learnt that it is important to tune sensors like the PIR sensor and photoresistor to the surroundings you expect to be working in. For example, a PIR sensor will work differently in the dark as it will in daylight.

    If I were to work on this further, I would want to really fine tune my sensor parameters. I would also prototype the actual wearable and see if it is a feasible design. I would also want to make the code more robust and make sure it works for all cases. I want to create some sort of input, maybe a potentiometer, for the photoresistor threshold such that the person can pick when they want this device turned on.

    Link to drive (pictures and code): https://drive.google.com/file/d/0Bz7Or4Zn580Cb0VHNVdYNzJ5cWc/view?usp=sharing
    Link to YouTube: https://youtu.be/EC0nI5keNt0

  15. For this assignment, I built off of the previous assignment. My idea was to create an interactive light display that replicates a ripple effect that directly corresponds to the motion of the user. It works in a way that requires the user to wave their hand over the light display, and the speed at which they move their hand will be reflected by the speed of the ripple effect in the LED display. I incorporated different modes of the display to fix the issues that I encountered before. In the modified version there is now a calibration mode that assesses the environment and the amount of light that the display is exposed to. Using this information the display can then store the highest average exposure value and use it as a reference for detecting the shadow of the moving hand. This is particularly important in darker environments where the difference in exposure is smaller and the maximum brightness is considerably low. Once the display goes through the calibration mode, it can then accurately detect the shadow and run the ripple mode.
    https://drive.google.com/open?id=0B62ArY8nFitqMXRFUGxfcFU4Nmc

  16. For my project, I implemented an “occupied bathroom switch” for both female and male restrooms. A lever switch turns on and off the LED sign depending on whether or not the door is closed. Another switch determines whether or not to display the female sign or the male sign.
    I used a small 8×8 matrix to display the information.

    I had the most trouble getting the switches to give me reliable information. I had to set my lever switches’s pin mode to INPUT_PULLUP to get it to give me the values that I wanted. There is some flickering on the LED screen due to the lever switch that persists but that is hard to control because I’m using a lever switch as an on off button. I tried using a momentary switch instead but it made less sense to me so I switched back to a lever switch

    Link to code and documentation: https://drive.google.com/drive/folders/0B3_nRvY5FHyHQ0lldkQ5QUVKdjg?usp=sharing

  17. For this assignment I made a very straightforward counting mechanism. I used the framework from my last assignment, simply switching the IR distance sensor out for a tactile switch. I counted the number of times I pressed this switch, and the displayed that on the line of LEDs. After they were all lit, the counter reset. I then added several other patterns using for loops to generate the flashing repetition of the LEDS.

    I had quite a bit of trouble getting the counter to work with a for loop, and ended up using a workaround with several if statements to do the counting of the button presses. The switch cases were relatively straightforward after I figured that out.

    If I were to add something to this, I would make each of the switch cases display something more interesting than simply a counter or a random pattern. Perhaps I could set each case to display the count in binary, doing so using a sequence instead of hard coding it like I did here.

    link to zip: https://drive.google.com/open?id=0B_rqoxuDYou6ZlJCeHFHWHNjdnc

  18. My project is based on the idea of a physical/digital calendar. By pushing a button, that means a new day for this machine. The leds can try to tell people the different information: which day is it in this week, is today a solar term. The highest angle of the sun for the day throught the servo (based on the location in pittsburgh).
    Swiching into a different mode, the leds will switch from day mode to night mode. In night mode, the leds will tell different information about the moon, is it a full moon? How full will the moon be tonight.

    In this project, I had lots of syntax problems, besides that the servo didn’t work for the first several tries. Besides that, the delay in the program was a bit too long for the first time and sometimes it doesn’t register the button push. However, in one mode, the button register too fast, creating other problems.

    https://drive.google.com/a/andrew.cmu.edu/file/d/0ByluH07JIf_MT1JpUkRDcUw2ems/view?usp=sharing

  19. I want to change the LEDs’ behavior (speed or color alteration) based off of potentiometer reading
    I used the serial Monitor to read the min and max analog values for the potentiometer- they range from 90 to about 950
    We can map the potentiometer readings onto an integer var value (connected to labels 1 through 4) that the switch case loop will read to decide how LEDs behave.
    My Arduino and I have a rocky relationship. We are trying to communicate and our therapist recommended a flowchart for me to organize my thoughts before talking to it. What do I want it to do? How will it do it?

    Int var = map (potReading, potMax, potMin, 1, 4)
    Proposed Plan:
    Case 1:
    Range 1- consistent red
    Case 2:
    Range 2- consistent blue
    Case 3:
    Range 3- red and blue slow alteration
    Case 4:
    Range 4- red and blue fast alteration
    https://www.arduino.cc/en/Tutorial/SwitchCase was used to be familiarized with the format of code. I initially found that there were not 4 distinct cases being shown, case 1 and 2 just seemed like they stayed on all the time. I adjusted my code so the potentiometer value range was smaller, starting from 200 (arbitrary number greater than 90). I still can’t get the potentiometer to read correctly every time though.

    Code, pictures, video and documentation (full) are in the drive:
    https://drive.google.com/drive/folders/0B6vucT1cFrpgMTBkLUFkZXFPWWs?usp=sharing

Leave a Reply