英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论