In: Electrical Engineering
b. Copy the text below into your program. /*
* Purpose: Read a 0V-5V value from analog pin A1
* and convert it to a 10-bit (0-1023) number. */
void setup() {
Serial.begin(115200); //set serial comm to 115 kbps }
void loop()
{ int pot_val; //input - potentiometer value
// analogRead() converts 0V-5V to 0-1023 pot_val = analogRead(1);
//read from Analog pin 1 Serial.println(pot_val); //print to serial monitor }
c. Add the function delay() from lab0 to make the readings 1x per second.
d. Write code to display formatted output on the serial monitor as shown below:
Voltage Integer Binary HEX
0.406 83 1010011 53
0.415 85 1010101 55 ...
(ii) Write a formula for converting an integer value (0 to 1023) to an analog voltage, where 0V corresponds to integer 0 and 5V corresponds to integer 1023.
b) The analogRead(pin) function reads the value from the specified analog pin. It returns a 10-bit integer that maps input voltages between 0 and 5 volts to 0 and 1023. More information about the function can be found here: https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
The original program is:
/*
* Purpose: Read a 0V-5V value from analog pin A1
* and convert it to a 10-bit (0-1023) number.
*/
void setup() {
Serial.begin(115200); // set serial comm to 115 kBaud
}
void loop() {
int pot_val; // input - potentiometer value
// analogRead() converts 0V-5V to
0-1023
pot_val = analogRead(1); // read from Analog pin 1
Serial.println(pot_val); // print to
serial monitor
}
c) A delay can be realized by using the delay function. It accepts a single argument, the delay in miliseconds. The program with the added delay functionality:
/*
* Purpose: Read a 0V-5V value from analog pin A1
* and convert it to a 10-bit (0-1023) number.
*/
void setup() {
Serial.begin(115200); // set serial comm to 115 kBaud
}
void loop() {
int pot_val; // input - potentiometer value
// analogRead() converts 0V-5V to
0-1023
pot_val = analogRead(1); // read from Analog pin 1
Serial.println(pot_val); // print to serial monitor
delay(1000);
}
d) We can make use of the second argument of the Serial.print() function to specify the format of the output. More information about the function can be found here: https://www.arduino.cc/en/Serial/Print
/*
* Purpose: Read a 0V-5V value from analog pin A1
* and convert it to a 10-bit (0-1023) number.
*/
void setup() {
Serial.begin(115200); // set serial comm to 115 kBaud
Serial.println("Voltage Integer Binary HEX");
}
void loop() {
int pot_val; // input - potentiometer value
// analogRead() converts 0V-5V to
0-1023
pot_val = analogRead(1); // read from Analog pin 1
Serial.print(pot_val * 5.0 /
1023);
Serial.print("\t");
Serial.print(pot_val);
Serial.print("\t");
Serial.print(pot_val, BIN);
Serial.print("\t");
Serial.println(pot_val, HEX);
delay(1000);
}
(ii)
Please leave a positive rating if the answer is satisfactory or leave a comment if more explanation is needed.