Monday, March 25, 2013

Arduino Basics - Pot Controlled LED Array W/ Reverse Switch And Processing Graphics

The Schematic




The Code


[sourcecode language="c"]
int but = 2;
int bval = 0;
bool state = 0;
int pot = A2;
int pval = 0;
int leds[10] = {12,11,10,9,8,7,6,5,4,3};

void setup()
{
Serial.begin(9600);
pinMode(but, INPUT);
for(int x = 3; x <= 12; x++) pinMode(x, OUTPUT);
}

void loop()
{
bval = digitalRead(but);
if (bval == 1) state = !state;

if (state == 1)
{
Serial.println(analogRead(pot));
pval = analogRead(pot);
pval = map(pval, 0, 1023, 0, 9);

for (int x = 9; x >= 0; x--) digitalWrite(leds[x], LOW);
for (int x = 9; x >= pval; x--) digitalWrite(leds[x], HIGH);
}
else if (state == 0)
{
Serial.println(analogRead(pot));
pval = analogRead(pot);
pval = map(pval, 0, 1023, 0, 9);

for (int x = 0; x <= 9; x++) digitalWrite(leds[x], LOW);
for (int x = 0; x <= pval; x++) digitalWrite(leds[x], HIGH);
}

delay(100);
}
[/sourcecode]

The Implementation




Adding Graphics With Processing




The Processing Code


[sourcecode language="c"]
import processing.serial.*;

Serial myPort;
int xPos = 1;

void setup () {
size(400, 300);
println(Serial.list());

myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil('\n');

background(0);
}

void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
String inString = myPort.readStringUntil('\n');

if (inString != null) {
inString = trim(inString);

float inByte = float(inString);
float hue1 = inByte;
float hue2, hue3;
hue1 = map(inByte, 0, 1023, 0, 255);
inByte = map(inByte, 0, 1023, 0, height);

// Have a little fun with the colors using
// the potentiometer as input
if (hue1 <= 200) {
hue2 = hue1 + 50;
} else {
hue2 = hue1 - 50;
}

if (hue1 >= 55) {
hue3 = hue1 - 50;
} else {
hue3 = hue1 + 50;
}

// Draw the line
stroke(hue1, hue2, hue3);
line(xPos, height, xPos, height - inByte);

if (xPos >= width) {
xPos = 0;
background(0);
} else {
xPos++;
}
}
}
[/sourcecode]

In Action


http://youtu.be/1nVp5KJoAPI

1 comment:

  1. [...] The Schematic The Code The Implementation Adding Graphics With Processing The Processing Code In Action http://youtu.be/1nVp5KJoAPI  [...]

    ReplyDelete