int led_pin = 9; int servo_pin = 2; /* refresh time for servomotor */ int refresh_ms = 20; /* interval for switching servomotor to new position */ int switch_ms_default = 1000; int switch_ms = switch_ms_default; /* microsecond values for servomotor pulse */ int pos[] = { 2300, 1850, 1400, 950, 500 }; /* array for storing photoresistor readings */ int photo[] = { 0, 0, 0, 0, 0 }; /* current index of the pos array */ int curidx = 0; /* value by which photo[] values are decreased each cycle */ int decay = 1; /* interval for switching LED on and off */ int led_switch_ms_default = 800; int led_switch_ms = led_switch_ms_default; /* current status of LED pin */ int led_status = LOW; /* longs for storing millisecond values for various periodical events */ long last_pulse = 0; long last_switch = 0; long last_led = 0; /* number of times we've switched the LED on and off */ long switch_count = 0; /* variable for storing values read in from serial port */ byte in = 0; void setup() { pinMode(led_pin, OUTPUT); pinMode(servo_pin, OUTPUT); Serial.begin(9600); } void loop() { /* flip the LED every led_switch_ms milliseconds */ if (millis() - last_led >= led_switch_ms) { led_status = !led_status; digitalWrite(led_pin, led_status); last_led = millis(); } /* pulse the servomotor every refresh_ms milliseconds */ if (millis() - last_pulse >= refresh_ms) { digitalWrite(servo_pin, HIGH); delayMicroseconds(pos[curidx]); digitalWrite(servo_pin, LOW); last_pulse = millis(); } /* switch the position of the servomotor every switch_ms milliseconds */ if (millis() - last_switch >= switch_ms) { curidx++; if (curidx > 4) { curidx = 0; } /* every seven switches, set position to a semi-random value */ if (switch_count % 7 == 0) { curidx = in % 5; } last_switch = millis(); switch_count++; } /* serial code: send five zeros, followed by byte values for each element in the photo[] array */ for (int i = 0; i < 5; i++) { Serial.print(0, BYTE); } /* read in analog value, add to photo[] array, decay value, print to serial */ for (int j = 0; j < 5; j++) { photo[j] += analogRead(j) / 9; if (photo[j] > 1024) { photo[j] = 1024; } photo[j] -= decay; if (photo[j] <= 0) { photo[j] = 1; } Serial.print(photo[j]/4, BYTE); } /* read in serial value when available, change LED switch interval and decay accordingly */ if (Serial.available()) { in = Serial.read(); led_switch_ms = led_switch_ms_default + in * 20; decay = (in / 16) + 1; } }