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 » Using strcpy

December 19, 2012
by Nichben
Nichben's Avatar

I got the following to work in Cywin C++ but not on my Atmega168. It stops at the conditional statment. Please have a look and see what's happening. this is section of code from my program to operate a bipolar stepper motor. I've modified it to leave out the strcopy and it works fine but I just want to get the strcpy to work on my atmega168. Thanks,JB

// Portplay.c
// for NerdKits with ATmega168
// jBenziger

#define F_CPU 14745600

#include <stdio.h>
#include <math.h>

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>
#include <string.h>

#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/uart.h"
int main() {
  char dc[3];           // this sets up a character array
  //lcd_init();
  //FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
  uart_init();
  FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
  stdin = stdout = &uart_stream;
  delay_ms(5000);
  while(1){
  printf_P(PSTR("\r\n Enter direction (f or r): "));
  scanf_P(PSTR("%s"), &dc);
  printf_P(PSTR("\ndirection is %s\n"), dc);
  if(*dc == 'f' || *dc=='c'){           // This one compares the first char of name to a literal char "f" or "c"
  //*(name + 2) uses the 3rd char to compare or printout or whatever.
  //if(strcmp(name,"f") ==0 || strcmp(name,"c") == 0){   // This one compares the string name to a literal string "f" or "c"
    strcpy(dc,"CW");            
    }
    else
    {
    strcpy(dc,"CCW");           
    }
  printf_P(PSTR("\ndirection is now %s\r\n"), dc); //displays the last element in the char array, ie: N or O.?
  }
  return 0;
}
December 19, 2012
by pcbolt
pcbolt's Avatar

JB -

You might need "dc" to be 4 bytes long. I think "strcpy" adds the trailing '0' (string terminator) to the array. I've had trouble assigning quoted strings sometimes as well. You could try using the <avr/pgmspace.h> function "strcpy_P()" like this:

strcpy_P(dc, PSTR("CW"));

Haven't tried it but it might be worth a shot. There's also a line in your makefile that you could try changing...see This Thread for more details.

December 20, 2012
by Nichben
Nichben's Avatar

PC-

I actually tried your second suggestion and followed the link 'This Thread'. One of the posts suggested substituting this line in the makefile:

avr-objcopy -j .text -O

with this one:

avr-objcopy -j .text -j .data -O

I suspected something in the Make and that's why I tried this first. It now works great. Many thanks! JB

Post a Reply

Please log in to post a reply.

Did you know that the microcontroller's crystal oscillator can be used to keep accurate time? Learn more...