Delay-less delays
Arduino
code
long timer1 = 0;
int timer1offset = 200;
long timer2 = 0;
int timer2offset = 300;
long timer3 = 0;
int timer3offset = 20;
long timer4 = 0;
int timer4offset = 300;
int led1pin = 7;
int led2pin = 6;
int led3pin = 11;
int led4pin = 10;
int pin1val = LOW;
int pin2val = LOW;
int readPin = 4;
int readPinVal = 0;
void setup() { // The standard stuff...
Serial.begin(9600);
pinMode(led1pin, OUTPUT);
pinMode(led2pin, OUTPUT);
pinMode(led3pin, OUTPUT);
timer1 = millis();
timer2 = millis();
timer3 = millis();
}
// Das Loop...
void loop() {
// Timer 1
if((timer1 + timer1offset) < millis() ) {
timer1 = millis();
pin1val = !pin1val;
}else{
doBlink(led1pin,pin1val);
}
// Timer 2
readPinVal = analogRead(readPin);
if((timer2 + readPinVal) < millis() ) {
timer2 = millis();
pin2val = !pin2val;
}else{
doBlink(led2pin,pin2val);
}
// Timer 3
if ((timer3 + timer3offset) < millis() ) {
doPWMled(led3pin, 128, 1);
timer3 = millis();
}
}
void doBlink(int whichPin, int whichVal) {
digitalWrite(whichPin,whichVal);
}
int pinVal = 0;
int rampUp = 1;
void doPWMled(int whichPin, int topVal, int rampSpeed) {
if (rampUp) {
pinVal = pinVal + rampSpeed;
}else{
pinVal = pinVal - rampSpeed;
}
if (pinVal>=topVal) {
rampUp = 0;
}
if (pinVal <= 0) {
rampUp = 1;
}
analogWrite(whichPin,pinVal);
Serial.println(pinVal);
}
Processing & Arduino Communications
Arduino
Code
int ledPWMpin = 11;
byte byteVal = 0;
char myString[] = "No Connection";
void setup()
{
// begin the serial communication
Serial.begin(9600);
pinMode(ledPWMpin, OUTPUT);
}
void loop()
{
byte byteVal;
// check if data has been sent from the computer
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255)
byteVal = Serial.read();
Serial.println(byteVal,DEC);
// set the brightness of the LED
analogWrite(ledPWMpin, byteVal);
}else{
Serial.println(myString);
}
}
Processing
Code
import processing.serial.*; // Import the 'serial' library to add
// serial port functionality to processing.
// The '*' after serial tells processing to
// import all the sub libraries associated with
// serial.
Serial myPort; // Serial is now an object type for which we can
// declare a variable, 'myPort,' in which the
// instance of the object is stored.
void setup()
{
size(256, 256); // Open a window that 256 x 256 pixels in size.
// Note that 256 corresponds to the number of
// values that the Arduino analogWrite can handle.
println("Available serial ports:");
println(Serial.list());
// Uses the first port in this list (number 0). Change this to
// select the port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your
// Arduino sketch.
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw()
{
// write the current X-position of the mouse to the serial port as
// a single byte
myPort.write(mouseX);
}
