NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Receiving the Temp Sensor Input via Serial

February 23, 2011
by Twarter369
Twarter369's Avatar

Hello all. I am having trouble getting a piece of code to work. In essence, what I want to do is have the MCU send the raw ADC data back to my c++ via the serial conn. The flow of the program goes like this: A user clicks a button, the program sends a "3" along the serial port, the MCU interprets this as the command to take the temp and send it back along the serial. The c++ program starts listening on the serial port for communication and waits to update the temp label with the incoming data.

Does anyone have a c++/MCU example of this direction of communication? I was going to pick apart the digital scale code to see how it is handled in that project. Are there any others you guys can recommend?

February 23, 2011
by 6ofhalfdozen
6ofhalfdozen's Avatar

Twarter,

While not exactly the same thing, I did something similar in my VB controling LEDs test. I believe my VB code is shown in that post and there are references to a post by Nerdful on the mcu parts. Search for VB posts in the forum and it should come up. i know C++ is not VB, but you should be able to pick apart my code and translate into C++ pretty easily. The mcu side is the mcu side, and you would need to change the "turning on LED" into firing the ADC and returning the data similar to what the NK does for the temp sensor project. That should give you a rough idea of where to go.

February 23, 2011
by Noter
Noter's Avatar

Visual C++ 6.0 example ...

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <ctype.h>
#include <tchar.h>
#include <malloc.h>
#include "httoi.h"
#include "commPort.h"
#include "iHexFile.h"
char chrIn;
int main(int argc, char* argv[])
{
    if(argc<cmdArgStart){
        printf("required args: 1) port, 2) baud ");
        return 1;
    }
    if(OpenCommPort(argv[1], argv[2])){
        CloseCommPort();
        return 1;
    }
    if(SetCommTimeout(1000)){
        CloseCommPort();
        return 1;
    }
    if(PutCommChar('g'){
        CloseCommPort();
        return 1;
    }
    if(GetCommChar(&chrIn)){
        CloseCommPort();
        return 1;
    }
    printf("comm input = %02x\n", chrIn);
    CloseCommPort();
    return 0;
February 23, 2011
by Noter
Noter's Avatar

Oops - this is probably the important piece ... comport.h

DCB dcb;
HANDLE hCom;
COMMTIMEOUTS cTimeout;
BOOL fSuccess;
TCHAR *pcCommPort = TEXT("COM1"); //  Most systems have a COM1 port

void PrintCommState(DCB dcb, char *port){
    //  Print some of the DCB structure values
    printf("\nPort = %s, BaudRate = %d, ByteSize = %d, Parity = %d, StopBits = %d\n", 
        port,
        dcb.BaudRate, 
        dcb.ByteSize, 
        dcb.Parity,
        dcb.StopBits
        );
}

int OpenCommPort(char *port, char *baud){
  //  Open a handle to the specified com port.
   hCom = CreateFile((LPCTSTR) port,
                    GENERIC_READ | GENERIC_WRITE,
                    0,    //  must be opened with exclusive-access
                    NULL, //  default security attributes
                    OPEN_EXISTING, //  must use OPEN_EXISTING
                    0,    //  not overlapped I/O
                    NULL  //  hTemplate must be NULL for comm devices
                    );

   if (hCom == INVALID_HANDLE_VALUE) 
   {
       //  Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   //  Initialize the DCB structure.
   ZeroMemory(&dcb, sizeof(DCB));
   dcb.DCBlength = sizeof(DCB);

   //  Build on the current configuration by first retrieving all current
   //  settings.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   //PrintCommState(dcb);       //  Output to console

   //  Fill in some DCB values and set the com state: 
   //  57,600 bps, 8 data bits, no parity, and 1 stop bit.
   dcb.BaudRate = atol(baud);     //  baud rate
   dcb.ByteSize = 8;             //  data size, xmit and rcv
   dcb.Parity   = NOPARITY;      //  parity bit
   dcb.StopBits = ONESTOPBIT;    //  stop bit

   dcb.fBinary=true;
   dcb.fNull=false;
   dcb.fTXContinueOnXoff=false;
   dcb.fRtsControl=RTS_CONTROL_DISABLE;
   dcb.fDsrSensitivity=false;
   dcb.fDtrControl=DTR_CONTROL_DISABLE;
   dcb.fOutX=false;
   dcb.fInX=false;
   dcb.fOutxCtsFlow=false;
   dcb.fOutxDsrFlow=false;

   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

   //  Get the comm config again.
   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess) 
   {
      //  Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   PrintCommState(dcb,port);       //  Output to console

   //printf ("Serial port %s successfully reconfigured.\n", port);

    return 0;
}

int SetCommTimeout(int timeout_ms){
    cTimeout.ReadIntervalTimeout = MAXDWORD;
    cTimeout.ReadTotalTimeoutConstant = timeout_ms;
    cTimeout.ReadTotalTimeoutMultiplier = MAXDWORD;
    cTimeout.WriteTotalTimeoutConstant = 0;
    cTimeout.WriteTotalTimeoutMultiplier = 0;
    fSuccess=SetCommTimeouts(hCom, &cTimeout);
    if (!fSuccess){
        printf ("SetCommTimeouts failed with error %d.\n", GetLastError());
        return (1);
    }
    return 0;
}

int CloseCommPort(){
    fSuccess=CloseHandle(hCom);
    if (!fSuccess){
        printf ("CloseHandle failed with error %d.\n", GetLastError());
        return (1);
    }
    return 0;
}

int PutCommChar(UCHAR chrOut){
    unsigned long bytesWritten;
    fSuccess=WriteFile(hCom,&chrOut,1,&bytesWritten,0);
    if (bytesWritten!=1){
        printf ("WriteFile wrote %d bytes.\n", bytesWritten);
        return (2);
    }
    if (!fSuccess){
        printf ("WriteFile failed with error %d.\n", GetLastError());
        return (1);
    }
    return 0;
}

int GetCommChar(UCHAR *chrIn){
    unsigned long bytesRead;
    fSuccess=ReadFile(hCom,chrIn,1,&bytesRead,0);
    if (!fSuccess){
        printf ("ReadFile failed with error %d.\n", GetLastError());
        return (1);
    }
    if (bytesRead!=1){
        printf ("timeout on read port %d\n",bytesRead);
        return (2);
    }
    return 0;
}
February 23, 2011
by Twarter369
Twarter369's Avatar

Wow, that is a lot to digest. Thanks guys. I believe I may have found what I was looking for in the docs.

Here is a sample of the setup for my com port

 SerialPort^ mySerialPort = gcnew SerialPort("COM1");

    mySerialPort->BaudRate = 9600;
    mySerialPort->Parity = Parity::None;
    mySerialPort->StopBits = StopBits::One;
    mySerialPort->DataBits = 8;
    mySerialPort->Handshake = Handshake::None;

    mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceviedHandler);

    mySerialPort->Open();

    Console::WriteLine("Press any key to continue...");
    Console::WriteLine();
    Console::ReadKey();
    mySerialPort->Close();

private:
    static void DataReceviedHandler(
                        Object^ sender,
                        SerialDataReceivedEventArgs^ e)
    {
        SerialPort^ sp = (SerialPort^)sender;
        String^ indata = sp->ReadExisting();
        Console::WriteLine("Data Received:");
        Console::Write(indata);
    }
};

I should be able to use the SerialDataRecieved Event Handler, which I would add directly before sending the "3"....I hope, like this.

I will report back with my results or any other questions that come up!

Post a Reply

Please log in to post a reply.

Did you know that you can input numbers in binary via a DIP switch, and output them to the LCD? Learn more...