text:
What is the difference between a 3 pin and 4 pin ultrasonic range sensor?
I am following a tutorial that uses an arduino and ultrasonic range sensor, it calls for a 3 pin module (Paralax 28015-ND) and I have a 4 pin module (http://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf).  The 3 pin seems to have one signal pin (both input and output) and the 4 pin has two separate signal pins (a trigger and echo).  How would I need to change the code and wiring if I am using the 4 pin?  Here is the code from the tutorial:
     /* Ping))) Sensor

   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse
   to return.  The length of the returning pulse is proportional to
   the distance of the object from the sensor.

   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping

   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe
   modified again 02 Apr 2016
   by Randy Sarafan

   This example code is in the public domain.

 */

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 4;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

There are already libraries that do that for HC-SR04, the code is quite simple, just take a look at it and you'll see how you can modify your program.

It's simple enough... instead of:
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

You would have
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

(of course you have to define echoPin to be whatever pin you choose to connect ECHO to).
And to save processing time you can have all your pinMode() calls in setup since there is no need to change mode on the fly any more.


text:
Showing chronometer on PC controlling the begining and end of time by Arduino
I'm really new on this Arduino thing, so I don't know whether what I'm gona ask is feasible or not.
I'd like to make a chronometer in the computer but the controlling button (beginning and end of count) not to be some computer key. So I was wandering if I could make a button controlled by the arduino - maybe via a piezoelectric element?
Besides the problem of not knowing what to use as a button, I don't really know if it's possible to make a graphical interface (i know how to programme in C, Python, ...) showing the numbers in the screen of the computer and the beginning and end of counting controlled by that button. Is this possible to do?
Thanks for any help to both questions!

Yes. Is there a particular reason you want to use a piezo rather than, say, a pushbutton?

Besides the problem of not knowing what to use as a button -- How about... a button...?

No, I just thought that with a piezo I could make a larger button (something like Buzz! game button - this is for a demonstration to use with kids)...
What about the interface with software? Where can I read about it?

You should clarify your question by telling us WHAT should trigger the start and stop: human finger (then any push button is suitable), light detection, presence detection... Voting to close the question until clarification is provided.

Yes, the human finger is the right answer. Like I said, it's somehting like Buzz! game button - this is to use for a demonstration with kids where they have to start and end the counting.

It's perfectly possible to do, and the way I would probably do it is to use one of the ATMega32U4 based Arduinos (such as the Arduino Leonardo or the somewhat smaller Arduino Micro) to act like a keyboard. A keyboard with just one key - your chosen button.
Then you program the computer to respond to the keycode the Arduino sends to start and stop the chronometer. You could even use an off the shelf chronometer program that starts and stops with a specific keypress and tell the Arduino to send that keypress. It would probably take about 5 minutes to write the software - if that.

Yes! That's exatcly the kind of think I want to do. My problem is just really how to make the connection between the Arduino software (I'm writing the code to programm Arduino via the official software provided in Arduino website) and the GUI - I will probably make the chronometer in Tkinter... Do you have any suggestion? Where can I read about that?

If you use an ATMega32U4 based Arduino and use Keyboard.print(...) there is no "connection" between the Arduino and your program. The PC just sees the Arduino as a keyboard and you just react to a keypress in your software. You could use the same software with any run of the mill keyboard too if you wanted.

I'm using Arduino Uno... Is it still possible to do so with this Arduino?

There are ways, but none of them very nice. For the Uno you are really limited to just a serial connection. There's millions of examples around showing you how to communicate through serial with a PC.

This simple communication cannot be done by the USB cable? Would it have to be through the serial?

The USB cable is the serial!!!

Oh yes. Okay. Then I'll read about serial communication. I wasn't aware of the existence of it. Like I said, I'm really new on this thing. Thanks.

I am already familiarized with the concept of serial communication. I can turn on/off LED via Serial Monitor.
I can also connect it with Python and I've made a small program that makes the LED blink - and this works perfectly.
However I now added a pushbutton to my circuit, so that when it is pressed, the blinking process is interrupted. But this is not working. My attempt was to send a Serial.print when the pushbutton is pressed with the message "Exiting\n".
Part of my Arduino code is:
if(digitalRead(BUTTON) == HIGH){
Serial.print("Exiting\n");
while(1){}
}

And part of my Python code is:
while True:
    arduino.write("Y")
    print arduino.readline()
    time.sleep(0.5)
    arduino.write("N")
    time.sleep(0.5)

    try:
       if arduino.readline() == 'Exiting\n':
          print arduino.readline()
          break
    except:
          print("nothing\n")

The problem is that when I run the program, it gets stucked in the line
if arduino.readline() == 'Exiting\n':

Any help?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino Nano nRF24L01+ DFPlayer Mini SPI Problem
I'm working with an Arduino Nano board clone (CH340) on wireless control of DFPlayer Mini, transceiver sending a Struct variable with MachinePrefix (just in case), sound type (I have more folders by type of machines) and number of sounds.
The transceiver works fine, but the receiver doesn't. If I upload data into the Arduino, the DFPlayer plays the first song once (row 43 - myDFPlayer.play(1)), but after nRF24 init is not working.
After nRF24 init I'm still receiving data in valid format and range. If I comment out the nRF24 part, the DFPlayer is working, but together not. I read about working two devices on one SPI bus but I don't understand what's wrong. I think the problem is the same MOSI pin. In my opinion it should work but did not.
Any suggestions?
Here is the code of receiver:

#include
#include "RF24.h"
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

RF24 myRadio (8, 9); // CE, CS
byte addresses[][6] = {"Sx001"};

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

struct dataStruct {
  short machinePrefix;
  short soundType;
  short soundNumber;
} dataReceived;

void setup() {
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);
  delay(1000);
  Serial.println(F("RF24+dfplayermini-recever"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }

  Serial.println(F("DFPlayer Mini online."));
  myDFPlayer.setTimeOut(500);
  myDFPlayer.volume(5);  //Set volume value. From 0 to 30
  myDFPlayer.play(1);  //Play the first mp3
  //----------------------------
  delay(1000);
  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate(RF24_250KBPS);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power
  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();
  Serial.println(F("RF24 online."));
}//--(end setup )---

void loop() {  /****** LOOP ******/
  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
  if (myRadio.available()) { // Check for incoming data from transmitter
    while (myRadio.available()) { // While there is data ready
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload
    }
    Serial.println("loop");
    myDFPlayer.loop(3);
    if (dataReceived.machinePrefix == 11001) {
      Serial.println("same device prefix");
      int playingData = dataReceived.soundNumber;
      if (myDFPlayer.available()) {
        Serial.println("player available");
        Serial.println(myDFPlayer.readType());
        Serial.println(myDFPlayer.read());
      }
      myDFPlayer.play(2);
    }
    Serial.println(dataReceived.machinePrefix);
    Serial.println(dataReceived.soundType);
    Serial.println(dataReceived.soundNumber);
    Serial.println("-----------------------------");
  } //END Radio available
}//--(end main loop )---

/*----------*/
void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

if not difficult, show the code of the transmitter. pls)

When using SPI, pin 10 should never be used as an INPUT. Otherwise the Atmega can go into SPI Slave mode. But you use pin 10 as the RX pin.
Just swap pin 9 and 10, and update your code accordingly.

Thank you so much, i hadn't thought about changing pins to other digital pins on the Arduino, because my low understanding of Softwareserials...
Now i use pins D4 and D5 for dfplayer and it worked like a charm.

Just make sure you set pin 10 as an OUTPUT.

authors: Сергей Овчинников

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Avrdude fails at specific baudrates
I'm seeing something very strange. If I run:
ard-reset-arduino /dev/ttyACM0;
/usr/share/arduino/hardware/tools/avr/bin/avrdude -C/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:`pwd`/.build/main.ino.hex:i;

Avrdude uploads my sketch to an Arduino Uno just fine. However, if I change the buadrate to 57600, it fails with the error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I've tried manually pressing the Arduino's reset button just before I upload, but there's no change.
Why is this happening? If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

Arduino bootloaders doesn't have any baud rate detection and baud rate is fixed (for the different boards there might be different baud rates)
Only Leonardo (and others with native USB) are almost idependent on baud rate  except for 1200bauds used as "reset". (However it runs at maximum speed that the MCU can handle)

Details for these modes can be found in boards.txt

If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

The bootloader is a piece of code designed to work at a specific baud rate. As KIIV said in his answer only the USB-based Arduinos would be relatively immune to changing the rate.
What your own code does, after being uploaded, is completely irrelevant.

Avrdude fails at specific baudrates

Your title really should be: "Avrdude only works at one baudrate (the one it was designed to use for a specific board)"


text:
Multi Level Button Menu
Have been working on a Button Menu for a while now and can't break thru to the 3rd level, which in theory would give access to levels 4/5/6/etc.
It's layed out long hand, I'll neaten the code up after its working.
Could you pls have a look and see if you can access level 3....
Also if there is an alternative for multi level menus, happy to look at those also, just after something that works, have tried dozens that i have found on the web.....either no sketch with the video(how i hate that) or sketch just doesn't work period.
Thanks in advance
Doug
    /*
Description : Simple Menu function on LCD
          Button Function:
            Up/Down - change Menu Page
            Select - enter page
            Left - Exit

Link: http://youtu.be/cMqif5ICS5M

+++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

int keypad_pin = A0;
int keypad_value = 0;
int keypad_value_old = 0;

bool menu2 = false;
char btn_push;

int selection1 = 0;
int selection2 = 0;

int mainMenuPage = 1;
int mainMenuPageOld = 1;
int mainMenuTotal = 4;

int levelMenuPage = 1;
int levelMenuPageOld = 1;
int levelMenuTotal = 4;

void setup()
{
  Serial.begin(9600);
lcd.begin(20, 4);  //Initialize a 2x16 type LCD

MainMenuDisplay();
delay(1000);

}
void loop()
{
MainmenuBtn();

if((btn_push == 'S')&&(menu2 == false))//enter selected menu
{
  Serial.println("i'm here");
    WaitBtnRelease();
    switch (mainMenuPage)
    {
        case 1:
          MenuA();
          break;
        case 2:
          MenuB();
          break;
        case 3:
          MenuC();
          break;
        case 4:
          MenuD();
          break;
    }

      MainMenuDisplay();
      WaitBtnRelease();
  }
  else
{
   if((btn_push == 'S')&&(menu2 == true))//enter selected menu
{
  LevelmenuBtn();
    WaitBtnRelease();
    switch (levelMenuPage)
    {
        case 1:
          MenuA2();
          break;
        case 2:
          MenuB2();
          break;
        case 3:
          MenuC2();
          break;
        case 4:
          MenuD2();
          break;
    }

      LevelMenuDisplay();
      WaitBtnRelease();
  }

  delay(10);
}
}
//--------------- End of loop() loop ---------------------
void MainmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(mainMenuPage > mainMenuTotal)
      mainMenuPage = 1;
      Serial.println(mainMenuPage);
}
else if(btn_push == 'D')
{
    mainMenuPage--;
    Serial.print(mainMenuPage);
    if(mainMenuPage == 0)
      mainMenuPage = mainMenuTotal;
      Serial.println(mainMenuPage);
}

if(mainMenuPage != mainMenuPageOld) //only update display when page change
{
    MainMenuDisplay();
    mainMenuPageOld = mainMenuPage;
}
}
void LevelmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(levelMenuPage > levelMenuTotal)
      levelMenuPage = 1;
      Serial.println(levelMenuPage);
}
else if(btn_push == 'D')
{
    levelMenuPage--;
    Serial.print(levelMenuPage);
    if(levelMenuPage == 0)
      levelMenuPage = levelMenuTotal;
      Serial.println(levelMenuPage);
}

if(levelMenuPage != levelMenuPageOld) //only update display when page change
{
    LevelMenuDisplay();
    levelMenuPageOld = levelMenuPage;
}
}
void MainMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (mainMenuPage)
{
    case 1:
      lcd.print("1. Menu A");
      break;
    case 2:
      lcd.print("2. Menu B");
      break;
    case 3:
      lcd.print("3. Menu C");
      break;
    case 4:
      lcd.print("4. Menu D");
      break;
}
}
void LevelMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (levelMenuPage)
{
    case 1:
      lcd.print("1. Menu A2");
      break;
    case 2:
      lcd.print("2. Menu B2");
      break;
    case 3:
      lcd.print("3. Menu C2");
      break;
    case 4:
      lcd.print("4. Menu D2");
      break;
}
}
void MenuA()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A");
 menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection1=1;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuA2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection2=1;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuB()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here

 selection1=2;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuB2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here
 selection2=2;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuC()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection1=3;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuC2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection2=3;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuD()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection1=4;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuD2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection2=4;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}

char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
nul     <450
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);

if(keypad_value < 50)
return 'R';
else if(keypad_value < 190)
return 'U';
else if(keypad_value < 290)
return 'D';
else if(keypad_value < 350)
return 'L';
else if(keypad_value < 400)
return 'S';
else if(keypad_value < 450)
return 'N';

}

void WaitBtnRelease()
{
  while( analogRead(keypad_pin) < 600){}
}

Doug, please give us the setup. Are there just 3 buttons with BUTTON1 selecting the MAINMENU and BUTTON2 scrolling UP the menu selected by BUTTON1 and BUTTON3 scrolling DOWN the menu selected by BUTTON1. And by pressing again BUTTON1,the selection is SET - as in the layout below:
BUTTON1 selects CURRENT from selections like VOLTAGE, CURRENT, AMPHR. BUTTON2 selects UPWARDS 100mA, 300mA, 500mA, 750mA, 1000mA
BUTTON3 selects DOWNWARDS 100mA, 300mA, 500mA, 750mA, 1000mA
Finally, PRESSING BUTTON1 fixes on the selection made by either BUTTON2 OR BUTTON3. We need to know how many buttons there are an

please give us the setup. Are there just 3 buttons with BUTTON1 selecting the MAINMENU and BUTTON2 scrolling UP the menu selected by BUTTON1 and BUTTON3 scrolling DOWN the menu selected by BUTTON1. And by pressing again BUTTON1,the selection is SET - as in the layout below: BUTTON1 selects CURRENT from selections like VOLTAGE, CURRENT, AMPHR. BUTTON2 selects UPWARDS 100mA, 300mA, 500mA, 750mA, 1000mA BUTTON3 selects DOWNWARDS 100mA, 300mA, 500mA, 750mA, 1000mA Finally, PRESSING BUTTON1 fixes on the selection made by either BUTTON2 OR BUTTON3.

We need to know how many buttons there are and what each button do, and which button FIXES the selection made. Thanks, George

Look to this section of the code " read buttons  " and you will see that I have listed the buttons used and their purpose..I have included the 6th button NULL to indicate that you can have more buttons than I have actually used (5) if required. Please read and study the code and comments as all the info you need is their. The final code is listed below and has the header containing "/ Rebuilt by Doug 07/02/2017 Australia." This is tested and works

Ok...nobody bought into this and I understand why...menus have been done to death, but not being one to quite I have answered my own question.
Here is a simple, fool proof button menu, that i think has NO limit in depth.
I have just tested this before posting, so if you don't get it to work, check your wiring. instructions at the bottom of the sketch.
    /* Rebuilt by Doug 07/02/2017 Australia.
 * This is a bare bones menu using buttons to navigate and select, there are no special libraries,
 * I am using an I2C LCD2004, but any display will work with minor mods. This has been translated from,
 * I believe Slovakian, that was fun, stripped down and modified for button control, I have found that
 * buttons are less picky than rotary encoders, even the good ones, just my experience.
 * I believe that I have removed all unnecessary script, but I may have missed some.
 * look at the last 2 --page()-- sections for instruction on extending down even further, I don't think
 * that there is a limit to how many levels you can have, how many do you really need.
 * The original sketch is from: Stanislav Petrek of Slovakia, you can find sketch on YouTube comments.
 * https://www.youtube.com/watch?v=gIP29m12wjQ&t=41s
 * Have fun with the translation  ;-}
 * The last thing I did before posting was to relaod and test this sketch, so it works.
 */
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

// menu system
int poz = 0; //  cursor position on actual page
int poz_max = 1;
int poz_min = 0;

int pozOld = 0;
int pozNew = 0;

int page = 0; //  actual page
int page_max = 1;
int page_min = 0;

int press = 0;
int press_max = 1;

int keypad_pin = A0;                      //analoge A0 to sense button values.
int keypad_value = 0;
int keypad_value_old = 0;

//bool menu2 = false;
char btn_push;
//****************************************************************setup*****************************************
void setup() {
Serial.begin(9600);
lcd.begin(20, 4);
lcd.clear();
lcd.home();
}
//************************************************************loop************************************************
void loop() {
MainmenuBtn();
if (btn_push == 'S') //enter selected menu
{
press++;
delay(250);
if (press > press_max) {
  press = 0;
}
}
// page select
switch (page) {

case 0:
  page0();
  break;
case 1:
  page1();
  break;
case 2:
  page2();
  break;
case 3:
  page3();
  break;
case 4:
  page4();
  break;
case 5:
  page5();
  break;
}
}
//****************************************************up/down************************************************
void MainmenuBtn()
{
btn_push = ReadKeypad();
WaitBtnRelease();
if (btn_push == 'U')
{
poz++;
if (poz > poz_max) {
  poz = poz_max;
}
}
else if (btn_push == 'D')
{
poz--;
if (poz < poz_min) {
  poz = poz_min;
}
}
pozNew = poz;
if (pozNew != pozOld) { //only update display when page change
pozOld = pozNew;
}
}
//*************************************************************read buttons***********************************
char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
*********************adjust these values to suit your keypad***********************
nul     >400
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);
if (keypad_value < 50)
return 'R';
else if (keypad_value < 190)
return 'D';
else if (keypad_value < 290)
return 'U';
else if (keypad_value < 350)
return 'L';
else if (keypad_value < 400)
return 'S';
else if (keypad_value > 400)
return 'N';
}
//********************************************************button release*************************************
void WaitBtnRelease()
{
while ( analogRead(keypad_pin) < 600) {}
}
//*******************************************************Front Page 0*******************************************
void page0() {
poz_min = 0;
poz_max = 3;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Pg1 Pg2 Pg3 Pg4     ");
lcd.setCursor(0, 2);
lcd.print("                    ");
lcd.setCursor(0, 3);
lcd.print("                    ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("---                 ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 1;
  }
  break;
case 1:
  lcd.setCursor(0, 1);
  lcd.print("    ---             ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 2;
  }
  break;
case 2:
  lcd.setCursor(0, 1);
  lcd.print("        ---         ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 3;
  }
  break;
case 3:
  lcd.setCursor(0, 1);
  lcd.print("            ---     ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 4;
  }
  break;
}
}
//*************************************************Pages 1*****************************************
void page1() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page1               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page1 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page1 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page1 Case2    exit ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 0;
  }
  break;
}
}
//*************************************************Pages 2*****************************************
void page2() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page2               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page2 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page2 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page2 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 1;
  }
  break;
}
}
//*************************************************Pages 3*****************************************
void page3() {
poz_min = 0;
poz_max = 2;
press_max = 1;
lcd.setCursor(0, 0);
lcd.print("Page3               ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case0         ");
  if (press == 1) {
    lcd.setCursor(0, 1);
    lcd.print("                    ");
    //navi();
  }
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 2;
  }
  break;
}
}
//*************************************************Pages 4*****************************************
void page4() {
poz_min = 0;
poz_max = 1;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page4               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page4 Case0  branch ");
  if (press == 1) {
    press = 0;
    page = 5;                                   //branches to page5() menu
    poz = 0;                                    //at position 0 on button 'S' press
    break;

  case 1:
    lcd.setCursor(0, 1);
    lcd.print("Page4 Case1  exit   ");
    if (press == 1) {
      press = 0;
      page = 0;
      poz = 3;
    }
    break;
  }
  }
}
//*************************************************Pages 5*****************************************
void page5() {
poz_min = 0;                      //see void MainmenuBtn()
poz_max = 1;                      //see void MainmenuBtn()
press_max = 1;                    //used when you have multiple selection within a section-increase number
                                  //see  original script for example
lcd.setCursor(0, 0);
lcd.print("Page5               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page5 Case0         ");
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page5 Case1  exit   ");
  if (press == 1) {                 //variable set to '1' when the 'S' key is pressed
    press = 0;
    page = 4;                         //this is the page() that you return to after the 'S' button is pressed
    poz = 1;                          //this is the 'case' number that you will return to for that page
  }
  break;
}
}

I have only inserted print statements where operational code can be placed, to keep it universally open. To reduce the size of the Global variables use the >>lcd.print(F("TEXT"));<< method, it works really well. Also works on Serial.print....Something for you to fiddle with.

I think that the reason why nobody tried this is that you did a huge work on your first example, so maybe someone (I admit, me too) postponed this because they had too few time at the moment. Anyway good job at actually writing a working version and thumbs up for your attitude. If your own answer successfully answers your question, mark it as accepted (when you can) so that everybody coming here will know that your code works

Thanks Mate...will do, but how do I mark as accepted???, never done it before.

What do you know, there is a HELP page up top...I have to wait 48 hours to accept...  ;-)   Update--have just about finished making a Menu with this and it is quite smooth once I got the hang of it..several levels deep. There actually is no practical limit to the depth. pleasantly surprised.

yes, you have to wait (that's to prevent some people from abusing this function to quickly gain reputation, I think). But.. Well, this is a perfectly legit case: you asked, nobody answered, you found a solution and shared it... Thank you for your effort :)

I am pretty new to all this but I cannot find a simple answer in your code. What pin numbers on the Arduino do I use to attach each button to? I am using standard everyday push buttons and a breadboard for this project. A0 is not enough for it to work. There has to be more to it. What am I missing?

The buttons are connected thru a resistor arrays to  a single analog input pin (hard to explain without a schematic). Each button result in a different voltage when pressed. So, reading the voltage you can know what button was pressed. Nice trick.

Deve, you are not missing anything, it was exactly as you read it.  Since you are pretty new I would look at a straight forward keypad that consumes 8 pins if I was you.  If you are short of space you can always put that though a GPIO Expander that is controlled by I2C.

Deve this link should explain how to set up the buttons    http://forum.arduino.cc/index.php?topic=8558.0


text:
What is the opposite of this data operation?
If I store in an array a double-value in this format, in which format I should be able to read the same double out?
double myDouble = 12.123456;
byte myArray[] = {0x00, 0x00, 0x00, 0x00};

myArray[0] = (myDouble >> 0);
myArray[1] = (myDouble >> 8);
myArray[2] = (myDouble >> 16);
myArray[3] = (myDouble >> 24);

Shifting a double? You don't really want to do that.

Please show the declarations of myArray and myDouble to show their exact type.

I edited the question.

You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.
Example:
  union
    {
    byte myArray [4];
    double myDouble;
    } foo;

   foo.myArray [0] = Serial.read ();
   foo.myArray [1] = Serial.read ();
   foo.myArray [2] = Serial.read ();
   foo.myArray [3] = Serial.read ();

   double f = foo.myDouble;

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, double and float are the same on the 8-bit Arduinos (they are only 4 bytes).

in the simplest form (compiler dependent however), a pointer will do.

Would you mind developing your answer further, so that we can clearly see how it really answers the OP question?


text:
Arduino audio frequency reader
I have a simple project for my arduino : light some leds when i send a certain frequency from my smartphone through the jack output . For example ,
 I play a simple audio file generated with a frequency generator (it generates sinwaves, sawtooth, quadrate waves...) at 1kHz --> a red led turns on
I play another frequency (5kHz) --> a green led turns on.
I read similar questions , but they needed a precise reading of the signal frequency, so they had to convert from AC to DC and from 700mV to 2,5V, is it necessary in my case ? I can also prepare a track with a program called audacity with the current remaining always positive but oscillating between 0 and 0,7 mV.
How can i realize my project in the simplest way possible ?
Thank you

It might be easier use a single frequency, and turning this 'sound' on and off in a certain pattern. E.g. sound on for a second is red, sound on for half a second is green.

With a relatively clean source like a direct connection, timing the zero crossings in software should be simple.  The main issue is that you need to build a network which turns the audio signal into a digital one, by biasing it to cross the threshold, ideally rapidly.  Some ideas to consider are utilizing the ATmega's built-in comparator pin, bias resistors and a DC block capacitor, or even using a tiny audio transformer to create a high impedance signal that rapidly swings across the full logic range, and then clip it to safe levels.  This is a problem that has been solved many times before.

@ChrisStratton,  do you have a link to this  “tiny audio transformer”?  I haven't been able to find any that are tiny.  Small, yes; eg EI14 Audio Transformer 1300 : 8 Ohm about 12 mm on a side; but tiny, no.

That is the kind of thing I meant, yes.  Compared to the radios of the era where it was used, it was tiny.  Congrats on even still finding one - they used to be all over the place, but with the change to class D IC amps they are mostly relegated to history... struggled to find even one to experiment with when I wanted to try mis-purposing one a few years ago.

Connect the signal to an analogue input on the Arduino, via a DC blocking capacitor, with a potential divider centring it around 2.5v.  Make sure the voltage swing is within range, which it should be.
Keep the frequencies of the signal low, under say 2KHz.  For example, use 500Hz, 1000Hz, 1500Hz, 2000Hz.
Sample (analogRead()) the signal as fast as you can (which is about 10KHz) for a short while, recording the min and max values.  From this, you can find the centre value, 1/4 value and 3/4 value.
Now to find your frequency, sample until the signal goes above the 3/4 value.  Get the time with micros().  Sample until the signal goes below 1/4, and then sample until it goes above 3/4 again and get the time with micros().  Do this a few times and average them.  The difference between the two times is approximately your sample period, so you can easily find the frequency.
Determine which of your chosen frequencies most closely matches the frequency you've sampled.

If you can properly bias your signal, say with a cap and a pot, you
could read it with a digital input. You can then time the rising edges
with micros(), either by polling the pin or using an interrupt. You
could achieve greater accuracy by using the “input capture” feature of a
16-bit timer, if you are using an AVR-based Arduino and are not afraid
of getting your hands dirty with low-level programming.
You need to get the right voltage range for this to work though. On an
Arduino Uno, for example, the thresholds for the input switching from
HIGH to LOW and back are typically around 2.1 and 2.6 V
respectively, so you must make sure that your signal amply covers this
range. If you can get 1 V peak to peak, that should be enough, and
you can then use the pot to tune the offset.


text:
ESP8266-12E and MCP23017 , unable to identify the application
After googling much I have found that MCP23017 can be used with esp8266-12e for more number of output pins.
I have tried all the programs from different tutorials on internet but could not make it work.
Basically my question is , i want to control all the 16 leds connected to GPA0-7 AND GPB0-7 individually , hence i need a program snippet for make it work.
I am using AP mode for esp8266-12e and sending get methods with params to identify which led to turn on/off.
Even i have written the basic program , can anyone help me completing the entire program. thanks for the help in advanced.
Pins i have connected are
ESP8266-12E    |   MCP23017
−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−
GPIO-14 (scl)  |  PIN-12 (SCL)
GPIO-2 (sda)   |  PIN 13 (SDA)
GND            |  A0,A1,A2

My code:
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void handleRoot() {
    server.send(200, "text/html", "
You are connected
");
}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);
    server.on("/", handleRoot);

    server.on("/led1", [](){});
    server.on("/led2", [](){});
    server.on("/led3", [](){});
    server.on("/led4", [](){});
    // up to 16 leds i have written same method.

    server.begin();
}

void loop() {
    server.handleClient();
}

You have an MCP23017 which connects to the device using the I2C protocol, which means you need the  library.  You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line.
You will then need to send commands to the device to initialise it and set the pins to OUTPUT.  (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).
When running you will need to update the state of this pins by sending messages such as  0x09 0xFF to turn them all on.
It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard.  You will be able to use an Arduino library on an ESP8266.
These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)

A very useful link and the description you have provided Matt.
I need to read and understand whats written in the docs and implement it. it will take time for me to do it. But thanks for the guidance. I think i will need more ahead.

hi , i tried to connect 4.7k and 22k resistors for sda , scl
sda --22k-- Vcc(+5v) And
scl --22k-- vcc(+5v)
but still not getting anything.
i have been trying to program this since a lot of days , but not be able to do it.
can u please help me more in this.
i am using this code in arduino
https://github.com/pedrominatel/esp8266-arduino-examples/blob/master/mcp23017/mcp23017_esp8266.cpp

the changes in this example i have done are line 152 : MCP23017_init(u8_MCP23017_address, 4,5);
i tried this too becuase in some datasheets it has 4=sda and 5=scl

any guidance please.

Step 1 Try using I2CScanner http://playground.arduino.cc/Main/I2cScanner rather than your own code to make sure that the hardware is functioning.  ESP pins number in the code do not match the pin number on the boards usually.  Find an image (on Google) of your ESP board with the pin numbers listed and use the GPIO_n numbers.

i tried 4 i2cscanner programs , but none of them are detecting the  i2c address. also tried to connect wires to different pins for trial and error , still not working.
please guide.

If I2CScanner can't find it you either have a circuit wiring problem, or faulty hardware.  Just use  the Arduino and MCP IC and minimal wires and 2 pull up resistors.

Wired whole thing again.
the result in i2c scanner i got is ;
I2C device found at address 0x38  !
whats next???

@KarmaCoding - Now you need to write a handler function for you on handlers to call.  You could do it from scratch http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/ or you could use a library https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library.  All you are doing is sending a one byte address and some data to the chip (using wire.write) and you should have flashing Leds in no time.  Once you get the hang of this you will understand just about all I2C devices.


text:
Flash a hex file to an MCU/Arduino over the air?
I have a processor AT328 , Arduino bootloaded, and a Bluetooth on the serial lines Tx,Rx .
I would like to program the chip over Bluetooth, not using a computer or IDE, but mobile phone with my own Hex uploader.
So, if the hex file was just a huge text that you have to send, i would obviously just send it and thats it, as I understand there is a mechanism ?
Question : How exactly a Hex file is sent over serial to program the chip ? is it like any other text file? is there any mechanism I have to write? specific baud rate? is there any article about this ?

with a phone, you can run the "AVR dude" application with STK500 emulation to send the hex file as a serial stream to an arduino chip which as the bootloader on it.

read up on how Arduino initiates the programming operation from the IDE - it literally just passes some data to "AVR dude" which runs on command line in Unix and Windows environments, and i'm sure runs on Android somehow

Do some research  and you'll find that this is either a solved problem, or a combination of individually solved ones, though not without issues that may be of concern.

I did research a lot. There is not even a single solution to this for iOS.

Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in the datasheet (and it's a really good datasheet, at that). If you're still up for it, read on.
Bootloader
The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.
The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.
(Note that you must program your chip normally at least once, to put the bootloader on it.)
One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:
Bluetooth
Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is non-trivial to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.
As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)
Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.
Bonus: Flashing
You are correct that a .hex file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is not simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has a nice tutorial on SPI.) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in an application note.
Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.

It is indeed a complex subject, but I believe if you look around you'll find the flashing Arduino type devices via a bluetooth module talking to the (or at least a) bootloader is a demonstrated capability, though I'm not sure I'd want to rely on it in comparison to a more thought-through OTA scheme.

@Ernest3.14 Thanks, you assume too many things, I think I know what SPI is because I am on my way to the third electrical engineering degree. I do not use a cheap module but a very good chip from a large company, and using ESP is pretty stupid, I don't even have enough space to start explaining why.

Awesome, I wasn't sure so I put it in just to be safe :P


text:
How to make the motor move after a certain period of time?
Basically I want my motor to run after let's say 10 seconds passed since the program started up.
The amount of time is determined by user input, and I have already coded for that. The motor is connected to a breadboard and powered by a 9v battery, also connected to the breadboard.
The thing is, the motor runs as soon as I connect it to the breadboard. How can I use the Arduino board to make the motor wait 10 seconds before it moves? I am new to both circuitry and code... Sorry for my cluelessness.
Thanks so much.

Please first post your current code so we have somethign to start from.

You will need to add a logic level mosfet of the appropriate size and specs to control the power to the motor.  You can drive the gate of the mosfet from a pin through a current limiting resistor with a larger bleed resistor.  For a brushed motor you'll need a ceramic RF supressor cap plus flyback diode for back EMF protection:

simulate this circuit – Schematic created using CircuitLab
For greater RF supression (if your motor is pretty beefy) you can use a 0.1uF between each input lead and the motor case.
When you turn the pin on, motor turns on, low turns off.  Using analog and appropriate R values you can control motor speed (setting 0-255):
int motorControl = [your pin];

void setup()
{
  pinMode(motorControl, OUTPUT);
}

void loop()
{
  delay(10000); // delay 10 seconds plus board boot time
  analogWrite(motorControl, 255); // turn motor on full
}

You can time the delay with a stop watch and adjust to be exactly 10s by dropping the delay() call to compensate for the boot up time of the board.
More about MOSFETS here:
https://electronics.stackexchange.com/questions/81935/mosfet-usage-and-p-vs-n-channel

Just a question: why the 220 Ohm resistor?

As mentioned several times, it serves to limit the current to protect the arduino when having to charge the capacitance of the MOSFET gate. The outputs expect something on the order of pF so trying to charge the nF capacitance overstresses.  Without the current limiting resistor, the arduino will eventually fail and likely take the MOSFET (and possibly other pieces) with it if the MOSFET goes linear and overheats.

I would recommend connecting the motor to a controller of some sort of a controller, maybe a relay or something like that, and then write some code that waits 10 seconds, and then turns on your controller / relay. That will turn on the motor.


text:
Arduino HC05 - AT commands won't respond
A little while ago i tried using AT commands on my HC05 bluetooth module using my arduino mega 2560 and it worked fine , skipping a few weeks ahead i tried doing the same , only now i suddenly doesn't work , i tried replacing the arduino and HC05 module , even used the same script for the commands. So i unplugged the module's VCC , pressed the button on the module , reconnected the VCC and the module was blinking every 2 seconds (it's in AT mode !) , now i go ahead to the serial monitor and using that script i typed the command i wanted to execute and it just didn't do nothing , i saw the serial LED on the arduino blink , but nothing was written in the serial monitor and nothing was changed in the arduino.
Does anyone know how to solve this ? it worked perfect before , but now it wont D:

Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.

Here's the solution!
First, you have to wire the board like the solution 2 in the instruction.
http://www.elecfreaks.com/wiki/index.php?title=Bluetooth_Shield
Then, Use this code!
/*********************************************************************
 **  Description:                                                    **
 **  This file is a sample code for your reference.                  **
 **                                                                  **
 **  Copyright (C) 2011 ElecFreaks Corp.                             **
 **  Created by ElecFreaks Robi.W /29 Sep 2011                      **
 **                                                                  **
 **  http://www.elecfreaks.com                                       **
 *********************************************************************/
void setup()
{
   Serial.begin(57600);
   Serial1.begin(38400);

}

void loop()
{
  int i = 0;
  char someChar[32] = {0};
  // when characters arrive over the serial port...
  if(Serial.available()) {
    Serial.print("------->  ");
    do{
      someChar[i++] = Serial.read();
      //As data trickles in from your serial port you are grabbing as much as you can,
      //but then when it runs out (as it will after a few bytes because the processor
  //is much faster than a 9600 baud device) you exit loop, which then
 // restarts,
  //and resets i to zero, and someChar to an empty array.So please be sure to keep this delay
      delay(3);
    }while (Serial.available() > 0);
    Serial1.println(someChar);
    Serial.println(someChar);
  }

  while(Serial1.available())
      Serial.print((char)Serial1.read());
}


text:
Working on my second project and I'm confused about proper procedure for turning on the arduino
The first project I did was just making the led blink (it was pulsing a signal to pin 13. I'm guessing most of you have seen similar tutorials).
Today I plugged in some wires and resistors and wrote a program for a volt meter.
How am I to stop the pulses on the output pins from my previous project from messing everything up in the newer project in that interval of time after plugging in the usb and before compiling/ uploading the new code?
The question occurred to me when I saw the led blinking from the last project, before I could hit the upload button... maybe I'm wrong, but I'm envisioning this causing problems for me in the future as my circuits become more and more complex.

Just upload a blank sketch (only void setup() {} void loop() {}) before you start.

If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch.  Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment.  Typically, Arduinos are reset at the beginning of each download.
Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset.  Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.

Someone voted this down, which is absolutely their prerogative, but I'm voting it up because it is a possible (if somewhat complex) solution. :)

@NickGammon, it's true that loading an empty sketch, or the new sketch, before attaching the new hardware is a better approach.  But if a board gets built in to controlled equipment before the old sketch is removed, powering it up not-reset  could be risky.  Is there a simpler approach than keeping the board reset?

The timing can be dodgy (you need to release reset fairly precisely) but I agree it is a viable solution, which is why I voted for it.

It is also a recommended solution for escaping from a sketch that has a watchdog timer set so quickly that the bootloader can't load.


text:
Using HC-12 radio on UNO or NANO without software serial
On the Arduino UNO and NANO with the serial port connected to an on-board device connected to a USB port, I can obviously send and receive messages to the serial console......now the question:
I have no idea how to use the serial port to send data elsewhere, specifically to an HC-12 radio type device that communicates serially. I cannot use a software serial port because of timing issues, so I need to use the HW port.
During development I expect to use the serial console for diagnostic messages, but I also need to use the port to send and receive data using the radio.
So, how does the handshake/protocol handle both the serial console in the IDE and something else, or better yet, can it handle sending OR receiving data to or from 2 devices at the same time?
Does anyone use the HC-12 type device using the one onboard serial port on an UNO or NANO?
Remember, the goal is to use the HW serial port to communicate with the HC-12 buy issuing Serial.print commands, which logically will also go to the serail console of the IDE.

So you want to design a protocol to exchange data on two devices? You will need a way do discriminate between them. If you can modify the bytes you can send 7 bits per byte (the standard ASCII values) and use the most significant to send the information of the stream you are using (e.g. if the bit is 1 you are using the HC-12, if it is 0 the debug). Then each program will ignore the wrong bytes. If you want to be able to view all the bytes in a serial monitor (so no modification allowed), then, you can force each message to be new-line-terminated and begin with a character. continue..

continue.. e.g. "D: Message content" is a debug message and "H: Message content" is a HC-12 message. Then you read the stream line by line and you will find the receiver reading the first bit. Just a side note: on both devices you will see what you are sending to both of them, i.e. the HC will see the debug and the serial monitor will see the HC, BUT the arduino will listen ONLY to the HC12. If this is an issue, you can put a 3-state buffer to block the HC-12, then enable or disable it with a pin. You will still receive the HC commands on the debug, but the other problems are solved.

The primary function is to send or receive HC-12 data, but the USB HW will obviously be connected to the same HW ports......simply put, if I send data to the radio, will it also be seen on the serial console through the USB?

I'd like to just use Serial.print commands to send data to the radio and the USB at the same time....no special or different protocol, just simple serial communications. The USB is only for debugging.

Well, as I said if you directly connect the TX of the HC to the RX of the arduino and the RX of the HC to the TX of the arduino you will get the following behavior: what you send through Serial.print or write will go to BOTH the debug console and the HC. What you receive through the HC12 will enter the arduino. What you receive from the debug console (i.e. what you type in the console) gets lost.If you want a different behavior, use a 3-state buffer. When it is enabled you get the previous behavior, when disabled you just send data to the serial console and receive from the serial console too.


text:
Having problems registering my SIM800 with the network
I have a SIM808, connected via hardware serial to an Arduino Mega. Communication between the Arduino and the SIM808 is fine. However, the quality of the signal is listed as 0 all the time. (AT+CSQ)
I've checked, and there is definitely 2G (and 3G) signal. Power is fine. SIM is unlocked, and works in other M2M equipment.
The network status lights blink rapidly (ie searching for a network) for about 5 seconds. Then it takes one long blink, then goes back to blinking rapidly.
The module is picking up the names of the available networks, yet does not seem to be able to register.
I'm using a prepaid data SIM card from Vodacom (South Africa).

I think you are not giving it enough power, SIM800 module needs 5v/2A stable power source in order to register to network. Try to use a desktop computer power supply it has 5v/2A output wire (refer to colors).

Actually the SIM800 should not be supplied with more than 4.4 V according to the datasheet.  I would be interested to know how this problem was resolved.
I have a similar problem.  I cannot get the SIM800 to connect to Three or the O2 network even though both SIMs work in my mobile phone.
In my case the SIM800 is connected directly to two 18650 Li-Ion batteries in parallel so I don't think it is lack of power.  Perhaps a big capacitor would help.  I will give it a try.  Failing that it might just have a much less adequate antenna and needs to be out in the open.


text:
Firmata C++ library for host?
Firmata seems to be a popular protocol for communicating between the Arduino and host computer. However, there only seems to be C/C++ libraries for the Arduino. Most Firmata libraries for the host appear to be in Python. I've found a few C/C++ Firmata libraries for the host, but they seem incomplete and unmaintained. Is anyone aware of a full-featured C++ Firmata library designed to run on the host computer?

Do you have an update or answer on this?  I am looking after the same

@JoseECalderon, No. I was researching this as part of a ROS project, but I ended up going with the rosserial_arduino package, which implements its own similar protocol.

openFrameworks appears to have this capability. It's written in C++.
From openFrameworks - Communication:

Arduino and other serial devices communication
The communication module has classes to communicate with other devices
  by now through the serial protocol. This mainly allows to communicate
  with devices like the Arduino. There's 2 classes in this module,
  ofSerial which allows to communicate with any device through the
  serial protocol. It can be used to send custom commands to for example
  an Arduino sketch that will receive them and do something in response
  like turn an LED on, move a motor... It also works the other way
  around, you can send messages from the Arduino (or any other serial
  device), for example the read from a temperature sensor to
  openFrameworks.
The second class, ofArduino, is specific to the arduino, it uses a
  protocol called firmata to send messages to and from the arduino that
  way you don't need to care about implementing the communication
  protocol from the Arduino sketch to openFrameworks and viceversa but
  instead you can just send and read values directly to and from any pin
  in the Arduino.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
No reply from GSM module
I have an arduino due sending and receiving data from a server using a GSM module (UBLOX SARA-U270). The issue I am having with it is that after a period of time working correctly the module stops replying or replies with random characters. It has been suggested to me that if I receive no reply to a command and continue to send commands it can cause issues like this and I need to take action before I send any more commands but I am unsure of what this action should be.
I was wondering is there a recommended action to be taken if I receive an empty response from an AT command to a GSM module after it has been previously working. I am currently working to find out the cause of the issue but I just wanted to know what should be done if an AT command that replies with nothing.
To try and correct this issue I have a function in place which if the module hasn't received data correctly for 1 minute will clear the modules setting using the AT+CFUN=1,1 command and resend all the setting to the module. My issue is that because the module is not replying, my AT+CFUN=1,1 command does nothing.  Physically removing the power to the module seems to be the only thing that will get it running correctly again.
And suggestions or advice would be greatly appreciated, Thanks guys.

Good question, I'm experiencing similar problems (different GSM module). My initial thoughts were something to do with the baud rate, however, tried various different options and same issue eventually happens. Second thought was then power, I've read on few occassions that if the correct power isn't supplied then it can cause undesirable behaviour.

Hi James, I think the most important thing, with regards to these modules is to pay close attention to the timeouts for each command. Ensure that you don't send any other commands to the module until you either receive a reply to the last command or have waited the full timeout for the sent command. I rewrote my code paying close attention to this and had much more success.


text:
Power save Sleep Mode Arduino
I'm trying to use this example link
source:
#include <avr/sleep.h>

/* Sleep Demo Serial
 * -----------------
 * Example code to demonstrate the sleep functions in an Arduino.
 *
 * use a resistor between RX and pin2. By default RX is pulled up to 5V
 * therefore, we can use a sequence of Serial data forcing RX to 0, what
 * will make pin2 go LOW activating INT0 external interrupt, bringing
 * the MCU back to life
 *
 * there is also a time counter that will put the MCU to sleep after 10 secs
 *
 * NOTE: when coming back from POWER-DOWN mode, it takes a bit
 *       until the system is functional at 100%!! (typically <1sec)
 *
 * Copyright (C) 2006 MacSimski 2006-12-30
 * Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

int wakePin = 2;                 // pin used for waking up
int sleepStatus = 0;             // variable to store a request for sleep
int count = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  pinMode(wakePin, INPUT);

  Serial.begin(9600);

  /* Now it is time to enable an interrupt. In the function call
   * attachInterrupt(A, B, C)
   * A   can be either 0 or 1 for interrupts on pin 2 or 3.
   *
   * B   Name of a function you want to execute while in interrupt A.
   *
   * C   Trigger mode of the interrupt pin. can be:
   *             LOW        a low level trigger
   *             CHANGE     a change in level trigger
   *             RISING     a rising edge of a level trigger
   *             FALLING    a falling edge of a level trigger
   *
   * In all but the IDLE sleep modes only LOW can be used.
   */

  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                      // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
    /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     * there is a list of sleep modes which explains which clocks and
     * wake up sources are available in which sleep mode.
     *
     * In the avr/sleep.h file, the call names of these sleep modes are to be found:
     *
     * The 5 different modes are:
     *     SLEEP_MODE_IDLE         -the least power savings
     *     SLEEP_MODE_ADC
     *     SLEEP_MODE_PWR_SAVE
     *     SLEEP_MODE_STANDBY
     *     SLEEP_MODE_PWR_DOWN     -the most power savings
     *
     * For now, we want as much power savings as possible, so we
     * choose the according
     * sleep mode: SLEEP_MODE_PWR_DOWN
     *
     */
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    /* Now it is time to enable an interrupt. We do it here so an
     * accidentally pushed interrupt button doesn't interrupt
     * our running program. if you want to be able to run
     * interrupt code besides the sleep function, place it in
     * setup() for example.
     *
     * In the function call attachInterrupt(A, B, C)
     * A   can be either 0 or 1 for interrupts on pin 2 or 3.
     *
     * B   Name of a function you want to execute at interrupt for A.
     *
     * C   Trigger mode of the interrupt pin. can be:
     *             LOW        a low level triggers
     *             CHANGE     a change in level triggers
     *             RISING     a rising edge of a level triggers
     *             FALLING    a falling edge of a level triggers
     *
     * In all but the IDLE sleep modes only LOW can be used.
     */

    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{
  // display information about the counter
  Serial.print("Awake for ");
  Serial.print(count);
  Serial.println("sec");
  count++;
  delay(1000);                           // waits for a second

  // compute the serial input
  if (Serial.available()) {
    int val = Serial.read();
    if (val == 'S') {
      Serial.println("Serial: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
    }
    if (val == 'A') {
      Serial.println("Hola Caracola"); // classic dummy message
    }
  }

  // check if it should go to sleep because of time
  if (count >= 10) {
      Serial.println("Timer: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
  }
}

I'm using a Tester for test really efficient of power saving; I read only a power save of 2 mA. Is it possible the Arduino Mega saves only that in sleep mode? Or am I doing something wrong?

You need a bare ATmega chip if you want to go low power. Otherwise you are continuously powering the 16U2 serial–USB bridge, the 3.3 V regulator and the power LED.

how i can shut down the serial usb Bridge , the 3,3 regulator and led power?

By unsoldering them, or cutting their traces.

I have a page about power saving. About the first suggestion on that page is to not use an Arduino "board" (particularly one with a USB interface chip, power LED and voltage regulator). They all take power - a lot of it. These boards are designed for prototyping, not low-power use in the field.
Something like this would be better:

Of course, that isn't an Atmega2560 chip. They only come in surface-mount and will be hard to solder yourself. You may be able to get an Atmega2560 board in minimal form. Or downgrade to a smaller processor that you can assemble yourself. The Atmega644P comes in PDIP which is easy enough to work with.
If you don't need all that RAM and program memory, you could go down to an Atmega328P which are easy to work with and can get down to 100 nA power consumption under the right circumstances.

You could conceivably do what Edgar Bonet suggested and cut traces on your Mega2560 board, but be warned that if you do that you won't be able to program the board via the USB interface afterwards. You can still program via the ICSP socket however, if you have a suitable programmer.

What are you using as resonator there?

This one - I can't remember where I got it from.

The Arduino Uno has a resonator on it for the main chip (not a crystal) so using a resonator is fine.

Nice information. What are you using as resonator there? The only one I know is using xtal+2cap

See amended answer.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How do I go from modules to PCB?
For my engineering class, I am designing a digital scale.  I have already made a working proof-of-concept by using jumper wires to connect several arduino modules to an Arduino UNO.
I want to make a PCB to simplify the design, and not just have a mess of arduino modules.  I want the design to be flat and small, so I need to make a custom PCB, integrating each module onto the board.  Say I'm not using a protoboard, but sending it to a company to get it custom manufactured.  This PCB would use through-hole components, and not SMD.
I am trying to build the eagle files for the PCB.  I have rounded up the SCH file for each arduino module, and the arduino itself.
I am trying to make this PCB in the easiest and fastest way possible.
Should I just copy and paste, and connect the modules' SCH files into one big SCH file?  Then create a BRD file to create the proper footprints and holes?
Thanks

You can probably start by removing all the stuff you don't need: pin headers, the ATmega16U2 (if you can use an ISP), the 3.3V regulator (if you use 5V logic), ...

Yes, avoid copy-pasting everything, since there are a lot of unnecessary components. See what you need from the original schematics, then insert them and, in the end, make the BRD. And... Personally I prefer SMD components (down to a 1mm pitch is easy to hand-solder them, and with a bit of manual skills and flux you can go down to 0.5mm pitch with common tools)

That's a great way to start. But it would be a good idea to try and understand what all the different components are doing. Also look at the layout of the originals. For example, you can see that the crystal for the ATMega is pretty close to the chip itself. Also sprinkle some extra capacitor footprints. If you get some intermittent problems adding some bypass capacitors can often fix things.


text:
On extending scrolling 8x8 bitmap to 32x32 or 32x64 (see clip)
I am using an Adafruit 64x32 RGB LED panel with my Arduino Mega 2560. I tried to find/construct working examples of a 32x32 or wider scrolling text/bitmap but have failed.
The smaller version is working and is calling two functions for it to implement:
loadSprite(IMAGES2,60);
bildmittig_sprite(data,dpink,300);

IMAGES2 is of type const PROGMEM byte IMAGES2[][8] and is an array
of several 8x8 bitmaps
data is a buffer data array element,    containing the dynamic
movement of bitmaps, called in the void loop()

For the whole code here. For the video clip smaller scroller here.
For the video clip to what I would like to extend to:

 Russian Letters: http://dropbox.com/s/n2ilxqgubn83ii9/MOV_0056.mp4?dl=0
 Or Chinese Letters: http://dropbox.com/s/9rad116adc575u1/MOV_0057.mp4?dl=0

loadSprite() looks like this:
void loadSprite(const PROGMEM byte bild[][8],int anzahl) {
  for(int row=0; row < 8; row++) {
    //iterate through each row
    data[row] = 0;
    //reset the row we're working on
    for(int column=0; column < 8; column++) {
      //iterate through each column
      data[row] = data[row] + ((powers[column] & (pgm_read_byte(&(bild[index][row])) << offset)));
      //loads the current charachter offset by offset pixels
      data[row] = data[row] + (powers[column] & (pgm_read_byte(&(bild[index+1][row])) >> (8-offset)));
      //loads the next charachter offset by offset pixels
    }
  }
  offset++;
  //increment the offset by one row
  if(offset==8){offset = 0; index++; if(index==anzahl){index=0;}}
  //if offset is 8 load the next character pair for the next time through
}

The displaying function (places it i the middle of 32x32 panel) like this:
void bildmittig_sprite (byte bild[8],word cchsv, int duration) {
  for(int i = 0; i <8; i++) {
    for(int ii = 0; ii<8; ii++) {
      int bit = (bild[i] >> ii) & 1;
      if(bit == 0) {
        matrix.drawPixel(7-ii+12, 12+i, black);
      } else {
        matrix.drawPixel(7-ii+12, 12+i, cchsv);
      }
    }
  }
  delay(duration);
}

Working for 8x8 bitmaps, It eludes me how I could possible extend the coding (scrolling) for bitmaps like this:
const PROGMEM unsigned char rus5[] = {
  0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0xff, 0x03,
  0x00, 0x00, 0x78, 0x00,
  0x00, 0x00, 0x38, 0x00,
  0x00, 0x00, 0x3c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1e, 0x00,
  0x00, 0xfc, 0xde, 0x0f,
  0x00, 0x8f, 0xef, 0x1f,
  0x80, 0x07, 0x3f, 0x3c,
  0xc0, 0x03, 0x0f, 0x3c,
  0xe0, 0x01, 0x0f, 0x3c,
  0xe0, 0x01, 0x07, 0x3c,
  0xf0, 0x80, 0x07, 0x3c,
  0xf0, 0x80, 0x03, 0x3c,
  0x70, 0x80, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x0f,
  0x78, 0xe0, 0x01, 0x0f,
  0x78, 0xf0, 0x81, 0x07,
  0xf0, 0xf8, 0xc3, 0x03,
  0xf0, 0xef, 0xf6, 0x01,
  0xe0, 0xf7, 0x7c, 0x00,
  0x00, 0xf0, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x80, 0xff, 0x03, 0x00,
  0x00, 0x00, 0x00, 0x00
};

I tried variants of concatenation, like:

4 bytes as a row, stitching together several with beforehand created
data (data1 ... data4) elements (also adjust coherence for vertical elements).
And then have them displayed at the correct place to be able to use
the existing code but so far only vertical concatenation seemed to
work briefly.

I am at the end of my wits for this project, but maybe somebody else sees a better way.

I've looked at your code briefly, long enough to get the impression that each array like rus5[] contains 32 groups of 4 bytes each, with each 4-byte group representing a row of a character.  [If not, let me know.]  Also, I read the question a time or two, but don't see specified what direction you want to scroll, and whether you will scroll a string of characters or just one character.  Anyhow, in following I suppose you want to scroll a string horizontally with characters entering at the right end of the display and scrolling off the left end.
To support horizontal scrolling, arrange your bit maps such that each group of 4 bytes represents the 32 bits of a single column of the display.  Regarding four bytes as an unsigned long, suppose the LSB (least significant bit) corresponds to the top LED in a column.  Use code like the following to set pixels, supposing cn = current column number; d = number of character columns already scrolled off, in range 0 to 31; maxCol = number of display columns; and t[] is a three-character string corresponding to three characters currently on the 64x32 display.  [That is, a right-hand part of t[0] is at the left end of display; then all of t[1] appears; then a left-hand part of t[2].]  [Generally, where this sets cc=0, you would set it to point at a current-character in a longer string, instead of at the first character in a three-character array t[]; and would advance one character each time d gets up to 32.]
cc = 0;     // index of first character to display
c = t[cc];  // first character to display
e = d;      // how far we have scrolled so far
for (cn=0; cn<maxCol; ++cn) {
  unsigned long colData = pgm_read_dword(charData[c][e]);
  for (ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    c = t[++cc];  // Set c to next character
    e = 0;        // Start with leftmost col of character
  }
}

Edit 1: In the code above, charData[c][e] is an unsigned long int.  Its 32 bits represent column e of ascii character c, with the LSB representing the top-row pixel.  To create charData[][], write a program on your development system that reads whatever bitmaps you have now and writes out code to properly set up charData[][] in ProgMem.
Note, for initial scroll-testing, you could skip writing a development-system program to re-orient characters and instead test with character-data arrays as they are.  Characters might display sideways or upside down, but would scroll ok anyway.  Or, if bytes are not in proper Endianness to be an unsigned long, they would display in four mis-ordered slices.
Edit 2 With the following code,
void  scroller (const PROGMEM byte bildo1[][4],const PROGMEM byte bildo2[][4],int maxCol, word cchsv) {

int d = 0;
int cc = 0;
unsigned long c[32];

for(int ii=0;ii<32;ii++) {
  c[ii]=0;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][0]))<< 24;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][1]))<< 16;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][2]))<< 8;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][3]));
}
int e = d;      // how far we have scrolled so far
for (int cn=0; cn<maxCol; ++cn) {
  unsigned long colData = c[e];
  for (int ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    for(int ii=0;ii<32;ii++) {
      c[ii]=0;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]))<< 24;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 16;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 8;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]));
    }
    e = 0;        // Start with leftmost col of character
  }
}}

chrisoutwright reports getting an image like the following [cropped from a larger dropbox.com image]:

Cutting this into 4 equal-size horizontal slices and swapping slices top to bottom, we get:
That image suggests packing the bytes in reverse order, eg via
c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]));
c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 8;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 16;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]))<< 24;

Continuing on, if we rotate the left half of the above 90° then flip the rotated image left to right we get a reasonable facsimile of the letter 春 :

The "flip left to right" amounts to reading bits out MSB first instead of LSB first.  During testing, one might do that by saying
matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1;

instead of
matrix.drawPixel(cn, ro, (colData&1)? cchsv : black); colData >>= 1;

but in the longer run, a development-system program should be used to re-orient characters instead of using up MCU memory space and time for bitmap organizing.

To make the characters scroll, add a parameter (eg, byte escroll) to the calling sequence.  Discard variable d if it isn't used within scroller, and instead of initializing e to d (which is always zero hence does not allow for scrolling) initialize it via
e = escroll;

In the routine that calls scroller(), say something like
byte es=0;
while (scrolling) {
  scroller(bildo1, bildo2, maxCol, cchsv, es);
  delay(msPerScrollStep);
  ++es;
  if (es >= 32) {
    es = 0;
    // do stuff here about next characters to display
  }
}

That is, call scroller() within a scroll-timing loop (or perhaps put the timing into scroller(), whichever meshes better with overall design).
Note, with the code as it stands, plus suggested changes, bildo2 will scroll in a second time1 unless a third character is supplied to scroll in.
1For example, with maxCol of 64, if es is 16, whenscroller() is called, e will go from 16 to 31 displaying the second half of bildo1, then from 0 to 31 displaying all of bildo2, then from 0 to 15 displaying the front half of bildo2.

I have taken a brief look at the code above. How is charData[c][e] defined exactly?
Also is it true that one would not see a combination of "bitmaps" with the code above, as the column-scanning needs finishing the first letter?
Nevertheless I will have a go with it as soon as I am at the working table.
Thank you very much so far jwpat7

@chrisoutwright, see edit 1.   The code shown displays characters adjacently as it scrolls them across, so portions of first and third characters show up, plus all of the middle, 1-2-3 left to right.  If you need a blank column between chars, do that within the “Done with current character” section.

at jwpat7, would you mind to integrate the code into a callable function?
I tried it myself but am getting invalid types when trying to obviate the charData[c][e] step (can I use a pointer variable to store rus5[]  and others together to get something like the mentioned  t[cc] ?)

I suppose, for testing purposes only testing two bitmap[32][4], such a function  would not work?

In that code the type of c[][] isn't shown, but probably should instead be unsigned long c[32], with the loop that loads c something like for(int j=0; j<32; ++j) { c[j]=0;     for(int i=0; i<4; ++i) {                               c[j] = (c[j]<<8) | pgm_read_byte(&(bildo1[j][i]));}} (if I correctly understand bildo1) and if an endianness problem occurs, try bildo1[j][4-i] instead.

I have re-uploaded another version of the code in the link above.
Now the letter 春 (being used twice and rotated is from my side), looks like this, with no scrolling sadly. What did happen exactly?

thank you for the excellent explanation in the edit2. Apart from the flipping matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1; The scrolling works now. Only the speed is a bit slow, (end-version) when the delay is set to minimum, it might be because of the many loops or else.

I finished to soon my scrolling test. In this Version the scrolling is stopped intentionally at 32 (so one letter) everything beyond, the output is jumbled till the beginning cycle. Any ideas on how to remedy that last bit? I think speed issues arise naturally in this sort of programming.

Let us continue this discussion in chat.


text:
Arduino Mega + ESP8266 - Post Data to website issue
I'm trying to post data to my SQL database and it seems that I'm not sending the data correctly. My PHP file is working since I have tried it and it writes to the database.
I am getting an esp.find("SEND OK") but I must be sending it wrong or something.
Here is the code:
DT 0050 - GLASSES - from sun to sound - chk oil filter malibu old or new?
void loop() {
    // call sensors.requestTemperatures() to issue a global temperature
    // request to all devices on the bus
    Serial.print(" Requesting temperatures...");
    sensors.requestTemperatures();  // Send the command to get temperatures
    char tempC = sensors.getTempCByIndex(0);
    char buffer[10];
    Serial.println("DONE");
    Serial.print("Temperature for Device 1 is: ");
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire
    Serial.print(sensors.getTempCByIndex(0));   // "byIndex"
    delay(5000);
    data = "temperature=" + tempC;  // d
    httppost();
    delay(1000);
}

void httppost() {
    esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");   //start a TCP connection.
    if (esp.find("OK")) {
       Serial.println("\r\nTCP connection ready");
    }
    delay(1000);
    String postRequest =
        "POST /http://manilla.technoaid.net/esp8266.php HTTP/1.1\r\n"
        "Host: 66.96.134.25\r\n" "User-Agent: Arduino/1.0\r\n"
        "Connection: close\r\n"
        "Content-Type: application/x-www-form-urlencoded\r\n"
        "Content-Length: \r\n" "data";
    **String sendCmd = "AT+CIPSEND=";
    esp.print(sendCmd);
    esp.println(postRequest.length());
    delay(1000);
    if (esp.find(">")) {
        Serial.println("Sending..");
        esp.print(postRequest);
        if (esp.find("SEND OK")) {
            Serial.println("Packet sent");
            while (esp.available()) {
                String tmpResp = esp.readString();
                Serial.println(tmpResp);
            }
            // close the connection
            esp.println("AT+CIPCLOSE");
        }
    }
}

Your **String and your empty Content-Length look suspicious. Also, there should ne \r\n\r\n between the headers and the actual data.


text:
Run different code on different type of reset in arduino nano
I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this.
I have 2 leds and my nano... Along with the laptop and any other necessary components.

The MCUSR register (page 79 of the datasheet) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:
if (MCUSR & (1 << 0)) { // POR
    digitalWrite(4, HIGH);
} else if (MCUSR & (1 << 1)) { // External Reset
    digitalWrite(5, HIGH);
}

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.

Note that the information in MCUSR is lost on boards running optiboot, such as Uno. Luckily the standard bootloader on the Nano doesn't do this so it likely won't be an issue in this case but it's worth mentioning because it's common for people to burn the optiboot bootloader to Nanos as it's otherwise far superior to the stock one.

If the usb-to-serial is actually resetting the MCU right after power-up, you could try using the PORF bit in the MCUSR. When first power-on, this bit is set. If you clear this bit, and then press the reset button, this bit will still be 0 when the sketch start again.


text:
How do I "conditionally" include libraries and declare global objects of them?
I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries.  After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.
Example:
const bool useLCD = true;

...

#if (useLCD)
  #include "NHD_4x20.h"
  NHD_4x20 lcd(9);
#endif

These statements are before the setup() and loop() functions.  This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.
Is there some simple trick to accomplish this that I'm overlooking here ?
Thanks in advance !

Please take also note before version 1.6.6/1.6.7 preprocessor conditionals were very sketchy.

const bool useLCD = true;

should be:
#define useLCD 1

Here is a complete working example of how to use preprocessor macros for conditional compilation:
#define USE_A 1
// #define USE_B 1

#if (USE_A)
int a = 4;
#endif

#if (USE_B)
int b = 6;
#endif

void setup() {
    Serial.begin(115200);
    Serial.print(F("The result is: "));
#if (USE_A)
    Serial.println(a * 2);
#endif
#if (USE_B)
    Serial.println(b * 2);
#endif
}

void loop() {
}

Thanks, Majenko.
Just tried it...  Same "has not been defined" error.

Sorry, Manjenko !  Had a typo !!  Worked !!  Thanks a lot !!

That's OK then :) I just posted an example as well.


text:
Inputting list of data
Sorry if this question has been asked but I can't seem to find an answer because I don't really know if I'm phrasing the question correctly.
I'm trying to control a grid of LED to light up in a specific sequence that is based on a long list of data (and loops over time). Is there any way to bring in the data automatically? (vs individually coding the digitalWrites and delays) I think I found a reference project a few days ago but I lost it.
Thanks!

Your question is too vague to answer in detail, but in broad terms, probably yes.

Google for loops and arrays - that should get you started.

Your question is vague so I have made some assumptions, I hope they are right.
The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.
You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy).
You are asking is there an alternative to doing this:
// Step 1
digitalWrite (LED1, HIGH);
digitalWrite (LED4, HIGH);
digitalWrite (LED8, HIGH);
delay (100);
digitalWrite (LED1, LOW);
digitalWrite (LED4, LOW);
digitalWrite (LED8, LOW);
// Step 2
// And so on...

Yes there are, and there are many, I think this is probably going to be the easiest to start with.
Coding the data in a 2D array.
An array is a fixed length list of values of the same type.  One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.
#define LED0 2
#define LED1 3
// and so on

Alternative array version
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

I have declared the array as const because the values in it aren't going to change.  The array is going to hold integers (because that's what digitalWrite() takes as a pin number) and there are 9 of them.  Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.
So how does this help you?  Well you can define an array of 'steps' and each step has a list of which LEDs are switched on.  As your code loops through the steps it turns the specified LEDs, waits and then turns them off.  The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step).  I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino.  Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.
const bool theSteps[MaxSteps][MaxLEDs] =
{
    {false, false, false, false, false, false, false, false, false}
  , {false, true , false, false, true , false, true , false, false}
  , {false, false, true , true , false, false, false, true , false}
  , {true , false, false, false, false, true , true , false, false}
};

You still have to code the data within the program, but its much smaller
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

const bool theSteps[MaxSteps][MaxLEDs] =
{
    { false, false, false, false, false, false, false, false, false }
    ,{ false, true , false, false, true , false, true , false, false }
    ,{ false, false, true , true , false, false, false, true , false }
    ,{ true , false, false, false, false, true , true , false, false }
};

#define StepDelay 100

void setup()
{
}

void loop()
{
    for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
    {
        for (int step = 0; step < MaxSteps; ++step)
        {
            for (int led = 0; led < MaxLEDs; ++led)
            {
                if (theSteps[step][led])  // If the LED should be on
                {
                    digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
                }
            }
        }
        if (onOff < 1)
            {
                  delay(StepDelay);
            }
    }
}

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.

Thanks! I forgot about arrays because I haven't coded in a while... I'm still fiddling with the code because I'm actually trying to do 3 separate arrays of data that shifts/scrolls across one direction (step++ at the end of each loop and shifting the array for each set of data) but I think I've almost got it.


text:
Arduino library making
I make my own library for arduino.
The file structure is like below.
AAA - README.md
    - examples - A - A.ino
               - B - B.ino
    - AAA.h
    - BBB.h
    - CCC.h
    - BBB.cpp
    - CCC.cpp

It works well. But I want to grouping a library source files like below.
AAA - same as above
    - src - AAA.h
          - BBB.h
          - CCC.h
          - BBB.cpp
          - CCC.cpp

It doesn't work at all.
Arduino IDE shows the message

Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?

I'm going to assume your library structure is like this because the structure you described above would not cause that error:
AAA
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the 1.5 library format. Putting all the source files in the src subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:
AAA
|_library.properties
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp