如何在tinygo中映射两个值范围?

huangapple go评论88阅读模式
英文:

How to map two value ranges in tinygo

问题

我正在使用Golang编程语言和tinygo来编程Arduino Uno。我正在尝试映射两个值的范围。一个是范围在0-1000之间的编码器,另一个是范围在0-65535之间的tinygo ADC。我正在读取ADC范围的值,并需要将其转换为0-1000的范围(编码器)。

我尝试了几种方法,但基本问题是数据类型。例如,下面的公式结果为0:

var encoderValue uint16 = 35000
float := float64(1000/65535) * float(encoderValue)
英文:

I'm using Golang to program a arduino uno with tinygo. I am trying to map two value ranges.
One is an encoder with a range between 0-1000 and the other is tinygo's ADC range between 0-65535. I am reading the ADC range and need to covert it to the range of 0-1000 (encoder).

I have tried several things but the basic issue that I'm running into is data types. The below formula for example equals 0:

var encoderValue uint16 = 35000
float := float64(1000/65535) * float(encoderValue)

答案1

得分: 1

1000/65535 是一个整数除法,结果为 0。无论你将结果转换为 float64,它都会变成 0.0

使用浮点数常量:

var encoderValue uint16 = 35000
x := float64(1000.0/65535) * float64(encoderValue)
fmt.Println(x)

这将输出(在 Go Playground 上尝试):

534.0657663843748
英文:

1000/65535 is an integer division and will result in 0. It doesn't matter if you convert the result to float64, then it'll be 0.0.

Use floating point constant(s):

var encoderValue uint16 = 35000
x := float64(1000.0/65535) * float64(encoderValue)
fmt.Println(x)

This will output (try it on the Go Playground):

534.0657663843748

huangapple
  • 本文由 发表于 2021年11月6日 05:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/69859246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定