Show Posts
Pages: 1 2 [3] 4 5 ... 54
31  Using Arduino / Programming Questions / Re: programming confusion on: August 18, 2014, 07:10:50 pm
Yes. The comma operator can be used to separate complex expressions. For example, you could also do silly stuff like:

Code:
  for (int i, j = 9; j < 10; j++)


That said, most use the single line definitions rather than stacking them.
32  Using Arduino / Programming Questions / Re: My error correction doesn't seem to work? on: August 17, 2014, 01:15:10 pm
First, it would make your code more readable if you used Ctrl-T before you posted it.

Second, you set val in setup(), but never read or update it again. val2 is updated in loop() and compared to val3, but val3 is always based upon the value read in setup(). It would seem to me that if you are counting something, what that count is when the program starts doesn't matter much later on.

Third, your Serial.print() calls are placed in such a way they don't seem to do much good. Since val never changes in loop(), why print it out? Also, since val3 is just val + 100, it never varies either, which means val3 is a constant. If so, why not just set it as a const and be done with it?

Fourth, this code fragment:

Code:
  if (val2 > val3 )
  {
    delay(200);                     //wait icase of false positive reading
    if (val2 > val3)               //check sensor again
    {

is never going to change state. The delay() call has no way to change either val2 (since analogRead() isn't called but is the only thing that can change val2) or val3 (which is a constant).

Am I missing something?

33  Using Arduino / Programming Questions / Re: How to convert float to char* LCD sprintf on: August 17, 2014, 12:19:12 pm
I don't understand why you would have to use sprintf() simply to send the output to the LCD display. Use dtostrf() as Peter_n suggested and then just send the buffer to the LCD object using the print() method.
34  Using Arduino / Programming Questions / Re: Where can I learn programming for arduino? on: August 17, 2014, 11:51:03 am
Search "Arduino C" on Amazon and read the reviews. Be forewarned that some books skimp on the C parts and concentrate on the hardware while others go more into the language. Most books have a "Look Inside" banner on their covers on the web page. Click on that and then read the Table of Contents to see if it covers the language. Some "intro programming" books only have a couple of chapters on actual programming.

The reviews should help you ferret things out. Also, pay attention to the number of reviews, since one or two is not a very good sample. I'm biased, but I think Beginning C for Arduino is good since it was written by a teacher with over 30 years experience. Great programmers don't necessarily make good teachers.
35  Using Arduino / Programming Questions / Re: Planning and Implementing an Arduino Program on: August 17, 2014, 11:18:53 am
Robin2: Very helpful. In the organization element, after over 30 years of teaching university-level programming courses, to me the design part is where most students drop the ball. Agile technology suggests the planning doesn't have to be elaborate, like the old IBM BDUF (Big Design Up Front) approach. As a result, I use the Five Programming Steps (details in Beginning C for Arduino and several other of my books):

   Step 1. Initialization. Sets the environment for running the program. Opens ports, DB connections,
         file handles, memory allocations, etc. Like many Windows programs that update the File menu
         with the most-recently used files, this step gets things ready. Done before the user "sees" anything.
         For the Arduino, setup() seems appropriate.

   Step 2. Input. Gather the data that will be used by the program. Verify its validity if possible and react
         if not as expected. Usually means reading sensors, pots, ports...whatever. This is usually an early
         segment of the loop() code. Using function calls helps to encapsulate the code.

   Step 3. Processing. Virtually all programs take data in one form, crunch on it, and output it in another
         form. The "crunching" is done in this step. In most cases, an algorithm directs the processing.
         Sometimes multiple processing steps must be done to interact and produce a given result. This is
         also part of the loop() code, but Steps 2 and 3 isolate each other by using function calls.

   Step 4. Output. This is where the results of Step 3 are presented. The output may be displayed on LEDs,
         LCD display, sensors, meters, printers, data files, or passed on to anther process where it becomes
         Step 2 for that process. Again, a function call should be used to decouple the output from the other
         steps as much as possible.

   Step 5. Termination. This is where most programs clean up after themselves...freeing memory allocations,
         closing DB connections, closing ports, turning sensors off, releasing file handles, etc. In many cases, it
         "undoes" what Step 1 did. For microcontroller applications, most do not have a Step 5 as they are often
         designed to run forever, or until power is removed or there is component failure.

Beginning students rarely take the time to think through a simple set of design steps. Taking these Five Steps and doing a sideways refinement often saves a ton of time down the road.
36  Using Arduino / Programming Questions / Re: RESOLVED - Program 5_05 from "Programming Arduino" book error on: August 16, 2014, 02:04:24 pm
Your punctuationTranspose() function is not correct. In each case, you have something like:

Code:
  case 1:
  ch=='.';      // The equality operator doesn't do anything here
  newch= 0;
  break;

If fact, if you look at every case, you assign newch a value that is exactly 1 less than ch. In essence, all your function does is reduce the index number by 1. I think this is because you forgot that C arrays begin with 0, not 1. You can prove this to yourself by replacing your  punctuationTranspose() with:

Code:
byte  punctuationTranspose(
  newch = ch - 1;
  return newch;
}

It also seems like your punctuation array has a lot of duplicate entries in it, which is wasteful, especially on boards like there which have limited memory. Indeed, the punctuationTranspose() function isn't needed at all. Try:

Code:

 else if (ch >= 33  &&  ch <=  95)                      // is it punctuation?   THIS SEQUENCE DOES NOT WORK!!//Now it does
   {

      //punctuationTranspose();      // Get rid of the next two lines...
      //flashSequence (punct[newch]);

      flashSequence (punct[ch - 1]);
   }

There are several other things that don't make sense to me, but these should make you stop and review your code.
   
37  Using Arduino / Programming Questions / Re: The default number of float fraction issue on: August 16, 2014, 10:20:53 am
@robtillaart: I'm not a big fan of expressions like:

Code:
int i= f * 1000;
int i= round(f * 1000.0);

because both rely on "silent casts" to work correctly. While the code compiles without error, it's dangerous because you're trying to pour 4 bytes of data into a 2-byte bucket. The compiler my company produced had a "picky flag" that could be set from 1 to 10. Level 10 was as fussy as the Lint utility on Unix and the code above would not pass without error. Using an explicit cast at least better documents what you are doing:

Code:
int i= (int) (f * 1000.0);
int i= (int) round(f * 1000.0);
38  Using Arduino / Programming Questions / Re: RESOLVED - Program 5_05 from "Programming Arduino" book error on: August 16, 2014, 09:31:07 am
You might want to change cattledog's function punctuationTranspose() from a bunch of if expressions to a switch. The reason is because, if the character coming in happens to be a period character, it matches the first test, but the code then performs 15 unnecessary if tests.
39  Using Arduino / Programming Questions / Re: RESOLVED - Program 5_05 from "Programming Arduino" book error on: August 16, 2014, 09:25:32 am
After you typed in a sentence on the Serial monitor and clicked Send, did you bother to look at the LED on the Arduino board?
40  Using Arduino / Programming Questions / Re: The default number of float fraction issue on: August 16, 2014, 08:34:08 am
Looks like we double-posted. To answer your question about why the expression

Code:
int i= (int) f * 1000;

doesn't work, the order of precedence of operators means that f is cast to an int before it's multiplied. You need to force the multiplication with parentheses first:

Code:
int i= (int) (f * 1000);
41  Using Arduino / Programming Questions / Re: The default number of float fraction issue on: August 16, 2014, 08:26:35 am
When you use the Serial object to print a float, it defaults to 2 decimal places. I think you can use:

Code:
float val = 1.2345678;

Serial.print(val, 5);     // Show 5 decimal places.

42  Using Arduino / Programming Questions / Re: Modifying code to count up using eight digit, 7-seg displays, a MAX7219 and Uno on: August 15, 2014, 11:33:20 pm
That wouldn't be too hard. In loop(), you'd need to monitor the pin that the switch is connected to  and when it is pressed, call my Reset() function. When you get a little more comfortable with programming the Arduino, you could use an interrupt to sense the button push.

Added:

I just reread what you asked and you didn't want to reset the clock to zero. In that case, when your code senses a button press, call a function that simply goes into a while loop looking at the switch pin. When it sees the pin is released, it exits your function and returns to loop(). Since none of the variables have changed, it should pick up where it left off. You may need to use interrupts to do this properly.
43  Using Arduino / Programming Questions / Re: Program 5_05 from "Programming Arduino" book error on: August 15, 2014, 11:29:46 pm
I found it distracting to see the onboard LED flashing Morse while the I/O leds were also flashing because Simon didn't buffer the input. Also, you can simplify a few things, too. I also commented out the Serial call that displays the letter just display on the LED because of the I/O LED flashing while it was sent. Lastly, Morse code is normally a 1:3 ration dits to dahs, character spacing is 3 dits, and word spacing is 7 dits. Farnsowrth encoding screws these timings up, but the ratios here are commonly used.


Code:
//Sketch 5_05Test   Morse Interpreter including punctuation

int ledPin = 13;
int dotDelay = 150;                                               //set the delay to a quarter second

char* letters[] =
{
  ".-", "-...", "-.-.", "..", ".",                          //A-Z
  "..-.", "--.", "....", "..",
  ".---", "-.-", ".-..", "--", "-.",
  "---", ".--.", "--.-", ".-.",
  "...", "-", "..-", "...-", ".--",
  "-..-", "-.--", "--.."
};

char* numbers[] =
{
  "-----", ".----", "..---", "...--", "....-",  //numbers 0-9
  ".....", "-....", "--...", "---..", "----."
};

char* punct[] =
{
  ".-.-.-", "--..--", "..--..", ".----.",          //(punctuation marks) . , ? '
  "-.-.--", "-.--.", "-.--.-", ".-...",           // ! ( ) &
  " ---...", "-.-.-.", "-...-", ".-.-.",            // : ; = +
  "-....-", "..--.-", ".-..-.", "...-..-",           // - _ " &
  ".--.-."                                                 // @
};


void setup()
{
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
  Serial.println("To send text to be displayed in Morse Code, type words above and press Send");
}

void loop()
{
  char ch;
  char buff[100];
  int i;

  if (Serial.available() > 0)
  {
    i = Serial.readBytesUntil('\n', buff, 99);    //read all
    buff[i] = '\0';
    i = 0;
    while (buff[i]) {
      ch = toupper(buff[i++]);
      if (ch >= 'A' && ch <= 'Z')                           // is it a capital letter?
      {
        flashSequence(letters [ch - 'A']);
      }
      else if (ch >= '0' && ch <= '9')                          // is it a number?
      {
        flashSequence (numbers[ch - '0']);
      }
      else if (ch >= '.'  &&  ch <=  '@')                      // is it punctuation?   THIS SECQUENCE DOES NOT WORK!!
      {
        flashSequence (punct[ch] - '.');
      }
      else if (ch == ' ')                                          // is it a blaqnk space?
      {
        delay(dotDelay * 7);                                     //gap between words
      }
      {
        //Serial.print(ch);
      }
    }
  }
}

void flashSequence (char* sequence)
{
  int i = 0;
  while  (sequence[i])
  {
    flashDotOrDash(sequence[i++]);
  }
  delay(dotDelay * 3);                              //gap between letters
}

void flashDotOrDash (char dotOrDash)
{
  digitalWrite(ledPin, HIGH);
  if (dotOrDash == '.')
  {
    delay (dotDelay);
  }
  else                                          // must be a -
  {
    delay (dotDelay * 3);
  }
  digitalWrite(ledPin, LOW);
  delay(dotDelay);                              //gap between flashes
}
44  Using Arduino / Programming Questions / Re: Modifying code to count up using eight digit, 7-seg displays, a MAX7219 and Uno on: August 15, 2014, 10:40:00 pm
I just got the same LED control and was playing around with it. I'm not sure I understand exactly what you're trying to do, but it seems like you want a "count up" clock. The code below is an approximation, but is not going to be accurate since I used delay() and just guessed at the delay period. It would work better using interrupts and an RTC, but this might help you with the code part of it. Note that I changed the pin assignments to match my setup. You'll need to change those for yours.

Code:
#include <LedControl.h>    //We cant do anything without importing a suitable library!

// Lets start with the pinouts to the Max7219 led driver

int DIN = 10;              // Pin 1  on the Max72xx
int CLK = 13;              // Pin 13 on the Max72xx
int LOADCS = 11;           // Pin 12 on the Max72xx

int flashDelay = 100;      // delay in MS (100=1/10th second)
int ledBrightness = 5;    // range is 0-15.  0=lowest, 15 = full power

// define the LedControl instance - if I want more I can setup lc2, lc3 etc
// ************************************************************************

LedControl lc = LedControl(DIN, CLK, LOADCS, 8); // DIN, CLK, Load/CS, 1 = only one chip MAX chip attached.
int frame0, frame1;
int seconds0, seconds1;
int minutes0, minutes1;
int hours0, hours1;

void setup()
{
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  pinMode(LOADCS, OUTPUT);

  // take pins out of power save mode.  No updates otherwise.
  //for (int index = 0; index < lc.getDeviceCount(); index++) {
    lc.shutdown(0, false);
  //}
  Reset();
  lc.setDigit(0, 0, 0, false);       // These two lines add the numerical hours
  for (int i = 1; i < lc.getDeviceCount(); i++) {
    lc.setDigit(0, i, 0, (i % 2 == 0) ? true : false);       // These two lines add the numerical hours
  }

  lc.setIntensity(0, ledBrightness  ); //set the brightness
}

void loop()                     // here comes the good stuff, the main loop!
{

  BumpFrame();
  // First lets display the hours
}
// *** That's All Folks!!! Jack Bauer eat your heart out! ***
// code provided by Blair Thompson

void  BumpFrame()
{
  delay(30);    // Count to 29 from 0 every second
 
  lc.setDigit(0, 0, frame0++, false);       // These two lines add the numerical hours
  if (frame0 == 10) {
    frame1++;
    frame0 = 0;
  }
  if (frame1 < 3) {
    lc.setDigit(0, 1, frame1, false);       // These two lines add the numerical hours
  } else {
    frame1 = 0;
    lc.setDigit(0, 1, frame1, false);       // These two lines add the numerical hours
    BumpSeconds();
  }
}

void  BumpSeconds()
{
  seconds0++;
  if (seconds0 == 10) {
    seconds1++;
    seconds0 = 0;
  }
  lc.setDigit(0, 2, seconds0, true);       // These two lines add the numerical hours

  if (seconds1 < 6) {
    lc.setDigit(0, 3, seconds1, false);       // These two lines add the numerical hours
  } else {
    seconds1 = 0;
    seconds0 = 0;
    lc.setDigit(0, 3, seconds1, false);       // These two lines add the numerical hours
    BumpMinutes();
  }
}

void  BumpMinutes()
{
  minutes0++;
  if (minutes0 == 10) {
    minutes1++;
    minutes0 = 0;
  }
  lc.setDigit(0, 4, minutes0, true);       // These two lines add the numerical hours

  if (minutes1 < 6) {
    lc.setDigit(0, 5, minutes1, false);       // These two lines add the numerical hours
  } else {
    minutes1 = 0;
    minutes0 = 0;
    lc.setDigit(0, 5, minutes1, false);       // These two lines add the numerical hours
   BumpHours();
  }
}

void  BumpHours()
{
  hours0++;
  if (hours0 == 10) {
    hours1++;
    hours0 = 0;
  }
  lc.setDigit(0, 6, hours0, true);       // These two lines add the numerical hours

  if (hours1 < 6) {
    lc.setDigit(0, 7, hours1, false);       // These two lines add the numerical hours
  } else {
    hours1 = 0;
    hours0 = 0;
    Reset();
  }
}

void Reset()
{
  lc.setDigit(0, 0, 0, false);       // These two lines add the numerical hours
  for (int i = 1; i < lc.getDeviceCount(); i++) {
    lc.setDigit(0, i, 0, (i % 2 == 0) ? true : false);       // These two lines add the numerical hours
  }
}
45  Using Arduino / Programming Questions / Re: delay function parameter minimum on: August 14, 2014, 10:53:44 pm
If you look at the course code in wiring.c, passing in a 0 for the parameter should cause no issues.
Pages: 1 2 [3] 4 5 ... 54