'use strict';
goog.provide('Blockly.Arduino.BTarduino');
goog.require('Blockly.Arduino');

///////////////////////////////////////////Declearations 

var kMuName = 'Mu'
var funMuVs2GetColorRCGLabel = '\
int MuVs2GetColorRCGLabel(MuVisionSensor& Mu, int x, int y) {\n\
  static int x_last = -1;\n\
  static int y_last = -1;\n\
  x = x>100 ? 100:(x<0 ? 0:x);\n\
  y = y>100 ? 100:(y<0 ? 0:y);\n\
  if (x != x_last) {\n\
    x_last = x;\n\
    Mu.write(VISION_COLOR_RECOGNITION, kXValue, x);\n\
  }\n\
  if (y != y_last) {\n\
    y_last = y;\n\
    Mu.write(VISION_COLOR_RECOGNITION, kYValue, y);\n\
  }\n\
  return Mu.GetValue(VISION_COLOR_RECOGNITION, kStatus);\n\
}\n\
                              ';
var funMuVs2GetColorDetectLabel= '\
int MuVs2GetColorDetectLabel(MuVisionSensor& Mu, const int label) {\n\
  static int label_last = -1;\n\
  if (label_last != label) {\n\
    label_last = label;\n\
    Mu.write(VISION_COLOR_DETECT, kLabel, label);\n\
  }\n\
  return Mu.GetValue(VISION_COLOR_DETECT, kStatus);\n\
}\n\
        ';

  Blockly.Arduino.metrix_LED_Init = function() {
  var SDA = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  var SCL = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
  var matrixName = this.getFieldValue('matrixName');
  var fre = this.getFieldValue('Brightness');
     Blockly.Arduino.definitions_['define_Display0'] = '#include <Adafruit_GFX.h>';
     Blockly.Arduino.definitions_['define_Display1'] = '#include <TM1640.h>';
     Blockly.Arduino.definitions_['define_Display2'] = '#include <TM16xxMatrixGFX.h>';
     // Blockly.Arduino.definitions_['define_Display3'] = '#include <gfxfont.h>';
     // Blockly.Arduino.definitions_['define_Display4'] = '#include <TM16xx.h>';
     // Blockly.Arduino.definitions_['define_Display6'] = '#include <TM16xxFonts.h>';
     Blockly.Arduino.definitions_['define_Display3'] = '#include <TM16xxMatrix.h>';
     Blockly.Arduino.definitions_['define_Display8'] = 'TM1640 module('+SDA+','+SCL+');';
     Blockly.Arduino.definitions_['define_Display9'] = '#define MODULE_SIZECOLUMNS 16';
     Blockly.Arduino.definitions_['define_Displaz1'] = '#define MODULE_SIZEROWS 8';
     Blockly.Arduino.definitions_['define_Displaz2'] = 'TM16xxMatrixGFX matrix(&module, MODULE_SIZECOLUMNS, MODULE_SIZEROWS);';
     Blockly.Arduino.definitions_['define_Displaz3'] = 'TM16xxMatrix matrix1(&module, 8, 8);';
     Blockly.Arduino.setups_['matrix.set1'] = 'matrix.setRotation(0);';
     Blockly.Arduino.setups_['matrix.set2'] = 'matrix.setMirror(true);';
     Blockly.Arduino.setups_['matrix.set3'] = 'matrix.setIntensity('+fre+');'; 
     var code = '';
     return code;
};

Blockly.Arduino.Metrix_display = function() {
  //var matrixName = this.getFieldValue('matrixName');
  var textString = Blockly.Arduino.valueToCode(this, 'TEXT', Blockly.Arduino.ORDER_ASSIGNMENT);
  //var code = matrixName + '.test_vk1640b('+textString+');\n'
  var code='define_Displayz( "'+textString+'");\n';
  var funcName='define_Displayz';
  var code2='void '+funcName+'(String tape) {\n'+
    ' int wait = 160;\n'+ 
    ' int spacer = 1;\n'+
   '  int width = 5 + spacer;\n'+ 
   ' int i = 5;\n'+
   ' matrix.fillScreen(LOW);\n'+
   ' int letter =   i/width;\n'+
   ' int x = (matrix.width() - 1) - i % width;\n'+
   ' int y = (matrix.height() - 14) / 2;\n'+ 
   ' while ( x + width - spacer >= 0 && letter >= 0 ) {\n'+
   '   if ( letter < tape.length() ) {\n'+
  '      matrix.drawChar(x, y, tape[letter], HIGH, LOW, 1);\n'+
  '    }\n'+
  '    letter--;\n'+
  '    x -= width;\n'+
  '  }\n'+
  '  matrix.write(); \n'+
  '  if (tape.length()>1){  \n'+
  '  for ( int i = 0 ; i < width * tape.length() + matrix.width() - 1 - spacer; i++ ) {\n'+
  '  matrix.fillScreen(LOW);\n'+
  '  int letter =   i/width;\n'+
  '  int x = (matrix.width() - 1) - i % width;\n'+
  '  int y = (matrix.height() - 14) / 2; \n'+
  '  while ( x + width - spacer >= 0 && letter >= 0 ) {\n'+
  '    if ( letter < tape.length() ) {\n'+
  '      matrix.drawChar(x, y, tape[letter], HIGH, LOW, 1);\n'+
  '    }\n'+
  '    letter--;\n'+
  '    x -= width;\n'+
  '  }\n'+
  '  matrix.write(); \n'+
  '  delay(wait);\n'+
  '} \n'+ 
  '  }\n'+
  '  }\n';
  //return code;
   Blockly.Arduino.definitions_[funcName] = code2;
   return code;//, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Metrix_display_icon  = function() {
var Icon = this.getFieldValue('String');
//var Icon = Blockly.Arduino.valueToCode(this, 'String', Blockly.Arduino.ORDER_ASSIGNMENT);
// var str = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC);
// var Value = str.charAt(2);
Blockly.Arduino.definitions_['define_Matrix1'] = 'unsigned char love[] = {0x00,0x66,0x99,0x99,0x42,0x24,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix2'] = 'unsigned char up[] = {0x00,0x18,0x3C,0x5A,0x18,0x18,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix3'] = 'unsigned char down[] = {0x00,0x18,0x18,0x18,0x5A,0x3C,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix4'] = 'unsigned char left[] = {0x00,0x10,0x20,0x7E,0x7E,0x20,0x10,0x00};';
Blockly.Arduino.definitions_['define_Matrix5'] = 'unsigned char right[] = {0x00,0x08,0x04,0x7E,0x7E,0x04,0x08,0x00};';
Blockly.Arduino.definitions_['define_Matrix6'] = 'unsigned char triangle[] = {0x00,0x00,0x10,0x38,0x7C,0x00,0x00,0x00};';
Blockly.Arduino.definitions_['define_Matrix7'] = 'unsigned char bittable[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};';
//siyang
Blockly.Arduino.definitions_['define_Matrix8'] = 'unsigned char smile[] = {0x00,0x42,0xA5,0x00,0x00,0x24,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix10'] = 'unsigned char happy[] = {0x00,0x42,0x24,0x42,0x00,0x24,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix11'] = 'unsigned char sad[] = {0x00,0x00,0xE7,0x00,0x00,0x00,0x3C,0x00};';
Blockly.Arduino.definitions_['define_Matrix12'] = 'unsigned char error[] = {0x00,0x44,0x28,0x10,0x28,0x44,0x00,0x00};';
Blockly.Arduino.definitions_['define_Matrix13'] = 'unsigned char correct[] = {0x00,0x00,0x02,0x44,0x28,0x10,0x00,0x00};';
Blockly.Arduino.definitions_['define_Matrix14'] = 'unsigned char circle[] = {0x00,0x18,0x24,0x42,0x42,0x24,0x18,0x00};';
Blockly.Arduino.definitions_['define_Matrix15'] = 'unsigned char squarez[] = {0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00};';

//Blockly.Arduino.definitions_['define_RX1'] = '#include "IOTComm.h"';
// Blockly.Arduino.definitions_['define_RX2'] = '#define MAX_DATA_LEN  64';  
var funcName='showMatrixIcon';
var code2='void '+funcName+'(unsigned char data[]) {\n'+
  'int i,j = 0;\n'+
  'for(i = 0 ; i < 8 ; i ++){\n'+
  '  for(j = 0 ; j < 8 ; j ++){\n'+
  '    if(data[i] & bittable[j]){\n'+
  '       matrix1.setPixel(i, j, true);\n'+
  '    }\n'+
  '  }\n'+
  '}\n'+
  '}\n';
   Blockly.Arduino.definitions_['define_Matrix9'] = code2;
   var code=''+funcName+'('+Icon+');\n';
   return code;//[code, Blockly.Arduino.ORDER_ATOMIC];
  };
 
Blockly.Arduino.Lattice_LED_clear = function() {
  var matrixName = this.getFieldValue('matrixName');
  var textString = Blockly.Arduino.valueToCode(this, 'TEXT', Blockly.Arduino.ORDER_ASSIGNMENT);
 var code = 'matrix1.setAll(false);\n';
  return code;
};
// Blockly.Arduino.Lattice_LED_clear1 = function() {
//   var matrixName = this.getFieldValue('matrixName');
//   var textString = Blockly.Arduino.valueToCode(this, 'TEXT', Blockly.Arduino.ORDER_ASSIGNMENT);
//   Blockly.Arduino.definitions_['define_show'] = 'char clear[] = {0};';
//  var code = 'matrix1.setAll(false);\n';
//   return code;
// };

Blockly.Arduino.fade_led = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  //Blockly.Arduino.definitions_['include_Adafruit_GFX'] = '#include <Adafruit_GFX.h>';
  //Blockly.Arduino.definitions_['include_TM1640'] = '#include <TM1640.h>';
  //Blockly.Arduino.definitions_['include_FastPID'] = '#include <FastPID.h>';
  var code='fade_led('+dropdown_pin+');\n';
  var funcName='fade_led';
  var code2='int brightness=0; void '+funcName+'(int led) {\n'
 +'pinMode(led, OUTPUT);\n'
 //+ ' int brightness=0;\n'
 + ' int fadeAmount=5;\n'
 + '  analogWrite(led,brightness);\n'
 + '  brightness = brightness + fadeAmount;\n'
 + '    if (brightness <= 0 || brightness >= 255) {\n'
 + '     fadeAmount = -fadeAmount;\n'
 + '     }\n'
 + '   delay(30);\n'
 + '}\n';
     Blockly.Arduino.definitions_[funcName] = code2;
     Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
   return [code, Blockly.Arduino.ORDER_ATOMIC];
};
 
 //matrix.setIntensity(2); //0-7

Blockly.Arduino.metrix_brightness=function(){
  // var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
   var fre = this.getFieldValue('Brightness');
   Blockly.Arduino.setups_['matrix.setIntensity'] = 'matrix.setIntensity('+fre+');';
   var code =''
   return code;
};

Blockly.Arduino.my_led = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_stat = this.getTitleValue('STAT');
  Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
  var code = 'digitalWrite('+dropdown_pin+','+dropdown_stat+');\n'
  return code;
};

Blockly.Arduino.Input_Value= function () {
    // Boolean values HIGH and LOW.
    var code = this.getFieldValue('NUM') 
    return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.my_LED_analog_write= function () {
    var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_ATOMIC);
    //var dropdown_stat = this.getFieldValue('STAT');
    var value_num = Blockly.Arduino.valueToCode(this, 'NUM', Blockly.Arduino.ORDER_ATOMIC);
    //Blockly.Arduino.setups_['setup_output'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
    var code = 'analogWrite(' + dropdown_pin + ',' + value_num + ');\n';
    return code;
};
// Blockly.Arduino.tone_notes1 = function() {
//   var code = this.getFieldValue('STAT');
//   return [code, Blockly.Arduino.ORDER_ATOMIC];
// };

Blockly.Arduino.my_buzzer=function(){
   var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
   var fre = this.getFieldValue('STAT');
   var code = ""; 
   if(window.isNaN(dropdown_pin)){
      code = code+'pinMode('+dropdown_pin+', OUTPUT);\n';
   }else{
      Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
   }
   code += "tone("+dropdown_pin+","+fre+");\n";
   return code;
};

Blockly.Arduino.my_speaker3= Blockly.Arduino.my_buzzer;


Blockly.Arduino.no_tone=function(){
   var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
   var code='';
   if(window.isNaN(dropdown_pin)){
     code = code+'pinMode('+dropdown_pin+', OUTPUT);\n';
   }else{
     Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
   }
   code += "noTone("+dropdown_pin+");\n";
   return code;
};
Blockly.Arduino.no_tone1= Blockly.Arduino.no_tone;

Blockly.Arduino.my_potentiometer = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  //Blockly.Arduino.setups_['setup_input_'+dropdown_pin] = 'pinMode('+dropdown_pin+', INPUT);';
  var code = 'analogRead('+dropdown_pin+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

////analog port same
Blockly.Arduino.my_flame = Blockly.Arduino.my_potentiometer;
Blockly.Arduino.my_relay = Blockly.Arduino.my_led;
Blockly.Arduino.my_joystick= Blockly.Arduino.my_potentiometer;
Blockly.Arduino.my_light = Blockly.Arduino.my_potentiometer;
Blockly.Arduino.VoiceSensor= Blockly.Arduino.my_potentiometer;


Blockly.Arduino.Moisture = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  //Blockly.Arduino.setups_['setup_input_'+dropdown_pin] = 'pinMode('+dropdown_pin+', INPUT);';
  var code = 'map(analogRead('+dropdown_pin+'),0,1023,0,100)';   //siyang
  return [code, Blockly.Arduino.ORDER_ATOMIC];
  
};

Blockly.Arduino.my_pyroelectric_infrared = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  Blockly.Arduino.setups_['setup_input_'+dropdown_pin] = 'pinMode('+dropdown_pin+', INPUT);';
  var code = 'digitalRead('+dropdown_pin+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};
// Blockly.Arduino.my_pyroelectric_infrared = Blockly.Arduino.
Blockly.Arduino.my_button=Blockly.Arduino.my_pyroelectric_infrared;
Blockly.Arduino.infrared_tracking=Blockly.Arduino.my_pyroelectric_infrared;
Blockly.Arduino.IR_Distance =Blockly.Arduino.my_pyroelectric_infrared;


Blockly.Arduino.my_dht = function () {
    var sensor_type = this.getFieldValue('TYPE');
    var dropdown_pin = this.getFieldValue('PIN');
    var what = this.getFieldValue('WHAT');
    Blockly.Arduino.definitions_['define_dht'] = '#include <dht.h>';
    Blockly.Arduino.definitions_['define_dht_' + dropdown_pin] = 'dht myDHT_' + dropdown_pin + ';';
    var funcName = 'dht_' + dropdown_pin + '_get' + what;
    var code = 'int' + ' ' + funcName + '() {\n'
      + '  int chk = myDHT_' + dropdown_pin + '.read' + sensor_type + '(' + dropdown_pin + ');\n'
      + '  int value = myDHT_' + dropdown_pin + '.' + what + ';\n'
      + '  return value;\n'
      + '}\n';
    Blockly.Arduino.definitions_[funcName] = code;
    return [funcName + '()', Blockly.Arduino.ORDER_ATOMIC];
  }

  Blockly.Arduino.my_speaker1=function(){
     var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
     var fre = Blockly.Arduino.valueToCode(this, 'FREQUENCY', Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
     var code="tone("+dropdown_pin+","+fre+");\n";
     Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
     return code;
  };
  // Buzzer Passive
  Blockly.Arduino.my_speaker2=function(){
    Blockly.Arduino.definitions_['define_Speaker1'] = '#include <NewTone.h>';
     var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
     var fre = Blockly.Arduino.valueToCode(this, 'FREQUENCY',
        Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
     var dur = Blockly.Arduino.valueToCode(this, 'DURATION',
        Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
     var code="NewTone("+dropdown_pin+","+fre+","+dur+");\n";
     Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
     return code;
  };

 Blockly.Arduino.distancesensor = function () {
   var dropdown_pin1 = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
   var dropdown_pin2 = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);

   // Blockly.Arduino.setups_['setup_output_' + dropdown_pin1] = 'pinMode(' + dropdown_pin1 + ', OUTPUT);';
   // Blockly.Arduino.setups_['setup_output_' + dropdown_pin2] = 'pinMode(' + dropdown_pin2 + ', INPUT);';
   // var funcName = 'checkdistance(' + dropdown_pin1 + ',' + dropdown_pin2');';
   var funcName='getDistance';
   var code=''+funcName+'('+dropdown_pin1+','+dropdown_pin2+')';
   var code2=' const int '+funcName+'(int trig,int echo){\n'+
    'pinMode(trig,OUTPUT);\n'+
    'digitalWrite(trig,LOW);\n'+
    'delayMicroseconds(2);\n'+
    'digitalWrite(trig,HIGH);\n'+
    'delayMicroseconds(10);\n'+
    'digitalWrite(trig,LOW);\n'+
    'pinMode(echo, INPUT);\n'+
    'return pulseIn(echo,HIGH,30000)/58.0;\n'+
    '}\n';
   Blockly.Arduino.definitions_[funcName] = code2;
   //return code;//, Blockly.Arduino.ORDER_ATOMIC];
   return [code, Blockly.Arduino.ORDER_ATOMIC];
};

//MPU6050
 Blockly.Arduino.MPU6050imu = function() {
 Blockly.Arduino.definitions_['includeMPU6050']='#include <MPU6050.h>';
 Blockly.Arduino.definitions_['include_Wire'] = '#include <Wire.h>';
 Blockly.Arduino.definitions_['var_declare_MPU6050'] = 'MPU6050 mpu;';
 Blockly.Arduino.setups_['setup_ngyro'] = 'mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G);';
 var MPU6050_TYPE = this.getFieldValue('MPU6050_TYPE');
 var code = MPU6050_TYPE;
 return [code, Blockly.Arduino.ORDER_ATOMIC];
};

//MPU6050
 Blockly.Arduino.MPU6050_refres = function() {
 var code = 'Vector normAccel = mpu.readNormalizeAccel();\nVector normGyro = mpu.readNormalizeGyro();\n';
 return code;
};
//RGB
  Blockly.Arduino.rgb_LED =function(){
    var value_led = Blockly.Arduino.valueToCode(this, '_LED_', Blockly.Arduino.ORDER_ATOMIC);
    var colour_rgb_led_color = this.getFieldValue('RGB_LED_COLOR');
    var color = goog.color.hexToRgb(colour_rgb_led_color);
    var rgb_brightness = Blockly.Arduino.valueToCode(this, 'BRIGHTNESS', Blockly.Arduino.ORDER_ATOMIC);
      var dropdown_rgbpin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_ATOMIC);
      var value_ledcount = Blockly.Arduino.valueToCode(this, 'rgb_count', Blockly.Arduino.ORDER_ATOMIC);
      Blockly.Arduino.definitions_['define_i2c'] = '#include <Wire.h>';
      Blockly.Arduino.definitions_['include_display'] = '#include "Mixly.h"';
      Blockly.Arduino.definitions_['var_rgb_display'] = 'Adafruit_NeoPixel  rgb_display' + '(' + value_ledcount + ',' + dropdown_rgbpin + ');';
      Blockly.Arduino.setups_['setup_rgb_displaybegin_'] = 'rgb_display.begin();';
      Blockly.Arduino.setups_['setup_rgb_display_initshow'] = 'rgb_display.show();';
    var code = 'rgb_display'+'.setPixelColor('+value_led+'-1, '+color+');\n'+
    'rgb_display.setBrightness('+ rgb_brightness +');\n';
    code+='rgb_display'+'.show();\n'; 
    return code;
  };  

  Blockly.Arduino.IRremote = function() {
    var variable = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
    Blockly.Arduino.definitions_['var_declare'+variable] = 'long '+variable+';';
    var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
    var branch = Blockly.Arduino.statementToCode(this, 'DO');
    var branch2 = Blockly.Arduino.statementToCode(this, 'DO2');
    var varName = Blockly.Arduino.variableDB_.getName(this.getFieldValue('VAR'),Blockly.Variables.NAME_TYPE);
    Blockly.Arduino.definitions_['define_ir_recv'] = '#include <IRremote.h>';
    //Blockly.Arduino.definitions_['var_declare'+varName] = 'long '+varName+';\n';
    Blockly.Arduino.definitions_['var_ir_recv'+dropdown_pin] = 'IRrecv irrecv_'+dropdown_pin+'('+dropdown_pin+');\ndecode_results results;\n';
    Blockly.Arduino.setups_['setup_ir_recv_'+dropdown_pin] = 'irrecv_'+dropdown_pin+'.enableIRIn();';
    var code="if (irrecv_"+dropdown_pin+".decode(&results)) {\n"
    code += '  '+variable+'=results.value;\n';
    code += '  String type="UNKNOWN";\n';
    ////////////////////////////////////////////////////////////////
    code += '  String typelist[14]={"UNKNOWN", "NEC", "SONY", "RC5", "RC6", "DISH", "SHARP", "PANASONIC", "JVC", "SANYO", "MITSUBISHI", "SAMSUNG", "LG", "WHYNTER"};\n';
    code += '  if(results.decode_type>=1&&results.decode_type<=13){\n';
    code += '    type=typelist[results.decode_type];\n'
    code += '  }\n';
    //code += '  Serial.print("IR TYPE:"+type+"  ");\n';
    code += branch;
    code +='  irrecv_'+dropdown_pin+'.resume();\n'
    code +='} else {\n';
    code +=branch2;
    code +='}\n';
    return code;
  };


   Blockly.Arduino.IR_val  = function() {
    //var value_listen = Blockly.Arduino.valueToCode(this, 'Voice_in', Blockly.Arduino.ORDER_ATOMIC)|| '\"\"'
    var input_IR_Value = (this.getFieldValue('VAL'));

    var code='results.value=='+input_IR_Value+'';
    var code2 = code < 0 ?
    Blockly.Arduino.ORDER_UNARY_PREFIX : Blockly.Arduino.ORDER_ATOMIC;
    return [code, code2];
};
  
   Blockly.Arduino.IRremote2 = function() {
    //var value_listen = Blockly.Arduino.valueToCode(this, 'Voice_in', Blockly.Arduino.ORDER_ATOMIC)|| '\"\"'
    var input_IR_Value = (this.getFieldValue('VAL'));

    var code=''+input_IR_Value+'';
    var code2 = code < 0 ?
    Blockly.Arduino.ORDER_UNARY_PREFIX : Blockly.Arduino.ORDER_ATOMIC;
    return [code, code2];
};
  //////voice 
 Blockly.Arduino.Voice_Init  = function() {
  var RX = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  var TX = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
  var SerialName = this.getFieldValue('SerialName');
     Blockly.Arduino.definitions_['define_SoftwareSerial'] = '#include <SoftwareSerial.h>';
     Blockly.Arduino.definitions_[SerialName] = 'SoftwareSerial Voice_Serial('+RX+','+TX+');'; 
     Blockly.Arduino.setups_['setup_mySerial.begin'] = 'Voice_Serial.begin(9600);';
     Blockly.Arduino.setups_['Serial.begin'] = 'Serial.begin(9600);';
  var code='receiveVoice();\n';
  var funcName='receiveVoice';
  var code2= 'String incomdate; void '+funcName+'() {\n'+
  'while (Voice_Serial.available() > 0)\n'+  
  ' {\n'+
  '  incomdate = Voice_Serial.readString();\n'+
  '   delay(2);\n'+
  '}\n '+
  '}\n '+
  'void Reply_Voice(String stringData) {\n'+
  'for (int i = 0; i < stringData.length(); i++)\n'+
  '{\n'+
  '  Voice_Serial.write(stringData[i]);\n'+  
  '}\n'+
  'Serial.println(incomdate);\n'+
  'incomdate="";\n'+
  '  }\n';
     Blockly.Arduino.definitions_[funcName] = code2;
   return code;
};

Blockly.Arduino.logic0= function() {
var value_listen = Blockly.Arduino.valueToCode(this, 'input', Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
var value_Reply = Blockly.Arduino.valueToCode(this, 'output', Blockly.Arduino.ORDER_ATOMIC)|| '\"\"'

var code='if (incomdate=="'+value_listen+'"){\n'+          
'mySerial.write("'+value_Reply+'");\n'+
// '            Serial.println("WakeUP");\n'+ 
// '            memset(sendx, 0, sizeof(sendx));\n'+    
'         incomdate="";\n'+
'}\n ';
  return code;
};

Blockly.Arduino.Voice_in  = function() {
    //var value_listen = Blockly.Arduino.valueToCode(this, 'Voice_in', Blockly.Arduino.ORDER_ATOMIC)|| '\"\"'
    var value_listen = (this.getFieldValue('Voice_in'));

    var code='incomdate=="'+value_listen+'"';
    var code2 = code < 0 ?
    Blockly.Arduino.ORDER_UNARY_PREFIX : Blockly.Arduino.ORDER_ATOMIC;
    return [code, code2];
};


Blockly.Arduino.Voice_out  = function() {
var value_Reply = (this.getFieldValue('Voice_out'));
var funcName='Reply_Voice';
// var code2='void '+funcName+'(String stringData) {\n'+
//   'for (int i = 0; i < stringData.length(); i++)\n'+
//   '{\n'+
//   '  mySerial.write(stringData[i]);\n'+  
//   '}\n'+
//   'Serial.println(incomdate);\n'+
//   'incomdate="";\n'+
//   '  }\n';
//Blockly.Arduino.definitions_[funcName] = code2;
var code=''+funcName+'("'+value_Reply+'");\n';
return code; //[code,Blockly.Arduino.ORDER_ATOMIC]; 
};

Blockly.Arduino.Voice_clear= function() {
  var code='incomdate="";\n';
     return code;
};

// Blockly.Arduino.definitions_[funcName] = code2;
//    return [code, Blockly.Arduino.ORDER_ATOMIC];

// Blockly.Arduino.logic0= function() {
//   //IMPORTANT: delete unneeded lines
//   var value_listen = Blockly.Arduino.valueToCode(block, 'listen', Blockly.Arduino.ORDER_ATOMIC);
//   var value_Reply = Blockly.Arduino.valueToCode(block, 'reply', Blockly.Arduino.ORDER_ATOMIC);
//   // Blockly.Arduino.includes_[] = 'libraries code'
//   // Blockly.Arduino.variables_[] = 'variables'
//   // Blockly.Arduino.definitions_[] = 'instance'
//   // Blockly.Arduino.userFunctions_[] = 'functions'
//   // Blockly.Arduino.setups_[]='arduino code for setup()'
//   var code='voicerognition();\n';
//   var funcName='voicerognition';
//   var code2='void'+funcName+'() {\n' 
// 'String incomdate;\n'+
// 'while (mySerial.available() > 0)\n'+  
// '    {\n'+
// '          incomdate = mySerial.readString();\n'+
// '          Serial.println(incomdate);\n'+
// '          delay(2);\n'+
// '          if (incomdate==value_listen){\n'+          
// '            mySerial.write(value_Reply);\n'+
// '            Serial.println("WakeUP");\n'+ 
// '            memset(sendx, 0, sizeof(sendx));\n'+    
// '            }\n'+
// '         incomdate="";\n'+
// '}\n ';
//   // return code;
//    Blockly.Arduino.definitions_[funcName] = code2;
//    return [code, Blockly.Arduino.ORDER_ATOMIC];
// };

  Blockly.Arduino.TM1640_7segment= function() {
  var SDA = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  var SCL = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
  var matrixName = this.getFieldValue('matrixName');
  var fre = this.getFieldValue('Brightness');
  
     Blockly.Arduino.setups_['matrix.setIntensity'] = 'matrix.setIntensity('+fre+');';
     Blockly.Arduino.definitions_['include_TM16400'] = '#include <Adafruit_GFX.h>';
     Blockly.Arduino.definitions_['include_TM16401'] = '#include <TM1640.h>';
     Blockly.Arduino.definitions_['include_TM16402'] = '#include <TM16xxMatrixGFX.h>';

     Blockly.Arduino.definitions_['include_TM16403'] = 'TM1640 module('+SDA+','+SCL+');';
     Blockly.Arduino.definitions_['include_TM16404'] = '#define MODULE_SIZECOLUMNS 16';
     Blockly.Arduino.definitions_['include_TM16405'] = '#define MODULE_SIZEROWS 8';
     Blockly.Arduino.definitions_['include_TM16406'] = 'TM16xxMatrixGFX matrix(&module, MODULE_SIZECOLUMNS, MODULE_SIZEROWS);'; 
     var code = '';
     return code;
};


Blockly.Arduino.TM1640_DisplayString  = function() {
  //var matrixName = this.getFieldValue('matrixName');
var textString = Blockly.Arduino.valueToCode(this, 'VALUE', Blockly.Arduino.ORDER_ASSIGNMENT);
  //var code = matrixName + '.test_vk1640b('+textString+');\n'

var code ='module.setDisplayToString('+textString+');\n';
return code;//, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.TM1640_DisplayString1  = function() {
  //var matrixName = this.getFieldValue('matrixName');
var textString = Blockly.Arduino.valueToCode(this, 'VALUE', Blockly.Arduino.ORDER_ASSIGNMENT);
  //var code = matrixName + '.test_vk1640b('+textString+');\n'
var code ='char str[5];\n'+
'sprintf(str, "%d", '+textString+');\n'+ 
'module.setDisplayToString(str);\n'+
'memset(str,0, sizeof(str));\n';
return code;//, Blockly.Arduino.ORDER_ATOMIC];
};


Blockly.Arduino.Clear_TM1640 = function() {
  //var matrixName = this.getFieldValue('matrixName');
  //var textString = Blockly.Arduino.valueToCode(this, 'VALUE', Blockly.Arduino.ORDER_ASSIGNMENT);
var code = 'module.clearDisplay();\n'
return code;
};

Blockly.Arduino.MuInit = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var dropdown_serial = this.getFieldValue('SERIAL');
  var offset = parseInt(dropdown_mu_obj)
  var address = 0x60 + offset;
  var RX = Blockly.Arduino.valueToCode(this, 'PIN3', Blockly.Arduino.ORDER_ATOMIC);
  var TX = Blockly.Arduino.valueToCode(this, 'PIN4', Blockly.Arduino.ORDER_ATOMIC);
  // var RX = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  // var TX = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
  
  Blockly.Arduino.definitions_['include_vs2'] = '#include "MuVisionSensor.h"';
  Blockly.Arduino.definitions_['include_vs3'] = '#include "SoftwareSerial.h"';
  //Blockly.Arduino.definitions_[matrixName] = ' '+kMuName+dropdown_mu_obj+'('+RX+','+TX+');';
  Blockly.Arduino.definitions_["mySerial"] = 'SoftwareSerial myCamSerial('+TX+','+RX+');'; 

  Blockly.Arduino.definitions_['var_vs2_mu'+dropdown_mu_obj] = 'MuVisionSensor '+kMuName+dropdown_mu_obj+'(0x'+address.toString(16)+');';
  // if (dropdown_serial == 'Wire') {
  //   Blockly.Arduino.definitions_['define_i2c'] = '#include <Wire.h>';
  //   Blockly.Arduino.setups_['setup_i2c'] = 'Wire.begin();\n';
  // }
  Blockly.Arduino.setups_['setup_i2c'] = ''+dropdown_serial+'.begin(9600);\n'+
  'uint8_t err = 0;\n'+
  ' '+kMuName+dropdown_mu_obj+'.begin(&'+dropdown_serial+');\n'+ 
  'if (err == MU_OK) {\n'+
  '  Serial.println("MU initialized.");\n'+
  '} else {\n'+
  '  do {\n'+
  '    delay(5000);\n'+
  '  } while (1);\n'+
  // ' '+kMuName+dropdown_mu_obj+'.VisionBegin(VISION_BALL_DETECT);\n'+
  '}\n';
  var code ='';
  return code;
};

Blockly.Arduino.SoftwareSerial = function() {
var dropdown_uart_baud = this.getFieldValue('BAUD');
var dropdown_serial = this.getFieldValue('SERIAL');
Blockly.Arduino.setups_['Serial.begin2'] = 'mySerial.begin('+dropdown_uart_baud+');';
  var code = '';
  return code;
};

Blockly.Arduino.Vs2VisionBegin2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var dropdown_vision_status = this.getFieldValue('VisionStatus');
  var dropdown_vision_type = this.getFieldValue('VisionType');
  Blockly.Arduino.setups_['Mu.begin1'] = kMuName+dropdown_mu_obj+'.Vision'+dropdown_vision_status+'('+dropdown_vision_type+');';
  var code = '';
  return code;
};
Blockly.Arduino.Vs2Detected2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var dropdown_vision_type = this.getFieldValue('VISION_TYPE');
  var code = kMuName+dropdown_mu_obj+'.GetValue('+dropdown_vision_type+', kStatus)';
  return [code, Blockly.Arduino.ORDER_ATOMIC];  
};

Blockly.Arduino.Vs2DetectedRegionColor2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var input_value_x = Blockly.Arduino.valueToCode(this, "XValue",
                      Blockly.Arduino.ORDER_NONE) || '50';
  var input_value_y = Blockly.Arduino.valueToCode(this, "YValue",
                      Blockly.Arduino.ORDER_NONE) || '50';

  Blockly.Arduino.definitions_['funMuVs2GetColorRCGLabel'] = funMuVs2GetColorRCGLabel;
  var code = 'MuVs2GetColorRCGLabel('+kMuName+dropdown_mu_obj+', '+input_value_x+', '+input_value_y+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Vs2GetColorLabel2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var color_dic = {'#000000':'MU_COLOR_BLACK', '#ff0000':'MU_COLOR_RED', '#00ff00':'MU_COLOR_GREEN',
                  '#ffff00':'MU_COLOR_YELLOW', '#0000ff':'MU_COLOR_BLUE', '#ff00ff':'MU_COLOR_PURPLE',
                  '#00ffff':'MU_COLOR_CYAN', '#ffffff':'MU_COLOR_WHITE'};
  var color = color_dic[this.getFieldValue("RCGColor")];

  var code = '('+kMuName+dropdown_mu_obj+'.GetValue(VISION_COLOR_RECOGNITION, kLabel) == '+color+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Vs2DetectedColorDetect2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var color_dic = {'#000000':'MU_COLOR_BLACK', '#ff0000':'MU_COLOR_RED', '#00ff00':'MU_COLOR_GREEN',
                  '#ffff00':'MU_COLOR_YELLOW', '#0000ff':'MU_COLOR_BLUE', '#ff00ff':'MU_COLOR_PURPLE',
                  '#00ffff':'MU_COLOR_CYAN', '#ffffff':'MU_COLOR_WHITE'};
  var color = color_dic[this.getFieldValue("DetectColor")];

  Blockly.Arduino.definitions_['funMuVs2GetColorDetectLabel'] = funMuVs2GetColorDetectLabel;
  var code = 'MuVs2GetColorDetectLabel('+kMuName+dropdown_mu_obj+', '+color+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Vs2GetMessage2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MU_OBJ');
  var dropdown_vision_type = this.getFieldValue('VISION_TYPE');
  var dropdown_detected_message = this.getFieldValue('DETECTED_MESSAGE');
  var code = kMuName+dropdown_mu_obj+'.GetValue('+dropdown_vision_type+', '+dropdown_detected_message+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Vs2GetCardType2 = function() {
  var dropdown_mu_obj = this.getFieldValue('MuObj');
  var dropdown_vision_type = this.getFieldValue('VisionCardType');
  var dropdown_card_type = this.getFieldValue('CardType');
  var code = '('+kMuName+dropdown_mu_obj+'.GetValue('+dropdown_vision_type+', kLabel) == '+dropdown_card_type+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

/// iot
Blockly.Arduino.iot_config = function () {
  var wifi_id = Blockly.Arduino.valueToCode(this, 'WiFi_ID', Blockly.Arduino.ORDER_ATOMIC);
  var wifi_pass = Blockly.Arduino.valueToCode(this, 'wifi_pass', Blockly.Arduino.ORDER_ATOMIC);
  var Project_key = Blockly.Arduino.valueToCode(this, 'wifi_key', Blockly.Arduino.ORDER_ATOMIC);
  Blockly.Arduino.definitions_['define_IOTa'] = '#include "IOTComm.h"';
  Blockly.Arduino.definitions_["define_IOTb"] = 'IOTCommClass iotcom;'; 
  Blockly.Arduino.definitions_['define_IOTc'] = 'char Topic[MAX_TOPIC_LEN]= {0};';
  Blockly.Arduino.definitions_['define_IOTd'] = 'char buffer1[MAX_DATA_LEN] = {0};';
  //var server_add = Blockly.Arduino.valueToCode(this, 'server_add', Blockly.Arduino.ORDER_ATOMIC);
  //var board_type = JSFuncs.getPlatform();
  Blockly.Arduino.definitions_['Define_IOTe'] = 'char wifissid[]= ' + wifi_id+ ';';
  Blockly.Arduino.definitions_['define_IOTf'] = 'char wifipassword[] = ' + wifi_pass + ';';
  Blockly.Arduino.definitions_['define_IOTg'] = 'char pjkey[]= ' + Project_key+ ';';
  Blockly.Arduino.setups_['Define_IOT7'] = 'iotcom.setserialBegin();\n'+
  'iotcom.setWifiName(wifissid);\n'+
  'iotcom.setWifiPassword(wifipassword);\n'+ 
  'iotcom.setProjectKey(pjkey);\n'+
  // 'Serial.println("MU initialized.");\n'+
  // 'iotcom.setServerAddr(seraddr);\n'+
  'iotcom.connect();\n';
  var code = '';
  return code;
};


Blockly.Arduino.iot_Serial = function() {
  var RX = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  var TX = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
Blockly.Arduino.setups_['Serial.begin2'] = 'iotcom.setSerialPort('+RX+','+TX+');';
  var code = '';
  return code;
};

Blockly.Arduino.iot_send = function() {
  var Input_topic = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC);
  var x = Blockly.Arduino.valueToCode(this, 'input1', Blockly.Arduino.ORDER_ATOMIC);
  var code ='iotcom.publishMsg('+Input_topic+','+x+');';
  return code;
};

/// IOT RECIEVE IN LOOP
// Blockly.Arduino.iot_receive_Init  = function() {
//   var branch = Blockly.Arduino.statementToCode(this, 'DO');
//   var code="while (iotcom.available() > 0){\n"
//          +" iotcom.readMsg(Topic, buffer1);\n"
//          +" int buffer_Val= atoi(buffer1);\n"
//          +" String Topic_str= String(Topic);\n"
//     code += branch;
//     code +='memset(Topic,0, sizeof(Topic));\n'
//           +'memset(buffer1,0, sizeof(buffer1));\n'
//     code +='}\n';
//     return code;
//   };

Blockly.Arduino.iot_receive = function () {
  var Payload_type = this.getFieldValue('Payload');
  var str = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC)
  var value1 = str.charAt(1);
  var value2 = str.charAt(2);
  var Value = value1.concat(value2);
  var Data_Source=this.getFieldValue('Data_Source');
//Blockly.Arduino.definitions_['Define_IOTZ_'+Value+''] = 'char submodelID'+Value+'[] = '+str+';';
//Blockly.Arduino.definitions_['define_RX1'] = '#include "IOTComm.h"';
//Blockly.Arduino.definitions_['define_RX2'] = '#define MAX_DATA_LEN  64';
//Blockly.Arduino.setups_['setup_Receive_'+Value+''] = 'iotcom.subscribe'+Data_Source+'Topic(submodelID'+Value+');';
var funcName='Receive_';
var code2='const int '+funcName+'Buffer() {\n'+
' while (iotcom.available() > 0){\n'+
' iotcom.readMsg(Topic, buffer1);\n'+
' int val5= atoi(buffer1);\n'+
' memset(buffer1,0,sizeof(buffer1));\n'+
' return val5;\n'+
'  }\n'+
//'  delay(24);'+
'  }\n'+
' String '+funcName+'Topic() {\n'+
//'  String Topic_Str;\n'+
'  if (iotcom.available() > 0)\n'+
'  {\n'+
'    iotcom.readMsg(Topic, buffer1);\n'+
'    String String(Topic); \n'+  
'  }\n'+
' return Topic;\n'+
' memset(Topic,0, sizeof(Topic));\n'+
'  }\n';
Blockly.Arduino.definitions_[funcName] = code2;
var code=''+funcName+''+Payload_type+'()';
return [code,Blockly.Arduino.ORDER_ATOMIC];
   // Blockly.Arduino.definitions_['define_Matrix9'] = code2;
   // var code=''+funcName+''+Payload_type+'()';
   // return code;// [code,Blockly.Arduino.ORDER_ATOMIC];
  }

Blockly.Arduino.Iot_Init_Receive= function() {
var funcName='checkValidData';
var code3='checkValidData'+funcName+'';
var code2=' bool '+funcName+'(){\n'+
'  bool dataflag = false;\n'+
'  memset(buffer1, 0, sizeof(buffer1));\n'+
'  memset(Topic, 0, sizeof(Topic));\n'+
'  if(iotcom.available() > 0){\n'+
'  dataflag = iotcom.readMsg(Topic, buffer1);\n'+
'  }\n'+
'  return dataflag;\n'+
'}\n';
   Blockly.Arduino.definitions_[funcName] = code2; 
   var code=''+funcName+'()';
   return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Receive_Topic = function() {
var str = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC)
var value1 = str.charAt(1);
var value2 = str.charAt(2);
var Value = value1.concat(value2);
// Blockly.Arduino.setups_['setup_Receive_'+Value+''] = 'iotcom.subscribe'+Data_Source+'Topic(submodelID'+Value+');';
//Blockly.Arduino.definitions_["Receive_Topic1"] = "code2"; 
   var code='(String)Topic == (String)submodelID'+Value+'';
   return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Receive_Value = function() {
var funcName='valueReceve';
//Blockly.Arduino.definitions_["Receive_Buffer1"] = 'int Buffer'; 
var code = 'atoi(buffer1)';
return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.iot_receiveTopic= function () {
var str = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC)
var value1 = str.charAt(1);
var value2 = str.charAt(2);
var Value = value1.concat(value2);
var Data_Source=this.getFieldValue('Data_Source');
// Blockly.Arduino.definitions_['Define_IOT6'] = 'char Topic[MAX_TOPIC_LEN]= {0};';
// Blockly.Arduino.definitions_['Define_IOT7'] = 'char buffer1[MAX_DATA_LEN] = {0};';
Blockly.Arduino.definitions_['Define_IOTZ_'+Value+''] = 'char submodelID'+Value+'[] = '+str+';';
  //Blockly.Arduino.definitions_['define_RX1'] = '#include "IOTComm.h"';
  //Blockly.Arduino.definitions_['define_RX2'] = '#define MAX_DATA_LEN  64';
Blockly.Arduino.setups_['setup_Receive_'+Value+''] = 'iotcom.subscribe'+Data_Source+'Topic(submodelID'+Value+');';
//Blockly.Arduino.setups_['setup_Receive_'+Value+''] = 'iotcom.subscribe'+Data_Source+'Topic(submodelID'+Value+');';
//var code2='const int '+funcName+'Buffer() {\n'+
//Blockly.Arduino.definitions_[funcName] = code2;
  var code = '';
  return code;
   // Blockly.Arduino.definitions_['define_Matrix9'] = code2;
   // var code=''+funcName+''+Payload_type+'()';
   // return code;// [code,Blockly.Arduino.ORDER_ATOMIC];
  }
  
Blockly.Arduino.iot_receive_Display= function () {
var str = Blockly.Arduino.valueToCode(this, 'Input_topic', Blockly.Arduino.ORDER_ATOMIC)
var value1 = str.charAt(1);
var value2 = str.charAt(2);
var Value = value1.concat(value2);

Blockly.Arduino.definitions_['define_IOTt'] = 'unsigned char love[] = {0x00,0x66,0x99,0x99,0x42,0x24,0x18,0x00};';
Blockly.Arduino.definitions_['define_IOTh'] = 'unsigned char up[] = {0x00,0x18,0x3C,0x5A,0x18,0x18,0x18,0x00};';
Blockly.Arduino.definitions_['define_IOTi'] = 'unsigned char down[] = {0x00,0x18,0x18,0x18,0x5A,0x3C,0x18,0x00};';
Blockly.Arduino.definitions_['define_IOTj'] = 'unsigned char left[] = {0x00,0x10,0x20,0x7E,0x7E,0x20,0x10,0x00};';
Blockly.Arduino.definitions_['define_IOTk'] = 'unsigned char right[] = {0x00,0x08,0x04,0x7E,0x7E,0x04,0x08,0x00};';
Blockly.Arduino.definitions_['define_IOTl'] = 'unsigned char triangle[] = {0x00,0x00,0x10,0x38,0x7C,0x00,0x00,0x00};';
Blockly.Arduino.definitions_['define_IOTm'] = 'unsigned char bittable[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};';

//siyang
// Blockly.Arduino.definitions_['define_IOTone'] = 'unsigned char one[] = {0x00,0x08,0x18,0x08,0x08,0x08,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTtwo'] = 'unsigned char two[] = {0x00,0x3C,0x04,0x3C,0x20,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTthree'] = 'unsigned char three[] = {0x00,0x3C,0x04,0x3C,0x04,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTfour'] = 'unsigned char four[] = {0x00,0x08,0x18,0x28,0x7C,0x08,0x08,0x00};';
// Blockly.Arduino.definitions_['define_IOTfive'] = 'unsigned char five[] = {0x00,0x3C,0x20,0x3C,0x04,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTsix'] = 'unsigned char six[] = {0x00,0x3C,0x20,0x3C,0x24,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTseven'] = 'unsigned char seven[] = {0x00,0x3C,0x04,0x08,0x10,0x20,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTeight'] = 'unsigned char eight[] = {0x00,0x3C,0x24,0x3C,0x24,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTnine'] = 'unsigned char nine[] = {0x00,0x3C,0x24,0x3C,0x04,0x3C,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTsmile'] = 'unsigned char smile[] = {0x00,0x42,0xA5,0x00,0x00,0x24,0x18,0x00};';
// Blockly.Arduino.definitions_['define_IOThappy'] = 'unsigned char happy[] = {0x00,0x42,0x24,0x42,0x00,0x24,0x18,0x00};';
// Blockly.Arduino.definitions_['define_IOTsad'] = 'unsigned char sad[] = {0x00,0x00,0xE7,0x00,0x00,0x00,0x3C,0x00};';
// Blockly.Arduino.definitions_['define_IOTerror'] = 'unsigned char error[] = {0x00,0x44,0x28,0x10,0x28,0x44,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTcrrect'] = 'unsigned char crrect[] = {0x00,0x00,0x02,0x44,0x28,0x10,0x00,0x00};';
// Blockly.Arduino.definitions_['define_IOTcircle'] = 'unsigned char circle[] = {0x00,0x18,0x24,0x42,0x42,0x24,0x18,0x00};';
// Blockly.Arduino.definitions_['define_IOTsquare'] = 'unsigned char squarez[] = {0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00};';

Blockly.Arduino.definitions_['define_IOTn'] = 'char cmdup[]   = "00183C5A18181800";';
Blockly.Arduino.definitions_['define_IOTo'] = 'char cmddown[] = "001818185A3C1800";';
Blockly.Arduino.definitions_['define_IOTp'] = 'char cmdleft[] = "0010207E7E201000";';
Blockly.Arduino.definitions_['define_IOTq'] = 'char cmdright[] = "0008047E7E040800";';
Blockly.Arduino.definitions_['define_IOTr'] = 'char cmdtriangle[] = "000010387C000000";';
Blockly.Arduino.definitions_['define_IOTs'] = 'char cmdlove[] = "0066999942241800";';

//siyang
// Blockly.Arduino.definitions_['define_IOTOne'] = 'char cmdone[] = "0008180808080000";';
// Blockly.Arduino.definitions_['define_IOTTwo'] = 'char cmdtwo[] = "003C043C203C0000";';
// Blockly.Arduino.definitions_['define_IOTThree'] = 'char cmdthree[] = "003C043C043C0000";';
// Blockly.Arduino.definitions_['define_IOTFour'] = 'char cmdfour[] = "000818287C080800";';
// Blockly.Arduino.definitions_['define_IOTFive'] = 'char cmdfive[] = "003C203C043C0000";';
// Blockly.Arduino.definitions_['define_IOTSix'] = 'char cmdsix[] = "003C203C243C0000";';
// Blockly.Arduino.definitions_['define_IOTSeven'] = 'char cmdseven[] = "003C040810200000";';
// Blockly.Arduino.definitions_['define_IOTEight'] = 'char cmdeight[] = "003C243C243C0000";';
// Blockly.Arduino.definitions_['define_IOTNine'] = 'char cmdnine[] = "003C243C043C0000";';
// Blockly.Arduino.definitions_['define_IOTSmile'] = 'char cmdsmile[] = "0042A50000241800";';
// Blockly.Arduino.definitions_['define_IOTHappy'] = 'char cmdhappy[] = "0042244200241800";';
// Blockly.Arduino.definitions_['define_IOTSad'] = 'char cmdsad[] = "0000E70000003C00";';
// Blockly.Arduino.definitions_['define_IOTError'] = 'char cmderror[] = "0044281028440000";';
// Blockly.Arduino.definitions_['define_IOTCrrect'] = 'char cmdcrrect[] = "0000024428100000";';
// Blockly.Arduino.definitions_['define_IOTCircle'] = 'char cmdcircle[] = "0018244242421800";';
// Blockly.Arduino.definitions_['define_IOTSquare'] = 'char cmdsquarez[] = "007E424242427E00";';

Blockly.Arduino.definitions_['Defin_IOTZ_'+Value+''] = 'char submodelID_'+Value+'[] = '+str+';';
Blockly.Arduino.setups_['setup_Receive_'+Value+''] = 'iotcom.subscribeWebTopic(submodelID_'+Value+');';

var funcName='Display_From_Net';
var code2=' void '+funcName+'(String topicReceive){\n'+
 'if(((String)Topic == topicReceive)){\n'+
 'matrix1.setAll(0);\n'+
 ' if((String)buffer1 == (String)cmdup){\n'+
 '   showMatrixIcon(up);}\n'+
 ' else if((String)buffer1 == (String)cmdlove){\n'+
 '   showMatrixIcon(love);}\n'+
 ' else if((String)buffer1 == (String)cmddown){\n'+
 '   showMatrixIcon(down);}\n'+
 ' else if((String)buffer1 == (String)cmdleft){\n'+
 '   showMatrixIcon(left);}\n'+
 ' else if((String)buffer1 == (String)cmdright){\n'+
 '   showMatrixIcon(right);}\n'+
 ' else if((String)buffer1 == (String)cmdtriangle){\n'+
 '   showMatrixIcon(triangle); }\n'+
//  ' else if((String)buffer1 == (String)cmdone){\n'+
//  '   showMatrixIcon(one); }\n'+
//  ' else if((String)buffer1 == (String)cmdtwo){\n'+
//  '   showMatrixIcon(two); }\n'+
//  ' else if((String)buffer1 == (String)cmdthree){\n'+
//  '   showMatrixIcon(three); }\n'+
//  ' else if((String)buffer1 == (String)cmdfour){\n'+
//  '   showMatrixIcon(four); }\n'+
//  ' else if((String)buffer1 == (String)cmdfive){\n'+
//  '   showMatrixIcon(five); }\n'+
//  ' else if((String)buffer1 == (String)cmdsix){\n'+
//  '   showMatrixIcon(six); }\n'+
//  ' else if((String)buffer1 == (String)cmdseven){\n'+
//  '   showMatrixIcon(seven); }\n'+
//  ' else if((String)buffer1 == (String)cmdeight){\n'+
//  '   showMatrixIcon(eight); }\n'+
//  ' else if((String)buffer1 == (String)cmdnine){\n'+
//  '   showMatrixIcon(nine); }\n'+
//  ' else if((String)buffer1 == (String)cmdsmile){\n'+
//  '   showMatrixIcon(smile); }\n'+
//  ' else if((String)buffer1 == (String)cmdhappy){\n'+
//  '   showMatrixIcon(happy); }\n'+
//  ' else if((String)buffer1 == (String)cmdsad){\n'+
//  '   showMatrixIcon(sad); }\n'+
//  ' else if((String)buffer1 == (String)cmderror){\n'+
//  '   showMatrixIcon(error); }\n'+
//  ' else if((String)buffer1 == (String)cmdcrrect){\n'+
//  '   showMatrixIcon(crrect); }\n'+
//  ' else if((String)buffer1 == (String)cmdcircle){\n'+
//  '   showMatrixIcon(circle); }\n'+
//  ' else if((String)buffer1 == (String)cmdsquarez){\n'+
//  '   showMatrixIcon(squarez); }\n'+
 '}\n'+
 '}\n';
var funcName2='showMatrixIcon';
var code3='void '+funcName2+'(unsigned char data[]) {\n'+
  'int i,j = 0;\n'+
  'for(i = 0 ; i < 8 ; i ++){\n'+
  '  for(j = 0 ; j < 8 ; j ++){\n'+
  '    if(data[i] & bittable[j]){\n'+
  '       matrix1.setPixel(i, j, true);\n'+
  '    }\n'+
  '  }\n'+
  '}\n'+
  '}\n';
   Blockly.Arduino.definitions_['define_IOTu'] = code3;
   Blockly.Arduino.definitions_['define_IOTv'] = code2; 
   var code=''+funcName+'(submodelID_'+Value+');\n';
   return code;//[code,Blockly.Arduino.ORDER_ATOMIC];
  }

Blockly.Arduino.Pulse_Init  = function () {
// var dropdown_pin1 = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
// var dropdown_pin2 = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
// var dropdown_Type = this.getFieldValue('ValIn');
Blockly.Arduino.definitions_['define_Pulse1'] = '#include "heartRate.h"';
Blockly.Arduino.definitions_['define_Pulse2'] = '#include "MAX30105.h"';
Blockly.Arduino.definitions_['define_Pulse3'] = 'MAX30105 particleSensor;';
Blockly.Arduino.definitions_['define_Pulse4'] = 'const byte RATE_SIZE = 4;';
Blockly.Arduino.definitions_['define_Pulse5'] = 'byte rates[RATE_SIZE];';
Blockly.Arduino.definitions_['define_Pulse6'] = 'byte rateSpot = 0;';
Blockly.Arduino.definitions_['define_Pulse7'] = 'long lastBeat = 0;';
Blockly.Arduino.definitions_['define_Pulse8'] = 'float beatsPerMinute;';
Blockly.Arduino.definitions_['define_Pulse9'] = 'int beatAvg;';
Blockly.Arduino.setups_['setup_Pulse'] = ' if (!particleSensor.begin(Wire, I2C_SPEED_FAST))\n'+
  'Serial.begin(9600);\n'+
  'Serial.println("Initializing...");\n'+
  'if (!particleSensor.begin(Wire, I2C_SPEED_FAST))\n'+
  '{\n'+
  '  Serial.println("MAX30105 was not found. Please check wiring/power. ");\n'+
  '  while (1);\n'+
  ' }\n'+
  'Serial.println("Place your index finger on the sensor with steady pressure.");\n'+
  'particleSensor.setup();\n'+
  'particleSensor.setPulseAmplitudeRed(0x0A);\n'+
  'particleSensor.setPulseAmplitudeGreen(0);\n';
  var code = '';
  return code;
};

Blockly.Arduino.Pulse = function () {
var dropdown_Type = this.getFieldValue('ValIn');
//Blockly.Arduino.definitions_['define_Pulse1'] = 'MAX30105 particleSensor;';
var funcName='Get_Pulse_Value';
var code2=' const int '+funcName+'(int returncons){\n'+
'  long irValue = particleSensor.getIR();\n'+
'  if (checkForBeat(irValue) == true)\n'+
'  {\n'+
'    long delta = millis() - lastBeat;\n'+
'    lastBeat = millis();\n'+
'    beatsPerMinute = 60 / (delta / 1000.0);\n'+
'    if (beatsPerMinute < 255 && beatsPerMinute > 20)\n'+
'    {\n'+
'      rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array\n'+
'      rateSpot %= RATE_SIZE; //Wrap variable\n'+
'      beatAvg = 0;\n'+
'      for (byte x = 0 ; x < RATE_SIZE ; x++)\n'+
'        beatAvg += rates[x];\n'+
'      beatAvg /= RATE_SIZE;\n'+
'}}\n'+
'if (returncons==1){\n'+
'    return beatsPerMinute;\n'+
'  }\n'+
'  else if (returncons==2){\n'+
'    return beatAvg;\n'+
'    }\n'+
'    else if (returncons==3){\n'+
'      return irValue;\n'+
'}}\n';
   Blockly.Arduino.definitions_['define_PulseL'] = code2; 
   var code=''+funcName+'('+dropdown_Type+')';
   return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.Record = function() {
 //var matrixName = this.getFieldValue('matrixName');
 var Record_pin = Blockly.Arduino.valueToCode(this, 'PIN1',Blockly.Arduino.ORDER_ATOMIC);
 var Play_pin = Blockly.Arduino.valueToCode(this, 'PIN2',Blockly.Arduino.ORDER_ATOMIC);
 var dur = Blockly.Arduino.valueToCode(this, 'DURATION',
           Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
 // var State = Blockly.Arduino.valueToCode(this, 'STATE',
 //        Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
 var State = this.getFieldValue('STATE');
 Blockly.Arduino.definitions_['Record'+Record_pin+''] = '#define REC_Pin_'+Record_pin+' '+Record_pin+'';
 Blockly.Arduino.definitions_['Record'+Play_pin+''] = '#define PLAY_Pin_'+Play_pin+' '+Play_pin+'';
 Blockly.Arduino.definitions_['Record1'] = '#define playTime '+dur+'';
 Blockly.Arduino.definitions_['Record2'] = '#define recordTime '+dur+'';

 Blockly.Arduino.setups_['define_Z3'] = ' pinMode(REC_Pin_'+Record_pin+',OUTPUT);';
 Blockly.Arduino.setups_['define_Z4'] = 'pinMode(PLAY_Pin_'+Play_pin+',OUTPUT);';
 Blockly.Arduino.setups_['define_Z5'] = 'Serial.begin(9600); ';
 var funcName='RecordPlay';
 var code2='void '+funcName+''+Record_pin+'_'+Play_pin+'(int state) {\n'+
 'if(state ==1){ \n'+
 'digitalWrite(PLAY_Pin_'+Play_pin+', HIGH); \n'+
 'delay(playTime); \n'+
 'digitalWrite(PLAY_Pin_'+Play_pin+', LOW);  \n'+
 'Serial.println("Playbak Started");  \n'+
 '} \n'+
 'else if(state==2){\n'+
 'digitalWrite(REC_Pin_'+Record_pin+', HIGH);\n'+
 'Serial.println("Recording started");\n'+
 'delay(recordTime);\n'+
 'digitalWrite(REC_Pin_'+Record_pin+', LOW); \n'+         
 '} \n'+                   
 'delay(500);\n'+
 '}\n';
  //return code;
   Blockly.Arduino.definitions_[''+funcName+''+Record_pin+'_'+Play_pin+''] = code2;
   var code=''+funcName+''+Record_pin+'_'+Play_pin+'( '+State+');\n';
   return code;//, Blockly.Arduino.ORDER_ATOMIC];
};

  Blockly.Arduino.RFID_Init = function() {
    var PwmPin= Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
    var DigitalPin = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
    var space = Blockly.Arduino.valueToCode(this, 'Legnth', Blockly.Arduino.ORDER_ATOMIC);
    Blockly.Arduino.definitions_['define_RFID1'] = '#include "BT_NFC.h"';
    Blockly.Arduino.definitions_['define_RFID2'] = '#include "SoftwareSerial.h"';
    Blockly.Arduino.definitions_['define_RFID3'] = 'NFC nfc;';
    Blockly.Arduino.definitions_['define_RFID4'] = 'char payload[64] = {0};';
    Blockly.Arduino.definitions_['define_RFID5'] = 'int ID_length =16;'; 
    Blockly.Arduino.setups_['setup_RFID1'] = 'nfc.Begin('+DigitalPin+','+PwmPin+');';
    var code=""
    return code;
  };

 Blockly.Arduino.RFID_Write  = function () {
  //Blockly.Arduino.setups_['setup_Pulse'] = ' if (!particleSensor.begin(Wire, I2C_SPEED_FAST))\n'+
  var Value1 = Blockly.Arduino.valueToCode(this, 'RFID_ID', Blockly.Arduino.ORDER_ATOMIC);
  Blockly.Arduino.definitions_['define_RFID6'] = 'char ID_length1[] = "'+Value1+'";';
  var code = 'nfc.writeBytes(ID_length1,strlen(ID_length1));\n';
  return code;
};


Blockly.Arduino.RFID_Read  = function () {
  var funcName='ReadPayload';
  var code2='String '+funcName+'() {\n'+
   'nfc.readBytes(payload,ID_length);\n'+
   'String IDreceive=(String)payload;\n'+
   'return IDreceive;\n'+
   '}\n';
   Blockly.Arduino.definitions_['define_RFID7'] = code2;
  var code = ''+funcName+'()';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.RFID_HasCard  = function () {
  //Blockly.Arduino.setups_['setup_Pulse'] = ' if (!particleSensor.begin(Wire, I2C_SPEED_FAST))\n'+
  var Value12 = Blockly.Arduino.valueToCode(this, 'RFID_ID', Blockly.Arduino.ORDER_ATOMIC);
  var funcName='ReadPayload';
  var code2='String '+funcName+'() {\n'+
   'nfc.readBytes(payload,ID_length);\n'+
   'String IDreceive=(String)payload;\n'+
   'return IDreceive;\n'+
   '}\n';
  Blockly.Arduino.definitions_['define_RFID7'] = code2;
  var code = ''+funcName+'()=="'+Value12+'"';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};
 
Blockly.Arduino.RFID_Clear_Read  = function () {
  // var =payload;
  var code = 'memset(payload,0, sizeof(payload));';
  return code;//[code, Blockly.Arduino.ORDER_ATOMIC];
};


// Blockly.Arduino.RFID_Available =function(){
//   var code = 'nfc.available() == true';
//   return [code, Blockly.Arduino.ORDER_ATOMIC];
// };

Blockly.Arduino.RFID_Available = function() {
    var branch = Blockly.Arduino.statementToCode(this, 'DO');
    var branch2 = Blockly.Arduino.statementToCode(this, 'DO2');
    var code="if(nfc.available() == true){\n"
    code += branch;
    // code +='memset(payload,0, sizeof(payload));\n'
    code +='} else {\n';
    code +=branch2;
    code +='memset(payload,0, sizeof(payload));\n'
    code +='}\n';
    return code;
  };

Blockly.Arduino.Motor_Drive = function () {
  var speed = Blockly.Arduino.valueToCode(this, 'speed', Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
  var Port = this.getFieldValue('Portname');
  var Direction2 = this.getFieldValue('Direction');
  if(Port == 'A'){
  	Blockly.Arduino.setups_['setup_output5'] = 'pinMode(4,OUTPUT);';
  	Blockly.Arduino.setups_['setup_output6'] = 'pinMode(3,OUTPUT);';
  }
  if(Port == 'B'){
  	Blockly.Arduino.setups_['setup_output7'] = 'pinMode(2,OUTPUT);';
  	Blockly.Arduino.setups_['setup_output8'] = 'pinMode(5,OUTPUT);';
  }
  if(Port == 'C'){
  	Blockly.Arduino.setups_['setup_output1'] = 'pinMode(8,OUTPUT);';
  	Blockly.Arduino.setups_['setup_output2'] = 'pinMode(6,OUTPUT);';
  }
  if(Port == 'D'){
  	Blockly.Arduino.setups_['setup_output3'] = 'pinMode(7,OUTPUT);';
  	Blockly.Arduino.setups_['setup_output4'] = 'pinMode(9,OUTPUT);';
  }
  
  var funcName = 'motor';
  var code2 = 'void motorC(int direction2,int speed2){\n'+  
'  digitalWrite(8,direction2);\n'+
'  analogWrite(6,speed2);\n'+
'  }\n'+
'void motorD(int direction2,int speed2){\n'+
'  digitalWrite(7,direction2);\n'+
'  analogWrite(9,speed2);\n'+
'  }\n'+
'void motorA(int direction2,int speed2){\n'+
'  digitalWrite(4,direction2);\n'+
'  analogWrite(3,speed2);\n'+
'  }\n'+
'void motorB(int direction2,int speed2){\n'+
'  digitalWrite(2,direction2);\n'+
'  analogWrite(5,speed2);\n'+
'}\n';
  Blockly.Arduino.definitions_[funcName] = code2;
  var code=''+funcName+''+Port+'('+Direction2+','+speed+');\n';
  return code;
};

Blockly.Arduino.My_Servo = function () {
  var dropdown_pin = this.getFieldValue('PIN');
  var value_degree = Blockly.Arduino.valueToCode(this, 'DEGREE', Blockly.Arduino.ORDER_ATOMIC);
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '0'

	var code = 'for (int i = 0; i < 50; i++) {\n' +
	'  int pulsewidth = (' + value_degree + '*11) + 500;\n' +
	'  digitalWrite(' + dropdown_pin + ', HIGH);\n' +
	'  delayMicroseconds(pulsewidth);\n' +
	'  digitalWrite(' + dropdown_pin + ', LOW);\n' +
	'  delayMicroseconds(20000 - pulsewidth);\n' +
  '}\n' +
  'delay(' + delay_time + ');\n'
  return code;
};


//siyang
Blockly.Arduino.robotvoice_robot_pins_digital = function() {
  var code = this.getFieldValue('PIN');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.robotvoice_robot_pins_digital = function() {
  var code = this.getFieldValue('BUSY');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.robotvoice_pins_voice = function() {
  var code = this.getFieldValue('VOICE');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};


Blockly.Arduino.controls_whileUntil = function () {
    // Do while/until loop.
    var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL',
        Blockly.Arduino.ORDER_NONE) || 'false';
    var branch = Blockly.Arduino.statementToCode(this, 'DO');
    if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
        branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
            '\'' + this.id + '\'') + branch;
    }
    if (this.getFieldValue('MODE') == 'UNTIL') {
        if (!argument0.match(/^\w+$/)) {
            argument0 = '(' + argument0 + ')';
        }
        argument0 = '!' + argument0;
    }
    return 'while (' + argument0 + ') {\n' + branch + '}\n';
};

Blockly.Arduino.robotvoice_voice = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var busy = Blockly.Arduino.valueToCode(this, 'BUSY',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_voice =  Blockly.Arduino.valueToCode(this, 'VOICE',Blockly.Arduino.ORDER_ATOMIC);
  var wait_time = Blockly.Arduino.valueToCode(this, 'WAIT', Blockly.Arduino.ORDER_ASSIGNMENT) || '0'; 
   Blockly.Arduino.setups_['setup_output_sda'] = 'pinMode('+dropdown_pin+', OUTPUT);\n';
   Blockly.Arduino.setups_['setup_input_sda'] = 'pinMode('+busy+', INPUT);';
   var code =  'send_data('+dropdown_voice+'); //volume control 0xE0-E7;\n';
       code += 'delay('+wait_time +');\n'
   
   var funcName = 'voice_out';
   
   var code2 =  'void send_data(int addr)\n ';
       code2 += '{int i;digitalWrite('+dropdown_pin+' , LOW);\n';
       code2 += 'delay(3); //>2ms\n';
       code2 += 'for(i=0;i<8;i++)\n';
       code2 += '{digitalWrite('+dropdown_pin+ ', HIGH);\n';
       code2 += 'if(addr&1){delayMicroseconds(2400); //>2400us\n';
       code2 += '          digitalWrite('+dropdown_pin+', LOW);\n';
       code2 += '          delayMicroseconds(800);} //>800us\n';
       code2 += 'else{ delayMicroseconds(800); //>800us\n';
       code2 += '      digitalWrite('+dropdown_pin+ ' , LOW);\n';
       code2 += '      delayMicroseconds(2400);} //>2400us\n';
       code2 += '      addr>>=1;} //地址值右移一位\n';
       code2 += '      digitalWrite('+dropdown_pin+', HIGH);\n';
	   code2 += 'while(digitalRead(' + busy + ') == 0);}\n';
	  
	   
   Blockly.Arduino.definitions_['funcName'] = code2;   
   
  return code;
};

//siyang  BTvoice
Blockly.Arduino.robotvoice_robot_pins_digital = function() {
  var code = this.getFieldValue('PIN');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.robotvoice_robot_pins_digital = function() {
  var code = this.getFieldValue('BUSY');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.BT_robotvoice_pins_voice = function() {
  var code = this.getFieldValue('BTVOICE');
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.controls_whileUntil = function () {
    // Do while/until loop.
    var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL',
        Blockly.Arduino.ORDER_NONE) || 'false';
    var branch = Blockly.Arduino.statementToCode(this, 'DO');
    if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
        branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
            '\'' + this.id + '\'') + branch;
    }
    if (this.getFieldValue('MODE') == 'UNTIL') {
        if (!argument0.match(/^\w+$/)) {
            argument0 = '(' + argument0 + ')';
        }
        argument0 = '!' + argument0;
    }
    return 'while (' + argument0 + ') {\n' + branch + '}\n';
};

Blockly.Arduino.BT_robotvoice_voice = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var busy = Blockly.Arduino.valueToCode(this, 'BUSY',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_voice =  Blockly.Arduino.valueToCode(this, 'VOICE',Blockly.Arduino.ORDER_ATOMIC);
  var wait_time = Blockly.Arduino.valueToCode(this, 'WAIT', Blockly.Arduino.ORDER_ASSIGNMENT) || '0'; 
   Blockly.Arduino.setups_['setup_output_sda'] = 'pinMode('+dropdown_pin+', OUTPUT);\n';
   Blockly.Arduino.setups_['setup_input_sda'] = 'pinMode('+busy+', INPUT);';
   var code =  'send_data('+dropdown_voice+'); //volume control 0xE0-E7;\n';
       code += 'delay('+wait_time +');\n'
   
   var funcName = 'voice_out';
   
   var code2 =  'void send_data(int addr)\n ';
       code2 += '{int i;digitalWrite('+dropdown_pin+' , LOW);\n';
       code2 += 'delay(3); //>2ms\n';
       code2 += 'for(i=0;i<8;i++)\n';
       code2 += '{digitalWrite('+dropdown_pin+ ', HIGH);\n';
       code2 += 'if(addr&1){delayMicroseconds(2400); //>2400us\n';
       code2 += '          digitalWrite('+dropdown_pin+', LOW);\n';
       code2 += '          delayMicroseconds(800);} //>800us\n';
       code2 += 'else{ delayMicroseconds(800); //>800us\n';
       code2 += '      digitalWrite('+dropdown_pin+ ' , LOW);\n';
       code2 += '      delayMicroseconds(2400);} //>2400us\n';
       code2 += '      addr>>=1;} //地址值右移一位\n';
       code2 += '      digitalWrite('+dropdown_pin+', HIGH);\n';
	   code2 += 'while(digitalRead(' + busy + ') == 0);}\n';
	  
	   
   Blockly.Arduino.definitions_['funcName'] = code2;   
   
  return code;
};

Blockly.Arduino.my_trafficled = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_stat = this.getTitleValue('STAT');
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '0'
  Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
  var code = 'digitalWrite('+dropdown_pin+','+dropdown_stat+');\n'+
            'delay('+ delay_time +')\n';
  return code;
};

Blockly.Arduino.my_trafficled1 = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_stat = this.getTitleValue('STAT');
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '0'
  Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
  var code = 'digitalWrite('+dropdown_pin+','+dropdown_stat+');\n'+
            'delay('+ delay_time +')\n';
  return code;
};

Blockly.Arduino.my_trafficled2 = function() {
  var dropdown_pin = Blockly.Arduino.valueToCode(this, 'PIN',Blockly.Arduino.ORDER_ATOMIC);
  var dropdown_stat = this.getTitleValue('STAT');
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '0'
  Blockly.Arduino.setups_['setup_output_'+dropdown_pin] = 'pinMode('+dropdown_pin+', OUTPUT);';
  var code = 'digitalWrite('+dropdown_pin+','+dropdown_stat+');\n'+
            'delay('+ delay_time +')\n';
  return code;
};

//sentry camera
Blockly.Arduino.sentryVision_Init = function() {
  var dropdown_sen_obj = this.getFieldValue('Sen_OBJ');
  var dropdown_serial = this.getFieldValue('SERIAL');
  var offset = parseInt(dropdown_sen_obj)
  var address = 0x60 + offset;
  var RX = Blockly.Arduino.valueToCode(this, 'PIN3', Blockly.Arduino.ORDER_ATOMIC);
  var TX = Blockly.Arduino.valueToCode(this, 'PIN4', Blockly.Arduino.ORDER_ATOMIC);
  // var RX = Blockly.Arduino.valueToCode(this, 'PIN1', Blockly.Arduino.ORDER_ATOMIC);
  // var TX = Blockly.Arduino.valueToCode(this, 'PIN2', Blockly.Arduino.ORDER_ATOMIC);
  
  Blockly.Arduino.definitions_['include_vs2'] = '#include "SoftwareSerial.h"';
  Blockly.Arduino.definitions_['include_vs3'] = '#include "Sentry.h"';
  Blockly.Arduino.definitions_['include_vs4'] = '#include <Wire.h>';
  //Blockly.Arduino.definitions_[matrixName] = ' '+kMuName+dropdown_mu_obj+'('+RX+','+TX+');';
  Blockly.Arduino.definitions_['sentry'] = 'typedef Sentry2 Sentry;';
  Blockly.Arduino.definitions_["mySerial"] = 'SoftwareSerial myCamSerial('+TX+','+RX+');'; 
  Blockly.Arduino.definitions_['sentry1'] = 'Sentry sentry;';
  Blockly.Arduino.definitions_['signed'] = 'unsigned long ts = millis();';
  Blockly.Arduino.definitions_['signed1'] = 'unsigned long tn = ts;';
  // if (dropdown_serial == 'Wire') {
  //   Blockly.Arduino.definitions_['define_i2c'] = '#include <Wire.h>';
  //   Blockly.Arduino.setups_['setup_i2c'] = 'Wire.begin();\n';
  // }
  var funcName='serial_putc';
  var funcName2='fdevopen';
  Blockly.Arduino.setups_['setup_i2c'] = 'Serial.begin(9600);\n'+
  ' '+funcName2+'(&'+funcName+',0);\n'+
  ' '+dropdown_serial+'.begin(9600);\n'+
  ' sentry_err_t err = sentry.begin(&'+dropdown_serial+');\n';
  var code ='';
  var code2='int '+funcName+'(char c, struct __file*) {\n';
     code2 +='Serial.write(c);\n';
     code2 += 'return c;\n';
     code2 += '}' ;
     Blockly.Arduino.definitions_[funcName] = code2;
  return code;
};

Blockly.Arduino.sentry_setawb = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  Blockly.Arduino.setups_['Sen.begin1'] = 'sentry.CameraSetAwb('+dropdown_vision_type+');';
  var code = '';
  return code;
};

Blockly.Arduino.sentry_setzoom = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  Blockly.Arduino.setups_['Sen.begin2'] = 'sentry.CameraSetZoom('+dropdown_vision_type+');';
  var code = '';
  return code;
};

Blockly.Arduino.sentry_begin = function() {
  var dropdown_vision_status = this.getFieldValue('VisionStatus');
  var dropdown_vision_type = this.getFieldValue('VisionType');
  Blockly.Arduino.setups_['Sen.begin3'] = 'err = sentry.Vision'+dropdown_vision_status+'('+dropdown_vision_type+');';
  var code = '';
  return code;
};

Blockly.Arduino.Sentrydetect = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var code = 'sentry.GetValue('+dropdown_vision_type+',kStatus)';
  return [code, Blockly.Arduino.ORDER_ATOMIC];  
};

Blockly.Arduino.SenGetMessage = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var dropdown_detected_message = this.getFieldValue('DETECTED_MESSAGE');
  var code = 'sentry.GetValue('+dropdown_vision_type+', '+dropdown_detected_message+')';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.SenGetCardType = function() {
    var code2 = 'const char* card_classes[] = {\n';
    code2 += '"unknown",\n';
    code2 +='"forward",      "left",       "right",    "turn_around",  "park",\n';
    code2 +='"green_light",  "red_light",\n';
    code2 +='"speed_40",     "speed_60",   "speed_80",\n';
    code2 +='  "check",        "cross",      "circle",   "square",       "triangle",\n';
    code2 +='"plus",         "minus",      "divide",   "equal",\n';
    code2 +='"zero",         "one",        "two",      "three",        "four",\n';
    code2 += '"five",         "six",        "seven",    "eight",        "nine",\n';
    code2 +='"unknown",\n';
    code2 +='"Aa", "Bb", "Cc", "Dd", "Ee", "Ff", "Gg", "Hh", "Ii", "Jj", "Kk", "Ll", "Mm", "Nn",\n';
    code2 +='"Oo", "Pp", "Qq", "Rr", "Ss", "Tt", "Uu", "Vv", "Ww", "Xx", "Yy", "Zz"\n';
    code2 +='};\n';
    var code = 'card_classes[sentry.GetValue(Sentry::kVisionCard, kLabel)]';
    Blockly.Arduino.definitions_['funcName'] = code2;
    return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.SenGet20ClassType = function() {
  var code2 = 'const char* detect_classes[] = {\n';
  code2 += '"unknown",\n';
  code2 +='"Airplane",      "Bicycle",       "Bird",    "Boat",  "Bottle",\n';
  code2 +='"Bus",  "Car",\n';
  code2 +='"Cat",     "Chair",   "Cow",\n';
  code2 +='"DiningTable",        "Dog",      "Horse",   "Motorbike",       "Person",\n';
  code2 +='"PottedPlant",         "Sheep",      "Sofa",   "Train",\n';
  code2 +='"zeroTvmonitor"\n';
  code2 +='};\n';
  var code = 'card_classes[sentry.GetValue(Sentry::kVision20Classes, kLabel)]';
  Blockly.Arduino.definitions_['funcName'] = code2;
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};
  
Blockly.Arduino.Otherlabeldetect = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var code = 'sentry.GetValue('+dropdown_vision_type+',kLabel)';
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.SenGetCardTypet = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var code = 'sentry.GetValue(Sentry::kVisionCard, kLabel) == '+dropdown_vision_type;
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.SenGet20ClassType2 = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var code = 'sentry.GetValue(Sentry::kVision20Classes, kLabel) =='+dropdown_vision_type;
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};
  
Blockly.Arduino.SenGetBlob = function() {
  var code2 = 'const char* blob_classes[] = {\n';
  code2 += '"UNKNOWN", "BLACK", "WHITE", "RED", "GREEN", "BLUE", "YELLOW"\n';
  code2 +='};\n';
  var code = 'blob_classes[sentry.GetValue(Sentry::kVisionBlob, kLabel)]';
  Blockly.Arduino.definitions_['funcName'] = code2;
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.SenGetBlob2 = function() {
  var dropdown_vision_type = this.getFieldValue('VisionType');
  var code = 'sentry.GetValue(Sentry::kVisionBlob, kLabel) =='+dropdown_vision_type;
  return [code, Blockly.Arduino.ORDER_ATOMIC];
};
  
  
  
  
  
  
  

  
  
  
  
  
  
