| ((value>>7) & B111)); Serial.write( value & B1111111);} void readSerialPort() {
byte pin; int newVal; static byte actuatorHighByte, actuatorLowByte; static byte readingSM = 0;
if (Serial.available()) { if (readingSM == 0) { actuatorHighByte = Serial.read(); if (actuatorHighByte >= 128) readingSM = 1; } else if (readingSM == 1) { actuatorLowByte = Serial.read(); if (actuatorLowByte < 128) readingSM = 2; else readingSM = 0; }
if (readingSM == 2) { lastDataReceivedTime = millis(); pin = ((actuatorHighByte >> 3) & 0x0F); newVal = ((actuatorHighByte & 0x07) << 7) | (actuatorLowByte & 0x7F);
if(arduinoPins[pin].state != newVal) { arduinoPins[pin].state = newVal; updateActuator(pin); } readingSM = 0; } } else checkScratchDisconnection();} void reset() with xbee module, we need to simulate the setup execution that occurs when a usb connection is opened or closed without this module { resetPins(); reset pins
sendSensorValues(); // protocol handshaking lastDataReceivedTime = millis();} void updateActuator(byte pinNumber) {
if (arduinoPins[pinNumber].type==digital) digitalWrite(pinNumber, arduinoPins[pinNumber].state); else if (arduinoPins[pinNumber].type==pwm) analogWrite(pinNumber, arduinoPins[pinNumber].state);} void sendUpdateServomotors() {
for (byte p = 0; p < 10; p++) if (arduinoPins[p].type == servomotor) servo(p, arduinoPins[p].state);} void servo (byte pinNumber, byte angle) {
if (angle != 255) pulse(pinNumber, (angle * 10) + 600);} void pulse (byte pinNumber, unsigned int pulseWidth) {
digitalWrite(pinNumber, HIGH); delayMicroseconds(pulseWidth); digitalWrite(pinNumber, LOW);} void checkScratchDisconnection() the reset is necessary when using an wireless arduino board (because we need to ensure that arduino isn't waiting the actuators state from Scratch) or when scratch isn't sending information (because is how serial port close is detected) { if (millis() - lastDataReceivedTime > 1000) reset(); reset state if actuators reception timeout = one second } S4AFirmware16.inoS4AFirmware16.ino </pre>