T
T
Tururupark2021-04-24 05:38:07
Arduino
Tururupark, 2021-04-24 05:38:07

How to compare a variable with an array element?

The Arduino uses an analog input to measure voltage. The resulting value must be compared with the table value (100 rows) and, based on the comparison, the corresponding value should be assigned to another variable. So far I know this way of comparison:

float value = (float)analogReag(A1)*5*1000/1024;
int value_int = (int)value_int;
switch(value_int) {
case(4442): 
current = 120;
...

But something tells me that this method is too long. You can represent the table as a two-dimensional array, but I don’t know what to do next. How to make the measured voltage compared with the table quickly? (without finding dependencies in the table and writing formulas)
int [] [] ={
 {120, 4442}
{121, 4222}
...}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Zaitsev, 2021-04-24
@Tururupark

You provided a code snippet

float value = (float)analogReag(A1)*5*1000/1024;
int value_int = (int)value_int;
switch(value_int) {
case(4442):
current = 120;

Is there an error on the second line? Should be int value_int = (int)value;?
If so, why should the int value of analogReag be converted to float, and then back to int? This will not increase the bit depth, so you can do this:
//Объявли массив table из 1024 значений
//Для каждого значения ввели правильный ответ
int table[] = {12, 34, 64, 33, ..., 954}

//Где-то в коде
int value = analogReag(A1);
current = table[value];

This will reduce your table by half, the selection will be as fast as possible. The payback will be some non-obviousness of filling the table, because. you will have to operate not with the voltage value, but with the ADC readings.

A
Alexander Skusnov, 2021-04-24
@AlexSku

Binary search tree or hash table.
Although 100 pairs is about nothing. Did you time it? Here somewhere from 100 thousand you can already worry.
By the way, you are throwing away the formula in vain. Perhaps cubic splines could help you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question