Перейти к основному содержанию
Логотип

Robotics on transpor ...

    • Қазақша ‎(kk)‎
    • Русский ‎(ru)‎
    • English ‎(en)‎
  • Вход
SYSTEMS.ENU Свернуть Развернуть
PLATONUS.ENU DIRECTUM.ENU MAIL.ENU MY.ENU MOODLE.ENU MOOC.ENU
SYSTEMS.ENU Свернуть Развернуть
PLATONUS.ENU DIRECTUM.ENU MAIL.ENU MY.ENU MOODLE.ENU MOOC.ENU
  1. Курсы
  2. Дистанционное обучение
  3. Факультеты
  4. Транспортно-энергетический факультет
  5. Кафедра Транспортная инженерия
  6. Robotics on transport (Балабекова К.Г.) 2025-2026 учебный год.
  7. Piezoelectric element. Temperature sensor
  8. The purpose of the lecture: Creating your own function. The purpose and role of the temperature sensor and piezoelectric element.
  • Дополнительно

The purpose of the lecture: Creating your own function. The purpose and role of the temperature sensor and piezoelectric element.

Требуемые условия завершения

The content of the lecture:

1.1. Creating your own function

1.2. Piezoelectric element. Tan function (pin, frequency, duration).

1.3. Temperature sensor. Technical Specifications of TMP36

Didactic units: piezoelectric element, temperature sensor, functions

 

5.1.          Creating your own function

A funct ion is a piece of program code that can be accessed from another place in the program. In short, this is a set of commands that can be called by referring to this function by name. You can say that a function is a kind of one small library. The syntax for writing a function is as follows.

Запомнить!

<Тип данных> <имя функции> (<набор параметров>)

{тело функции}

Each function has a data type int, float, byte, long, double, Boolean, single, real, sword, short int, etc. to which the function name is assigned. Parameters are specified in parentheses, for example, integer or real variables.

The function can be divided into two types. The first function that returns nothing and the second type that returns something. If the function returns nothing, it is declared a void data type, which means "emptiness" from the English translation of the void setup function that you already know() and void loop(). Functions that return values are declared by the data type int, float, byte, long, etc. The keyword of the returned function is return.

Here are some examples related to creating your own functions. In the first case, consider a function that returns nothing, i.e. the void data type

Надпись: void setup(){ Serial.begin(9600);
}
void loop(){ myFunction(); delay(200);
}
void myFunction(){ Serial.println("Tamura");
}

This function, presented in Listing 6.1, is performed as follows. A new function is being created with the data type and name void myFunction(). In the body of the function, we write the command to output the message Serial.println("Tamura"). In order to output messages through the monitor port, we must refer to this function, which is located in another function. In our case, this is void loop(). By writing the myFunction() function, we automatically display the message on the monitor screen.

In the second case, consider a function that returns some value from one created function to another (listing 6.2).

 

Листинг 6.2. Функция, которая возвращает значение

void setup(){ Serial.begin(9600);

}

void loop(){ int c;

c = Sum(5,10);

Serial.println(c); delay(200);

}

int Sum(int a, int b){ Надпись: int result; result = a + b;
return(result); // возвращаемый результат
}


This program code works as follows. A new function is created with the name Sum and the parameters of the integer variables int Sum(int a,int b). Next, the formula for adding two variables result=a+b is set under this function. In the void loop() function, values 5 and 10 are assigned to these variables, then the Sum() function is sent to the body to add the result a+b. After adding two variables to the value 15, the return operator returns void loop() with assignment of a new variable int c and outputs the value to the monitor Serial.println(c)..

 

6.1. Piezoelectric element. Ton function(pin, frequency, duration)

A piezoelectric element is an electromechanical transducer, one of the varieties of which is a piezoelectric sound emitter, which is also called a piezoelectric speaker, simply a bell. A piezodynamic converts an electrical voltage into a membrane oscillation. These vibrations create the sound. The general view of the piezoelectric element is shown in Figure 6.1.

 

 1

Fig.6.1. Piezoelectric element general view

 

Now let's start writing the program code. To generate sounds on an Arduino using a piezoelectric element, we will use the to(pin, frequency, duration) function. Let's consider its essence and apply it in an experiment.

The syntax of the ton(in, frequency, duration) function is used to get a certain sound signal emitting from a piezoelectric element. In this function, the pin value means the number of the digital port according to the numbering of the Arduino, on which the signal will be played. Frequency is the frequency of the output sound expressed in hertz

 

(Hz). If we want to specify the duration of the signal playback, then we can additionally run the duration command. Duration is the duration of the signal playback, expressed in milliseconds. Here is an example of connecting a piezoelectric element (Fig.6.2).

 1

Fig. 6.2. Piezoelectric element connection

Листинг 6.3. Пьезоэлемент

int pin = 8; void setup() {

pinMode(pin, OUTPUT);

}

void loop() {

tone (pin, 500); //включаем на 500 Гц delay(1000);

tone(pin, 1000); //включаем на 1000 Гц delay(1000);

}

The program code with the connection of the piezoelectric element to the Arduino board is shown in Figure 6.3. The program works as follows. At the beginning, one variable is declared connected to the digital pin 8. In the void setup function() we establish contact with the exit mode. In the void loop() function, we perform an action with a sound output with a frequency of 500 Hz, seconds later we set the change of the second sound with a purity of 1000 Hz.

6.1. Temperature sensor. Technical Specifications of TMP36

The temperature sensor is one of the useful devices that is often used in modern automatic control and monitoring devices. Even your computer has several temperature sensors at once, with which the system monitors the overheating of key components – the processor, video card, power supply, and other nodes. The most popular example of using a home temperature sensor is a thermostat. This is a device that constantly monitors the air temperature and regulates the supply of energy to the heating system. An adjacent example is a boiler for heating water.

 3

Figure 6.3. General view of the temperature sensor

 

Arduino uses various temperature sensors, such as TMP35, TMP37, LM35, LM335, etc. All of them differ in temperature measurement ranges, errors, current consumption, dimensions, etc. The operating range of such sensors varies from -40°C to +125°C. In our experiments, we will use the TMP36 sensor (Fig.6.3).

Here is an example of connecting and writing code for this sensor. The TMP36 brand temperature sensor has three legs: power supply, output voltage and grounding. We connect as follows, connect the left leg of the sensor to a 5V power source, connect the middle leg to the analog port A0 and connect the extreme right leg of the sensor to the GRD ground (Fig.6.4).

 

 1

 

Fig.6.4. Connection diagram of the temperature sensor

 

For the operation of temperature measurement by the sensor, we will write the code of the program presented in listing 6.4. The essence of the program is as follows. In the execution function, the voltages coming from the middle leg of the temperature sensor are read and converted into digital values from 0 to 1023 using an ADC. The converted values are assigned to the temp variable. Next, we convert from digital values to voltage according to the formula voltage =(tmp·5.0)/ 1024 and by multiplying by 1000 we convert to millivolts. Millivolts are declared with the variable name as milliVolt. Next, we convert from millivolts to degrees according to the formula (millivolt–500) / 10, followed by the output of a message through the monitor port.

 

 

Листинг 6.4. Вывод сообщения температуры через порт монитора

int tmp;

float voltage; // объявляем переменные типа float float milliVolt; // объявляем переменные типа float float tmpCel; // объявляем переменные типа float void setup(){

pinMode(A0,INPUT); Serial.begin(9600);

}

void loop(){

tmp = analogRead(A0); // считываем напряжение voltage = (tmp * 5.0)/1024; // переводим в напряжение milliVolt = voltage * 1000; // переводим в милливольт tmpCel = (milliVolt-500)/10; // переводим в градусы Serial.print("Celsius: ");

Serial.println(tmpCel); delay(50);

}

The result of measuring the temperature expressed in a unit of measurement in degrees is shown in Figure 6.2.

 

1 

Рис.6.2. Temperature message output


Эта лекция ещё не готова к использованию.
Сводка хранения данных
Скачать мобильное приложение
Яндекс.Метрика