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 » Tempsensor Project

January 14, 2011
by tomroth
tomroth's Avatar

I've had the tempsensor project sitting on my desk and running off of the usb port for about a week now. Works great. I was looking at the code and the last line says it is for writing a message to the serial port. Is that to display the temperature on the PC? If so, do I need to write my own app or has someone already written one, and if so, where can I get it from? If no app has been written, any suggestions on going about doing it?

Thanks!

Tom

January 14, 2011
by tsaavik
tsaavik's Avatar

Start a terminal program (Hyperterminal, Putty, Realterm, etc) and point it at your Nerdkit's emulated comport. If you see gobbledygook, make sure to set the baud rate to 115200 (8N1) and you should see the temperature output scrolling by like crazy.

January 14, 2011
by tomroth
tomroth's Avatar

Thanks! Works great.

January 14, 2011
by Ralphxyz
Ralphxyz's Avatar

And then you can take some of the Python code from Tutorials and graph the output.

I think it was the Scale (strain gage) project that output a graph on the pc.

Of course you would need to install Python and start to learn it's syntax.

Ralph

January 14, 2011
by tomroth
tomroth's Avatar

I just wrote a Visual Basic 2008 program that grabs the information and displays it in a windows form. Super simple and short. If anybody is interested I can give you the code.

Tom

January 14, 2011
by Rick_S
Rick_S's Avatar

I'd love the code, will it run in vb express 2010? I've been curious of how to use the serial port in VB. I haven't messed with VB for decades and It's totally foreign to me now.

Rick

January 14, 2011
by Rick_S
Rick_S's Avatar

I'd love the code, will it run in vb express 2010? I've been curious of how to use the serial port in VB. I haven't messed with VB for decades and It's totally foreign to me now.

Rick

January 14, 2011
by Rick_S
Rick_S's Avatar

Sorry for the double post,... not exactly sure how that happened :D

January 14, 2011
by tomroth
tomroth's Avatar

It should run just fine on 2010. It may do a conversion to 2010, but there should be no problem. A couple of notes: 1) Build a form with a lable named Display_Temp and add a timer named tmrDelay. 2) I manually entered my com port number instead of discovering it. Just change the code to match your com port number. 3) I commented out the line with lblParse in it. I am playing with parsing the number out of the string and converting it to a number type variable for another project I am working on. 4) Let me know if you have any other questions or issues!

Tom

Imports System.IO.Ports

Public Class Temperature

    Dim x As Integer = 0
    Dim Value As String = ""
    Public s As New SerialPort

    Private Sub Temperature_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        tmrDelay.Interval = 1000
        tmrDelay.Start()

    End Sub

    Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click

        s.Close()
        Me.Close()

    End Sub

    Private Sub Init_Serial()

        Display_Temperature()
        Return

    End Sub
    Private Sub Display_Temperature()

        s.PortName = "COM5"
        s.Open()
        s.BaudRate = 115200
        s.DataBits = 8
        s.StopBits = 1
        s.Parity = Parity.None
        Display_Temp.Text = s.ReadLine
        Value = s.ReadLine
        'lblParse.Text = Value.Length

    End Sub

    Private Sub tmrDelay_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrDelay.Tick

        Display_Temperature()
        s.Close()

    End Sub
End Class
January 15, 2011
by Rick_S
Rick_S's Avatar

It worked well. I had to add a button named btnEnd, to the form and name the form Temperature. Then after that, it fired right up and was displaying the temperature.

Thanks for the code, I appreciate it.

Rick

January 15, 2011
by tomroth
tomroth's Avatar

Yeah, I thought about that button this morning. Sorry about that.

Tom

January 15, 2011
by SirHobbes3
SirHobbes3's Avatar

I'm doing the tempsensor project and i need some help.

Log: From Windows Command Prompt on Saturday, January 15, 2011 at 4:25pm

This is what shows up: C:Users*your username here*DownloadsCode-Nerkits UsbCodetempsensor_edu>

Then i type in: C:Users*your username here*DownloadsCode-Nerkits UsbCodetempsensor_edu>make

Then i recieve this: C:Users*your username here*DownloadsCode-Nerkits UsbCodetempsensor_edu>make avrdude -c avr109 -p m168 -b 115200 -P /dev/ttyUSB0 -U flash:w:tempsensor.hex:a avrdude: ser_open<>:can't open device "dev/ttyUSB0":The system cannot find the path specified.

Then... make: *** [tempsensor-upload] Error 1

This is on the tempsensor project and it DOES NOT say to change the path from USB0 to COM#. But i tried that to no avail. Could someone give me some insight into this problem?

Would be helpful

SirHobbes3

January 15, 2011
by tomroth
tomroth's Avatar

You need to get rid of "dev/ttyUSB0" totally and replace it with COM#. Don't just change the USB0 part, the entire thing in quotes goes away.

Tom

January 15, 2011
by Rick_S
Rick_S's Avatar

Try the tempsensor folder instead of the tempsensor_edu folder. The files in that folder are for the adventurous to fill in a lot of blank spaces in the code and as such are incomplete.

If you have built the tempsensor circuit as shown in the guide, go to the tempsensor folder, edit your makefile as needed, and you should be able to program. Also, when you change the makefile in windows, you need to replace the dev/ttyUSB0 with comX where X is the number of the port windows assigned your USB/Serial cable.

So your line would go from:

AVRDUDEFLAGS=-c avr109 -p m168 -b 115200 -P /dev/ttyUSB0

To:

AVRDUDEFLAGS=-c avr109 -p m168 -b 115200 -P com2

(if your cable was at com2)

Rick

January 15, 2011
by Rick_S
Rick_S's Avatar

One last note, you have to change the makefile in all your projects to reflect where the USB/Serial cable is located on your computer. The /dev/ttyUSB0 is for Linux/Mac systems and won't work with Windows.

Rick

January 15, 2011
by SirHobbes3
SirHobbes3's Avatar

Ok guys, thanks a lot!!!! I'll try this. I'll post back really soon.

January 15, 2011
by SirHobbes3
SirHobbes3's Avatar

!!!! It works!! Thanks guys!

January 15, 2011
by Rick_S
Rick_S's Avatar

No problem glad to be of help.

January 16, 2011
by tomroth
tomroth's Avatar

My app has been running continuously on my desktop for over a day now and it's great. I had to add a "Try-Catch" and insert the "Display_Temp.Text = s.ReadLine" statement in it. Seems the data would get lost every now and then and would then throw an error. This gets rid of that. Anyway, my new question is I want to stop using the Nerdkit USB to Serial adaptor and just use a regular serial cable. This will give me the ability to program the DTR pin to use as a reset output. The green wire on the Nerdkit cable on pin 3 of the MCU sends the data. I don't even have the yellow attached. I assumed that the green wire would be equivalent to pin 3 on a serial cable, which is the receive pin. So I cut a serial cable, found pins 3 and 5(GND) and attached them to the MCU. No Data. Any ideas as to why and how to fix it?

Thanks!

Tom

January 16, 2011
by Rick_S
Rick_S's Avatar

The serial output from the microcontroller is TTL level and inverted and must go through at minimum an inverter and something to drop the higher (up to 12v) voltages down to 5V.

There are several methods to do this, Maxim makes several RS232 to TTL ic's such as the MAX232 series. You can purchase pre-made boards on ebay for not a lot of money.

The inversion can be done with simple transistors as well. Simple circuits to do this can be found on the web. For instance the Arduino serial single sided board uses the transistor method. Here is a link to it's schematic. You can see the serial connection in the lower left side of the schematic as well as your DTR reset.

January 16, 2011
by tomroth
tomroth's Avatar

I took microprocessors two semesters ago and learned all about the MAX232. Now I'm staring a use for it right in the face and didn't realize it! I have some MAX232's so I'll connect the MCU to it and see if I can get it working. Thanks!

Tom

January 17, 2011
by Jalex
Jalex's Avatar

Hi tomroth Yea, I had that Com# problem in the make file as well.

January 17, 2011
by Jalex
Jalex's Avatar

Hi Tom I see you like Visual Basic too. I like your ptogram there. I use it for games and graphics and never did too much with the com ports But I like it a lot. What is the deal with VB10, is it released yet? I still use VB6. Jim

January 18, 2011
by tomroth
tomroth's Avatar

OK, I give up. I added the MAX232 to my ciruit, changed the COM port in my VB.net program and nothing. If I step through the program and hover over my s.readline variable, I get a value, but not the value currently displayed on the LED output. The nerdkit usb to serial works fine for this. So, I opened TeraTerm and, keeping both COM's connected, looked at the output. Both work perfecly. If I hold my fingers on the tempsensor I get live updates of the temperature for both COM ports! What gives? Is there some difference in the VB.net program for using a MAX232? Shouldn't be. I assume the nerdkit version has one built into it. Any thoughts??? I really need to get my COM port (going through a usb to serial adaptor, I might add), to work. I need the DTR pin for use as a reset. I don't think the nerdkit version can give me that option, only 4 wires. Any help would be greatly appreciated!!!

Tom

January 19, 2011
by mrobbins
(NerdKits Staff)

mrobbins's Avatar

Hi Tom,

Just for "sanity check"... I've seen strange intermittent-appearing serial port issues happen when there wasn't a ground connection between PC and microcontroller circuit. When you switched over to your MAX232-based setup, did you include a ground connection between the PC serial port ground and the microcontroller circuit ground?

Mike

January 19, 2011
by tomroth
tomroth's Avatar

I have pin 5 from my home made serial connector connected to the blue negative rail. I am powering the setup from the usb nerdkit, but have used the 9v battery as well. I just don't get what is happening. Why will they both work in TeraTerm, and only the nerdkit in vb.net?

January 20, 2011
by mrobbins
(NerdKits Staff)

mrobbins's Avatar

Oh, I see -- I misunderstood your original description.

I haven't personally used VB.NET, but I can make guesses: 1) serial port flow control settings, 2) some sort of buffering going on, 3) line break differences. And I assume that TeraTerm is closed when you experiment with your VB.NET software so that they aren't both trying to access the same COM port?

January 21, 2011
by tomroth
tomroth's Avatar

I'm not sure what you mean by line break differences. I did change the flow to hardware and Xon/Xoff with no change. The port should be set to 115200 baud, 8 data bits, 1 stop bit, and no parity, correct?

February 05, 2011
by AndrewHI
AndrewHI's Avatar

need help with tempsensor code attached copy of my compile errors I think I have copied the tempsensor.c file correctly http://img84.imageshack.us/img84/4517/screenshotth.jpg

February 06, 2011
by Rick_S
Rick_S's Avatar

From the looks of things, you are in a non-standard folder. Mainly because it's showing you in a \Code\Atempsensor_edu folder. The standard folders are tempsensor and tempsensor_edu. I have to assume you wrote your own program, in which case you'd need to show us the code.

If you navigate to the \Code\tempsensor\ folder. That folder contains a fully operational tempsensor.c file. Don't forget to modify the makefile in that folder for your system settings. Then try to upload that to the chip to make sure everything is ok. If that uploads, showing us your code can help us help you more.

Also, if you copy and paste your code into the forum, be sure to select the code and press the Indent Selection as Code Block button below so it gets formatted properly in the forum.

Rick

March 25, 2011
by Silver07
Silver07's Avatar

Hi, I was wondering what you have to change in the tempsensor code to make the out put in degrees C.

silver07

March 25, 2011
by tomroth
tomroth's Avatar

My original program does that. Add this code to your VB app:

    test = (Temperature - 32) / 1.8
    lblParse.Text = test & "° C"

Where lblParse is a lable on your form. It's just simple math to convert degrees F to degrees C.

Tom

March 25, 2011
by Silver07
Silver07's Avatar

Thanks Tom, how can I get the tempsensor program in VB

March 26, 2011
by Rick_S
Rick_S's Avatar

Add this line in the main function as shown here:

// Convert to ° C

temp_avg = (temp_avg-32)/1.8;

Place it just before the // write message to LCD comment.

Rick

March 26, 2011
by tomroth
tomroth's Avatar

Silver,

The code for the Tempsensor project is near the top of this post. Just copy and paste it into visual studio or VB Express and add the appropriate buttons and lables and such.

Tom

May 26, 2011
by Rachid
Rachid's Avatar

tomroth, I tried running your VB code using visual studio 2010 and I am getting this error which I dont even know where to start debugging

'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_32mscorlibv4.0_4.0.0.0b77a5c561934e089mscorlib.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:rachidWindowsApplication1WindowsApplication1binDebugWindowsApplication1.exe', Symbols loaded. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.VisualBasicv4.0_10.0.0.0b03f5f7f11d50a3aMicrosoft.VisualBasic.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystemv4.0_4.0.0.0b77a5c561934e089System.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Corev4.0_4.0.0.0b77a5c561934e089System.Core.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Windows.Formsv4.0_4.0.0.0b77a5c561934e089System.Windows.Forms.dll' 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsassemblyGAC_MSILMicrosoft.VisualStudio.Debugger.Runtime10.0.0.0b03f5f7f11d50a3aMicrosoft.VisualStudio.Debugger.Runtime.dll' 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Drawingv4.0_4.0.0.0b03f5f7f11d50a3aSystem.Drawing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILAccessibilityv4.0_4.0.0.0b03f5f7f11d50a3aAccessibility.dll' 'WindowsApplication1.exe' (Managed (v4.0.30319)): Loaded 'C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Runtime.Remotingv4.0_4.0.0.0__b77a5c561934e089System.Runtime.Remoting.dll' The program '[8300] WindowsApplication1.exe: Program Trace' has exited with code 0 (0x0). The program '[8300] WindowsApplication1.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

May 26, 2011
by tomroth
tomroth's Avatar

Does your form have a button named "btnEnd" and have you created a timer named "tmrDelay"?

Tom

May 26, 2011
by 6ofhalfdozen
6ofhalfdozen's Avatar

Hi Rachid, That is not an error message. I had to look it up, but that tells you your code completed with no errors, BUT you were running in a special debug mode and not trying a standard program run. Also, it sounds like this occurs when you are running WPF forms instead of standard forms. Try making a standard windows form, adding the buttons, compile/test, then adding Tom's code. It should work better.

the following link has more on that message: http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/867d73ed-2350-4008-a1b8-b7f6e1662058/

hope that helps.

December 23, 2011
by christian
christian's Avatar

Hi tomroth (and everyone else), I'm new to serial comm programming. I also have the temperature sensor.I would like to know if you have a similar version of your VB application in Visual C++. If not please suggest any ideas of where to get a reference app on serial com programming ( Visual C++ ) that will help me show the output of the temperature sensor. I will greatly appreciated (I have searched on the web but the few apps I found, I could not understand much of their code and when I tried to compile them got all sorts of errors). Your app is short and a lot easier to understand compared to others. Thank you!

December 23, 2011
by hevans
(NerdKits Staff)

hevans's Avatar

Hi christian,

I haven't spent too much time doing windows development, but for the little time I did do it for the microsoft MSDN documentation was very helpful. They have what appears to be reasonably good documentation for the Serial Port Class. Perhaps that can get you going in the right direction.

Humberto

December 23, 2011
by pcbolt
pcbolt's Avatar

@ christian

I actually modified a C program recently to read the Com ports from a console window. I compiled it with Visual C++ so it should easily adapt to a Windows format. The MSDN documentation is a little sketchy on some parts, but it does show some ways you can extend control over the Com ports. Here is the listing I compiled:

// Complete listing

    #include <windows.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>

    #define MAX_RX_BUF  64

    ///GLOBALS///
    /// Old Comm Port settings

    DCB m_dcbOld;
    COMMTIMEOUTS m_ctoOld;

HANDLE init_comm(){

HANDLE m_hComm;
DCB m_dcbNew;
COMMTIMEOUTS m_ctoNew;

m_hComm = CreateFile(
        "COM4",                     // windows assigned ID of port 
        GENERIC_READ,     // desired access, can be | with GENERIC_WRITE
  0,                                // comm must be opened w/exclusive-access
  NULL,                         // no security attributes
  OPEN_EXISTING,        // comm devices must use this
  NULL,                         // non-overlapped I/O <---Lots of flexibility w/ overlapped
  NULL);                        // hTemplate must be NULL for comm devices

if (m_hComm == INVALID_HANDLE_VALUE)
{
    printf("Cannot open port \n");
    m_hComm = NULL;
    return m_hComm;
}

    // CHANGING PORT SETTINGS
    // - 1) Retrieve and save old values in global variable
    // - 2) Copy to a new DCB struct
    // - 3) Change values as needed
    // - 4) Update the new values

// Part 1)
if (!GetCommState(m_hComm, &m_dcbOld))
{
    printf("Can't get baud\n");
    CloseHandle(m_hComm);
    return NULL;
}

// Part 2 and 3
m_dcbNew = m_dcbOld;                        // old compilers don't like this
m_dcbNew.BaudRate = CBR_115200;
m_dcbNew.Parity = NOPARITY;
m_dcbNew.StopBits = ONESTOPBIT;

// Part 4
if (!SetCommState(m_hComm, &m_dcbNew))
{
    printf("Can't set baud\n");
    CloseHandle(m_hComm);
    return NULL;
}

    // CHANGING COMM TIMEOUTS (See PORT SETTINGS comments for steps)
    // Note: Timeouts keep ReadFile() from blocking execution

// Part 1
if (!GetCommTimeouts(m_hComm, &m_ctoOld))
{
    printf("Can't get timeouts\n");
    CloseHandle(m_hComm);
    return NULL;
}

// Part 2 and 3
m_ctoNew = m_ctoOld;
m_ctoNew.ReadIntervalTimeout = 50;
m_ctoNew.ReadTotalTimeoutConstant = 50;
m_ctoNew.ReadTotalTimeoutMultiplier = 50;
m_ctoNew.WriteTotalTimeoutConstant = 50;
m_ctoNew.WriteTotalTimeoutMultiplier = 50;

// Part 4
if (!SetCommTimeouts(m_hComm, &m_ctoNew))
{
    printf("Can't get timeouts\n");
    CloseHandle(m_hComm);
    return NULL;
}

return m_hComm;
}

     void restore_comm(HANDLE m_hComm){

// Just restore the old comm settings and timeouts
// No error checking here...not much can be done now

SetCommTimeouts(m_hComm, &m_ctoOld);
SetCommState(m_hComm, &m_dcbOld);
return;
}

      void main(){

HANDLE m_hComm;
char cBuf[MAX_RX_BUF];
DWORD dRead = 0;
BOOL bResult;
char cTest;

printf("Press X or x to exit....\n");

m_hComm = init_comm();
if (m_hComm == NULL){
    printf("Could not initialize Comm Port, exiting....\n"); 
    return;}

while (1){

    if (_kbhit()){          // check for keyboard hit since getch() blocks execution
        cTest = getch();
        if ((cTest == 'X') || (cTest == 'x')){
            printf("Program terminated by user,exiting....\n"); 
            break;
        }
    }

    bResult = ReadFile(
        m_hComm,                    // handle to port (see init_com() function)
        cBuf,                           // buffer to store read
        MAX_RX_BUF - 1,     // size to be read - need room to null terminate string
        &dRead,                     // number of bytes actually read
        NULL);                      // overlapped struct - not used here

    if (bResult){
        if (dRead >= MAX_RX_BUF) dRead = MAX_RX_BUF - 1;    // just in case
        cBuf[dRead] = '\0';         // null terminate buffer
        printf("%s", cBuf);
    }
} // continue on until user exits program

restore_comm(m_hComm);          // set things back they way they were found

return;
}

Post a Reply

Please log in to post a reply.

Did you know that you can build a digital read out (DRO) for a lathe or milling machine? Learn more...