Blockly.Blocks['oled_clear_screen'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Effacer l'écran");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("clear screen oled");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_clear_screen'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'screen.clearBuffer() \n';
  return code;
};

Blockly.Blocks['oled_writestring'] = {
  init: function() {
    this.appendValueInput("string")
        .setCheck(null)
        .appendField("Ecrire sur l'ecran");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("Write String into ppy screen");
 this.setHelpUrl("");
 this.setMutator(new Blockly.Mutator(['mutator_color']));
  },

		mutationToDom: function() {
            var container = Blockly.utils.xml.createElement("mutation");
            container.setAttribute("items", this.itemCount_);
            return container
        },
		
        domToMutation: function(xmlElements) {
            this.itemCount_ = parseInt(xmlElements.getAttribute("items"),10);
            this.updateShape_()
        },
        decompose: function(workspace) {
            var containerBlock = workspace.newBlock("oled_writestring_withcontainer");
            containerBlock.initSvg();
			var connection = containerBlock.getInput('STACK').connection;
			// var connection = containerBlock.nextConnection;
            for (var i = 0; i < this.itemCount_; i++) {
                var itemBlock = workspace.newBlock("oled_writestring_withcolor");
                itemBlock.initSvg();
                connection.connect(itemBlock.previousConnection);
                connection = itemBlock.nextConnection;
            }
            return containerBlock
        },
        compose: function(containerBlock) {
			var itemBlock = containerBlock.getInputTargetBlock('STACK');
			// Count number of inputs.
			var connections = [];
			while (itemBlock) {
				connections.push(itemBlock.valueConnection_);
				itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
			}
			this.itemCount_ = connections.length;
			this.updateShape_();
		},
		updateShape_: function() {
			for (var i = 0; i < this.itemCount_; i++) {
				if (!this.getInput('ADD' + i)) {
					var input = this.appendDummyInput('ADD' + i);
					if (i == 0) {
						input.appendField("Color : ").appendField(new Blockly.FieldDropdown([["Blanc","Oled.WHITE"], ["Noir","Oled.BLACK"]]), 'color');
					}else if (i > 0) {
						this.removeInput('ADD' + i);
						window.alert("Erreur, vous ne pouvez pas mettre deux couleurs !");
						

					}
				}
			}
			// Remove deleted inputs.
			while (this.getInput('ADD' + i)) {
				this.removeInput('ADD' + i);
				i++;
			}
		}
};
Blockly.Python['oled_writestring'] = function(block) {
	var value_name = Blockly.Python.valueToCode(block, 'string', Blockly.Python.ORDER_ATOMIC);
	if(block.itemCount_ > 0){
		var dropdown_color = block.getFieldValue('color');
		var code = 'screen.bufferDrawString(' + value_name + ',' + dropdown_color + ')\n';
	}else{
		var code = 'screen.bufferDrawString(' + value_name + ')\n';

	}
	return code;
};

Blockly.Blocks['oled_setcursor'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Placer le curseur sur l'axe :");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("SetCursor screen");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_setcursor'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var code ='screen.setCursor('+ value_pos_x + ',' + value_pos_y+ ')\n';
  return code;
};

Blockly.Blocks['oled_display'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Afficher sur l'écran");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("Display");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_display'] = function(block) {
  var code = 'screen.display() \n';
  return code;
};

Blockly.Blocks['oled_drawpixel'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner un pixel");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y");
    this.appendDummyInput()
        .appendField("color")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "Color");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("drawpixel");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawpixel'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('Color');
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawPixel(' + value_pos_x + ',' + value_pos_y + ','+ dropdown_color+ ')\n';
  return code;
};

Blockly.Blocks['oled_drawline'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner une ligne");
    this.appendValueInput("pos_xs")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x start");
    this.appendValueInput("pos_ys")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y start");
	this.appendValueInput("pos_xe")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x end");
    this.appendValueInput("pos_ye")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y end");	
    this.appendDummyInput()
        .appendField("color")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "Color");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("drawline");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawline'] = function(block) {
  var value_pos_xs = Blockly.Python.valueToCode(block, 'pos_xs', Blockly.Python.ORDER_ATOMIC);
  var value_pos_ys = Blockly.Python.valueToCode(block, 'pos_ys', Blockly.Python.ORDER_ATOMIC);
  var value_pos_xe = Blockly.Python.valueToCode(block, 'pos_xe', Blockly.Python.ORDER_ATOMIC);
  var value_pos_ye = Blockly.Python.valueToCode(block, 'pos_ye', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('Color');
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawLine(' + value_pos_xs + ',' + value_pos_ys + ','+ value_pos_xe + ',' + value_pos_ye + ','+ dropdown_color+ ')\n';
  return code;
};

Blockly.Blocks['oled_autowrite'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Affichage auto écran")
        .appendField(new Blockly.FieldDropdown([["True","True"], ["False","False"]]), "bool");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("autowrite");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_autowrite'] = function(block) {
  var dropdown_bool = block.getFieldValue('bool');
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferAutoWrite('+ dropdown_bool + ')\n';
  return code;
};

Blockly.Blocks['oled_drawrec'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner un rectangle");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x:");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y:");
    this.appendValueInput("width")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("width:");
    this.appendValueInput("height")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("height:");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("color:")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "color");
    this.appendValueInput("filled")
        .setCheck("Boolean")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("filled:");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("draw rectangle");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawrec'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var value_width = Blockly.Python.valueToCode(block, 'width', Blockly.Python.ORDER_ATOMIC);
  var value_height = Blockly.Python.valueToCode(block, 'height', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('color');
  var value_filled = Blockly.Python.valueToCode(block, 'filled', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawRect('+ value_pos_x + ','+ value_pos_y + ',' + value_width + ',' + value_height + ',' + dropdown_color + ',' + value_filled +')\n';
  return code;
};

Blockly.Blocks['oled_drawcircle'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner un cercle");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x:");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y:");
    this.appendValueInput("rayon")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("r:");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("color:")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "color");
    this.appendValueInput("filled")
        .setCheck("Boolean")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("filled:");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("draw circle");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawcircle'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var value_rayon = Blockly.Python.valueToCode(block, 'rayon', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('color');
  var value_filled = Blockly.Python.valueToCode(block, 'filled', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawCircle('+ value_pos_x + ','+ value_pos_y + ',' + value_rayon + ',' + dropdown_color + ',' + value_filled +')\n';
  return code;
};

Blockly.Blocks['oled_setfont'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Screen set Font: ")
        .appendField(new Blockly.FieldDropdown([["FreeSans","Oled.FreeSans"], ["Org","Oled.Org"], ["FreeSansBold","Oled.FreeSansBold"], ["TomThumb","Oled.TomThumb"]]), "font");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_setfont'] = function(block) {
  var dropdown_font = block.getFieldValue('font');
  // TODO: Assemble Python into code variable.
  var code = 'screen.setFont('+ dropdown_font + ')\n';
  return code;
};

Blockly.Blocks['oled_drawroundrect'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner un rectangle arrondi");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x:");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y:");
    this.appendValueInput("width")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("width:");
    this.appendValueInput("height")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("height:");
    this.appendValueInput("radius")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("radius:");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("color:")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "color");
    this.appendValueInput("remplie")
        .setCheck("Boolean")
        .appendField("filled:");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawroundrect'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var value_width = Blockly.Python.valueToCode(block, 'width', Blockly.Python.ORDER_ATOMIC);
  var value_height = Blockly.Python.valueToCode(block, 'height', Blockly.Python.ORDER_ATOMIC);
  var value_radius = Blockly.Python.valueToCode(block, 'radius', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('color');
  var value_remplie = Blockly.Python.valueToCode(block, 'remplie', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawRoundRect('+ value_pos_x + ',' + value_pos_y + ',' + value_width + ',' + value_height + ',' + value_radius + ',' + dropdown_color + ',' + value_remplie + ')\n';
  return code;
};

Blockly.Blocks['oled_drawtriangle'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Dessiner un triangle");
    this.appendValueInput("pos_x")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x:");
    this.appendValueInput("pos_y")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y:");
    this.appendValueInput("pos_x1")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x1:");
    this.appendValueInput("pos_y1")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y1:");
    this.appendValueInput("pos_x2")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("x2:");
    this.appendValueInput("pos_y2")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("y2:");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("color:")
        .appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), "color");
    this.appendValueInput("remplie")
        .setCheck("Boolean")
        .appendField("filled:");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['oled_drawtriangle'] = function(block) {
  var value_pos_x = Blockly.Python.valueToCode(block, 'pos_x', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y = Blockly.Python.valueToCode(block, 'pos_y', Blockly.Python.ORDER_ATOMIC);
  var value_pos_x1 = Blockly.Python.valueToCode(block, 'pos_x1', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y1 = Blockly.Python.valueToCode(block, 'pos_y1', Blockly.Python.ORDER_ATOMIC);
  var value_pos_x2 = Blockly.Python.valueToCode(block, 'pos_x2', Blockly.Python.ORDER_ATOMIC);
  var value_pos_y2 = Blockly.Python.valueToCode(block, 'pos_y2', Blockly.Python.ORDER_ATOMIC);
  var dropdown_color = block.getFieldValue('color');
  var value_remplie = Blockly.Python.valueToCode(block, 'remplie', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = 'screen.bufferDrawTriangle(' + value_pos_x + "," + value_pos_y + ',' + value_pos_x1 + ',' + value_pos_y1 + ',' + value_pos_x2 + ',' + value_pos_y2 + ',' + dropdown_color + ',' + value_remplie + ')\n';
  return code;
};


/*		Delay 	*/

Blockly.Blocks['delay_ms'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Attendre");
    this.appendValueInput("time")
        .setCheck(null)
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("ms :");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(152);
 this.setTooltip("Wait ms");
 this.setHelpUrl("");
  }
};
Blockly.Python['delay_ms'] = function(block) {
  var value_time = Blockly.Python.valueToCode(block, 'time', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = 'delay('+ value_time + ')\n';
  return code;
};


Blockly.Blocks['milli'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("FCT Milli");
    this.setOutput(true, null);
    this.setColour(152);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['milli'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'millis()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

/*		Switch 		*/

Blockly.Blocks['switch_value'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Valeur du bouton USR");
    this.setOutput(true, null);
    this.setColour(220);
 this.setTooltip("Value of button (true or false)");
 this.setHelpUrl("");
  }
};
Blockly.Python['switch_value'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'userSwitch.value()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['switch_callback'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Switch CallBack");
    this.appendStatementInput("switchCallback")
        .setCheck(null);
    this.setColour(220);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['switch_callback'] = function(block) {
  var statements_switchcallback = Blockly.Python.statementToCode(block, 'switchCallback');
  // TODO: Assemble Python into code variable.
  var code = 'def swCallBack():\n' + statements_switchcallback + 'userSwitch.callback(swCallBack)\n';
  return code;
};
Blockly.Blocks['lcd_setcolor'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Changer la couleur du LCD :");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Couleur : ")
        .appendField(new Blockly.FieldColour("#ff0000"), "color");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_setcolor'] = function(block) {
  var colour_color = block.getFieldValue('color');

  // Extraire les composantes rouge, verte et bleue du code hexadécimal
  var r = parseInt(colour_color.slice(1, 3), 16);
  var g = parseInt(colour_color.slice(3, 5), 16);
  var b = parseInt(colour_color.slice(5, 7), 16);

  var code = "lcd.setColor(" + r + ", " + g + ", " + b + ")\n";
  return code;
};

Blockly.Blocks['lcd_setcolorcode'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Changer la couleur du LCD :");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Couleur");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("r:")
        .appendField(new Blockly.FieldNumber(0), "r")
        .appendField("g:")
        .appendField(new Blockly.FieldNumber(0), "g")
        .appendField("b:")
        .appendField(new Blockly.FieldNumber(0), "b");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
 Blockly.Python['lcd_setcolorcode'] = function(block) {
  var number_r = block.getFieldValue('r');
  var number_g = block.getFieldValue('g');
  var number_b = block.getFieldValue('b');
  var code = "" + "\r\n";
  code += "lcd.setColor("+number_r+", "+number_g+", "+number_b+")" + "\r\n";
  return code;
};
Blockly.Blocks['lcd_setcursor'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Activer le curseur :")
        .appendField(new Blockly.FieldDropdown([["Vrai","True"], ["Faux","False"]]), "bool");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);    
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_setcursor'] = function(block) {
  var dropdown_bool = block.getFieldValue('bool');
  // TODO: Assemble Python into code variable.
  var code = "lcd.cursor("+dropdown_bool+")" + "\r\n";
  // code += "" + "\r\n";
  return code;
};
Blockly.Blocks['lcd_blink'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Activer le curseur clignotant :")
        .appendField(new Blockly.FieldDropdown([["Vrai","True"], ["Faux","False"]]), "bool");
      this.setPreviousStatement(true, null);
      this.setNextStatement(true, null);    
      this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_blink'] = function(block) {
  var dropdown_bool = block.getFieldValue('bool');
  // TODO: Assemble Python into code variable.
  var code = "lcd.blink("+dropdown_bool+")" + "\r\n";
  // code += "" + "\r\n";
  return code;
};
Blockly.Blocks['lcd_placecursor'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Mettre le curseur:")
        .appendField("     ")
        .appendField("x:")
        .appendField(new Blockly.FieldNumber(0, 0, 16), "x")
        .appendField("y:")
        .appendField(new Blockly.FieldNumber(0, 0, 2), "y");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);    
        this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_placecursor'] = function(block) {
  var number_x = block.getFieldValue('x');
  var number_y = block.getFieldValue('y');
  // TODO: Assemble Python into code variable.
  var code = "lcd.setCursor("+number_x+","+number_y+")" + "\r\n";
  return code;
};
Blockly.Blocks['lcd_write'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Ecrire sur l'écran :")
        .appendField(new Blockly.FieldTextInput("..."), "texte");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_write'] = function(block) {
  var text_texte = block.getFieldValue('texte');
  // TODO: Assemble Python into code variable.
  var code = "lcd.print(\""+text_texte+"\")" + "\r\n";
  return code;
};
Blockly.Blocks['lcd_home'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Mettre le curseur au début")
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcd_home'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = "lcd.home()" + "\r\n";
  return code;
};
Blockly.Blocks['lcdclear'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Effacer l'écran")
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['lcdclear'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = "lcd.clear()" + "\r\n";
  return code;
};

Blockly.Blocks['serre_auto'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Serre Automatique :");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Température max :")
        .appendField(new Blockly.FieldNumber(0), "tempmax");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Température min :")
        .appendField(new Blockly.FieldNumber(0), "tempmin");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("CO2 min :")
        .appendField(new Blockly.FieldNumber(0), "c02min");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("CO2 max :")
        .appendField(new Blockly.FieldNumber(0), "c02max");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Humidité min :")
        .appendField(new Blockly.FieldNumber(0), "humimin");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Humidité sol min (%) :")
        .appendField(new Blockly.FieldNumber(0, 0, 100), "humisolmin");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Plage Horaire lumière : ")
        .appendField("Allumé de :")
        .appendField(new Blockly.FieldNumber(0, 0, 24), "lumde")
        .appendField("à :")
        .appendField(new Blockly.FieldNumber(0, 0, 24), "luma");
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['serre_auto'] = function(block) {
  var number_tempmax = block.getFieldValue('tempmax');
  var number_tempmin = block.getFieldValue('tempmin');
  var number_c02min = block.getFieldValue('c02min');
  var number_c02max = block.getFieldValue('c02max');
  var number_humimin = block.getFieldValue('humimin');
  var number_humisolmin = block.getFieldValue('humisolmin');
  var number_lumde = block.getFieldValue('lumde');
  var number_luma = block.getFieldValue('luma');
  // TODO: Assemble Python into code variable.
  var code = "TEMPERATURE_MAX = " + number_tempmax + "" + "\r\n";
code += "TEMPERATURE_MIN = " + number_tempmin + "" + "\r\n";
code += "CO2_MIN = " + number_c02min + "" + "\r\n";
code += "CO2_MAX = " + number_c02max + "" + "\r\n";
code += "HUMIDITE_MIN = " + number_humimin + "" + "\r\n";
code += "HUMIDITESOL_MIN = " + number_humisolmin + "" + "\r\n";
code += "PLAGEHORAIRE_LUMIERE = [" + number_lumde + " , " + number_luma + "]" + "\r\n";
code += "" + "\r\n";
code += "" + "\r\n";
code += "from ppy import delay, ADC, I2C" + "\r\n";
code += "from lib.I2CRelayController import RelayController" + "\r\n";
code += "from lib.LCD16x2RGB import LCD16x2RGB as LCD" + "\r\n";
code += "from lib.ds1307 import DS1307" + "\r\n";
code += "from lib.SCD30 import SCD30" + "\r\n";
code += "" + "\r\n";
code += "lcd = LCD()" + "\r\n";
code += "flag = 0" + "\r\n";
code += "Time = []" + "\r\n";
code += "ds1307 = DS1307()" + "\r\n";
code += "scd30 = SCD30()" + "\r\n";
code += "relayController = RelayController();" + "\r\n";
code += "adchumisol = ADC('A0')" + "\r\n";
code += "TimeNow = 0" + "\r\n";
code += "tabCapteur = []" + "\r\n";
code += "strco2 = \"\"" + "\r\n";
code += "strtemp = \"\"" + "\r\n";
code += "strhumi = \"\"" + "\r\n";
code += "strhumisol = \"\"" + "\r\n";
code += "CompteurSeconde = 0" + "\r\n";
code += "STATERELAY1 = False" + "\r\n";
code += "ForceStopLCD = False" + "\r\n";
code += "" + "\r\n";
code += "" + "\r\n";

// Fonction pour lire les capteurs 3-en-1
code += "def readCapteur3in1():" + "\r\n";
code += "    global strco2, strtemp, strhumi, strhumisol, adchumisol, STATERELAY1, ForceStopLCD" + "\r\n";
code += "    if (scd30.get_status_ready()):" + "\r\n";
code += "         tabCapteur = scd30.read_measurement()" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant la lecture des valeurs des capteurs
code += "    # Lecture des valeurs des capteurs" + "\r\n";

code += "    humisol = adchumisol.read();" + "\r\n";
code += "    c02 = tabCapteur[0];" + "\r\n";
code += "    temperature = tabCapteur[1];" + "\r\n";
code += "    humidite = tabCapteur[2];" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant les calculs sur l'humidité du sol
code += "    # Calculs sur l'humidité du sol" + "\r\n";

code += "    humisol = 0.00007981 * humisol * humisol + 0.09147747 * humisol - 2.61305630;" + "\r\n";
code += "    humisol = 0.00000013 * humisol * humisol * humisol - 0.00007222 * humisol * humisol + 0.06034558 * humisol;" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant le formatage des valeurs des capteurs
code += "    # Formatage des valeurs des capteurs" + "\r\n";

code += "    Value1 = \"{:.0f}\".format(c02);" + "\r\n";
code += "    Value2 = \"{:.0f}\".format(temperature);" + "\r\n";
code += "    Value3 = \"{:.0f}\".format(humidite);" + "\r\n";
code += "    Value4 = \"{:.0f}\".format(humisol);" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant la création de chaînes de caractères pour l'affichage sur l'écran LCD
code += "    # Création de chaînes de caractères pour afficher les valeurs sur l'écran LCD" + "\r\n";

code += "    strco2 = 'C02 : ' + Value1 + ' ppm ';" + "\r\n";
code += "    strtemp = 'Temp : ' + Value2 + ' °C ';" + "\r\n";
code += "    strhumi =  'Humi : ' + Value3 + ' %';" + "\r\n";
code += "    if (humisol >= 100):" + "\r\n";
code += "         Value4 = \"100\";" + "\r\n";
code += "    strhumisol = 'HumiSol :' + Value4 + ' %';" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant l'affichage des valeurs sur l'écran LCD en fonction des seuils
code += "    # Affichage des valeurs sur l'écran LCD en fonction des seuils" + "\r\n";

code += "    print(strco2, strtemp, strhumi, strhumisol);" + "\r\n";
code += "" + "\r\n";
code += "    lcd.setCursor(0, 0);" + "\r\n";
code += "" + "\r\n";

// Commentaire expliquant la gestion de la couleur de l'écran LCD en fonction de la température
code += "   # Gestion de la couleur de l'écran LCD en fonction de la température" + "\r\n";

code += "    if (temperature <= TEMPERATURE_MIN) :" + "\r\n";
code += "        lcd.setColor(0, 0, 255);" + "\r\n";
code += "        lcd.print(strtemp);" + "\r\n";
code += "        ForceStopLCD = True;" + "\r\n";
code += "    elif (temperature >= TEMPERATURE_MAX) :" + "\r\n";
code += "        lcd.setColor(255, 0, 0);" + "\r\n";
code += "        lcd.print(strtemp);" + "\r\n";
code += "        ForceStopLCD = True;" + "\r\n";
code += "    else :" + "\r\n";
code += "        lcd.setColor(255, 255, 255);" + "\r\n";
code += "        ForceStopLCD = False;" + "\r\n";



code += "    # Gestion des relais en fonction de la température et du CO2" + "\r\n";

code += "    if (temperature >= TEMPERATURE_MAX) :" + "\r\n";
code += "        if (STATERELAY1 != True) :" + "\r\n";
code += "            relayController.turn_on_channel(1);" + "\r\n";
code += "            STATERELAY1 = True;" + "\r\n";
code += "" + "\r\n";
code += "    elif (c02 < CO2_MIN) :" + "\r\n";
code += "        ForceStopLCD = True;" + "\r\n";
code += "        lcd.setColor(255, 0, 0);" + "\r\n";
code += "        lcd.print(strco2);" + "\r\n";
code += "        if (STATERELAY1 != True) :" + "\r\n";
code += "            relayController.turn_on_channel(1);" + "\r\n";
code += "            STATERELAY1 = True;" + "\r\n";
code += "" + "\r\n";
code += "    elif (c02 > CO2_MAX) :" + "\r\n";
code += "        ForceStopLCD = True;" + "\r\n";
code += "        lcd.setColor(255, 0, 0);" + "\r\n";
code += "        lcd.print(strco2);" + "\r\n";
code += "        if (STATERELAY1 != True) :" + "\r\n";
code += "            relayController.turn_on_channel(1);" + "\r\n";
code += "            STATERELAY1 = True;" + "\r\n";
code += "" + "\r\n";
code += "    else :" + "\r\n";
code += "        relayController.turn_off_channel(1);" + "\r\n";
code += "        STATERELAY1 = False;" + "\r\n";
code += "        ForceStopLCD = False;" + "\r\n";
code += "" + "\r\n";


code += "    # Gestion des relais en fonction de l'humidité" + "\r\n";

code += "    if (humidite < HUMIDITE_MIN) :" + "\r\n";
code += "        relayController.turn_on_channel(2);" + "\r\n";
code += "        delay(3000);" + "\r\n";
code += "        relayController.turn_off_channel(2);" + "\r\n";
code += "    else :" + "\r\n";
code += "        relayController.turn_off_channel(2);" + "\r\n";
code += "" + "\r\n";


code += "    # Gestion des relais en fonction de l'humidité du sol" + "\r\n";

code += "    if (humisol <= HUMIDITESOL_MIN) :" + "\r\n";
code += "        relayController.turn_on_channel(2);" + "\r\n";
code += "        delay(3000);" + "\r\n";
code += "        relayController.turn_off_channel(2);" + "\r\n";
code += "    else :" + "\r\n";
code += "        relayController.turn_off_channel(2);" + "\r\n";


code += "def LCDAffichage():" + "\r\n";
code += "    global flag, ForceStopLCD" + "\r\n";
code += "" + "\r\n";
code += "    if ForceStopLCD != True:" + "\r\n";
code += "        lcd.clear()" + "\r\n";
code += "        lcd.setCursor(0,0)" + "\r\n";
code += "        lcd.setColor(255,255,255)" + "\r\n";
code += "" + "\r\n";
code += "    lcd.clear()" + "\r\n";
code += "    if(flag == 1):" + "\r\n";
code += "        lcd.print(strco2)" + "\r\n";
code += "    elif(flag == 2):" + "\r\n";
code += "        lcd.print(strhumi)" + "\r\n";
code += "    elif(flag == 3):" + "\r\n";
code += "        lcd.print(strhumisol)" + "\r\n";
code += "    elif(flag == 0):" + "\r\n";
code += "        lcd.print(strtemp)" + "\r\n";
code += "" + "\r\n";
code += "    if(flag >= 3):" + "\r\n";
code += "        flag = 0" + "\r\n";
code += "    else:" + "\r\n";
code += "        flag += 1" + "\r\n";
code += "" + "\r\n";
code += "" + "\r\n";
code += "" + "\r\n";
code += "" + "\r\n";

code += "while True:" + "\r\n";
code += "" + "\r\n";
code += "    Time = ds1307.datetime(None)" + "\r\n";
code += "    delay(1000)" + "\r\n";
code += "    CompteurSeconde += 1" + "\r\n";
code += "" + "\r\n";
code += "    if Time[4] < PLAGEHORAIRE_LUMIERE[0] :" + "\r\n";
code += "" + "\r\n";
code += "        relayController.turn_off_channel(3)" + "\r\n";
code += "" + "\r\n";
code += "    elif Time[4] > PLAGEHORAIRE_LUMIERE[1] :" + "\r\n";
code += "" + "\r\n";
code += "        relayController.turn_off_channel(3)" + "\r\n";
code += "" + "\r\n";
code += "    else : relayController.turn_on_channel(3)" + "\r\n";
code += "#     print(Time[6], CompteurSeconde)" + "\r\n";
code += "    if CompteurSeconde == 5:" + "\r\n";
code += "        LCDAffichage()" + "\r\n";
code += "    if CompteurSeconde == 10:" + "\r\n";
code += "        #readTemp()" + "\r\n";
code += "        readCapteur3in1()" + "\r\n";
code += "        LCDAffichage()" + "\r\n";
code += "        print('10', Time)" + "\r\n";
code += "        CompteurSeconde = 0" + "\r\n"
return code;
};
// CAPTEUR //

// Blockly.Blocks['capteur_temp'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Capteur de température");
//     this.appendValueInput("Analogique_input")
//         .setCheck("String")
//         .setAlign(Blockly.ALIGN_RIGHT)
//         .appendField("Entrée Analogique:");
//     this.setInputsInline(true);
//     this.setPreviousStatement(true, null);
//     this.setNextStatement(true, null);
//     this.setColour(345);
//  this.setTooltip("");
//  this.setHelpUrl("https://sciencethic.com");
// }
// };
//  Blockly.Python['capteur_temp'] = function(block) {
//   var value_analogique_input = Blockly.Python.valueToCode(block, 'Analogique_input', Blockly.Python.ORDER_ATOMIC);
//   // TODO: Assemble Python into code variable.
//   var code = "from ppy import ADC" +"\r\n";
//   code += "from lib import afficheurWEBAPP" + "\r\n";
//   code += "A0 = ADC("+value_analogique_input+")" + "\r\n";
//   code += "unit = \"Â°C\" " + "\r\n";
//   code += "id = \"2\" " + "\r\n";
//   code += "afficheur = afficheurWEBAPP.afficheursWEBAPP() " + "\r\n";
//   code += "compteur = 0" + "\r\n";
//   code += "hundredvalue = 0" + "\r\n";
//   code += "value = 0" + "\r\n";
//   code += "while True:" + "\r\n";
//   code += "        m= A0.read()" + "\r\n";
//   code += "        m=m/4095 " + "\r\n";
//   code += "        temperature=235.27*m*m*m-346.75*m*m+267.28*m-50.898 " + "\r\n";
//   code += "        compteur += 1" + "\r\n";
//   code += "        hundredvalue += temperature" + "\r\n";
//   code += "        if compteur == 100:" + "\r\n";
//   code += "            value=\"{:.1f}\".format(hundredvalue / compteur)" + "\r\n";
//   code += "            afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
//   code += "            compteur = 0" + "\r\n";
//   code += "            hundredvalue = 0" + "\r\n";
//   return code;
// };

Blockly.Blocks['exao_thermometre_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Thermométre :")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(345);
    this.setTooltip("");
    this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-temp%C3%A9rature");
  }
};

Blockly.Python['exao_thermometre_TP'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var code = "from ppy import ADC" +"\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  code+="# Initialisation de l'entrée analogique" + "\r\n";
  code += "A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
  code+="# Définition de l'unité de mesure pour la température"+ "\r\n";
  code += "unit = \"Â°C\" " + "\r\n";
  code += "id = \"2\" " + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP() " + "\r\n";
  code += "value = 0" + "\r\n";
  code+="# Lecture de la valeur de l'entrée analogique"+ "\r\n";
  code += "m= A0.read()" + "\r\n";
  code+="# Normalisation de la valeur analogique (0-1)"+ "\r\n";
  code += "m=m/4095 " + "\r\n";
  code += "# Calcul de la température à partir de la valeur normalisée"+ "\r\n";
  code += "temperature=235.27*m*m*m-346.75*m*m+267.28*m-50.898 " + "\r\n";
  // code += "        if compteur == 100:" + "\r\n";
  // code += "            value=\"{:.1f}\".format(hundredvalue / compteur)" + "\r\n";
  code += "value=\"{:.1f}\".format(temperature)" + "\r\n";
  code += "afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
  // code += "            afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
  // code += "            compteur = 0" + "\r\n";
  // code += "            hundredvalue = 0" + "\r\n";
  return code;
};

Blockly.Blocks['exao_capteurpression_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur pression -1000 2000hPa:")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(-1000, 0, 2000), "Etalonnage");    
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-pression--1000hpa2000hpa");
  }
};

Blockly.Python['exao_capteurpression_TP'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var number_etalonnage = block.getFieldValue('Etalonnage');
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import ADC" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  code += "\r\n";
  code += "# Initialisation de la conversion analogique-numérique" + "\r\n";
  code += "A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
  code += "unit = \"hPa\"" + "\r\n";
  code += "id = \"2\"" + "\r\n";
  code += "\r\n";
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  code += "value = 0" + "\r\n";
  code += "\r\n";
  code += "# Lecture de la valeur analogique" + "\r\n";
  code += "m = A0.read()" + "\r\n";
  code += "\r\n";
  code += "# Calcul de la valeur avec étalonnage" + "\r\n";
  code += "value = round(((0.732421875 * m) - " + number_etalonnage + "), 2)" + "\r\n";
  code += "\r\n";
  code += "# Envoi de la valeur à l'afficheur" + "\r\n";
  code += "afficheur.envoyer(valeur=value, identifier=id, unit=unit)" + "\r\n";

  return code;
};

Blockly.Blocks['exao_capteurhydro_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur pression 0-50hPa:")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(0, 0, 50), "Etalonnage");
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-pression-0hpa50hpa");
  }
};
Blockly.Python['exao_capteurhydro_TP'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var number_etalonnage = block.getFieldValue('Etalonnage');
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import ADC" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  code += "\r\n";
  code += "# Initialisation de la conversion analogique-numérique" + "\r\n";
  code += "A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
  code += "unit = \"hPa\"" + "\r\n";
  code += "id = \"2\"" + "\r\n";
  code += "\r\n";
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  code += "value = 0" + "\r\n";
  code += "\r\n";
  code += "# Lecture de la valeur analogique" + "\r\n";
  code += "m = A0.read()" + "\r\n";
  code += "\r\n";
  code += "# Calcul de la valeur avec étalonnage" + "\r\n";
  code += "value = round(((0.732421875 * m) - " + number_etalonnage + "), 2)" + "\r\n";
  code += "\r\n";
  code += "# Envoi de la valeur à l'afficheur" + "\r\n";
  code += "afficheur.envoyer(valeur=value, identifier=id, unit=unit)" + "\r\n";


  return code;
};

Blockly.Blocks['exao_banane_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Entrée 0V - 5V bananes: ")
        .appendField(new Blockly.FieldDropdown([["A0","A0"], ["A1","A1"], ["A2","A2"], ["A3","A3"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(50);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#connecteur-sata--banane-0v-5v");
  }
};
Blockly.Python['exao_banane_TP'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  // TODO: Assemble Python into code variable.
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import ADC" + "\r\n";
  code += "from ppy import delay" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  
  code += "# Initialisation du capteur ADC avec l'entrée spécifiée" + "\r\n";
  code += "a0 = ADC('" + dropdown_analogique_input + "')" + "\r\n";
  
  code += "# Définition de l'identifiant" + "\r\n";
  code += "id = 1" + "\r\n";
  
  code += "# Définition de l'unité de mesure" + "\r\n";
  code += "unit = \"V\"" + "\r\n";
  
  code += "# Tension d'alimentation Vcc" + "\r\n";
  code += "Vcc = 5.0" + "\r\n";
  
  // code += "# Boucle pour mesurer en continu" + "\r\n";
  
  code += "# Lecture de la valeur brute du capteur" + "\r\n";
  code += "a0RawValue = a0.read()" + "\r\n";
  
  code += "# Conversion de la valeur brute en tension" + "\r\n";
  code += "a0Voltage = ( a0RawValue/4096 ) * Vcc" + "\r\n";
  code += "a0Voltage = round(a0Voltage,2)" + "\r\n";
  
  code += "# Envoi de la valeur de tension à l'afficheur web" + "\r\n";
  code += "afficheur.envoyer(valeur=a0Voltage,identifier=id,unit=unit)" + "\r\n";
  
  // code += "    delay(20)" + "\r\n";
  return code;
  
};

Blockly.Blocks['exao_Accel_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Accéléromètre axe :")
        .appendField(new Blockly.FieldDropdown([["X","X"], ["Y","Y"], ["Z","Z"]]), "axis");
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(140);
    this.setTooltip("Lit la valeur de l'accéléromètre pour l'axe sélectionné (X, Y ou Z)");
    this.setHelpUrl("");
  }
};
Blockly.Python['exao_Accel_TP'] = function(block) {
  // Obtenir l'axe sélectionné (X, Y ou Z)
  var dropdown_axis = block.getFieldValue('axis');
  
  // Assemblage du code Python
  var code = "# Importation des bibliothèques nécessaires\n";
  code += "from ppy import Accel\n";
  code += "from ppy import delay\n";
  code += "from lib import afficheurWEBAPP\n\n";

  code += "# Initialisation de l'afficheur web\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()\n";
  //code += "delay(500)\n\n";

  code += "# Définition de l'identifiant et des unités\n";
  code += "id = 1\n";
  code += "unit = 'g'\n";
  
  
  code += "# Initialisation de l'accéléromètre\n";
  code += "mma7660 = Accel()\n\n";
  
  // Vérification de l'axe choisi par l'utilisateur pour la mesure
  if (dropdown_axis === 'X') {
    // Lecture de la valeur brute pour l'axe X
    code += "# Lecture de l'accélération brute de l'axe X\n";
    code += "rawX = mma7660.x()\n";
    
    // Conversion de la valeur brute en unités 'g' (gravité terrestre)
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "convertedX = round(rawX / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web avec l'unité 'g'
    code += "# Envoi de la valeur X convertie à l'afficheur web\n";
    code += "afficheur.envoyer(valeur=str(convertedX), identifier=id, unit=unit)\n";
    


  } else if (dropdown_axis === 'Y') {
    // Lecture de la valeur brute pour l'axe Y
    code += "# Lecture de l'accélération brute de l'axe Y\n";
    code += "rawY = mma7660.y()\n";
    
    // Conversion de la valeur brute en unités 'g'
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "convertedY = round(rawY / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web
    code += "# Envoi de la valeur Y convertie à l'afficheur web\n";
    code += "afficheur.envoyer(valeur=str(convertedY), identifier=id, unit=unit)\n";
    


  } else if (dropdown_axis === 'Z') {
    // Lecture de la valeur brute pour l'axe Z
    code += "# Lecture de l'accélération brute de l'axe Z\n";
    code += "rawZ = mma7660.z()\n";
    
    // Conversion de la valeur brute en unités 'g'
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "convertedZ = round(rawZ / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web
    code += "# Envoi de la valeur Z convertie à l'afficheur web\n";
    code += "afficheur.envoyer(valeur=str(convertedZ), identifier=id, unit=unit)\n";
    

  }

  // Retourner le code sous forme de chaîne
  return code;
};

Blockly.Blocks['exao_capteurtelemetre_TP'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Télemètre")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(false, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#t%C3%A9lem%C3%A8tre-%C3%A0-ulstasons");
  }
};

Blockly.Python['exao_capteurtelemetre_TP'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import Pin" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  code += "from lib.USRanger import USRanger" + "\r\n";
  code += "from ppy import delay" + "\r\n";
  
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  
  code += "# Initialisation du capteur USRanger" + "\r\n";
  code += "usRanger = USRanger(Pin('" + dropdown_analogique_input + "'))" + "\r\n";
  
  code += "# Définition de l'identifiant" + "\r\n";
  code += "id = 3" + "\r\n";
  
  code += "# Définition de l'unité de mesure" + "\r\n";
  code += "unit = \"m\"" + "\r\n";
  
  code += "# Mesure de la distance avec le capteur USRanger" + "\r\n";
  code += "value = (usRanger.mesureEchoMicrosSec())" + "\r\n";
  
  code += "# Calcul de la distance en mètres" + "\r\n";
  code += "value = round((340 * (value/1000000))/2, 2)" + "\r\n";
  
  code += "# Envoi de la valeur à l'afficheur web" + "\r\n";
  code += "afficheur.envoyer(valeur=value, identifier=id, unit=unit)" + "\r\n";
  
  return code;
};

Blockly.Blocks['exao_thermometre'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Thermométre:")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(345);
    this.setTooltip("");
    this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-temp%C3%A9rature");
  }
};

 Blockly.Python['exao_thermometre'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var code = "# Définition de la fonction Thermometre" +"\r\n";
  code+= "def Thermometre():" +"\r\n";
  code+= "# Importation de la bibliothèque ppy pour ADC" +"\r\n";
  code+= "    from ppy import ADC" +"\r\n";
  //code += "from lib import afficheurWEBAPP" + "\r\n";
  code+="# Initialisation de l'entrée analogique" + "\r\n";
  code += "    A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
  //code+="# Définition de l'unité de mesure pour la température"+ "\r\n";
  //code += "    unit = \"Â°C\" " + "\r\n";
  //code += "    id = \"2\" " + "\r\n";
  //code += "afficheur = afficheurWEBAPP.afficheursWEBAPP() " + "\r\n";
  code += "    value = 0" + "\r\n";
  code+="# Lecture de la valeur de l'entrée analogique"+ "\r\n";
  code += "    m= A0.read()" + "\r\n";
  code+="# Normalisation de la valeur analogique (0-1)"+ "\r\n";
  code += "    m=m/4095 " + "\r\n";
  code += "# Calcul de la température à partir de la valeur normalisée"+ "\r\n";
  code += "    temperature=235.27*m*m*m-346.75*m*m+267.28*m-50.898 " + "\r\n";
  // code += "        if compteur == 100:" + "\r\n";
  // code += "            value=\"{:.1f}\".format(hundredvalue / compteur)" + "\r\n";
  code += "    value=\"{:.1f}\".format(temperature)" + "\r\n";
  code += "# Retourne la valeur" + "\r\n";
  code += "    return(value)"+ "\r\n";
  //code += "afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
  // code += "            afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
  // code += "            compteur = 0" + "\r\n";
  // code += "            hundredvalue = 0" + "\r\n";
  return code;
};

Blockly.Blocks['exaothermometrretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour Thermométre");
    this.setOutput(true, null);
    this.setColour(345);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['exaothermometrretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Thermometre()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['exao_capteurpression'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur pression -1000 2000hPa :")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(-1000, 0, 2000), "Etalonnage");    
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-pression--1000hpa2000hpa");
  }
};
Blockly.Python['exao_capteurpression'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
var number_etalonnage = block.getFieldValue('Etalonnage');
var code = "# Définition de la fonction Capteur pression -1000 2000hPa" + "\r\n";
code += "def Capteur_pression_1000_2000hPa():" + "\r\n";
code += "# Importation de la bibliothèque ppy pour ADC" + "\r\n";
code += "    from ppy import ADC" + "\r\n";
//code += "from lib import afficheurWEBAPP" + "\r\n";
//code += "\r\n";
code += "# Initialisation de l'entrée analogique" + "\r\n";
code += "    A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
//code += "    unit = \"hPa\"" + "\r\n";
//code += "    id = \"2\"" + "\r\n";
//code += "\r\n";
//code += "# Initialisation de l'afficheur web" + "\r\n";
//code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
code += "    value = 0" + "\r\n";
//code += "\r\n";
code += "# Lecture de la valeur analogique" + "\r\n";
code += "    m = A0.read()" + "\r\n";
//code += "\r\n";
code += "# Calcul de la valeur avec étalonnage" + "\r\n";
code += "    value = round(((0.732421875 * m) - " + number_etalonnage + "), 2)" + "\r\n";
//code += "\r\n";
code += "# Retourne la valeur" + "\r\n";
code += "    return(value)" + "\r\n";


  return code;
};

Blockly.Blocks['exaocapteurpressioretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour Capteur pression -1000 2000hPa");
    this.setOutput(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['exaocapteurpressioretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Capteur_pression_1000_2000hPa()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['exao_capteurhydro'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur pression 0-50hPa :")
        .appendField(new Blockly.FieldDropdown([["A0","'A0'"], ["A1","'A1'"], ["A2","'A2'"], ["A3","'A3'"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(0, 0, 50), "Etalonnage");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#capteur-de-pression-0hpa50hpa");
  }
};
Blockly.Python['exao_capteurhydro'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var number_etalonnage = block.getFieldValue('Etalonnage');
  var code = "# Définition de la fonction Capteur pression 0-50hPa" + "\r\n";
code += "def Capteur_pression_0_50hPa():" + "\r\n";
code += "# Importation de la bibliothèque ppy pour ADC" + "\r\n";
code += "    from ppy import ADC" + "\r\n";
//code += "from lib import afficheurWEBAPP" + "\r\n";
//code += "\r\n";
code += "# Initialisation de l'entrée analogique" + "\r\n";
code += "    A0 = ADC(" + dropdown_analogique_input + ")" + "\r\n";
//code += "    unit = \"hPa\"" + "\r\n";
//code += "    id = \"2\"" + "\r\n";
//code += "\r\n";
//code += "# Initialisation de l'afficheur web" + "\r\n";
//code += "    afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
code += "    value = 0" + "\r\n";
//code += "\r\n";
code += "# Lecture de la valeur analogique" + "\r\n";
code += "    m = A0.read()" + "\r\n";
//code += "\r\n";
code += "# Calcul de la valeur avec étalonnage" + "\r\n";
code += "    value = round(((0.0152625153 * m - 6.25) - " + number_etalonnage + "), 2)" + "\r\n";
//code += "\r\n";
code += "# Retourne la valeur" + "\r\n";
code += "    return(value)" + "\r\n";


  return code;
};

Blockly.Blocks['exaocapteurhydrretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour Capteur pression 0-50hPa");
    this.setOutput(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['exaocapteurhydrretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Capteur_pression_0_50hPa()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['exao_capteurtelemetre'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Télémètre :")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#t%C3%A9lem%C3%A8tre-%C3%A0-ulstasons");
  }
};
Blockly.Python['exao_capteurtelemetre'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var code = "# Définition de la fonction radar" + "\r\n";
  code += "def Telemetre():" + "\r\n";

  code += "# Importation de la bibliothèque ppy pour Pin" + "\r\n";
  code += "    from ppy import Pin" + "\r\n";

  code += "# Importation de la bibliothèque afficheurWEBAPP" + "\r\n";
  code += "    from lib import afficheurWEBAPP" + "\r\n";

  code += "# Importation de la bibliothèque USRanger" + "\r\n";
  code += "    from lib.USRanger import USRanger" + "\r\n";

  code += "# Importation de la bibliothèque ppy pour la fonction delay" + "\r\n";
  code += "    from ppy import delay" + "\r\n";

  code += "# Initialisation de l'objet USRanger avec la broche spécifiée" + "\r\n";
  code += "    usRanger = USRanger(Pin('" + dropdown_analogique_input + "'))" + "\r\n";

  // Vous pouvez ajouter un commentaire pour expliquer la ligne ci-dessous
  // code += "    a=input('taper ENTER pour effectuer la mesure') " + "\r\n";

  code += "# Mesure de la distance en microsecondes et conversion en mètres" + "\r\n";
  code += "    value = (usRanger.mesureEchoMicrosSec())" + "\r\n";
  code += "    value = round((340 * (value/1000000))/2, 2)" + "\r\n";

  code += "# Retourne la valeur" + "\r\n";
  code += "    return value" + "\r\n";

  
  
  // code += "radar()" + "\r\n";
  // code += "print(radar())" + "\r\n";
  // code += "   afficheur.envoyer(valeur=value,identifier=id,inputValue=v,inputUnit=inputUnite,unit=unit)" + "\r\n";
  // code += "afficheur.envoyer(valeur=value,identifier=id,unit=unit)" + "\r\n";
  return code;
};

Blockly.Blocks['exaocapteurtelemetrretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour capteur de distance");
    this.setOutput(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

Blockly.Python['exaocapteurtelemetrretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Telemetre()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['station_co2'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Station CO2");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['station_co2'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import delay, ADC, UART, Pin, I2C" + "\r\n";
  code += "from ppy import Pin" + "\r\n";
  code += "import time, struct, re" + "\r\n";
  code += "from lib.LCD16x2RGB import LCD16x2RGB as LCD" + "\r\n";
  code += "from time import sleep" + "\r\n";
  code += "from math import sin" + "\r\n";
  code += "from ppy import DAC" + "\r\n";
  code += "from ppy import millis" + "\r\n";
  code += "from ppy import DAC,Pin,ADC,Switch,micros" + "\r\n";
  code += "from time import sleep_us,sleep" + "\r\n";
  code += "from array import array" + "\r\n";
  
  code += "# Initialisation de l'écran LCD" + "\r\n";
  code += "lcd = LCD()" + "\r\n";
  code += "lcd.setColor(255,255,255)" + "\r\n";
  
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  
  code += "# Définition de l'unité de mesure" + "\r\n";
  code += "unit = \"ppm\"" + "\r\n";
  
  code += "# Définition de l'identifiant" + "\r\n";
  code += "id = \"3\"" + "\r\n";
  
  code += "# Durée de l'avertissement sonore en microsecondes" + "\r\n";
  code += "honk_duration = 3E3" + "\r\n";
  
  code += "# Délai entre deux avertissements sonores en microsecondes" + "\r\n";
  code += "delay_between_two_honk_ms = 10E3" + "\r\n";
  
  code += "# Moment de la dernière alerte sonore" + "\r\n";
  code += "honk_last_call = -delay_between_two_honk_ms" + "\r\n";
  
  code += "# Configuration du signal audio" + "\r\n";
  code += "dacOnA1 = DAC('A1',bits=12)" + "\r\n";
  code += "pi = 3.14" + "\r\n";
  code += "freq = 220" + "\r\n";
  code += "amplitude = 0.1" + "\r\n";
  
  code += "# Création du tampon audio" + "\r\n";
  code += "dacBufOnA1 = bytearray(100)" + "\r\n";
  code += "for i in range(len(dacBufOnA1):" + "\r\n";
  code += "    dacBufOnA1[i] = int(4095*(amplitude/100)) + int(int(4095*(amplitude/100)) * sin(2 * pi * i / len(dacBufOnA1)))" + "\r\n";
  
  code += "# Fonction pour lire et jouer un fichier audio" + "\r\n";
  code += "@micropython.native" + "\r\n";
  code += "def play(filePath,chunkSize=2048,freq=22050,sampleSize=2):" + "\r\n";
  code += "    global playerStopFlag" + "\r\n";
  code += "    file = open(filePath,'rb')" + "\r\n";
  code += "    file.read(44)" + "\r\n";
  code += "    dacOnAx = DAC('A0',bits=12) if sampleSize==2 else DAC('A0',bits=8)" + "\r\n";
  code += "    dacOnAx.write(2047) if sampleSize==2 else dacOnAx.write(127)" + "\r\n";
  code += "    interval = int( (( (( 1 / freq )*1000000) * chunkSize) )/sampleSize)" + "\r\n";
  code += "    buf1 = bytearray(chunkSize)" + "\r\n";
  code += "    buf2 = bytearray(chunkSize)" + "\r\n";
  code += "    file.readinto(buf1)" + "\r\n";
  code += "    while file.read(2) :" + "\r\n";
  code += "        dacOnAx.write_timed( buf1 , freq , mode=DAC.NORMAL)" + "\r\n";
  code += "        lastTransaction = micros()" + "\r\n";
  code += "        file.readinto(buf2)" + "\r\n";
  code += "        sleep_us( interval - ( micros() - lastTransaction ) )" + "\r\n";
  code += "        dacOnAx.write_timed( buf2 , freq , mode=DAC.NORMAL)" + "\r\n";
  code += "        lastTransaction = micros()" + "\r\n";
  code += "        file.readinto(buf1)" + "\r\n";
  code += "        sleep_us( interval - ( micros() - lastTransaction ) )" + "\r\n";
  code += "    playerStopFlag = False" + "\r\n";
  code += "    dacOnAx.write(2047) if sampleSize==2 else dacOnAx.write(127)" + "\r\n";
  code += "    file.close()" + "\r\n";
  
  code += "# Fonction pour mesurer la concentration de CO2" + "\r\n";
  code += "def CO2():" + "\r\n";
  code += "    global honk_last_call,dacOnA1,dacBufOnA1" + "\r\n";
  code += "    uart = UART(9600)" + "\r\n";
  code += "    uart.write(b'\\xFF\\x01\\x86\\x00\\x00\\x00\\x00\\x00\\x79')" + "\r\n";
  code += "    response = uart.read(9)" + "\r\n";
  code += "    high = response[2]" + "\r\n";
  code += "    low = response[3]" + "\r\n";
  code += "    Concentration_CO2 = high * 256 + low" + "\r\n";
  code += "    lcd.setCursor(0,0)" + "\r\n";
  code += "    lcd.print(\"[CO2]                 \")" + "\r\n";
  code += "    lcd.setCursor(0,1)" + "\r\n";
  code += "    lcd.print(str(Concentration_CO2))" + "\r\n";
  code += "    lcd.print(\" / 5000\")" + "\r\n";
  code += "    lcd.print(\" ppm             \")" + "\r\n";
  code += "    afficheur.envoyer(valeur=Concentration_CO2,identifier=id,unit=unit)" + "\r\n";
  code += "    if Concentration_CO2 > 800 :" + "\r\n";
  code += "        lcd.setColor(255,0,0)" + "\r\n";
  code += "        now = millis()" + "\r\n";
  code += "        if ( now - honk_last_call ) > delay_between_two_honk_ms :" + "\r\n";
  code += "            play(\"concentration_co2_eleve_aerer_s16.wav\",freq=22050)" + "\r\n";
  code += "            honk_last_call = now" + "\r\n";
  code += "    else :" + "\r\n";
  code += "        honk_last_call = -delay_between_two_honk_ms" + "\r\n";
  code += "        lcd.setColor(0,255,0)" + "\r\n";
  
  code += "# Boucle principale" + "\r\n";
  code += "while True:" + "\r\n";
  code += "    CO2()" + "\r\n";
  
  return code;
};

Blockly.Blocks['exao_banane'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Entrée 0V - 5V bananes : ")
        .appendField(new Blockly.FieldDropdown([["A0","A0"], ["A1","A1"], ["A2","A2"], ["A3","A3"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(50);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#connecteur-sata--banane-0v-5v");
  }
};
Blockly.Python['exao_banane'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  // TODO: Assemble Python into code variable.
  var code = "# Définition de la fonction Entrée 0V - 5V bananes" + "\r\n";
  code += "def Entree_0V_5V_bananes():" + "\r\n";
  code += "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "    from ppy import ADC" + "\r\n";
  code += "    from ppy import delay" + "\r\n";
  //code += "from lib import afficheurWEBAPP" + "\r\n";
  
  //code += "# Initialisation de l'afficheur web" + "\r\n";
  //code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  
  code += "# Initialisation de l'entrée analogique" + "\r\n";
  code += "    a0 = ADC('" + dropdown_analogique_input + "')" + "\r\n";
  
  //code += "# Définition de l'identifiant" + "\r\n";
  //code += "    id = 1" + "\r\n";
  
  //code += "# Définition de l'unité de mesure" + "\r\n";
  //code += "    unit = \"V\"" + "\r\n";
  
  code += "# Tension d'alimentation Vcc" + "\r\n";
  code += "    Vcc = 5.0" + "\r\n";
  
  // code += "# Boucle pour mesurer en continu" + "\r\n";
  
  code += "# Lecture de la valeur brute du capteur" + "\r\n";
  code += "    a0RawValue = a0.read()" + "\r\n";
  
  code += "# Conversion de la valeur brute en tension" + "\r\n";
  code += "    a0Voltage = ( a0RawValue/4096 ) * Vcc" + "\r\n";
  code += "    a0Voltage = round(a0Voltage,2)" + "\r\n";
  
  code += "# Renvoi de la valeur de tension" + "\r\n";
  code += "    return(a0Voltage)" + "\r\n";
  
  // code += "    delay(20)" + "\r\n";
  return code;
  
};

Blockly.Blocks['exaobananretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Entrée 0V - 5V bananes");
    this.setOutput(true, null);
    this.setColour(50);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

Blockly.Python['exaobananretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Entree_0V_5V_bananes()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['exao_capteur_luminosite'] = { 
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur de luminosité")
        .appendField(new Blockly.FieldDropdown([
            ["A0", "0"], 
            ["A1", "1"], 
            ["A2", "2"], 
            ["A3", "3"]
        ]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(200); // Couleur du bloc
    this.setTooltip("Configure le capteur de luminosité");
    this.setHelpUrl(""); // Ajoutez une URL d'aide si nécessaire
  }
};

Blockly.Python['exao_capteur_luminosite'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var code = "# Configuration du capteur de luminosité\r\n";
  code += "def Capteur_luminosite():\r\n";
  code+= "# Importation de la bibliothèque ppy pour ADC" +"\r\n";
  code += "    from ppy import ADC\r\n";
  code+="# Initialisation de l'entrée analogique" + "\r\n";
  code += "    capteur = ADC(" + dropdown_analogique_input + ")" + "\r\n";
  code+="# Lecture de la valeur brute" + "\r\n";
  code += "    luminosite = capteur.read() \r\n";
  code += "# Retourne la valeur" + "\r\n";
  code += "    return (luminosite)\r\n";
  return code;
};

Blockly.Blocks['retourneluminosite'] = { 
  init: function() {
    this.appendDummyInput()
        .appendField("Retour luminosité");
    this.setOutput(true, "Number");
    this.setColour(200); // Couleur différente pour le bloc de retour
    this.setTooltip("Renvoie la luminosité mesurée");
    this.setHelpUrl(""); // Ajoutez une URL d'aide si nécessaire
  }
};

Blockly.Python['retourneluminosite'] = function(block) {
  var code = "Capteur_luminosite()";
  return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['exao_capteur_dht11'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur Humidité et Température DHT11:")
        .appendField(new Blockly.FieldDropdown([
            ["D2", "D2"],
            ["D3", "D3"],
            ["D4", "D4"],
            ["D5", "D5"],
            ["D6", "D6"],
            ["D7", "D7"],
            ["D8", "D8"]
        ]), "pin");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(160);
    this.setTooltip("Initialise un capteur DHT11 sur le pin spécifié");
    this.setHelpUrl("");
  }
};

Blockly.Python['exao_capteur_dht11'] = function(block) {
  var pin = block.getFieldValue('pin');
  var code = "# Initialisation du capteur DHT11\n";
  code += "from ppy import Pin\n";
  code += "from lib.DHT11 import DHT11\n";
  code += "from utime import sleep\n";
  code += "capteur = DHT11(Pin('" + pin + "'))\n";
  return code;
};

Blockly.Blocks['retourhumidite'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour humidité");
    this.setOutput(true, "Number");
    this.setColour(160);
    this.setTooltip("Retourne l'humidité mesurée par le capteur DHT11");
    this.setHelpUrl("");
  }
};

Blockly.Python['retourhumidite'] = function(block) {
  var code = "# Récupération de l'humidité mesurée par le capteur DHT11\n";
  code += "humidite = capteur.humidity\n";
  code += "return humidite\n";
  return code;
};

Blockly.Blocks['retourtemperature'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour température");
    this.setOutput(true, "Number");
    this.setColour(160);
    this.setTooltip("Retourne la température mesurée par le capteur DHT11");
    this.setHelpUrl("");
  }
};

Blockly.Python['retourtemperature'] = function(block) {
  var code = "# Récupération de la température mesurée par le capteur DHT11\n";
  code += "temperature = capteur.temperature\n";
  code += "return temperature\n";
  return code;
};

Blockly.Blocks['exao_capteur_humidite_sol'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur d'humidité dans le sol")
        .appendField(new Blockly.FieldDropdown([
            ["A0", "0"],
            ["A1", "1"],
            ["A2", "2"],
            ["A3", "3"]
        ]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(5); // Couleur du bloc
    this.setTooltip("Configure le capteur d'humidité du sol et définit sa fonction de lecture.");
    this.setHelpUrl("https://wiki.seeedstudio.com/Grove-Moisture_Sensor/");
  }
};

Blockly.Python['exao_capteur_humidite_sol'] = function(block) {
  var pin = block.getFieldValue('analogique_input');
  var code = "# Configuration du capteur d'humidité du sol\n";
  code += "def Capteur_humidite_sol():\n";
  code += "    # Importation de la bibliothèque ppy pour ADC\n";
  code += "    from ppy import ADC\n";
  code += "    # Initialisation de l'entrée analogique\n";
  code += "    capteur = ADC(" + pin + ")\n";
  code += "    # Lecture de la valeur brute\n";
  code += "    humidite = capteur.read()\n";
  code += "    # Retourne la valeur\n";
  code += "    return humidite\n";
  return code;
};

Blockly.Blocks['retour_humidite_sol'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour humidité dans le sol");
    this.setOutput(true, "Number");
    this.setColour(5); // Même couleur que le bloc d'initialisation
    this.setTooltip("Renvoie la valeur d'humidité mesurée par le capteur d'humidité du sol.");
    this.setHelpUrl("https://wiki.seeedstudio.com/Grove-Moisture_Sensor/");
  }
};

Blockly.Python['retour_humidite_sol'] = function(block) {
  var code = "Capteur_humidite_sol()";
  return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

Blockly.Blocks['exao_capteur_vibration'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Capteur de vibration")
        .appendField(new Blockly.FieldDropdown([
            ["D2", "D2"],
            ["D3", "D3"],
            ["D4", "D4"],
            ["D5", "D5"],
            ["D6", "D6"],
            ["D7", "D7"],
            ["D8", "D8"]
        ]), "digital_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(30); // Couleur du bloc
    this.setTooltip("Configure le capteur de vibration sur un port digital.");
    this.setHelpUrl("https://wiki.seeedstudio.com/Grove-Piezo_Vibration_Sensor/");
  }
};

Blockly.Python['exao_capteur_vibration'] = function(block) {
  var dropdown_digit_input = block.getFieldValue('digital_input');
  var code = "# Configuration du capteur de vibration\n";
  code += "def Capteur_vibration():\n";
  code += "    # Importation de la bibliothèque Pin\n";
  code += "    from ppy import Pin\n";
  code += "    # Initialisation du port digital\n";
  code += "    capteur = Pin('" + dropdown_digit_input + "', mode=Pin.IN)\n";
  code += "    return capteur.value()\n";  // Lecture de l'état du capteur
  return code;
};

Blockly.Blocks['retour_vibration'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour état capteur vibration");
    this.setOutput(true, "Number");
    this.setColour(30); // Même couleur que le bloc d'initialisation
    this.setTooltip("Renvoie l'état du capteur de vibration (0 ou 1).");
    this.setHelpUrl("https://wiki.seeedstudio.com/Grove-Piezo_Vibration_Sensor/");
  }
};

Blockly.Python['retour_vibration'] = function(block) {
  var code = "Capteur_vibration()";
  return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};


Blockly.Blocks['exao_condesateur'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Charge Décharge Condensateur")
    this.appendDummyInput()
        .appendField("Entrée Analogique:")
        .appendField(new Blockly.FieldDropdown([["A0","A0"], ["A1","A1"], ["A2","A2"], ["A3","A3"]]), "analogique_input");
    this.appendDummyInput()
        .appendField("Sortie Digital:")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "Digit_input");
    this.setPreviousStatement(false, null);
    this.setNextStatement(false, null);
    this.setColour(50);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Capteurs#connecteur-sata--banane-0v-5v");
  }
};


Blockly.Python['exao_condesateur'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var dropdown_digit_input = block.getFieldValue('Digit_input');
  // TODO: Assemble Python into code variable.
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
  code += "from ppy import ADC" + "\r\n";
  code += "from ppy import Pin" + "\r\n";
  code += "from ppy import delay" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  
  code += "# Initialisation de l'afficheur web" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";

  code += "# Initialisation de la sortie digital spécifiée" + "\r\n";
  code += "PinAlim = Pin('" + dropdown_digit_input + "', Pin.OUT)" + "\r\n";
  
  code += "# Initialisation du capteur ADC avec l'entrée spécifiée" + "\r\n";
  code += "PinRead = ADC('" + dropdown_analogique_input + "')" + "\r\n";
  
  code += "# Définition de l'identifiant" + "\r\n";
  code += "id = 1" + "\r\n";
  
  code += "# Définition de l'unité de mesure" + "\r\n";
  code += "unit = \"V\"" + "\r\n";
  
  code += "# Tension d'alimentation Vcc" + "\r\n";
  code += "Vcc = 5.0" + "\r\n";

  code += "# Décharge du condensateur" + "\r\n";
  code += "PinAlim.low()" + "\r\n";
  code += "delay(8000)" + "\r\n";
  code += "# charge du condensateur (alimentation à 5V)" + "\r\n";
  code += "PinAlim.high()" + "\r\n";
  code += "a0RawValue = 0" + "\r\n";
  
  code += "# Boucle jusqu'à ce que le condensateur soit chargé" + "\r\n";
  
  code += "while a0RawValue < 4095*0.91:" + "\r\n";
  code += "    # Lecture de la valeur brute du capteur" + "\r\n";
  
  code += "    a0RawValue = PinRead.read()" + "\r\n";
  code += "    # Conversion de la valeur brute en tension" + "\r\n";
  code += "    a0Voltage = ( a0RawValue/4096 ) * Vcc" + "\r\n";
  code += "    a0Voltage = round(a0Voltage,2)" + "\r\n";
  code += "    # Envoi de la valeur de tension à l'afficheur web" + "\r\n";
  code += "    afficheur.envoyer(valeur=a0Voltage,identifier=id,unit=unit)" + "\r\n";
  code += "    # Attend 1 ms avant la prochaine mesure" + "\r\n";
  code += "    delay(1)" + "\r\n";
  
  code += "# Décharge du condensateur" + "\r\n";
  code += "PinAlim.low()" + "\r\n";
  code += "# Boucle jusqu'à ce que le condensateur soit déchargé" + "\r\n";

  code += "while a0RawValue > 4095-(4095*0.98):" + "\r\n";
  code += "    # Lecture de la valeur brute du capteur" + "\r\n";
  
  code += "    a0RawValue = PinRead.read()" + "\r\n";
  code += "    # Conversion de la valeur brute en tension" + "\r\n";
  code += "    a0Voltage = ( a0RawValue/4096 ) * Vcc" + "\r\n";
  code += "    a0Voltage = round(a0Voltage,2)" + "\r\n";
  code += "    # Envoi de la valeur de tension à l'afficheur web" + "\r\n";
  code += "    afficheur.envoyer(valeur=a0Voltage,identifier=id,unit=unit)" + "\r\n";
  code += "    # Attend 1 ms avant la prochaine mesure" + "\r\n";
  code += "    delay(1)" + "\r\n";
  
  // code += "    delay(20)" + "\r\n";
  return code;
  
};
Blockly.Blocks['exao_pression'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Pression Mariotte")
        .appendField(new Blockly.FieldDropdown([["A0","A0"], ["A1","A1"], ["A2","A2"], ["A3","A3"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(-1000, 0, 2000), "Etalonnage");   
    this.setPreviousStatement(false, null);
    this.setNextStatement(false, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-loi-de-mariotte");
  }
};
Blockly.Python['exao_pression'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var number_etalonnage = block.getFieldValue('Etalonnage');
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
code += "from ppy import ADC" + "\r\n";
code += "from lib import afficheurWEBAPP" + "\r\n";
code += "from ppy import delay" + "\r\n";

code += "# Initialisation de l'afficheur web" + "\r\n";
code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";

code += "# Initialisation du capteur ADC avec l'entrée spécifiée" + "\r\n";
code += "A0 = ADC('" + dropdown_analogique_input + "')" + "\r\n";

code += "# Définition de l'identifiant" + "\r\n";
code += "id = 3" + "\r\n";

code += "# Définition de l'unité de mesure" + "\r\n";
code += "unit = \"hPa\"" + "\r\n";

code += "# Définition de l'unité d'entrée" + "\r\n";
code += "inputUnite = \"mL\"" + "\r\n";

code += "# Boucle pour mesurer en continu" + "\r\n";
code += "while True:" + "\r\n";

code += "# Saisie du volume en mL" + "\r\n";
code += "    v = float(input('Volume en mL : '))" + "\r\n";

code += "# Lecture de la valeur brute du capteur" + "\r\n";
code += "    value = A0.read()" + "\r\n";

code += "# Calcul de la valeur avec étalonnage" + "\r\n";
code += "    value = round(((0.732421875 * value) - " + number_etalonnage + "), 2)" + "\r\n";

code += "# Calcul de l'inverse du volume" + "\r\n";
code += "    v = 1 / v" + "\r\n";

code += "# Envoi de la valeur à l'afficheur web" + "\r\n";
code += "    afficheur.envoyer(valeur=value,identifier=id,inputValue=v,inputUnit=inputUnite,unit=unit)" + "\r\n";

code += "# Demande de nouvelle mesure" + "\r\n";
code += "    t = input('\\n\\nNouvelle mesure ? (o/n)')" + "\r\n";

code += "# Sortie de la boucle si la réponse est 'n'" + "\r\n";
code += "    if (t == 'n'):" + "\r\n";
code += "        break" + "\r\n";

code += "# Attente de 500 millisecondes avant la prochaine mesure" + "\r\n";
code += "    delay(500)" + "\r\n";


  

  return code;
};

Blockly.Blocks['exao_Bernoulli'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("TP Bernoulli");

    // Première entrée - Capteur 0 - 50 hPa
    this.appendDummyInput()
        .appendField("Capteur 1 0-50 hPa:")
        .appendField(new Blockly.FieldDropdown([["A0", "A0"], ["A1", "A1"], ["A2", "A2"], ["A3", "A3"]], this.onFirstDropdownChange.bind(this)), "analogique_input");

    // Deuxième entrée - Capteur 0 - 50 hPa
    this.appendDummyInput()
        .appendField("Capteur 2 0-50 hPa:")
        .appendField(new Blockly.FieldDropdown(this.getFilteredDropdownOptions.bind(this)), "analogique_input1");

    this.setPreviousStatement(false, null);
    this.setNextStatement(false, null);
    this.setColour(230);
    this.setTooltip("");
    this.setHelpUrl("");
  },

  // Fonction appelée lorsque le premier menu déroulant change
  onFirstDropdownChange: function(newValue) {
    // Stocke la valeur sélectionnée dans la première entrée
    this.firstDropdownValue = newValue;

    // Met à jour dynamiquement les options du deuxième menu déroulant
    var secondDropdown = this.getField('analogique_input1');
    secondDropdown.menuGenerator_ = this.getFilteredDropdownOptions(); // Mise à jour des options disponibles
    secondDropdown.setValue(secondDropdown.menuGenerator_[0][1]); // Sélectionne la première option disponible
  },

  // Filtrer les options du deuxième menu déroulant
  getFilteredDropdownOptions: function() {
    var allOptions = [["A0", "A0"], ["A1", "A1"], ["A2", "A2"], ["A3", "A3"]];

    // Si une option est sélectionnée dans le premier menu, la retirer des options disponibles du deuxième menu
    if (this.firstDropdownValue) {
      allOptions = allOptions.filter(function(option) {
        return option[1] !== this.firstDropdownValue;
      }.bind(this));
    }

    return allOptions;
  }
};
Blockly.Python['exao_Bernoulli'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var dropdown_analogique_input1 = block.getFieldValue('analogique_input1');
  
  // Assemblage du code Python
  var code = "# Importation des bibliothèques nécessaires\n";
  code += "from math import sqrt, pi\n";
  code += "from ppy import ADC\n";
  code += "from lib import afficheurWEBAPP\n";
  code += "from ppy import delay\n\n";
  
  code += "# Initialisation de l'afficheur web\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()\n";
  code += "delay(500)\n\n";

  code += "valetalon0 = 0\n";
  code += "valetalon1 = 0\n";
  code += "Mesure0 = 0\n";
  code += "Mesure1 = 0\n\n";

  code += "# Étalonnage des capteurs\n";
  code += "for i in range(200):\n";
  code += "    A0 = ADC('" + dropdown_analogique_input + "')\n";
  code += "    A1 = ADC('" + dropdown_analogique_input1 + "')\n";
  code += "    value0 = A0.read()\n";
  code += "    valetalon0 += round(((0.0152625153 * value0 - 6.25) - 0), 2)\n";
  code += "    value1 = A1.read()\n";
  code += "    valetalon1 += round(((0.0152625153 * value1 - 6.25) - 0), 2)\n\n";

  code += "valetalon0 = valetalon0 / 200\n";
  code += "valetalon1 = valetalon1 / 200\n\n";

  code += "# Définition de l'identifiant et des unités\n";
  code += "id = 3\n";
  code += "unit = 'l/s'\n";
  code += "inputUnite = 'Pa'\n\n";

  code += "# Boucle pour mesurer en continu\n";
  code += "while True:\n";
  code += "    DiametreA = int(input('Diametre de superieur en mm : '))\n";
  code += "    DiametreB = int(input('Diametre de inferieur en mm : '))\n";
  
  code += "    for i in range(200):\n";
  code += "        A0 = ADC('" + dropdown_analogique_input + "')\n";
  code += "        A1 = ADC('" + dropdown_analogique_input1 + "')\n";
  code += "        value0 = A0.read()\n";
  code += "        Mesure0 += round(((0.0152625153 * value0 - 6.25) - valetalon0), 2)\n";
  code += "        value1 = A1.read()\n";
  code += "        Mesure1 += round(((0.0152625153 * value1 - 6.25) - valetalon1), 2)\n\n";

  code += "    Mesure0 = Mesure0 / 200\n";
  code += "    Mesure1 = Mesure1 / 200\n";
  
  code += "    DeltaP = round((Mesure0 - Mesure1) * 100, 2)\n\n";
  code += "    Qv = round(1000*sqrt((2 * DeltaP) / (((1 / ((pi * (DiametreB * 10**-3 / 2)**2)**2)) - (1 / ((pi * (DiametreA * 10**-3 / 2)**2)**2))) * 1.2)), 2)\n\n";

  code += "    # Envoi de la valeur à l'afficheur web\n";
  code += "    afficheur.envoyer(valeur=Qv, identifier=id, inputValue=DeltaP, inputUnit=inputUnite, unit=unit)\n";
  
  code += "    t = input('\\n\\nNouvelle mesure ? (o/n)')\n";
  code += "    if t == 'n':\n";
  code += "        break\n";
  
  code += "    delay(500)\n";

  return code;
};
Blockly.Blocks['exao_Accel'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Accéléromètre axe :")
        .appendField(new Blockly.FieldDropdown([["X","X"], ["Y","Y"], ["Z","Z"]]), "axis");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(140);
    this.setTooltip("Lit la valeur de l'accéléromètre pour l'axe sélectionné (X, Y ou Z)");
    this.setHelpUrl("");
  }
};
Blockly.Python['exao_Accel'] = function(block) {
  // Obtenir l'axe sélectionné (X, Y ou Z)
  var dropdown_axis = block.getFieldValue('axis');
  
  // Assemblage du code Python
  var code = "# Définition de la fonction Accelerometre\n";
  code += "def Accelerometre():\n";
  code += "# Importation des bibliothèques nécessaires\n";
  code += "    from ppy import Accel\n";
  code += "    from ppy import delay\n";
  //code += "    from lib import afficheurWEBAPP\n";

  //code += "# Initialisation de l'afficheur web\n";
  //code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()\n";
  //code += "delay(500)\n\n";

  //code += "# Définition de l'identifiant et des unités\n";
  //code += "    id = 1\n";
  //code += "    unit = 'g'\n";
  
  
  code += "# Initialisation de l'accéléromètre\n";
  code += "    mma7660 = Accel()\n";
  
  // Vérification de l'axe choisi par l'utilisateur pour la mesure
  if (dropdown_axis === 'X') {
    // Lecture de la valeur brute pour l'axe X
    code += "# Lecture de l'accélération brute de l'axe X\n";
    code += "    rawX = mma7660.x()\n";
    
    // Conversion de la valeur brute en unités 'g' (gravité terrestre)
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "    convertedX = round(rawX / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web avec l'unité 'g'
    code += "# Renvoi de la valeur X convertie\n";
    code += "    return(str(convertedX))\n";
    


  } else if (dropdown_axis === 'Y') {
    // Lecture de la valeur brute pour l'axe Y
    code += "# Lecture de l'accélération brute de l'axe Y\n";
    code += "    rawY = mma7660.y()\n";
    
    // Conversion de la valeur brute en unités 'g'
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "    convertedY = round(rawY / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web
    code += "# Renvoi de la valeur Y convertie\n";
    code += "    return(str(convertedY))\n";
    


  } else if (dropdown_axis === 'Z') {
    // Lecture de la valeur brute pour l'axe Z
    code += "# Lecture de l'accélération brute de l'axe Z\n";
    code += "    rawZ = mma7660.z()\n";
    
    // Conversion de la valeur brute en unités 'g'
    code += "# Conversion de la valeur brute en 'g' avec arrondi à 2 décimales\n";
    code += "    convertedZ = round(rawZ / 21.33, 2)\n";
    
    // Envoi de la valeur convertie vers l'afficheur web
    code += "# Renvoi de la valeur Z convertie\n";
    code += "    return(str(convertedZ))\n";
    

  }

  // Retourner le code sous forme de chaîne
  return code;
};

Blockly.Blocks['exaoAcceretour'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour Accéléromètre");
    this.setOutput(true, null);
    this.setColour(140);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

Blockly.Python['exaoAcceretour'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = 'Accelerometre()';
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['exao_hydro'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Pression hydrostatique")
        .appendField(new Blockly.FieldDropdown([["A0","A0"], ["A1","A1"], ["A2","A2"], ["A3","A3"]]), "analogique_input");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Etalonnage: ")
        .appendField(new Blockly.FieldNumber(0, 0, 50), "Etalonnage");
    this.setPreviousStatement(false, null);
    this.setNextStatement(false, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-loi-hydrostatique");
  }
};
Blockly.Python['exao_hydro'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var number_etalonnage = block.getFieldValue('Etalonnage');
  var code = "# Importation des bibliothèques nécessaires" + "\r\n";
code += "from ppy import ADC" + "\r\n";
code += "from lib import afficheurWEBAPP" + "\r\n";
code += "from ppy import delay" + "\r\n";

code += "# Initialisation de l'afficheur web" + "\r\n";
code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";

code += "# Initialisation du capteur ADC avec l'entrée spécifiée" + "\r\n";
code += "adc = ADC('" + dropdown_analogique_input + "')" + "\r\n";

code += "# Définition de l'identifiant" + "\r\n";
code += "id = 3" + "\r\n";

code += "# Définition de l'unité de mesure" + "\r\n";
code += "unit = \"hPa\"" + "\r\n";

code += "# Définition de l'unité d'entrée" + "\r\n";
code += "inputUnite = \"cm\"" + "\r\n";

code += "# Initialisation de la valeur" + "\r\n";
code += "value = 0" + "\r\n";

code += "# Boucle pour mesurer en continu" + "\r\n";
code += "while True: " + "\r\n";

// code += "# Attente de la pression sur ENTER pour effectuer la mesure" + "\r\n";
// code += "   a=input('taper ENTER pour effectuer la mesure') " + "\r\n";

code += "# Saisie de la profondeur en cm" + "\r\n";
code += "   v=input('Profondeur en cm : ')" + "\r\n";

code += "# Lecture de la valeur brute du capteur" + "\r\n";
code += "   m= adc.read()" + "\r\n";

code += "# Calcul de la valeur avec étalonnage" + "\r\n";
code += "   value = round(((0.0152625153 * m - 6.25)- "+number_etalonnage+"),2)" + "\r\n";

code += "# Envoi de la valeur à l'afficheur web" + "\r\n";
code += "   afficheur.envoyer(valeur=value,identifier=id,inputValue=v,inputUnit=inputUnite,unit=unit)" + "\r\n";

code += "# Saisie de la décision pour une nouvelle mesure" + "\r\n";
code += "   t=input('\\n\\nNouvelle mesure ? (o/n)')" + "\r\n";

code += "# Sortie de la boucle si la réponse est 'n' (en minuscules)" + "\r\n";
code += "   if(t == \"n\"):" + "\r\n";
code += "         break" + "\r\n";


code += "# Attente de 500 millisecondes avant la prochaine mesure" + "\r\n";
code += "   delay(500);" + "\r\n";





  return code;
};

Blockly.Blocks['exao_usranger'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Vitesse du son")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
    this.setPreviousStatement(false, null);
    this.setNextStatement(false, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-vitesse-du-son");
  }};
  Blockly.Python['exao_usranger'] = function(block) {
    var dropdown_analogique_input = block.getFieldValue('analogique_input');

    var code = "# Importation des bibliothèques nécessaires" + "\r\n";
    code += "from ppy import Pin" + "\r\n";
    code += "from lib import afficheurWEBAPP" + "\r\n";
    code += "from lib.USRanger import USRanger" + "\r\n";
    code += "from ppy import delay" + "\r\n";

    code += "# Initialisation de l'afficheur web" + "\r\n";
    code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";

    code += "# Initialisation du capteur USRanger avec la broche spécifiée" + "\r\n";
    code += "usRanger = USRanger(Pin('"+dropdown_analogique_input+"'))" + "\r\n";

    code += "# Définition de l'identifiant" + "\r\n";
    code += "id = 8" + "\r\n";

    code += "# Définition de l'unité de mesure" + "\r\n";
    code += "unit = \"s\"" + "\r\n";

    code += "# Définition de l'unité d'entrée" + "\r\n";
    code += "inputUnite = \"m\"" + "\r\n";

    code += "# Initialisation de la valeur mynValue" + "\r\n";
    code += "mynValue = 0" + "\r\n";

    code += "# Boucle pour mesurer en continu" + "\r\n";
    code += "while True:" + "\r\n";

    code += "# Saisie de la distance en mètres" + "\r\n";
    code += "    v = input('Distance en m : ')" + "\r\n";

    code += "# Mesure de l'écho en microsecondes et conversion en secondes" + "\r\n";
    code += "    value = usRanger.mesureEchoMicrosSec() / 1000000" + "\r\n";

    code += "# Envoi de la valeur à l'afficheur web" + "\r\n";
    code += "    afficheur.envoyer(valeur=v, identifier=id, inputValue=value, inputUnit=unit, unit=inputUnite)" + "\r\n";

    code += "# Saisie de la décision pour une nouvelle mesure" + "\r\n";
    code += "    t = input('\\n\\nNouvelle mesure ? (o/n)')" + "\r\n";

    code += "# Sortie de la boucle si la réponse est 'n'" + "\r\n";
    code += "    if(t == \"n\"):" + "\r\n";
    code += "        break" + "\r\n";

    return code;
};

Blockly.Blocks['sortiejack'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Générateur de fréquence sur sortie audio");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Fréquence:")
        .appendField(new Blockly.FieldNumber(0, 20, 20000), "NAME");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Port digital")
        .appendField(new Blockly.FieldDropdown([["D3","D3"], ["D4","D4"],["D6","D6"],["D8","D8"]]), "Digit");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Durée d'une note (ms):")  // Ajout d'un nouveau champ pour la durée de la note en millisecondes
        .appendField(new Blockly.FieldNumber(1000, 1, 10000), "noteDurationMs"); // Champ pour la durée en millisecondes
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(120);
    this.setTooltip("");
    this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-g%C3%A9n%C3%A9rateur-de-fr%C3%A9quences-sur-sortie-audio");
  }
};

Blockly.Python['sortiejack'] = function(block) {
  var number_name = block.getFieldValue('NAME');
  var dropdown_digit = block.getFieldValue('Digit');
  var noteDurationMs = block.getFieldValue('noteDurationMs'); // Récupère la durée de la note en millisecondes
  var code = "# Importation de la bibliothèque tone" + "\r\n";
code += "from lib.tone import tone" + "\r\n";

code += "# Affectation de la valeur de noteDurationMs à toneDurationMs" + "\r\n";
code += "toneDurationMs = " + noteDurationMs + "\r\n";

code += "# Affectation de la valeur de dropdown_digit à pinToTone" + "\r\n";
code += "pinToTone = \"" + dropdown_digit + "\"" + "\r\n";

code += "# Affectation de la valeur de number_name à f" + "\r\n";
code += "f = " + number_name + "" + "\r\n";

code += "# Appel de la fonction tone avec les paramètres" + "\r\n";
code += "tone(pinToTone, f, toneDurationMs)" + "\r\n";

code += "# Utilisation de la durée de la note en millisecondes dans l'appel de la fonction" + "\r\n";
code += "toneDurationMs(pinToTone, f, " + noteDurationMs + ")" + "\r\n";

return code;

};

Blockly.Blocks['musiquetone'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Générateur de fréquence multiple");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Port digital")
        .appendField(new Blockly.FieldDropdown([["D3","D3"], ["D4","D4"],["D6","D6"],["D8","D8"]]), "Digit");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Tempo :")
        .appendField(new Blockly.FieldNumber(0, 1, 400), "tempo");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Répétition :")
        .appendField(new Blockly.FieldNumber(0, 1, 1000), "répet");
    this.appendStatementInput("note")
        .setCheck(null);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(120);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-g%C3%A9n%C3%A9rateur-de-fr%C3%A9quences-multiple-sur-sortie-audio");
	}
};
Blockly.Python['musiquetone'] = function(block) {
  var dropdown_digit = block.getFieldValue('Digit');
  var statements_note = Blockly.Python.statementToCode(block, 'note');
  var number_tempo = block.getFieldValue('tempo');
  var number_r_pet = block.getFieldValue('répet');
  // TODO: Assemble Python into code variable.
  var code = "# Importation de la bibliothèque time" + "\r\n";
  code += "from lib.tone import tone" + "\r\n";
  code += "import time" + "\r\n";
  
  code += "# Affectation de la valeur de dropdown_digit à pinToTone" + "\r\n";
  code += "pinToTone = \"" + dropdown_digit + "\"" + "\r\n";
  
  code += "# Création de la mélodie sous forme de tableau" + "\r\n";
  code += "melody = [" + "\r\n";
  code += statements_note + "\r\n";
  code += "]" + "\r\n";
  
  code += "# Définition de la fonction playMelody avec le tempo comme argument" + "\r\n";
  code += "def playMelody(tempo) :" + "\r\n";
  
  code += "# Calcul du nombre de notes dans la mélodie" + "\r\n";
  code += "    notes = int(len(melody)/2)" + "\r\n";
  
  code += "# Calcul de la durée d'une note entière en millisecondes" + "\r\n";
  code += "    wholenote = (60000 * 4) / tempo" + "\r\n";
  
  code += "# Boucle pour jouer chaque note de la mélodie" + "\r\n";
  code += "    for thisNote in range(0, notes * 2, 2):" + "\r\n";
  
  code += "# Lecture de la durée de la note" + "\r\n";
  code += "        divider = melody[thisNote + 1]" + "\r\n";
  
  code += "# Calcul de la durée de la note" + "\r\n";
  code += "        noteDuration = wholenote / divider" + "\r\n";
  
  code += "# Jouer la note avec la fonction tone" + "\r\n";
  code += "        tone(pinToTone, melody[thisNote], int(noteDuration * 0.9))" + "\r\n";
  
  code += "# Pause entre les notes si nécessaire" + "\r\n";
  code += "        pauseBetweenNotes = noteDuration * 0.1" + "\r\n";
  code += "        time.sleep(pauseBetweenNotes / 1000)" + "\r\n";

  code += "# Boucle pour jouer la mélodie plusieurs fois avec différents tempos" + "\r\n";
  code += "for i in range(0, " + number_r_pet + ") :" + "\r\n";
  code += "    playMelody(" + number_tempo + ")" + "\r\n";
  
  return code;
  
};
Blockly.Blocks['note'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Fréquence (Hz) :")
        .appendField(new Blockly.FieldDropdown([
          ["31 Hz", "31"], ["33 Hz", "33"], ["65 Hz", "65"], 
          ["131 Hz", "131"], ["262 Hz", "262"], ["294 Hz", "294"], 
          ["330 Hz", "330"], ["349 Hz", "349"], ["392 Hz", "392"],
          ["440 Hz", "440"], ["494 Hz", "494"], ["523 Hz", "523"],
          ["587 Hz", "587"], ["659 Hz", "659"], ["698 Hz", "698"],
          ["784 Hz", "784"], ["880 Hz", "880"], ["988 Hz", "988"],
          ["1047 Hz", "1047"], ["1175 Hz", "1175"], ["1319 Hz", "1319"],
          ["1397 Hz", "1397"], ["1568 Hz", "1568"], ["1760 Hz", "1760"],
          ["1976 Hz", "1976"], ["2093 Hz", "2093"]
      ]), "note");
    this.appendDummyInput()
        .appendField("Durée:")
        .appendField(new Blockly.FieldNumber(1), "timenote");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(120);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['note'] = function(block) {
  var dropdown_note = block.getFieldValue('note');
  var number_timenote = block.getFieldValue('timenote');
  // TODO: Assemble Python into code variable.
  var code = ""+dropdown_note+", "+number_timenote+ "," +"\r\n";
  return code;
};

Blockly.Blocks['aqcuisition_nbdonnee'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Acquisition | Durée définie");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Durée d'acquisition (s) :")
        .appendField(new Blockly.FieldNumber(0, 1), "tmps_aquis");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("ΔT (ms) :")
        .appendField(new Blockly.FieldNumber(0, 1), "perdiode");
    this.appendStatementInput("CodeEXAO")
        .setCheck(null);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(190);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['aqcuisition_nbdonnee'] = function(block) {
  var tmps_aquis = block.getFieldValue('tmps_aquis');
  var number_perdiode = block.getFieldValue('perdiode');
  var statements_codeexao = Blockly.Python.statementToCode(block, 'CodeEXAO');
  var code = "# Initialisation de la variable x" + "\r\n";
  code += "x = 0" + "\r\n";
  
  code += "# Initialisation du compteur de secondes (secondCount)" + "\r\n";
  code += "secondCount = 0" + "\r\n";
  
  code += "# Importation de la bibliothèque ppy pour la fonction delay" + "\r\n";
  code += "from ppy import delay" + "\r\n";
  
  code += "# Boucle pour attendre jusqu'à ce que secondCount atteigne la valeur spécifiée (" + tmps_aquis + ")" + "\r\n";
  code += "while secondCount != " + tmps_aquis + ":" + "\r\n";
  
  // Ajoute les déclarations spécifiées (statements_codeexao) à la boucle
  code += statements_codeexao;
  
  code += "# Pause pendant un certain nombre de millisecondes (" + number_perdiode + ")" + "\r\n";
  code += "  delay(" + number_perdiode + ")" + "\r\n";
  
  code += "# Incrémentation de la variable x" + "\r\n";
  code += "  x += " + number_perdiode + "\r\n";
  
  code += "# Vérification si x a atteint ou dépassé 1000 millisecondes (1 seconde)" + "\r\n";
  code += "  if x >= 1000:" + "\r\n";
  
  code += "# Incrémentation du compteur de secondes (secondCount) et réinitialisation de x" + "\r\n";
  code += "    secondCount += 1" + "\r\n";
  code += "    x = 0" + "\r\n";
  
  return code;
};
Blockly.Blocks['aqcuisition_inputinput'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Acquisition Start/Stop");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("ΔT (ms) :")
        .appendField(new Blockly.FieldNumber(0, 1), "perdiode1");
    this.appendStatementInput("CodeEXAO1")
        .setCheck(null);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(190);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['aqcuisition_inputinput'] = function(block) {
  var number_perdiode = block.getFieldValue('perdiode1');
  var statements_codeexao = Blockly.Python.statementToCode(block, 'CodeEXAO1');
  // TODO: Assemble JavaScript into code variable.
  var code = "# Importation de la bibliothèque ppy pour Pin" + "\r\n";
code += "from ppy import Pin" + "\r\n";

code += "# Importation de la bibliothèque afficheurWEBAPP" + "\r\n";
code += "from lib import afficheurWEBAPP" + "\r\n";

code += "# Importation de la bibliothèque USRanger" + "\r\n";
code += "from lib.USRanger import USRanger" + "\r\n";

code += "# Importation de la bibliothèque ppy pour la fonction delay" + "\r\n";
code += "from ppy import delay" + "\r\n";

code += "# Importation de la bibliothèque tone" + "\r\n";
code += "from lib.tone import tone" + "\r\n";

code += "# Définition de la fonction radar" + "\r\n";
code += "def radar():" + "\r\n";

code += "# Initialisation de l'objet USRanger avec le broche spécifiée" + "\r\n";
code += "    usRanger = USRanger(Pin('"+dropdown_pttele+"'))" + "\r\n";

code += "# Mesure de la distance en microsecondes et conversion en mètres" + "\r\n";
code += "    value = usRanger.mesureEchoMicrosSec()" + "\r\n";
code += "    value = round((340 * (value/1000000))/2, 2)" + "\r\n";

code += "# Retourne la valeur de distance" + "\r\n";
code += "    return value" + "\r\n";

code += "# Initialisation de la variable 'distance'" + "\r\n";
code += "distance = 0" + "\r\n";

code += "# Initialisation de l'objet afficheurWEBAPP" + "\r\n";
code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";

code += "# Boucle principale" + "\r\n";
code += "while True:" + "\r\n";

code += "# Appel de la fonction radar pour mesurer la distance" + "\r\n";
code += "    distance = radar()" + "\r\n";

code += "# Envoi de la distance mesurée à l'afficheur" + "\r\n";
code += "    afficheur.envoyer(valeur=distance,identifier=0,unit=\"m\")" + "\r\n";

code += "# Vérification si la distance est inférieure à 0.2 mètres" + "\r\n";
code += "    if distance < 0.2:" + "\r\n";

code += "# Définition de la durée de la tonalité" + "\r\n";
code += "        toneDurationMs = 100" + "\r\n";

code += "# Affectation de la broche audio spécifiée" + "\r\n";
code += "        pinToTone = \""+dropdown_ptaudio+"\"" + "\r\n";

code += "# Affectation de la fréquence de la tonalité" + "\r\n";
code += "        f = "+number_fson+"" + "\r\n";

code += "# Appel de la fonction tone pour jouer la tonalité" + "\r\n";
code += "        tone(pinToTone, f, toneDurationMs)" + "\r\n";

code += "# Pause en fonction de la distance mesurée" + "\r\n";
code += "    delay(int(500*distance))" + "\r\n";


  // code += " else:" + "\n" ;
  code += statements_codeexao ;
  // code += statements_codeexao + "\n";
  // code += " delay("+number_perdiode+")"+ "\r\n";
  // code += "  delay("+number_perdiode+")"+ "\r\n";
  // code += "  x += 1" + "\r\n";
  return code;
};
Blockly.Blocks['text_input'] = {
  init: function() {
      this.appendDummyInput()
          .appendField("Code :")
          .appendField(new Blockly.FieldMultilineInput(''), 'TEXT');
      this.setOutput(true, 'String');
      this.setColour(165);
      this.setTooltip("");
      this.setHelpUrl("");
  }
};

Blockly.Python['text_input'] = function(block) {
  var text = block.getFieldValue('TEXT') || ""; // Ne pas ajouter de guillemets par défaut
  var code = text;
  return [code, Blockly.Python.ORDER_ATOMIC];
};


// ACTIONNEUR //
// Bloc pour la commandeMatrice
// Bloc pour la commandeMatrice
Blockly.Blocks['commandeMatrice'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Matrice led");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Port digital")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "Digit");
    // this.appendDummyInput()
    //     .setAlign(Blockly.ALIGN_RIGHT)
    //     .appendField("Coordonnées X:")
    //     .appendField(new Blockly.FieldNumber(0, 0, 4), "X");
    // this.appendDummyInput()
    //     .setAlign(Blockly.ALIGN_RIGHT)
    //     .appendField("Coordonnées Y:")
    //     .appendField(new Blockly.FieldNumber(0, 0, 4), "Y");
    // this.appendDummyInput()
    //     .appendField("Couleur:")
    //     .appendField(new Blockly.FieldDropdown([["Vert", "#00ff00"], ["Rouge", "#ff0000"], ["Bleu", "#0000ff"]]), "COULEUR");
    // this.appendStatementInput("New Coordonnées X:")
    //    .setCheck(null);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(120);
    this.setTooltip("");
  }
};

// Bloc pour définir les coordonnées X et Y et choisir la couleur
Blockly.Blocks['setCoordonnees'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Set LED");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Coordonnée X:")
        .appendField(new Blockly.FieldNumber(0, 0, 4), "X");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Coordonnée Y:")
        .appendField(new Blockly.FieldNumber(0, 0, 4), "Y");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Couleur:")
        .appendField(new Blockly.FieldDropdown([["Vert", "#00ff00"], ["Rouge", "#ff0000"], ["Bleu", "#0000ff"]]), "COULEUR");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

// Génération du code Python pour la commandeMatrice
Blockly.Python['commandeMatrice'] = function (block) {
  var digit = block.getFieldValue('Digit');

  var code = '# DEBUT de Smart LED Basique )\n';
  code += '# Utilisation de SmartLED\n';
  
  code += 'from ppy import SmartLED\n';
  code += 'from ppy import delay, udelay\n';
  code += 'from ppy import Pin\n\n';

  code += 'Pin(\'' + digit + '\', Pin.OUT)\n';
  code += '# Declarer smartLED en on ' + digit + '\n';
  code += 'led = SmartLED(\'' + digit + '\')\n';
  code += '# La vitesse de communication peut être réglée ...\n';
  code += '# ..entre SmartLED.KHZ400/KHZ800\n';
  code += 'led = SmartLED(\'' + digit + '\', SmartLED.KHZ800)\n\n';

  code += '# Définir le nombre de LED et créer un tableau pour stocker les couleurs \n';
  code += 'num_leds_per_row = 5  # Nombre de LEDs dans chaque ligne\n';
  code += 'num_leds = num_leds_per_row * num_leds_per_row  # Nombre total de LEDs\n';
  code += 'led_colors = bytearray(0x00 for n in range(num_leds*3))  # Initialiser avec toutes les LEDs éteintes\n\n';
  code += 'led.write(led_colors)\n\n';

  code += '# Fonction pour définir la couleur de la LED à une position spécifique (x, y et z=0) \n';
  code += 'def set_led_color(x, y, r, g, b):\n';
  code += '    if 0 <= x < num_leds_per_row and 0 <= y < num_leds_per_row:\n';
  code += '        # Calculer l\'indice de la LED en fonction de la position (x, y)\n';
  code += '        index = y + x * num_leds_per_row\n\n';

  code += '        # Mettre à jour la couleur des LED dans le tableau \n';
  code += '        led_colors[index * 3] = g\n';
  code += '        led_colors[index * 3 + 1] = r\n';
  code += '        led_colors[index * 3 + 2] = b\n\n';

  code += '# Fonction pour mettre à jour la bande LED avec la couleur actuelle \n';
  code += 'def update_led_strip():\n';
  code += '    led.write(led_colors)\n\n';

  code += '# Fonction qui éteint les LEDs restantes sauf une \n';
  code += 'def clear_leds_except_one():\n';
  code += '    for i in range(num_leds):\n';
  code += '        if i != (1 + 2 * num_leds_per_row):\n';
  code += '            led_colors[i * 3] = 0\n';
  code += '            led_colors[i * 3 + 1] = 0\n';
  code += '            led_colors[i * 3 + 2] = 0\n\n';

  // Ajouter le code généré par le bloc setCoordonnees
  var setCoordonneesCode = Blockly.Python.blockToCode(block.getInputTargetBlock('New Coordonnées X:'));
  code += setCoordonneesCode;

  // Exemple d'utilisation de set_led_color (utilisez les noms de fonctions corrects)
  // code += 'set_led_color(' + x + ', ' + y + ', ' + r + ', ' + g + ', ' + b + ')\n';
  // code += 'update_led_strip()\n';
  // code += 'delay(10)\n\n';

  return code;
};

// Génération du code Python pour setCoordonnees
Blockly.Python['setCoordonnees'] = function(block) {
  // Récupérer les valeurs des champs du bloc setCoordonnees
  var x = block.getFieldValue('X');
  var y = block.getFieldValue('Y');
  var couleur = block.getFieldValue('COULEUR');

  // Convertir la couleur hexadécimale en valeurs RVB
  var r = parseInt(couleur.slice(1, 3), 16);
  var g = parseInt(couleur.slice(3, 5), 16);
  var b = parseInt(couleur.slice(5, 7), 16);

  // Générer le code pour allumer la LED avec les coordonnées et la couleur spécifiées
  var setLedCode = 'set_led_color(' + x + ', ' + y + ', ' + r + ', ' + g + ', ' + b + ')\n';
  setLedCode += 'update_led_strip()\n';
  setLedCode += 'delay(10)\n';

  // Retourner le code généré
  return setLedCode;
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Blockly.Blocks['Actionneur_Init'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Actionneur Initialisation:")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input")
        .appendField(new Blockly.FieldTextInput("variable"), "variable");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(220);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['Actionneur_Init'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var text_variable = block.getFieldValue('variable');
  var code = "from ppy import Pin" + "\r\n";
  code += ""+text_variable+" = Pin('"+dropdown_analogique_input+"', Pin.IN)" + "\r\n";
  // code += "touchetactile.value()" + "\r\n";
  return code;
};



Blockly.Blocks['Actionneur'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Retour Actionneur")
        .appendField(new Blockly.FieldTextInput("variable"), "variable")
        // .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
    this.setOutput(true, null);
    this.setColour(220);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['Actionneur'] = function(block) {
  // var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var text_variable = block.getFieldValue('variable');
  var code = ""+text_variable+".value()";
  return [code, Blockly.Python.ORDER_NONE];
};


Blockly.Blocks['LedInit'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Initialisation LED (any color):")
        .appendField(new Blockly.FieldTextInput("variable"), "variable")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['LedInit'] = function(block) {
  var dropdown_analogique_input = block.getFieldValue('analogique_input');
  var text_variable = block.getFieldValue('variable');
  var code = "from ppy import Pin" + "\r\n";
  code += ""+text_variable+" = Pin('"+dropdown_analogique_input+"', Pin.OUT)" + "\r\n";
  // code += "touchetactile.value()" + "\r\n";
  return code;
};
Blockly.Blocks['LedON'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("LED On")
        .appendField(new Blockly.FieldTextInput("variable"), "variable")
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['LedON'] = function(block) {
  var text_variable = block.getFieldValue('variable');
  var code = ""+text_variable+".on()" + "\r\n";
  return code;
};
Blockly.Blocks['LedOFF'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("LED OFF")
        .appendField(new Blockly.FieldTextInput("variable"), "variable")
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['LedOFF'] = function(block) {
  var text_variable = block.getFieldValue('variable');
  var code = ""+text_variable+".off()" + "\r\n";
  return code;
};

// Blockly.Blocks['TiltInit'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Interrupteur magnétique Initialisation:")
//         .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setPreviousStatement(true, null);
//     this.setNextStatement(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['TiltInit'] = function(block) {
//   var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "from ppy import Pin" + "\r\n";
//   code += "tilt = Pin('"+dropdown_analogique_input+"', Pin.IN)" + "\r\n";
//   // code += "touchetactile.value()" + "\r\n";
//   return code;
// };
// Blockly.Blocks['RetourTilt'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Retour Interrupteur magnétique")
//         // .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setOutput(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['RetourTilt'] = function(block) {
//   // var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "tilt.value()";
//   return [code, Blockly.Python.ORDER_NONE];
// };

// Blockly.Blocks['MouvementInit'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("CapteurMouvement Initialisation:")
//         .appendField(new Blockly.FieldDropdown([["D2","D2"]]), "analogique_input");
//     this.setPreviousStatement(true, null);
//     this.setNextStatement(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['MouvementInit'] = function(block) {
//   var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "from ppy import Pin" + "\r\n";
//   code += "CmouvementIR = Pin('"+dropdown_analogique_input+"', Pin.IN)" + "\r\n";
//   // code += "touchetactile.value()" + "\r\n";
//   return code;
// };
// Blockly.Blocks['MouvementRetour'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Retour CapteurMouvement")
//         // .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setOutput(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['MouvementRetour'] = function(block) {
//   // var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "CmouvementIR.value()";
//   return [code, Blockly.Python.ORDER_NONE];
// };


// Blockly.Blocks['InterFinCourseInit'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Interrupteur Fin de course Initialisation:")
//         .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setPreviousStatement(true, null);
//     this.setNextStatement(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['InterFinCourseInit'] = function(block) {
//   var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "from ppy import Pin" + "\r\n";
//   code += "interrupteurFC = Pin('"+dropdown_analogique_input+"', Pin.IN)" + "\r\n";
//   // code += "touchetactile.value()" + "\r\n";
//   return code;
// };
// Blockly.Blocks['InterFinCourseRetour'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Retour Interrupteur")
//         // .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setOutput(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['InterFinCourseRetour'] = function(block) {
//   // var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "interrupteurFC.value()";
//   return [code, Blockly.Python.ORDER_NONE];
// };



// Blockly.Blocks['InterrupteurInit'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Interrupteur Initialisation:")
//         .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setPreviousStatement(true, null);
//     this.setNextStatement(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['InterrupteurInit'] = function(block) {
//   var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "from ppy import Pin" + "\r\n";
//   code += "interrupteur = Pin('"+dropdown_analogique_input+"', Pin.IN)" + "\r\n";
//   // code += "touchetactile.value()" + "\r\n";
//   return code;
// };
// Blockly.Blocks['InterrupteurRetour'] = {
//   init: function() {
//     this.appendDummyInput()
//         .appendField("Retour Interrupteur")
//         // .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "analogique_input");
//     this.setOutput(true, null);
//     this.setColour(300);
//  this.setTooltip("");
//  this.setHelpUrl("");
//   }
// };
// Blockly.Python['InterrupteurRetour'] = function(block) {
//   // var dropdown_analogique_input = block.getFieldValue('analogique_input');
//   var code = "interrupteur.value()";
//   return [code, Blockly.Python.ORDER_NONE];
// };

// Entrée clavier
Blockly.Blocks['inputclavier'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Entrée clavier ");
    this.appendValueInput("NAME")
        .setCheck("String")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Texte :");
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(160);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['inputclavier'] = function(block) {
  var value_name = Blockly.Python.valueToCode(block, 'NAME', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = "input("+value_name+")"
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};
// MATRIX LED

Blockly.Blocks['LibAfficheurInit'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Afficheur Graphique/Numérique Initialisation:")
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(300);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['LibAfficheurInit'] = function(block) {
  var code = "from lib import afficheurWEBAPP" +"\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  // code += "touchetactile.value()" + "\r\n";
  return code;
};

Blockly.Blocks['LibAfficheur'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Affichage Graphique/Numérique : ");
    this.appendValueInput("vari")
        .setCheck(null)
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Variable :");
    this.appendValueInput("unit")
        .setCheck(null)
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("unité :");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['LibAfficheur'] = function(block) {
  var value_vari = Blockly.Python.valueToCode(block, 'vari', Blockly.Python.ORDER_ATOMIC);
  var value_unit = Blockly.Python.valueToCode(block, 'unit', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.

  var code = "afficheur.envoyer(valeur="+value_vari+",identifier=3,unit="+value_unit+")" + "\r\n";
  return code;
};

Blockly.Blocks['tp_radarderecule'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("TP Radar de recul");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Port du Télémètre :")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "PtTele");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Port de la sortie audio :")
        .appendField(new Blockly.FieldDropdown([["D2","D2"], ["D3","D3"], ["D4","D4"], ["D5","D5"] , ["D6","D6"], ["D7","D7"], ["D8","D8"]]), "PtAudio");
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("Fréquence du son :")
        .appendField(new Blockly.FieldNumber(0, 20, 20000), "fson");
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("https://github.com/SupportSciencethic/HelpBlock/wiki/Travaux-Pratiques#tp-radar-de-recul");
  }
};
Blockly.Python['tp_radarderecule'] = function(block) {
  var dropdown_pttele = block.getFieldValue('PtTele');
  var dropdown_ptaudio = block.getFieldValue('PtAudio');
  var number_fson = block.getFieldValue('fson');
  // TODO: Assemble Python into code variable.
  var code = "# Importation de la bibliothèque ppy pour Pin" + "\r\n";
  code += "from ppy import Pin" + "\r\n";
  
  code += "# Importation de la bibliothèque afficheurWEBAPP" + "\r\n";
  code += "from lib import afficheurWEBAPP" + "\r\n";
  
  code += "# Importation de la bibliothèque USRanger" + "\r\n";
  code += "from lib.USRanger import USRanger" + "\r\n";
  
  code += "# Importation de la bibliothèque ppy pour la fonction delay" + "\r\n";
  code += "from ppy import delay" + "\r\n";
  
  code += "# Importation de la bibliothèque tone" + "\r\n";
  code += "from lib.tone import tone" + "\r\n";
  
  code += "# Définition de la fonction radar" + "\r\n";
  code += "def radar():" + "\r\n";
  
  code += "# Initialisation de l'objet USRanger avec la broche spécifiée" + "\r\n";
  code += "    usRanger = USRanger(Pin('"+dropdown_pttele+"'))" + "\r\n";
  
  code += "# Mesure de la distance en microsecondes et conversion en mètres" + "\r\n";
  code += "    value = usRanger.mesureEchoMicrosSec()" + "\r\n";
  code += "    value = round((340 * (value/1000000))/2, 2)" + "\r\n";
  
  code += "# Retourne la valeur de distance" + "\r\n";
  code += "    return value" + "\r\n";
  
  code += "# Initialisation de la variable 'distance'" + "\r\n";
  code += "distance = 0" + "\r\n";
  
  code += "# Initialisation de l'objet afficheurWEBAPP" + "\r\n";
  code += "afficheur = afficheurWEBAPP.afficheursWEBAPP()" + "\r\n";
  
  code += "# Boucle principale" + "\r\n";
  code += "while True:" + "\r\n";
  
  code += "# Appel de la fonction radar pour mesurer la distance" + "\r\n";
  code += "    distance = radar()" + "\r\n";
  
  code += "# Envoi de la distance mesurée à l'afficheur" + "\r\n";
  code += "    afficheur.envoyer(valeur=distance,identifier=0,unit=\"m\")" + "\r\n";
  
  code += "# Vérification si la distance est inférieure à 0.2 mètres" + "\r\n";
  code += "    if distance < 0.2:" + "\r\n";
  
  code += "# Définition de la durée de la tonalité" + "\r\n";
  code += "        toneDurationMs = 100" + "\r\n";
  
  code += "# Affectation de la broche audio spécifiée" + "\r\n";
  code += "        pinToTone = \""+dropdown_ptaudio+"\"" + "\r\n";
  
  code += "# Affectation de la fréquence de la tonalité" + "\r\n";
  code += "        f = "+number_fson+"" + "\r\n";
  
  code += "# Appel de la fonction tone pour jouer la tonalité" + "\r\n";
  code += "        tone(pinToTone, f, toneDurationMs)" + "\r\n";
  
  code += "# Pause en fonction de la distance mesurée" + "\r\n";
  code += "    delay(int(500*distance))" + "\r\n";
  

  return code;
};

// TEST MUTATOR // 
Blockly.Blocks['puet'] = {
  init: function() {
    this.appendValueInput("string")
        .setCheck("String")
        .appendField("ppy Write String");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
	this.setTooltip("Write String into ppy screen");
	this.setHelpUrl("");
	this.setMutator(new Blockly.Mutator(['mutator_color']));
  },

		mutationToDom: function() {
            var container = Blockly.utils.xml.createElement("mutation");
            container.setAttribute("items", this.itemCount_);
            return container
        },
		
        domToMutation: function(xmlElements) {
            this.itemCount_ = parseInt(xmlElements.getAttribute("items"),10);
            this.updateShape_()
        },
        decompose: function(workspace) {
            var containerBlock = workspace.newBlock("oled_writestring_withcontainer");
            containerBlock.initSvg();
			var connection = containerBlock.getInput('STACK').connection;
			// var connection = containerBlock.nextConnection;
            for (var i = 0; i < this.itemCount_; i++) {
                var itemBlock = workspace.newBlock("oled_writestring_withcolor");
                itemBlock.initSvg();
                connection.connect(itemBlock.previousConnection);
                connection = itemBlock.nextConnection;
            }
            return containerBlock
        },
        compose: function(containerBlock) {
			var itemBlock = containerBlock.getInputTargetBlock('STACK');
			// Count number of inputs.
			var connections = [];
			while (itemBlock) {
				connections.push(itemBlock.valueConnection_);
				itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();
			}
			this.itemCount_ = connections.length;
			this.updateShape_();
		},
		updateShape_: function() {
			for (var i = 0; i < this.itemCount_; i++) {
				if (!this.getInput('ADD' + i)) {
					var input = this.appendDummyInput('ADD' + i);
					if (i == 0) {
						input.appendField("Color : ").appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), 'color');
					}
				}
			}
			// Remove deleted inputs.
			while (this.getInput('ADD' + i)) {
				this.removeInput('ADD' + i);
				i++;
			}
		}
};

	// console.log(b);
     // var b = this.appendDummyInput("ADD" + container).appendField("Color : ").appendField(new Blockly.FieldDropdown([["White","Oled.WHITE"], ["Black","Oled.BLACK"]]), 'color');
	// 0 == container;     



Blockly.Python['puet'] = function(block) {
	var value_name = Blockly.Python.valueToCode(block, 'string', Blockly.Python.ORDER_ATOMIC);
	if(block.itemCount_ > 0){
		var dropdown_color = block.getFieldValue('color');
		var code = 'screen.bufferDrawString(' + value_name + ',' + dropdown_color + ')\n';
	}else{
		var code = 'screen.bufferDrawString(' + value_name + ')\n';

	}
	return code;
};


/*		Mutator		*/

Blockly.Blocks['mutator_color'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Couleur :")
        .appendField(new Blockly.FieldDropdown([["Blanc","Oled.WHITE"], ["Noir","Oled.BLACK"]]), "NAME");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

Blockly.Blocks['oled_writestring_withcontainer'] = {
  init: function() {
    this.appendStatementInput("STACK")
        .setCheck(null)
        .appendField("Ecrire sur l'écran");
    this.setColour(45);
 this.setTooltip("Write String into ppy screen");
 this.setHelpUrl("");
  }
};

Blockly.Blocks['oled_writestring_withcolor'] = {
  init: function() {
    this.appendValueInput("string")
        .setCheck("String")
        .appendField("ppy Write String");
    this.appendDummyInput()
        .appendField("Color : ")
        .appendField(new Blockly.FieldDropdown([["Blanc","Oled.WHITE"], ["Noir","Oled.BLACK"]]), "color");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour(45);
 this.setTooltip("Write String into ppy screen");
 this.setHelpUrl("");
}

}

// is in
Blockly.Blocks['isin'] = {
  init: function() {
    this.appendValueInput("1")
        .setCheck(null);
    this.appendDummyInput()
        .appendField("est dans");
    this.appendValueInput("2")
        .setCheck(null);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour(225);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['isin'] = function(block) {
  var value_1 = Blockly.Python.valueToCode(block, '1', Blockly.Python.ORDER_ATOMIC);
  var value_2 = Blockly.Python.valueToCode(block, '2', Blockly.Python.ORDER_ATOMIC);
  // TODO: Assemble Python into code variable.
  var code = value_1 + " in " + value_2;
  // TODO: Change ORDER_NONE to the correct strength.
  return [code, Blockly.Python.ORDER_NONE];
};
Blockly.Blocks['ECEPC5'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("ECE_23_PC_5");
        
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};
Blockly.Python['ECEPC5'] = function(block) {
  // TODO: Assemble Python into code variable.
  var code = "# Importation des bibliothèques" + "\r\n";
  code += "from ppy import delay, ADC, Pin, millis" + "\r\n";
  code += "pinD2 = Pin('D2', Pin.OUT)" + "\r\n";
  code += "a0 = ADC('A0')" + "\r\n";
  code += "# Décharge du condensateur" + "\r\n";
  code += "pinD2.low()" + "\r\n";
  code += "delay(8000)" + "\r\n";
  code += "# Charge du condensateur (alimentation à 5V)" + "\r\n";
  code += "pinD2.high()" + "\r\n";
  code += "previousMillis = millis()" + "\r\n";
  code += "# La commande millis() renvoie la date de l'horloge interne du microcontrôleur en ms" + "\r\n";
  code += "while a0.read() < 4095:" + "\r\n";
  code += "     delay(1)   # Attend 1 ms avant la prochaine mesure" + "\r\n";
  code += "print(\"tau = \", millis() - previousMillis, \" ms\")" + "\r\n";
  
  return code;
};