Created
February 14, 2023 20:00
-
-
Save rahulbot/73cc9784f6e06c4018e3972679fb4acf to your computer and use it in GitHub Desktop.
Arduino data example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> // use a set of functions to control the servo | |
int potPosition; // keep track of the potentiometer's last value | |
int dataIndex; // keep track of the index of the data item we're showing | |
int servoPosition; // keep track of where the servo is | |
Servo myservo; // make a servo helper object | |
int SERVO_PIN = 3; // the phyiscal pin we'll attach the servo to | |
int data[] = {1,10,10,10,1,2,4,5,10,10,0}; // an array of made up data | |
// return the number of items in the array | |
int data_array_length() { | |
// number of buyes in the array / number of bytes in the first item | |
return sizeof(data) / sizeof(data[0]); | |
} | |
// figure out the biggest value in the array | |
int max_data_value() { | |
// start by comparing to first item in array | |
int maxVal = data[0]; | |
// now check each item in the array | |
for (int i = 0; i < data_array_length(); i++) { | |
// remember it if it it bigger than the current biggest value | |
maxVal = max(data[i], maxVal); | |
} | |
// return the biggest value | |
return maxVal; | |
} | |
// this is run once, when the board is reset | |
void setup() { | |
myservo.attach(SERVO_PIN); // attach the servo so we can send it commeands | |
} | |
// this is run over and over again forever | |
void loop() { | |
// first read the potiometer via the analog pin 0 - returns a value between 0 and 1023 based on the voltage | |
potPosition = analogRead(A0); | |
// translate the potiometer to a data index (between 0 and the length of the data array) | |
dataIndex = map(potPosition, 0, 1023, 0, data_array_length()); | |
// translate the data at the selected index into an array position | |
servoPosition = map(data[dataIndex], 0, max_data_value(), 20, 160); | |
// move the potiometer to the new position | |
myservo.write(servoPosition); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment