2 * Firmata is a generic protocol for communicating with microcontrollers
3 * from software on a host computer. It is intended to work with
4 * any host computer software package.
6 * To download a host software package, please click on the following link
7 * to open the download page in your default browser.
9 * http://firmata.org/wiki/Download
13 * This firmware reads all inputs and sends them as fast as it can. It was
14 * inspired by the ease-of-use of the Arduino2Max program.
16 * This example code is in the public domain.
23 int previousAnalogValues[TOTAL_ANALOG_PINS];
25 byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore
26 byte previousPINs[TOTAL_PORTS];
29 unsigned long currentMillis; // store the current value from millis()
30 unsigned long previousMillis; // for comparison with currentMillis
31 /* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you
32 get long, random delays. So only read analogs every 20ms or so */
33 int samplingInterval = 19; // how often to run the main loop (in ms)
35 void sendPort(byte portNumber, byte portValue)
37 portValue = portValue & portStatus[portNumber];
38 if (previousPINs[portNumber] != portValue) {
39 Firmata.sendDigitalPort(portNumber, portValue);
40 previousPINs[portNumber] = portValue;
48 Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
50 for (pin = 0; pin < TOTAL_PINS; pin++) {
51 if IS_PIN_DIGITAL(pin) pinMode(PIN_TO_DIGITAL(pin), INPUT);
54 for (port = 0; port < TOTAL_PORTS; port++) {
56 for (i = 0; i < 8; i++) {
57 if (IS_PIN_DIGITAL(port * 8 + i)) status |= (1 << i);
59 portStatus[port] = status;
69 for (i = 0; i < TOTAL_PORTS; i++) {
70 sendPort(i, readPort(i, 0xff));
72 /* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you
73 get long, random delays. So only read analogs every 20ms or so */
74 currentMillis = millis();
75 if (currentMillis - previousMillis > samplingInterval) {
76 previousMillis += samplingInterval;
77 while (Firmata.available()) {
78 Firmata.processInput();
80 for (pin = 0; pin < TOTAL_ANALOG_PINS; pin++) {
81 analogValue = analogRead(pin);
82 if (analogValue != previousAnalogValues[pin]) {
83 Firmata.sendAnalog(pin, analogValue);
84 previousAnalogValues[pin] = analogValue;