/**
@Author : Stéphane Paton
@Website : http://www.mangetamain.fr
@Ref : http://www.mangetamain.fr/decouvrez-les-attaques-par-canaux-auxiliaires-sur-cryptoprocesseurs.html
Code d'exemple de la libserial en C++ pour récupérer la valeur analogique d'un
port de sortie sur mon Arduino
*/
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <SerialStream.h>
void getVoltage();
inline double convertToDouble(std::string const& s);
int main(int argc,char** argv)
{
getVoltage();
return 0;
}
void getVoltage()
{
// Open the serial port.
float voltage;
using namespace LibSerial ;
SerialStream serial_port ;
serial_port.Open("/dev/ttyACM3");
if ( ! serial_port.good() )
{
std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] "
<< "Error: Could not open serial port."
<< std::endl ;
exit(1) ;
}
// Set the baud rate of the serial port.
serial_port.SetBaudRate( SerialStreamBuf::BAUD_9600 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the baud rate." << std::endl ;
exit(1) ;
}
// Set the number of data bits.
serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the character size." << std::endl ;
exit(1) ;
}
// Disable parity.
serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not disable the parity." << std::endl ;
exit(1) ;
}
// Set the number of stop bits.
serial_port.SetNumOfStopBits( 1 ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not set the number of stop bits."
<< std::endl ;
exit(1) ;
}
// Turn on hardware flow control.
serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_HARD ) ;
if ( ! serial_port.good() )
{
std::cerr << "Error: Could not use hardware flow control."
<< std::endl ;
exit(1) ;
}
// Lecture
std::string buffer;
char next_byte;
while ( true )
{
// Tant qu'on ne reçoit pas un "\n" sur le port série,
// on concatène le buffer
serial_port.get(next_byte);
if(next_byte != '\n') buffer = buffer+next_byte;
else
{
// Quand on a reçu le \n de fin de ligne, on affiche le buffer
// transformé en float (la tension) et on le vide
voltage = convertToDouble(buffer);
std::cout<<voltage<<std::endl;
buffer.clear();
}
}
}
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline double convertToDouble(std::string const& s)
{
std::istringstream i(s);
double x;
if (!(i >> x))
throw BadConversion("convertToDouble(\"" + s + "\")");
return x;
}