Codi 1

//char val = 0; // variable to store the data from the serial port
byte val;
byte code[6];
byte checksum;
byte bytesread;

void setup() {
  Serial.begin(19200); // connect to the serial port
}

// Format output for ScratchBoard emulation
// sensor=0-7, value=0-1023 (rescaled by Scratch to 0-100)
// 0="A", 1="B", 2="C", 3="D",
// 4="Slider", 5="Light", 6="Sound", 7="Button"

void ScratchBoardSensorReport(int sensor, int value)
{
  Serial.write( B10000000
                 | ((sensor & B1111)<<3)
                 | ((value>>7) & B111));
  Serial.write( value & B1111111);
}

void ScratchSend(byte *pcode)
{
  int b;
  //ScratchBoardSensorReport(15, 4);  //firmware id
  for (int i=0; i <= 3; i++) {
    b = pcode[i+1]; //ignorem el primer   
    //b = map(b, 0, 255, 0, 1020); // codi scratch t3 > 1020 ifTrue: [t3 _ 1023].   
    b = b * 4;
    ScratchBoardSensorReport(i, b);
  }
  //  
  ScratchBoardSensorReport(4, 0);
  ScratchBoardSensorReport(5, 0);
  ScratchBoardSensorReport(6, 0);
  ScratchBoardSensorReport(7, 0);
  // Let Scratch catch up with us
  delay(30);      
}

void ScratchSend0()
{
  for (int i=0; i <= 7; i++) {
    ScratchBoardSensorReport(i, 0);
  }
  // Let Scratch catch up with us
  delay(30);     
}

void loop () {
  checksum = 0;
  bytesread = 0;

  if(Serial.available() > 4 ) {
    Serial.read();    // we read ff
    for (int i=0; i<3; i++) {   
      checksum += Serial.read();    // we read 01, 06 and 10
    }
    while (bytesread < 6) {                        
      if( Serial.available() > 0) {
        val = Serial.read();
        code[bytesread] = val;
        if (bytesread != 5)
          checksum+=val;
        bytesread++;  // ready to read next digit
      }
    }

    // Output to Serial:
 
    if (bytesread == 6) {  // if 6 digit read is complete
      /*Serial.print("6-byte code: ");
      for (int i=0; i<5; i++) {
        if (code[i] < 16) Serial.print("0");
        Serial.print(code[i], HEX);      
        Serial.print(" ");
      }
      Serial.println();*/
        
      if (code[5] == checksum){  // si el checksum es correcte
        Serial.end();
        Serial.begin(38400);
        for (int i=0; i<33; i++) // enviem durant 1 segon, cada send triga 30 msegons           
          ScratchSend(&code[0]);  
        ScratchSend0();           
        Serial.end();
        Serial.begin(19200);
      }
    }
  }
}

Obra colocada bajo licencia Creative Commons Attribution Non-commercial Share Alike 3.0 License