[Diao Ye learns programming] Mathematical operations sqrt() in Arduino manual

insert image description here
insert image description here
What is an Arduino?
Arduino is an open source electronic prototyping platform that allows you to create a variety of creative projects with simple hardware and software. Whether you're a beginner or an expert, Arduino offers you endless possibilities. You can use Arduino to control sensors, lights, motors, robots, IoT devices, etc., as long as you can think of it, Arduino can help you achieve it.

If you want to learn more about Arduino, you can visit the official website of Arduino, where there are rich resources and tutorials for your reference. You can also join the Arduino community and exchange ideas and experiences with enthusiasts, students, designers and engineers from all over the world. In addition, you can also use Arduino's online programming tool to write code in the cloud and upload it to your development board.

Arduino is a constantly evolving and innovative platform with a wide range of applications and potential. I hope this manual can stimulate your interest and enthusiasm for Arduino, and let you enjoy the creativity and fun brought by Arduino

insert image description here

Wikipedia's definition
Arduino is an open source embedded hardware platform for users to make interactive embedded projects. In addition, Arduino, as an open source hardware and open source software company, has both projects and user communities. The company designs and manufactures Arduino boards and related accessories. These products are distributed under open source hardware and software licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL). Arduino allows anyone to build Arduino boards and distribute software. Arduino boards are sold commercially pre-assembled or purchased as DIY kits.

Introduced in 2005, the Arduino was designed as a student at the Ivrea Institute for Interactive Design in the Ivrea region of Italy, with the aim of providing novices and professionals with a low-cost and easy way to build interactive devices using sensors to interact with the environment. installation. Beginners and hobbyists can use Arduino to create devices such as sensors, simple robots, thermostats, and motion detectors.

The name Arduino comes from a bar in Ivrea, Italy, where some of the project's founders used to hang out. The bar is named after Arduin of Ivrea, count of the frontiers of Ivrea and king of Italy from 1002 to 1014.

insert image description here

Seventeen, Arduino mathematical operation sqrt()
sqrt() is a mathematical operation function in Arduino, which is used to calculate the square root of a number. It takes one parameter: the number whose square root is to be calculated, and returns the result of the calculation. Its scope of application:
1) Calculate some mathematical formulas or algorithms, such as Pythagorean theorem, quadratic equation, Newton's method, etc.
2) Realize some physical simulation or control, such as speed, acceleration, distance, angle, etc.
3) Realize some special effects, such as volume adjustment, LED light breathing light, etc.

Application scenarios:
1) Geometric calculation: The sqrt() function is often used in geometric calculation, such as calculating the length of the hypotenuse of a triangle, the radius of a circle or the radius of a ball, etc. By calculating the square root, dimensional information related to the geometric shape can be obtained.
2) Physical calculation: In physics, many formulas involve the calculation of square roots, such as velocity, acceleration, force, etc. Use the sqrt() function to easily calculate the values ​​of these physical quantities for physical experiments or simulations.
3) Data processing and analysis: In data processing and analysis, it may be necessary to perform square root operations on the data for normalization, smoothing, or other operations. The sqrt() function can be used to process data to meet specific data processing requirements.

When using the sqrt() function, you need to pay attention to the following:
1) The sqrt() function can accept integers or floating-point numbers as parameters, but the returned result type is the same as the parameter type. If the result is to be assigned to a variable of a different type, type conversion is required.
2) The sqrt() function can only accept one parameter, which is the value to be squared. If you want to calculate the square root of multiple values, you need to call the sqrt() function separately or use the multiplication operator.
3) The sqrt() function uses floating-point arithmetic, so rounding errors or overflows may occur. If more precise or larger-scale calculations are required, other libraries or methods can be used.
4) The parameters of the sqrt() function can be integer types (such as int, long, etc.) or floating point types (such as float, double, etc.). However, it should be noted that if the parameter is an integer type, the result may be truncated to an integer, resulting in a loss of precision. If you need to maintain floating-point precision, it is recommended to use floating-point types as parameters.
5) The parameter must be greater than or equal to zero. If the argument is negative, the function will return NaN (Not a Number).
6) When using the sqrt() function, you need to pay attention to the numerical range and precision issues. Make sure that the values ​​used are within the valid range of the function, and take care to avoid negative arguments and loss of precision.

The following are three practical application cases of Arduino mathematical operation sqrt():
Case 1: Measuring distance with ultrasonic sensor and LCD display. Ultrasonic sensors can transmit and receive sound waves, and calculate the distance based on the time difference of the sound waves. Use the sqrt() function to calculate the speed of the sound wave, taking into account the effect of temperature.

// 引入LiquidCrystal库
#include <LiquidCrystal.h>
// 定义超声波传感器和LCD显示屏的引脚
#define TRIG_PIN 2
#define ECHO_PIN 3
#define RS_PIN 7
#define EN_PIN 8
#define D4_PIN 9
#define D5_PIN 10
#define D6_PIN 11
#define D7_PIN 12
// 创建LiquidCrystal对象,指定引脚顺序
LiquidCrystal lcd(RS_PIN, EN_PIN, D4_PIN, D5_PIN, D6_PIN, D7_PIN);
// 定义温度传感器的引脚和初始温度,单位为摄氏度
#define TEMP_PIN A0
#define INIT_TEMP 20.0

void setup() {
    
    
  // 初始化串口通信,设置波特率为9600
  Serial.begin(9600);
  // 设置超声波传感器的引脚模式
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  // 初始化LCD显示屏,设置列数为16,行数为2,并清屏
  lcd.begin(16,2);
  lcd.clear();
}

void loop() {
    
    
  // 读取温度传感器的模拟值,并将其转换为摄氏度
  int temp_value = analogRead(TEMP_PIN);
  float temp = temp_value * (5.0 / 1023.0) * 100.0;
  
   // 使用sqrt()函数计算声波在当前温度下的速度,单位为厘米每微秒
   // 声波速度与温度成正比,公式为v = sqrt(1.4 * R * T)
   // 其中v是声波速度,R是空气的气体常数(29 J/(mol*K)),T是绝对温度(K)
   // 将单位换算后得到v = sqrt(0.000401 * T),T = temp + 273.15
   float speed = sqrt(0.000401 * (temp + 273.15));
   
   // 让超声波传感器发射10微秒的脉冲信号
   digitalWrite(TRIG_PIN, LOW);
   delayMicroseconds(2);
   digitalWrite(TRIG_PIN, HIGH);
   delayMicroseconds(10);
   digitalWrite(TRIG_PIN, LOW);
   
   // 计算超声波传感器接收到回响信号的时间差,单位为微秒
   long duration = pulseIn(ECHO_PIN, HIGH);
   
   // 根据声波的速度和时间差,计算距离,单位为厘米
   // 距离等于声波的速度乘以时间差除以2,因为声波是往返的
   float distance = speed * duration / 2.0;
   
   // 在LCD显示屏上显示当前的温度和距离,保留一位小数
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Temp: ");
   lcd.print(temp,1);
   lcd.print(" C");
   
   lcd.setCursor(0,1);
   lcd.print("Dist: ");
   lcd.print(distance,1);
   lcd.print(" cm");
}

Case 2: Use gyroscope and steering gear to realize the function of balancing the car. When the car is tilted, the steering gear turns the opposite angle to restore the balance of the car. Use the sqrt() function to calculate the tilt angle of the cart.

// 引入Wire库和Servo库
#include <Wire.h>
#include <Servo.h>
// 定义陀螺仪的地址
#define GYRO_ADDR 0x68
// 创建舵机对象
Servo servo;
// 定义舵机的引脚和初始角度
#define SERVO_PIN 9
#define INIT_ANGLE 90

void setup() {
    
    
  // 初始化串口通信,设置波特率为9600
  Serial.begin(9600);
  // 初始化I2C通信,加入I2C总线
  Wire.begin();
  // 向陀螺仪发送指令,激活陀螺仪
  Wire.beginTransmission(GYRO_ADDR);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  // 将舵机连接到第9号引脚,并转动到初始角度
  servo.attach(SERVO_PIN);
  servo.write(INIT_ANGLE);
}

void loop() {
    
    
   // 向陀螺仪发送指令,请求读取数据
   Wire.beginTransmission(GYRO_ADDR);
   Wire.write(0x3B);
   Wire.endTransmission(false);
   // 接收陀螺仪返回的数据,共14个字节
   Wire.requestFrom(GYRO_ADDR,14,true); 
   int acc_x = Wire.read()<<8|Wire.read(); 
   int acc_y = Wire.read()<<8|Wire.read(); 
   int acc_z = Wire.read()<<8|Wire.read(); 
   int temp = Wire.read()<<8|Wire.read(); 
   int gyro_x = Wire.read()<<8|Wire.read(); 
   int gyro_y = Wire.read()<<8|Wire.read(); 
   int gyro_z = Wire.read()<<8|Wire.read(); 
  
   // 计算X轴方向上的倾斜角度,单位为度,范围为-90到90
   // 使用sqrt()函数计算分母中的平方根项
   float angle_x = atan2(acc_x, sqrt(acc_y * acc_y + acc_z * acc_z)) * RAD_TO_DEG;
   
   // 根据倾斜角度计算舵机的目标角度,使其与倾斜角度相反,实现平衡效果
   int target_angle = INIT_ANGLE - angle_x;
   
   // 使用constrain()函数限制舵机的角度在0到180度之间
   target_angle = constrain(target_angle,0,180);
   
   // 将舵机转动到目标角度
   servo.write(target_angle);
}

Case 3: Use the gyroscope and LCD display to display the current tilt angle

// 引入Wire库和LiquidCrystal库
#include <Wire.h>
#include <LiquidCrystal.h>
// 定义陀螺仪的地址
#define GYRO_ADDR 0x68
// 定义LCD显示屏的引脚
#define RS_PIN 7
#define EN_PIN 8
#define D4_PIN 9
#define D5_PIN 10
#define D6_PIN 11
#define D7_PIN 12
// 创建LiquidCrystal对象,指定引脚顺序
LiquidCrystal lcd(RS_PIN, EN_PIN, D4_PIN, D5_PIN, D6_PIN, D7_PIN);

void setup() {
    
    
  // 初始化串口通信,设置波特率为9600
  Serial.begin(9600);
  // 初始化I2C通信,加入I2C总线
  Wire.begin();
  // 向陀螺仪发送指令,激活陀螺仪
  Wire.beginTransmission(GYRO_ADDR);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  // 初始化LCD显示屏,设置列数为16,行数为2,并清屏
  lcd.begin(16,2);
  lcd.clear();
}

void loop() {
    
    
   // 向陀螺仪发送指令,请求读取数据
   Wire.beginTransmission(GYRO_ADDR);
   Wire.write(0x3B);
   Wire.endTransmission(false);
   // 接收陀螺仪返回的数据,共14个字节
   Wire.requestFrom(GYRO_ADDR,14,true); 
   int acc_x = Wire.read()<<8|Wire.read(); 
   int acc_y = Wire.read()<<8|Wire.read(); 
   int acc_z = Wire.read()<<8|Wire.read(); 
   int temp = Wire.read()<<8|Wire.read(); 
   int gyro_x = Wire.read()<<8|Wire.read(); 
   int gyro_y = Wire.read()<<8|Wire.read(); 
   int gyro_z = Wire.read()<<8|Wire.read(); 
  
   // 计算X轴和Y轴方向上的倾斜角度,单位为度,范围为-90到90
   // 使用sqrt()函数计算分母中的平方根项
   float angle_x = atan2(acc_x, sqrt(acc_y * acc_y + acc_z * acc_z)) * RAD_TO_DEG;
   float angle_y = atan2(acc_y, sqrt(acc_x * acc_x + acc_z * acc_z)) * RAD_TO_DEG;
   
   // 使用map()函数将倾斜角度映射到LCD显示屏的字符位置上,范围为0到15
   int x_pos = map(angle_x, -90, 90, 0, 15);
   int y_pos = map(angle_y, -90, 90, 0, 15);
   
   // 在LCD显示屏上显示当前的倾斜角度,保留一位小数,并在对应的位置上显示一个点表示倾斜方向
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Angle X: ");
   lcd.print(angle_x,1);
   
   lcd.setCursor(0,1);
   lcd.print("Angle Y: ");
   lcd.print(angle_y,1);
   
   lcd.setCursor(x_pos,y_pos);
   lcd.print(".");
}

Case 4: Geometric calculation:

float sideA = 3.0; // 三角形的一条边长
float sideB = 4.0; // 三角形的另一条边长

float hypotenuse = sqrt(pow(sideA, 2) + pow(sideB, 2)); // 计算三角形的斜边长度

Serial.print("Hypotenuse length: ");
Serial.println(hypotenuse);

In this case, the sqrt() function is used to calculate the length of the hypotenuse of a triangle formed by two right-angled sides. First use the pow() function to calculate the sum of the squares of two right-angled sides, and then pass the result to the sqrt() function for square root calculation. Finally, the calculation results are output to the serial monitor for display or subsequent processing.

Case 5: Physical calculation:

float velocity = 10.0; // 物体的速度

float kineticEnergy = 0.5 * pow(velocity, 2); // 计算物体的动能

float mass = 2.0; // 物体的质量

float momentum = mass * sqrt(2 * kineticEnergy); // 计算物体的动量

Serial.print("Momentum: ");
Serial.println(momentum);

In this case, the momentum of the object is calculated using the sqrt() function. First calculate the kinetic energy of the object using the pow() function, and then calculate the momentum of the object based on the kinetic energy and mass. Finally, the calculation results are output to the serial monitor for display or subsequent processing.

Case 6: Data processing and analysis:

float dataValue = 25.0; // 数据值

float normalizedValue = sqrt(dataValue); // 对数据值进行平方根运算(数据归一化)

// 使用归一化后的数据值进行后续的处理或分析
// ...

In this case, the data is normalized using the sqrt() function. By taking the square root of the data, the data values ​​can be normalized to meet specific data processing needs. The normalized data values ​​can then be used for subsequent processing or analysis, such as comparison, calculation or output.

Case 7: Calculate the length of the hypotenuse of a right triangle:

float a = 3.0; // 直角三角形的一条边长
float b = 4.0; // 直角三角形的另一条边长
float c = sqrt(pow(a, 2) + pow(b, 2)); // 计算直角三角形的斜边长度

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

void loop() {
    
    
  Serial.print("直角三角形的斜边长度:");
  Serial.println(c);
  delay(1000);
}

In this example, we use the sqrt() function to calculate the length of the hypotenuse of a right triangle. By applying the Pythagorean theorem, calculate and extract the sum of the squares of the base and height of the square.

Case 8: Calculate the time for an object to fall freely:

float height = 10.0; // 物体的下落高度(单位:米)
float gravity = 9.8; // 重力加速度(单位:米/秒^2)
float time = sqrt(2 * height / gravity); // 计算物体自由落体的时间

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

void loop() {
    
    
  Serial.print("物体自由落体的时间:");
  Serial.println(time);
  delay(1000);
}

In this example, we use the sqrt() function to calculate the time for an object to fall freely. By applying the formula for the motion of a free-falling body, calculate and take the root of the product of the relationship between the squared height and the acceleration due to gravity.

Case 9: Calculate the frequency in spectrum analysis:

float period = 0.01; // 信号的周期(单位:秒)
float frequency = 1 / period; // 计算信号的频率

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

void loop() {
    
    
  Serial.print("信号的频率:");
  Serial.println(frequency);
  delay(1000);
}

In this example, we use the sqrt() function to calculate the frequency of a signal. Computes and squares the reciprocal of the period by applying the reciprocal relationship between frequency and period.

insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132649974