arduino实用数学函数之map()

本文深入探讨了数值范围映射的概念、原理及其在不同场景中的应用,包括如何使用map函数将数值从一个范围变换到另一个范围,同时强调了函数处理负数的能力和不产生分数的特点。详细介绍了参数意义、返回值以及示例代码,帮助读者理解并掌握这一基本而实用的数学技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map(value, fromLow, fromHigh, toLow, toHigh)
Description

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

把一个数从一个范围变换到另一个范围。


Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

不会把值强制限制在范围之内,因为超范围的值经常也是有用的。如果需要的范围做一限制。可以在这个函数之前或之后使用constrain() 函数。


Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers, for example

注意,两个范围中的“下界”要比“上界”大或下,这样map()可以用来反转一个范围,例如


y = map(x, 1, 50, 50, 1);


The function also handles negative numbers well, so that this example

函数也可以处理负数,例如


y = map(x, 1, 50, 50, -100);


is also valid and works well.

也有效和正确


The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.

map()函数使用整型,所以不会产生分数,分数将会被截去,并不是全面的或平均值(?)

Parameters 参数

value: the number to map

给map的值


fromLow: the lower bound of the value's current range

值现在的下界


fromHigh: the upper bound of the value's current range

值现在的上界


toLow: the lower bound of the value's target range

值目标范围的下界


toHigh: the upper bound of the value's target range

值目标范围的上界

Returns 返回值

The mapped value.

映射的值

Example


void setup() {}

void loop()
{
int val = analogRead(0); //读取0口的值
val = map(val, 0, 1023, 0, 255);//从0-1023映射到0-255
analogWrite(9, val);//把映射后的值写给9口
}

Appendix 附录

For the mathematically inclined, here's the whole function

对于数学上来说,这是整个函数

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}          

转载于:https://www.cnblogs.com/wzc4300741/p/5383810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值