Read through section 6.1 and complete the participation activities.
In this lecture you will:
AnalogIn
to read values from the analog pinsBy the end of this lecture you should be able to:
/*
* Copyright (c) 2017-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include <chrono>
// Initialize a pins to perform analog input and digital output functions
AnalogIn ain(A0);
DigitalOut dout(LED1);
Timer t1;
using namespace std::chrono;
int main(void)
{
while (1) {
// test the voltage on the initialized analog pin
// and if greater than 0.3 * VCC set the digital pin
// to a logic 1 otherwise a logic 0
if (ain > 0.3f) {
dout = 1;
} else {
dout = 0;
}
ain.set_reference_voltage(3.3);
t1.start();
// print the percentage and 16 bit normalized values
printf("percentage: %3.3f%%", ain.read() * 100.0f);
printf(" normalized: 0x%04X", ain.read_u16());
printf(" voltage: %3.3f\\n",ain.read_voltage());
t1.stop();
printf("The time taken was %llu milliseconds\\n", duration_cast<milliseconds>(t1.elapsed_time()).count());
t1.reset();
thread_sleep_for(1000);
}
}
/*
* Copyright (c) 2017-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include <chrono>
#include <cmath>
// Initialize a pins to perform analog input and digital output functions
AnalogIn ain(A0);
DigitalOut dout(LED1);
Timer t1;
using namespace std::chrono;
BufferedSerial pc(USBTX,USBRX);
char buff[6]; // largest value is 65535, new line
Ticker sample;
void sampleADC(){
unsigned short value = ain.read_u16();
buff[0] = value/10000 + 0x30;
value = value - (buff[0]-0x30)*10000;
buff[1] = value/1000 + 0x30;
value = value - (buff[1]-0x30)*1000;
buff[2] = value/100 + 0x30;
value = value - (buff[2]-0x30)*100;
buff[3] = value/10 + 0x30;
value = value - (buff[3]-0x30)*10;
buff[4] = value/1 + 0x30;
pc.write(&buff,6);
}
int main(void)
{
buff[5] = '\\n';
sample.attach(&sampleADC,100ms);
while (1) {
thread_sleep_for(100);
}
}
Read sections 7.1 – 7.5 (they are short and don’t have participation activities).