|
Intro to Physical Computing Syllabus Research & Learning Other Class pages
ITP Help Pages |
Tom ClassClass Notes: September 3, 2008
Arduino: first king of Italy. c based syntax. tty: teletype, cu: unix type methods and subroutines:
Programming a Switch to turn an LED on/off: void setup() { //tell the computer that pin 12 is an ouput pinMode(12, OUTPUT); //make pin 2 an input pinMode(2, INPUT); } void loop() { if (digitalRead(2) == HIGH) {
//put 5V out of pin 12
digitalWrite(12, HIGH);
}
else {
//put 0v out of pin 12
digitalWrite(12, LOW);
}
} int switchPin = 2; int switchCounterVar = 0; int switchStateVar = 0; int lastSwitchStateVar = 0; long theTimer = 0; long theDifference = 0; void setup() { pinMode(switchPin, INPUT); } void loop() { // read the switch
switchStateVar = digitalRead(switchPin);
// compare the switch to its previous state
if (switchStateVar != lastSwitchStateVar) {
// if the state has changed, increment the counter
if (switchStateVar == HIGH) {
// take note of when the button was pressed:
theTimer = millis();
}
// note how long the button was pressed for:
if (switchStateVar == LOW) {
theDifference = millis() - theTimer;
}
// save the current state as the last state,
//for next time through the loop
lastSwitchStateVar = switchStateVar;
}
} Class 2 Notes Mentioned that one week each person will enter their class notes to the class wiki. Today: Analog input. Note: Pins 0 and 1 on the Arduino are Tx and Rx for the Serial communication. Attached to the USB connection to upload/download the Arduino program. Using them may interfere with the communications. Install FTDI drivers without the Arduino plugged in The USB ports will not show up unless the Arduino is plugged in Reinstall Arduino after installing a new driver. (did I hear this correctly?) Encouraged enclosing lab projects in some way (a tissue box...etc) The placement of the buttons/enclosure will affect the user/human experience. Switches wired with pull-down resistor (as shown in the Arduino documentation). When the switch is closed, the power can find ground, so the digital input reads LOW rather than HIGH in Tom’s example of a pull-up resistor. ![]() Pull-up resistor schematic Two-position switch. Middle is common ground and closes to either of the outside legs when the switch is in one of the positions. Multi-position switch (like John’s project) Craig’s indicator lights: Conversation in interaction. The system tells you that it heard you. Get into the habit of building in some feedback so the user knows that the system is listening. Use mechanical attachments when using fragile or large pieces of metal where soldering may not work. Conductive glue...or just shove them together somehow. Use female/male connectors with 0.1” spacing for some breadboard compatible components. Making direct feedback makes the user more directly aware of their interaction rather than abstractions that have to be interpreted. Industrial designers can be lazy at times. Using serial communication to speak to the Arduino:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print(“Hello World”);
delay(100);
}
Press “Serial Monitor” on the Arduino IDE toolbar Tom presses the switch lead on the bottom of the Arduino. Without reference to power or ground, the input is “floating” - it’s acting as an antenna and picks up all stray electrical emissions...even those from your skin. Mentioned that it could be a good random number generator. Resistors: How to determine the resistors. Determine the voltage a component needs, and how much you are providing to it and calculate the difference. Voltage is always measured as the difference between two points. V = C*R (voltage = current * resistance) ![]() Simple resistor diagram Rule of thumb: Start with a big resistor and work down until the LED lights up. Use smallest LED as prudent. With a switch, start with a big resistor. Use biggest resistor as prudent. There wiggle room in electronics. Power regulators: Often have an input range and will convert to a steady output voltage. Analog sensors:
Analog inputs take in a variable voltage and use an Analog-Digital Convertor (ADC) to return an integer between 0-1023 (10-bit sensor, 2^10). Voltage divider: Two resistors in series will split the voltage between them (that’s where you place the lead to the analog input). Equal resistors will split the current equally. The ratio of the two resistors will determine the voltage between. Assuming that the two are nominally equal, if the variable resistor drops then the voltage will go up, if the variable resistor goes up the voltage goes down. ![]() Voltage divider Flex sensors...use hot glue as a strain relief and as an insulator. Wire up the switch and test with a fairly large resistor (10 kOhm - brown, black, orange. Look up Resistulator - OS X program) Demo:
// Analog input
int analogValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
analogValue = analogRead(0);
Serial.println(analogValue,DEC); // output acsii encoded decimal
}
Values from demo program are reporting a range from about 20-400. This indicates that the variable resistor and 10k are about equal. Try using a 1k resistor. Now the range is about 0-66. Indicates a smaller range coming in to the analog input. So, we can assume that the flex sensor’s range is about 5k min - 10k max resistance. With this circuit, we’ll never see the full range...so, how much range do we need? What can the person sense? What can your display use? Also, think about the physical construction of your components - this may affect the project as much as the components and code. Potentiometer - has three leads Most reliable analog sensor we’re going to get. Center pin goes to analog input, other two leads go to power and ground (separately, of course). Love-O-Meter assignment.
![]() convert an analog AC voltage (sound -1V - +1v) to 0-5V for the Arduino Divide the voltage with two equal resistors, and then feed that to the Analog input. Back to digital switches: Debounce Within a set time period check to see if the switch has changed. Simple example, with delays:
if(digitalRead(2) == HIGH) {
delay(10);
if(digitalRead(2) == HIGH)
//success
}
}
State change Look on Tom’s blog for Edge Detection: http://www.tigoe.net/pcomp/code Variable sizes int variable: 2 bytes long variable: 4 bytes Timers: use millis() to determine the milliseconds elapsed since the program began. store the time at a particular event, then subtract that time from the current time to determine the difference in time, or the duration of an event. Pseudo-code:
long theTimer = 0;
long theDifference = 0;
void loop() {
if(digitalRead == HIGH){
theTimer = millis();
}
if(digitalRead == LOW){
theDifference = millis() - theTimer;
}
}
Haptic feedback on Tom's blog - electric shock feedback. Reading discussion: http://library.books24x7.com/book/id_4587/viewer.asp?bookid=4587&chunkid=0532801905 There is a scale of interactivity. Design for the audience. What does the person want to know; what does the person need to know; what do they want to be engaged in? Become and expert in how people act; don’t necessarily become an expert in microcontrollers Class 3 - Sep. 17, 2008 Fabrication and construction techniques (Pong game from net objects class)
Feedback from observation assignment
Electricity
Class notes for Sept 24 remember to duplicate this on the itp help page. Analog Output and Intro Servomotors. This is an attempt at a transcipt of the class notes for PComp on 9.24.08. Please edit this if I misrepresented you or someone else, or you just really wish you would have said something at a specific time. Begin class with Class Questions.
TALK ABOUT OBSERVATIONS and READINGS
leading us into... analogWrite. How you get a changing voltage output from microcontroller?
void setup(){ pinMode (6, OUTPUT); } void loop(){ int sensor = analogRead (0); analogWrite (6, sensor/4); //to compensate for bit depth } with the LED connected to pin 6 and to ground the potentiometer connected to analog pin 0 The slide pot now dims the LED. SIDENOTE: 269 Electronics on Canal St. is really worth checking out for components. Tom: Now let's introduce a switch A 10kOhm switch circuit into pin 2 //when we switch from off to on LED on then fades. //search codeblog for "edge detection" int lastState = 0; int currentState = 0; void setup(){ pinMode (2, INPUT); pinMode (6, OUTPUT); } void loop(){ currentState = digitalRead(2); if (currentState != lastState) { if (currentState == 1) { //Set the LED level// ledLevel = 255; Serial.PrintIn("turned on"); } lastState = currentState; } turn on or off the LED analogWrite (6, ledLevel); //fade the LED level; if (ledLevel >0) { ledLevel --; } //serial monitor shows "turned on"// Tom: Read the switch and compare to the previous reading. If not equal and current state is 1 take action. Regardless of on or off, we want to save that the current state equals last state. The Left side is the container, the Right is what you are putting into it. On the video camera we see the LED doing a quick fade. The baseline should be at 0, though analogWrite never truly goes to 0, when LED 0, can do a digitalWrite to get to 0.
int lastState = 0; int currentState = 0; void setup(){ pinMode (2, INPUT); pinMode (6, OUTPUT); } void loop(){ currentState = digitalRead(2); if (currentState != lastState) { if (currentState == 1) { //Set the LED level// ledLevel = 255; Serial.PrintIn("turned on"); } lastState = currentState; } turn on or off the LED analogWrite (6, ledLevel); //fade the LED level; if (ledLevel >0) { ledLevel --; else { //turn the LED off; digitalWrite (6,LOW); } } Tom: The LED blinked, why? turn on or off the LED analogWrite (6, ledLevel); //fade the LED level; if (ledLevel >0) { turn on or off the LED analogWrite (6, ledLevel); ledLevel --; } else { //turn the LED off; digitalWrite (6,LOW); } } Pulse Width Modulation, or PWM.
missed information
if (millis() - lastFadeTime >10){ //fade the LED level if (ledLevel >0) { turn on or off the LED analogWrite (6, ledLevel); ledLevel --; } else { //turn the LED off; digitalWrite (6,LOW); } lastFadeTime = millis(); } }
NOW code switched so that (currentState==1) switch release now activiates LED
This will be saved on the wiki as "fade_switch"
set ledLevel to peak number, ex. 25 analogWrite can only be used on pins with PWM 3,5,6,9, 10, 11 NOW SERVOMOTORS! RC servomotor or hobby servo motor. only turns 180deg, but can position precisely within those. Any motor will draw more current than the pins can provide. one servo maybe on usb power, but more than that is too much. Arduino 12 has a simple servo library now. One limitation is that it can only run servo on PWM pins. Tom: let's start with new way and work back to this. in order to use the library, you have to import it. sketchbook\examples\library servo Servo myservo; int potpin = 0; // val = analogRead potpin) map is neat function floats take a lot of memory, don't use them here.
There are many ways to do this; to have a person doing an action and creating an unexpected response. Tom: There are many other types of motors.
Don't forget, tips and tricks on laser cutter this friday. 1 millisecond is one extreme, 2 milliseconds is the other extreme, pulse every 20mS no matter what. lets look at the code, also has instruction on map function minPulse and maxPulse lastPulse refreshTime analog value for reading this ex can use any digital IO pins turning pin on , delaying a couple microseconds, turning pin off
this method is in its delay. the PWM that analogWrite uses has an independent piece of hardware that sets n forgets the thing.
dim, sound,
TRANSISTORS... as mentioned many times, arduino can only output a small amount of current. A transistor, consisting of a base, a collector and an emitter. TIP 120 better for motors and such. can use an NPN2222 transistor, which is better for general switching.
so... 5v w=v*a 25w = 5v * 5=8ohms*current 5/8 of an amp (625mA) /*reading for next week User Illusion. Attend a safety session or we will be shut down*/ How to look at datasheets for npn2222. digikey supplies datasheets. We notice there are many different models. TO-92 or TO-220 form factor? I am still looking for good site to explain electronic packages. ours is a PNPN2222a Jeremiah: how did you determine that? Tom: NPN PNP one is p-dote one is n-dote? The middle layer is where the base is, the middle layer changes the PNP voltage and makes it turn off; NPN makes it turn on. diodes are 1n, like the 1n4004 (Check out Mims', Getting Started in Electronics for an illustrated explanation of this) The datasheet shows volt maxes at each pin. 6v max works fine for us working at 5v. Use transistors to control a awhole bunch of LEDs. Robert: Would we need external power?
Tom: This is one way to get 12v through arduino.
Alex: Since power is the same, why is it louder?
LED fading from a switch code from class today October 8 code: Arduino:
void setup() {
Serial.begin(9600);
while (Serial.available() <= 0 ) {
Serial.println("hello");
delay(300);
}
}
void loop() {
if (Serial.available() > 0) {
int inByte = Serial.read();
int mySwitch = digitalRead(2);
int x = analogRead(0);
int y = analogRead(1);
Serial.print(x, DEC);
Serial.print(",");
Serial.print(y, DEC);
Serial.print(",");
Serial.println(mySwitch, DEC);
}
}
Processing:
import processing.serial.*;
Serial myPort;
boolean firstContact = false;
float xPos = 0.0;
float yPos = 0.0;
float visible = 0.0;
void setup() {
size(600, 400);
String portName = Serial.list()[0];
println(portName);
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void draw() {
background(0);
fill(visible);
ellipse(xPos, yPos, 20, 20);
}
void serialEvent(Serial myPort) {
String inputString = myPort.readStringUntil('\n');
if (inputString != null) {
inputString = trim(inputString);
if (firstContact == false) {
if (inputString.equals("hello")) {
myPort.write("\n");
myPort.clear();
firstContact = true;
}
}
else {
// println(inputString);
int[] numbers = int(split(inputString, ","));
for (int thisNum = 0; thisNum < numbers.length; thisNum++) {
print(numbers[thisNum] + "\t");
}
println();
// make sure you have enough numbers:
if (numbers.length > 2) {
xPos = map(numbers[0], 400, 600, 0, width);
yPos = map(numbers[1], 400, 600, 0, height);
visible = numbers[2] * 255;
}
myPort.write("\n");
}
}
}
October 26 Class begins by going over the schedule for the rest of the semester. Now that mid term projects are completed, we’ll be spending a lot of our time working through final projects. There will be specialized lessons being taught, however, classes will be less structured in terms of assigned labs. Alex showcased his piece that involves using fans to ‘blow apart’ an image. The class spent time devising ways to construct a physical interface to manipulate the image in a myriad of ways. Some suggestions include: using a wiimote, a fan, IR light, conductive fabric, LED circular ring, etc. Anthony asks about a q-prox(?) sensor to detect presence. Tom suggests using a capacitive touch sensor senses the capacitive field using an antenna. It can tell if someone is close to it (an inch or so). Anthony wants to work with electromagnetism in some way – he’s not entirely sure what he wants to do with it yet. Tom asks, “Are you trying to showcase a sensor? Or show how that sensor effects something else? Try to do the latter.” He also explains that multi-touch is difficult because of interference and insists of trying to use a sensor that ‘does it all’, find one that is the best one (or multiple sensors) for the job. Jeremiah wants to improve the Arduino sound capabilities and enhance midi functionality. It’s a great idea and we discussed the feasibility and advantages of creating this (using a shield). The biggest advantage would be the portability (wearable) factor. However, there is a disadvantage in computing this kind of data on an arduino because its computer is small it could be inefficient – it might be better to simply transmit the midi data to a computer (which is much more powerful) via radio, especially if you will be amplifying sound using an external source. So, it’s something to consider – it all comes back to the same questions: “What is it’s intended use? How will you use it? And where will you be using it?” Many times it is beneficial to use existing protocols (ex: midi or serial), rather than developing your own because existing protocols often speak to multiple programming languages. This makes things much easier. Another project idea has to do with ‘a history chair’, that records who has spent time sitting in the chair. While it displays images or video of people who have spent time sitting in the chair, it records you as well. It’s almost like a mirror. However, this may need to be expanded slightly because all of the videos will display people watching other people watching. So, the details will make this project work – you remember the details. Does the recording happen immediately when the user sits? Can lighting effect or invoke a response? Is this a gallery space, a school principal’s office, a bar stool or something else? Is a message being displayed that the user is supposed to react to? Maybe we could use a movie theater chair or try to find a way to create the illusion that other people are around you. These are important things to consider before you being working. The idea is to show that the user feels a sense that they are part of a larger audience. Another project has to do with creating anti-paparazzi devices. For instance, a celebrity could rotate a purse (when a paparazzi dude appears) that would trigger an invisible flash located on a celebrities clothing that would ruin a photographer’s photographs. Perhaps it could use infrared LEDs that only the camera would pickup. Next we switched gears and began talking about advanced serial processing. What is important when considering using another protocol (such as midi) 1. How much data can I send? 2. How do we communicate with the protocol 3. How responsive is it Asynchronous has two independent clocks and they sync up Synchronous is one clock that simply pulses and gets what it can. Wiichuck uses synchronous serial. Then we spoke about XBee. A modem converts data into a series of pulses or tones. A receiver can decode these tones back into serial data. The XBee works this way as well via radio. The protocol is 802.15.4 (XBee commands scheme). Tom is showing how to communicate to an LCD screen using the XBee controller wirelessly from the desktop. Look ma, no wires! The program that is on the arduino is simple. It simply pulses data to the XBee. We need a serial term to write to this. Tom is using ZTerm because of the way that the protocol is structured. There are two modes: Data mode and command mode. Data mode talks to the radio. Command mode speaks through the radio. An AT command always starts with ‘AT’. For instance, ATDL sets the destination address. ATMY gets my address. ATID gets area networked identifier. ATID prohibits interference. The point is that we are configuring them so that we can communicate. Bookstore sells XBee Explorer (about 20 bucks) as a receiver for your laptop that works with the XBee transmitter. When typing in Zterm, everything is on one line, but you can changed this in ‘settings’ located in the menu bar of the program. You can broadcast from one transmitter to multiple receivers. XBee radios run on 3.3 volts. It’s best to use the breakout board for use with a breadboard. The terminal will revert to data mode after 3 seconds, so it’s important to type ‘+++’ to return to command mode. Typed into Zterm: +++ AT101066 ATDL3 ATMY1 ATWR (writes it to chips permanent memory) In processing, we can debug our circuit:
Import. Precessing.serial.*;
Serial myPort;
String myString;
Void setup()
{
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600)
}
void keyRelease()
{
if(key == ‘ ‘)
{
myPort.write(myString + “\n”);
myString = “”;
} else {
myString += key;
}
}
code from 10/29/08
import processing.serial.*;
Serial myPort;
String myString;
void setup() {
println(Serial.list() );
myPort = new Serial(this, Serial.list()[0], 9600);
myString = "";
}
void draw() {
}
// this part sends a string whenever you hit return.
// any other keys will be added to a string
void keyReleased() {
if ((key == ENTER)|| (key == RETURN)) {
// send the string
myPort.write(myString + "\n");
// clear my string:
myString = "";
}
else {
myString += key;
}
}
// this part is untested!!!!! It should change the addresss on the fly
void changeTheAddress(String newAddress) {
String message = "";
// send +++
message += "+++";
myPort.write(message +"\r");
// wait a sec until it says OK
while (inString != "OK") {
// wait for incoming OK
}
// send ATDL + address
message += "ATDL";
// send ATWR
// Send ATCN
myPort.write(message + newAddress + ",WR,CN" + "\r");
}
|