text:
How to add data without pre-defining variables?
I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.
What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello w, your ID number is xxx xxx xxx xxx xxx.
So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?
Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

This would be an array of structs, plus storage space for all the names.

Array of structs? Could you please explain? I'm still only intermediate at programming.

Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.
As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

For those who don't know
In C, data relevant to an object can be stored in a structure, or struct. You can put all sorts of different types of data in a struct, like so:
struct personalProfile {
    char    firstName[8];
    char    lastName[8];
    uint    cardID;           // 'uint' is an unsigned int...
    bool    accessAllowed;
};

You can then use that structure to create a 'personal profile' for however many people you want:
// within your main program:

struct personalProfile Person1;
struct personalProfile Person2;

// Now you can directly access individual aspects as so:

Person1.firstName = "John";
Person1.lastName = "Brown";
Person1.accessAllowed = TRUE;

Person2.firstName = "Dodgy";
Person2.lastName = "Dave";
Person2.accessAllowed = NOT_A_HOPE_IN_HELL;

You can use the members of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.
The best way to store multiple instances of a particular variable type is in an array:
struct personalProfile listOfPeople[5];

You now have an array of five (blank) structs, which can be accessed by listOfPeople[n].firstName = Potato;, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.
An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five structs in it you can't add or remove any. One solution is to create a massive array, and set all the values in each struct to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.
Next comes containers. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

EEPROM basics
The EEPROM library that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.
Using the function EEPROM.put(address, data) you can put ANY data type - an int, char or - you guessed it - a struct into the EEPROM, starting at the byte specified by address. Of course there has to be enough space so you can't put an int, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)
So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.
// within main program

struct personalProfile Person1;
struct personalProfile Person2;

// fill in the details for Person 1...
// fill in the details for Person 2...

// ...then put Person1 in the EEPROM at address 0.
EEPROM.put(0, Person1);

// Done. Now put in Person2. But where?
// You need to make sure you put them AFTER Person1.

int AddressJump = sizeof(personalProfile);

// AddressJump now equals how many bytes are need to store one person.

EEPROM.put(AddressJump, Person2);

Simple as that.
If you create a Person3, you're going to need to put them sizeof(personalProfile) bytes AFTER Person2, i.e. EEPROM.put(AddressJump*2, Person3);. So, you add PersonN to address AddressJump * (N-1).
Retrieving data is the same principle, except you use EEPROM.get():
// provided you've used the above snippet somewhere to actually
// populate the EEPROM with something!

struct personalProfile personA;

EEPROM.get(0, personA);

Serial.print("Person A is called:");
Serial.println(personA.firstName);

Again, you're going to need sizeof(personalProfile) to read the second, third, or Nth person. If you 'send EEPROM.get() to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't put one person on top of another (you could get in trouble for that) and you don't want to get someone that isn't there.

List management
This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.
Your first task is to determine what sort of array you want. Inevitably it's going to be a Linked List. This is an array of structs, where each struct element in the list contains the memory address of the following element, thus the list is linked. You need to consider:

How the array will be linked (if at all);
Whether or not the array is space-critical (does it have to be as small as possible);
Where the array is going to start;
How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!

WOW! a lot of info here. Love it. I have dealt with class/objects in JS and Python, but never knew about Structs in C. The only thing that I am fairly concern about is would I have to create each object by hand? because that is what I am trying to get around. I understand the storing part of them and pushing them to the EEPROM, and indexing them to reference, but it is more on the creation part that I am getting hung up on. Such as sally scanning her RFID card, enter her name, the objects are then automatically created under that class, and stored after that. So far, it's looking like...

I will have to use arrays with just the raw data and indexing. which I do not mind. But thank you for the tutorial on Structs, and the references. Also, Why can the EEPROM only be used 10k times?

@TL140 As part of your 'list management' you write a function for adding new entries. When it begins you create a new structure struct personalProfile NewEntry then fill in the details how you like, i.e. the name fields are typed in by Sally herself and the card details are automatically entered from the RFID reader. Call EEPROM.put() which copies the data from NewEntry, byte for byte, into the EEPROM. When your add-new-entries function finishes, NewEntry falls out of scope (it gets forgotten about, rather then strictly deleted), but the version in the EEPROM remains forever.

And as to why EEPROM has limited write-cycles: Google it! It's related to the way that data is stored so that its integrity remains once you remove power to it. As with everything, it's a trade-off between features.

Awesome! I think im catching on little by little. Still foggy on structs but they are a new concept for a new language so I'll just need to practice. I'll probably use a big array to simulate the EEPROM since I dont want to ruin my board's. I'm guessing I should also store a pointer in the EEPROM to reference my list? or is there a way i can read my EEPROM and see just how much space is already stored in it, then use that? Because, wouldn't updating that counter every time a card was read ruin my EEPROM pretty fast?

Wait a second: do you realise how much 100,000 is? Unless you're really trying you'll never reach that high! And don't forget it's write cycles; reading it is unlimited. To further convince you that it's OK, the EEPROM.put() function calls a sub-function called EEPROM.update(), which is a magic function that only writes a value to an address if the existing value is different. If your loop() function contains only one line: EEPROM.put(0, "Relax, TL140");, you could run your Arduino forever, and restart it to your hearts content, and the EEPROM would only ever be written to once.

I'll come back to my answer later (it's 2am) and start on some list-management explanations, with reduced EEPROM-write dependencies. Your board will be safe, I promise!

I see! I was under the misconception that it wrote a new value to it each time, so that if I accidentally coded an infinite for loop (I may be an intermediate level programmer, but I know way better than this! just using the worse case scenario.), 100,000 cycles that the code runs would burn out the EEPROM in minutes. Now I know that it doesn't work that way. I appreciate all your help! Thank you a ton!

@TL140: As you've chosen an answer (which wasn't mine!) I shalln't continue with my answer. If you need further assistance, perhaps start a new question with your specific problem.

@TL140 Now I feel somewhat guilty, I didn't mean to demand my answer be chosen. I recommend you search for information on the Arduino library EEPROMex. It's an extension for the standard EEPROM library and I think it will explain all manner of aspects of correctly and efficiently utilising the EEPROM. I've only just found it, and it looks pretty ace.

Both of the answers are very good and you have helped me a lot more. I tossed up between which one to pick and honestly yours is the better pick because most of my questions have been answered.I mainly voted his because it has one upvote and im too low rep to upvote yours. Still new to SE so im not sure how it works in its entirety.

The "key" is creating a means to access a table of IDs that you can search through for a given name or a given ID number. There are various ways of doing this and if you are unclear on these that can be discussed in due course. But, to start, I'll assume that making and searching some form of table or array is not a problem for you.
You obviously MUST have enough storage space for the maximum number of simultaneous IDS that you wish to store at any time. Call this "IDCount".
You can allocate IDCount ID storage locations by whatever means suits you.
In unused locations you store a dummy or null ID number.
eg ID 000 000 000 000 000 is probably invalid so can be used as an 'empty' indicator.
To add a new ID  either search through your table of IDs for an empty location and store the new ID there. To find a given ID match you search the table for the ID and , if it exists, retrieve the matching name.

"Improvements":
To reduce access times when the potential entries are large you can store all entries "at the bottom" and have a pointer to the 1st free location. New entries are added "at the end". If an entry is removed, all entries above it are moved down by one. eg   if entry N is removed:
for (entry >= N and entry < end_pointer)
...move entry N + 1 into location N
...and step N by 1.
Another method is to use a "linked list" where each entry has a pointer to the next entry in the list. New entries take an address from the empty_locations list and add their address to the used_locations list. Removed entries do the opposite. This can be fast and effective but also mind blowing for beginners and, when it goes wrong it can go VERY wrong. Best avoided initially.
The simple "search for 1st empty entry" method will usually work very well.

So breaking it down, I basically have to create an array, give it a definite storage value, use a for loop to fill everything with a null value, and then fill in accordingly using a checker to see if the data is != said null value? Seems fairly simple. Now what about the pairs of data? Should I nest the array? how would I go about using a lookup in a multi dimensional array?

@TL140 You can use a two dimensional array or if it suits use two arrays of the same size (number of entries)) but one dimensioned for names and the other for IDs as required. Whatever position you read or write from in the ID array, you can read and write from "blindly" in the name array as they are 2 parts of the same entry.


text:
Using a web server with Arduino
So I am not new to arduino, however, I am new with web servers. I am working on a project that can control a robotic arm that is at one location and I can be at my house. I know basic HTML, Basic CSS, Basic JavaScript, and a tiny bit of JQuery. Only reason I say basic is because I self taught all these languages to myself using codeacademy. So I have a few questions since I done research on the matter.
Can a project like this be done with just the languages I know? All the tutorials I have looked at say you have to know AJAX and JSON. I have no idea what these are.
Also, for the interface, I need to be able to take the value of the encoders on the robot and view them. I also need a button that will record the value at that point in time of the encoders so I can configure the points and maybe even name them. A box where I can see the points and their coordinates, and finally a box where i can place points in and then execute a sequence.
How tough should this be?

I cannot quite get what you are looking for. Could you explain what sort of architecture you have in mind? You have an Arduino board, with a WiFi (or Ethernet) adapter, right? and you want to connect it to a web server? or you want to run the web server on Arduino?

Uno with Ethernet shield.I want to run a server off the board that also is linked with the robot

You can use an Arduino Yun: it has a 32u4 microcontroller coupled with a cpu running linux. The linux side already has a webserver: together with the Bridge library, you can use REST-like APIs to control a sketch, or build a web app that uses that APIs.
One example of remotely control an Arduino (although using an Android app instead of html+js) is this. Here is its source code.

There is an example of using the ethernet shield as a simple web server on the arduino website:
http://arduino.cc/en/Tutorial/WebServer
Adafruit has another tutorial using an SDCard to hold the web application's files:
http://www.ladyada.net/learn/arduino/ethfiles.html
It would be possible to use the aforementioned techniques to host a simple web application.
Since the browser only understands HTML, CSS and JavaScript (browser plugins not withstanding), the application will have to be written using these languages.
The HTML file will describe the structure of the UI (text, buttons, etc.), the CSS will apply styles if necessary and the JavaScript will add the interaction code (e.g. what happens when you press a button). The JavaScript could request data from the arduino+ethernet shield using AJAX request and should be able to send data back the same way. Using jQuery, this should be pretty straightforward.
That said, it might be easier to use a full fledged network stack such as the one you can find on Linux (using a raspberry pi for example) and to communicate using the serial port with Linux. I have an example on GitHub (the documentation is lacking but I could update it if need be): https://github.com/ddm/arduino-express
But in that case you don't get to use the ethernet shield which you may have already bought...

source: Stack Exchange

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

sort: votes


text:
Serial communication stops when I connect the tx cable
I'm using the apc220 rf modules. Now I'm having the following problem:
My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.
Is my rf module broken, or can someone help me with this?

Which Arduino board are you using?

The Uno only has a single hardware UART. Are you attempting to use it to connect to both the USB-UART bridge and the RF module at the same time?

To have two serial ports on Arduino board like Uno use SoftwareSerial.h.
Example
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("Hello!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Now after opening Serial monitor you should see Hello! and then you can test SoftwareSerial.
DO NOT FORGET!!!
When you connect to pins 2,3 or etc, this is TTL voltage level. You can't connect direct to RS232.

I know about Software Serial. The problem is that I use the rf modules for a quadcopter project and I need the memory of the rx pin, I think (correct me if I'm wrong).

Ok, so if you know more than i expected :) Clear for me this: How you connect RF module and debug it at the same time having only 1 serial port? Remember that : pins 0 and 1 ar Tx, Rx for USB. You can use them only without USB attached

And yes it takes more than memory. I would go for HW serial. replacing with Mega maybe

Haha, I'm starting to know arduino bit by bit. :) Whem I'm uploading the code I always disconnect the rf module. After uploading the code I connect the rf module again. If I open the serial monitor it seems to work on 1 serial port. But I just ordered my arduino Mega because the serial communication is a big pain in the ass with the uno... :)

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


text:
LiquidCrystal library and timers don't seem to be compatible
If I set timer2 to Compare Match mode, my LCD display stops working. If I use Overflow Interrupt it works fine.
Here's my test code. I have a loop() function which does its thing, and a timer interrupt which increments another variable, just to show it's working.
#include <LiquidCrystal.h>
#include <avr/interrupt.h>
#include <avr/io.h>

LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD:

int i;
volatile int j;
void setup()
{
  i=0;
  j=0;
  //button adc input
  pinMode( A0, INPUT ); //ensure A0 is an input
  digitalWrite( A0, LOW ); //ensure pullup is off on A0
  //lcd backlight control
  pinMode( 10, OUTPUT ); //D10 is an output
  digitalWrite( 10, HIGH ); //backlight control pin D10 is high (on)
  //set up the LCD number of columns and rows:
  lcd.begin( 16, 2 );

  // setup timer interrupt
  cli(); //disable global interrupts
  TCCR1A = 0;   //set tccr1a and tccr1b to 0
  TCCR1B = 0;
  //set cs10 and cs12 bit so timer runs at clock iSpeed/ 1024
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);

  // Compare Match Mode **Doesn't work**:
  //set compare match register
  OCR1A = 15624;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Overflow mode **Works**
  // enable overflow interrupt
  // TIMSK1 = (1 << TOIE1);

  //enable global interrupt
  sei();
}
void loop()
{
  lcd.setCursor( 0, 0 ); //top left
  lcd.print(i);
  lcd.setCursor(0,1); //bottom left
  lcd.print(j);
  delay(500);
  lcd.clear();
  i++;
}

ISR(TIMER1_OVF_vect)
{
  j++;
}

If I use overflow interrupts it works fine, the loop() counter is displayed on the top line and the interrupt counter on the second, but by using overflow interrupts I'm limited to the whatever timing the various prescalers give me.
If I use compare match the LCD display just shows faint flickering squares on its first line, like it's doing something but too quickly for the LCD to display.
I looked at the source for liquidcrystal.cpp, and it doesn't seem to use any timer or interrupts, so I'm completely mystified.

Dang, it was a bit of a noobish error. I had the interrupt handler setup for the overflow interrupt, but when I swapped the code in for the Compare Match interrupt I didn't make a handler for it. So since there's an interrupt without a handler it seems it just resets, hence the flashy-flashy garbage I was seeing on the LCD.
Adding this fixed the problem:
ISR(TIMER1_COMPA_vect)
{
  j++;
}

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


text:
TCP communication between Arduino client and server
I'm currently trying to build an Arduino robot controlled via a wifi connection. I have an Arduino Mega running as a client and it successfully connects to the server on LAN via the Adafruit cc3000 wifi board. However instead of grabbing the contents of the JSON file and printing it to serial, I'm just getting a 100 continue response. While this means I'm doing something right, I don't know what to do next in order to grab the data I need. Do I need to get the 100 message then respond with the GET request, or is there a way that I can GET the data straight away?
Thank you all in advance. Here is the Arduino code I have so far:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <stdlib.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ 3  // MUST be an interrupt pin!
#define ADAFRUIT_CC3000_VBAT 5 // Apparently these can be any two pins
#define ADAFRUIT_CC3000_CS 10  // But I wouldn't change these...
// Use hardware SPI for the remaining pins (On a Mega 2560, SCK = 52, MISO = 50, and MOSI = 51)
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

#define WLAN_SSID "VM540258-2G"
#define WLAN_PASS "XXXXXXXX"
#define WLAN_SECURITY WLAN_SEC_WPA2

String readString = String(100); //string for fetching data from address
uint32_t ip = 3232235523; // This translates into the ip address we need
                          // 323223552X; 192.168.0.X

void setup(){
  Serial.begin(115200); //Can also work at 9600

  //Initialise CC3000 module
  Serial.println(F("\nInitializing CC3000..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }
  //Connect to the Wireless Access Point
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP()) { //Obtain IP addeess
    delay(100);
  }

  while (! displayConnectionDetails())
  {
    delay(1000);
  }
}

void loop(){
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  if (client.connected()) {
    client.println("GET /project-test/state.json HTTP/1.0"); //Make a request for state.json
    client.println(""); //Mandatory blank line?
    if (client.available()){
      char c = client.read();
      Serial.print(c);
      //read char by char HTTP request
      if (readString.length() < 100) {
       //store characters to string
       readString += c;
      }
    }
  }
  //Once we have obtained the data, disconnect from the server
  client.close();
  Serial.println(readString);
  delay(1000);
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

The initial JSON file I'm using contains the following:
{"speed_left":null,"speed_right":null,"direction_left":null,"direction_right":null}

And the serial output I get when I run the Sketch:
Initializing CC3000...
Started AP/SSID scan

Connecting to VM540258-2G...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.0.7
Netmask: 255.255.255.0
Gateway: 192.168.0.1
DHCPsrv: 192.168.0.1
DNSserv: 192.168.0.1

Connect to 192.168.0.3:80
100

Connect to 192.168.0.3:80
100

ad infinitum

you are missing the HOST header in the request, so the server tell you to 100 CONTINUE you request.
Also yes, the final empty row IS mandatory
for example, to ask www.example.com/index.html
GET /index.html HTTP/1.1
Host: www.example.com

The Host header isn't required under HTTP/1.0, which is what he appears to be using.  Those were the days before  we hosted multiple websites on the same server.

you are right, tecnically is not, but many server does not care, i'm quite sure as i can replicate this with google's server by telnet

I'm going to guess that it's a problem with your server not expecting an HTTP/1.0 request.  I note the following from RFC 1945 about the response codes:

9.1  Informational 1xx
This class of status code indicates a provisional response,
    consisting only of the Status-Line and optional headers, and is
    terminated by an empty line. HTTP/1.0 does not define any 1xx status
    codes and they are not a valid response to a HTTP/1.0 request.
    However, they may be useful for experimental applications which are
    outside the scope of this specification.

I'd recommend changing your request to be HTTP/1.1 compliant (with a Host: header as suggested by @lesto)

This seems to support the idea that the server is ignoring the http/1.0 and act as HTTP/1.1 instead

Okay, I have a better answer, again done without testing.
If I look at the BNF for an HTTP-message from the RFC, it indicates that the message body is terminated by a blank line.
So, you actually need 2 CRLFs (i.e. 2 blank lines).  The first one separates the headers from the body of the HTTP request.  You don't actually have a message body (which is fine, it is optional).  But, you'll need another CRLF to terminate the (blank) body.
Since you only sent one blank line, the server is sending you the continue status codes, prompting you to finish sending your message (i.e. the message body).
So, try adding another client.println("");


text:
Interference at digital input (UNO)
I was trying out a basic button tutorial on my new Arduino UNO. But for some reason, the Arduino was detecting the button as on (pressed) even when it was off (unpressed).
After some experimentation, I found that the digital pins were flickering between HIGH and LOW, even if there was just a loose wire plugged in with nothing at the other end. And the state of the button, etc. wasn't making any difference. I tried this with pins 5,6 and 7, and it's happening with all of them, even when the neighbouring pins are connected to the ground.
Is this behaviour normal or is there something wrong with my input pins?
Since I'm new to Arduino, there might also be something wrong with my testing code. Here's what I used...
const unsigned int LED_PIN = 12;
const unsigned int BUTTON_PIN = 7;
const unsigned int INDICATOR_PIN = 13;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(LED_PIN, LOW);
}

void loop() {
  const int BUTTON_STATE = digitalRead(BUTTON_PIN);

  if (BUTTON_STATE == HIGH) {
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(INDICATOR_PIN, LOW);
  }
  else if (BUTTON_STATE == LOW) {
    digitalWrite(LED_PIN, LOW);
    digitalWrite(INDICATOR_PIN, HIGH);
  }
}

This code makes the lights always in opposite states: when one is on, the other is off. When I ran the code, both lights seemed on, which meant they were probably flickering, which meant that there was some interference in the input pin.

It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.
The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.
Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your setup() function, you can enable the pull-up on your input pin like this:
pinMode(BUTTON_PIN, INPUT_PULLUP);

That will cause the input to appear HIGH when the button is not pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.

Thanks for the tip about the resistor! I also realized that my breadboard was separated in the middle, so my "ground" line wasn't actually connected to the Arduino's GND pin.


text:
what is fastest allowable serial baudrate?
what is the fastest serial read the Mega can do?
begin.Serial1(1024000) is accepted for compiling, but reading jibberish
any suggestions on a faster device?

The divisors should give you 1 Mbps even.  However, on that board it is not just the Mega2560 which needs to do this - the 8u2/16u2 USB-serial and its firmware has to manage it as well.  Fortunately, you have similar Atmel parts on both ends of that very short link, so customization should be possible (you could ignore the host request and simply set both dividers to 0).  But your software has to keep up, too.  You may want to look at a different architecture where the application processor itself speaks USB, leonardo-style.

Why do you need "the fastest serial baudrate"? This is to communicate with what device exactly?

Sorry, my mistake - looks like you are using a different UART than the one proxied to USB.

device is a FANUC CNC Serial encoder...1024000 baudrate is fixed, but only need to output request strobe, then capture 77 bits serial input into buffer, then ignore while running rest of program to decipher what was read, when done arduino generates clock pulse to send another 77 bit word... I have it triggered via the request strobe falling edge interrupt to read input, but havent figured out how to save this into a buffer (i'm kinda new to this stuff) or if its even possible...

The Arduino Mega 2560 runs at 16 MHz. There are online calculators making this easy, as the calculation is not a straight and simple formula.
http://wormfood.net/avrbaudcalc.php
which shows using 16 MHz

Baud Rate
UBRR(dec)
UBRR(hex)
% of error

300
3332
0x0D04
0.0

600
1666
0x0682
0.0

1200
832
0x0340
0.0

2400
416
0x01A0
0.0

4800
207
0x00CF
0.2

9600
103
0x0067
0.2

14400
68
0x0044
0.6

19200
51
0x0033
0.2

28800
34
0x0022
0.8

38400
25
0x0019
0.2

57600
16
0x0010
2.1 - Barely OK

76800
12
0x000C
0.2 - GOOD

115200
8
0x0008
3.7 - BAD

230400
3
0x0003
7.8 - BAD

250000
3
0x0003
0.0

Where it is noticeable that the Mega's Arduino boot loader uses
mega.menu.cpu.atmega2560.upload.speed=115200

which is above the acceptable 1% error rate.
While it is possible to support different baud rates than stated above, it is not advisable, as the above values are the standard values. Values in between are very atypical and likely not trustworthy on the corresponding other side of the connection.
As I see your above example is 1024000, it is also worth noting that HardwareSerial.cpp implements a method to convert the requested baud rate to configuration of the USART, and I would not necessarily trust it for non-standard baud rates, especially on older version of the Arduino IDE. You may want to try the latest 1.5.8+ and verify the rate.

This is interesting. Why does the default Arduino bootloader use a baudrate with such a high error rate?

You get the incorrect table. It's content of 16 MHz with U2Xn = 0.

You get the incorrect data from table. It's content of 16 MHz with U2Xn = 0. With setting U2Xn = 1, you can get UART run at 230.4K which is nearly at the boundry of RA-232 clock torrence. By disable Parity bit you can make it more stable. By the way, do not get a long cable, it's better to use a cable less then 0.5m.

It depends mainly on CPU frequency, see USART/Baud rate settings in datasheet. For example at 16MHz it might go up to 2Mbps. But you need also consider error in baudrate which is important if communication with "3rd party" device.

If you have both MCU under control you can also consider USART in SPI mode with sync clock.

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


text:
Arduino PWM malfunctioning
I am controlling 4 motors using the PWM ports on an Arduino Uno (3,9,10,11). For some reason, the motor hooked up to port 11 doesn't move with my current code. I know it's a code issue because I can create a new basic code that just moves the motor and it works fine, but for some reason it doesn't in this code.
#include <SPI.h>
#include <Pixy.h>

Pixy pixy;

int personX = 0;
int offCount = 0;

void setup()
{
  pinMode(3, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  Serial.begin(9600);
  while (! Serial);
  pixy.init();
}

void loop()
{
  static int i = 0;
  int j;
  uint16_t blocks;
  char buf[32];

  blocks = pixy.getBlocks();

  if (blocks)
  {
    personX = pixy.blocks[0].x;
  }

  if (blocks){
    Serial.println(personX);
    if (personX < 110){
      analogWrite(11, 130);
      analogWrite(3, 130);
      analogWrite(9, 250);
      analogWrite(10, 250);
    } else if (personX > 190){
      analogWrite(11, 250);
      analogWrite(3, 250);
      analogWrite(9, 130);
      analogWrite(10, 130);
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
    offCount = 0;
  } else {
    if (offCount < 1000){
      offCount = offCount + 1;
    } else {
      analogWrite(11, 190);
      analogWrite(3, 190);
      analogWrite(9, 190);
      analogWrite(10, 190);
    }
  }
}

Also, when I take the motor and swap it with another, the old one works in the new PWM port, but the new one stops working once I put it in port 11.

Pin 11 is shared between both PWM and SPI. By activating SPI you've disabled PWM from working on that pin. Either use another PWM pin instead, or switch to software SPI on different pins.

Thanks for the info! I realized that I can just split the PWM from 3 to also control the motor previously hooked up to port 11, but because I will need to use 11 at some point in the future, I will need to know how to use SPI. I am new the Arduino so I had to google what SPI is, but how do I switch to software SPI, and will it still work with the Pixy camera?

I recommend not using software SPI if you can help it. Instead either pick a MCU with more PWM channels (e.g. the ATmega1280 in the Arduino Mega or the ATmega128A found in... no Arduino that I know of), or find an external PWM controller that can be controlled via SPI or I2C.


text:
Prevent Arduino Mega from setting all Outputs to HIGH on Reset
The Arduino Mega 2560 Rev 3 has multiple relays connected to its digital output pins.
Whenever the Arduino is reset (using reset button, turning on Serial Monitor etc), the Arduino turns on all relays then turns them off. I cant find any function in my sketch that causes the outputs to go HIGH then LOW. Assuming this is a normal feature of the Arduino, how can we prevent this and ensure that the outputs do not flip to the HIGH state?

How are the relays connected to the pins? Is there a pull-up or pull-down resistor?

@Craig The relays are connected directly to Arduino's pins. There's no pull-up or pull-down resistors

But there are flyback diodes, right?

Maybe I have different hardware/bootloader, but I cannot reproduce this. Can you reproduce this with the standard blink sketch and nothing attached other than a single LED/relay?

@jippie When using the blink sketch, the relays do not turn on and off during the reset... Wonder what's happening

The ATmega2560 itself comes out of reset with all pins in high-Z (DDRx=0, PORTx=0). Your observations are likely due to the bootloader. Check the bootloader source to verify that it is responsible for this.

Thank you, sounds like this is a possible reason. How should I check the bootloader source in that Arduino?

Well, first you have to find it. Try the Arduino code repository, and failing that ask for it in the forums.

Is it possible to flash with another bootloader that is known to not have this issue? Additionally, the blink sketch does not cause the relays to turn on then off when Arduino is reset.

It is absolutely possible to flash it with another bootloader. That the blink sketch doesn't cause it raises suspicions though...

Could it be the relay board? I'm using the 5V version of this relay board: http://www.sainsmart.com/16-channel-12v-relay-module-for-pic-arm-avr-dsp-arduino-msp430-ttl-logic.html

The relay board you are using has active low inputs to control the relays.
In your sketch when you are initialising the pins as outputs they are by default set low (this is turning all your relays on).
set the pins as outputs and set them high, they will be low for a very short time (too short for the relay to turn on effectively).

too short for the... ?

Just to add my five cents. I also experienced a relay, driven by a bipolar npn lowside. turning on while timers, Serial etc init and then turn off again.
Using INTERNAL_PULLUP mode helped me as well.
have no idea why. It must have something to do with relays beeing current driven. Mine requires 20 mA at 5V

Assuming this is a normal feature of the Arduino,

It doesn't sound normal to me. Check with others to see if they have the same issue before you try to resolve an otherwise non existent problem.

how can we prevent this and ensure that the outputs do not flip to the HIGH state?

Design the relays to be active now.

There is an alternative to change the bootloader. Introduce a RC circuit in the relay driver that delay the rely to switch ON.
Note: Please add info about the relay and/or driver circuit for a better answer.


text:
MHz Sampling Rate for Arduino
How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?
If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

Arduino and Atmel are completely independent; that Arduino has chosen Atmel devices is more serendipity than anything else.

The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.
The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.


text:
Can the Arduino use this i2c LCD Panel
Can the Arduino Mega2560 use the New Haven NHD-0420D3Z-NSW-BBW-V3 LCD panel by controlling it with the New LiquidCrystal library? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for GND, VCC, SDA, SCL.

The I2C in that library is expecting a IO expander ASIC. The display you use requires different I2C commands. Better look around for a different library.

Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.
I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be too terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.


text:
Arduino 2560 as an Interface to 4 Serial Hardwares
I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.
Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?
The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.

Technically USB device can be composite device, say with 4 USB-CDC (or VCP - virtual comport) devices. Arduino Mega has no native USB, but it is possible to use V-USB library that emulates USB 1.1 device at physical layer using just 2 pins (hardware UART will not be used). But there are some issues: 1) it seems for 1 VCP device 3 endpoints are needed and V-USB can't provide that many, so likely library modification will be needed; 2) for Windows driver - not sure if it is possible to use standard VCP drivers for a such composite device

@Flanker Looks like it will be easier to use a USB to four channel RS232 module and connect Arduino to one of the four RS232 channels.

You might look at the FT4232H, though who knows what that will be like software wise.

In Arduino terms:
Serial will be committed to receiving data from the PC.
Connecting Serial1, Serial2, and Serial3 via RS232 will be easy.
Adding a 4th Software Serial (or NewSoft Serial or AltSoft Serial) via RS232 will also be straightforward. If you need high speeds for the 4th port, than a UART with SPI (or I2C) interface to the Mega might be a better idea.
The only tricky part is putting in some info in the data from the PC so the Mega can re-send it to the correct port.

Dang it, I need to remember to look at the dates of posts!

No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.
The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port.  Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).


text:
arduino sketch on Win7 vs. MAC op system?
I have a friend who is just getting started with Arduino UNO.  He downloaded a sketch and is using a UNO on Mac OS.  He loaded the sketch and verified.  it comes up with errors.  He sent me the same sketch and i opened it under Win7 arduino software.  verified, and it says it is fine.  i made an arduino file and emailed it back to him.  he is still getting the same errors.  can anyone help and let me know what is wrong?  i am not a MAC expert and wonder why  this works in win and not MAC????????  appreicate any help anyone can give me

Can you post the source code and the errors please? It's difficult to suggest anything useful otherwise.

Do you both have the Uno selected as target device in the IDE?

Are you using the same version of the Arduino IDE.

I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


text:
Improve sampling speed while using a multiplexer
I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).
However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks.
In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()
Is there any tricks I could use to improve my sampling rate faster ? Thanks...
Here is my multiplexer class :
class MUX {
public:
//mux control pins:
int s0 = 22;
int s1 = 24;
int s2 = 26;
int s3 = 28;

//SIG pin (not necessary WHEN sig is connect to 5V)
//int SIG_pin = 0;

//array to store channel :: muxChannel[channel numbers ][4 digit channel representation]
int muxChannel[16][4] = {
  {0, 0, 0, 0}, //channel 0
  {1, 0, 0, 0}, //channel 1
  {0, 1, 0, 0}, //channel 2
  {1, 1, 0, 0}, //channel 3
  {0, 0, 1, 0}, //channel 4
  {1, 0, 1, 0}, //channel 5
  {0, 1, 1, 0}, //channel 6
  {1, 1, 1, 0}, //channel 7
  {0, 0, 0, 1}, //channel 8
  {1, 0, 0, 1}, //channel 9
  {0, 1, 0, 1}, //channel 10
  {1, 1, 0, 1}, //channel 11
  {0, 0, 1, 1}, //channel 12
  {1, 0, 1, 1}, //channel 13
  {0, 1, 1, 1}, //channel 14
  {1, 1, 1, 1} //channel 15
};

void setupMux() {
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  Serial.println(F("Multiplexer initialized"));
}

void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }
}

What is the baud rate for the serial interface? Have you considered using millis() to time your code and see where most of the time is spent?

You may consider changing the i2c bus speed. Here is a forum post covering the steps http://forum.arduino.cc/index.php?topic=16793.0

Thanks guys , I've speed up my baud rate and it really helps , I also use Robert's proposal , help as well :)

It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:
If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?
for each sensor,
  setup mux;
  send start conversion command;
end

for each sensor,
  setup mux;
  while conversion not done,
    ;  // wait
  read and store value;
end

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.

The technique suggested by @JRobert (starting all the conversions in one loop, then running another loop to wait for completions and read results) looks reasonable.
Here are a couple of ways to shorten the code shown in the question:
First, instead of four int declarations to set the value of s0 ... s3, use an enum.  An enum is used to declare integer constants.
enum { s0 = 22, s1 = 24, s2 = 26, s3 = 28};

Second, don't bother with the lengthy, tedious, and unnecessary muxChannel array.  Delete the declaration of muxChannel and replace selectChannel with the following:
void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], channel & 1);
    channel /= 2;
  }
}

The expression channel & 1 picks off the least-significant-bit of channel.  The statement channel /= 2; divides channel by 2, which moves the next bit of channel into place for output.  You could instead say channel >>= 1; or channel = channel/2;, etc. if you prefer.
You might also look closely at your sensor boards to see if there is any way to add jumpers to get another bit or two of I2C device addressing, allowing you to avoid multiplexing.


text:
How to clear FIFO buffer on MPU6050?
my MPU6050 works very unstable , the problem is unable clear excessed FIFO buffer on MPU6050, I am using Jeff Rowberg's MPU library and according to his DMP example but without using interruptions,here is my modified code but I've tried several method listed in the library to clear buffer but doesn't work..
Thanks very much!
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"

MPU6050 mpu(0x69); //AD0=High

//MPU control/status vars
bool dmpReady = false;
uint8_t mpuIntStatus;  //actual interrupt status byte
uint8_t deviceStatus; //device status , 0 = success ,
uint16_t packetSize; //expected DMP packet size (defult 42) -- ?
uint16_t fifoCount; //count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO buffer storage

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

volatile bool mpuInterrupt = false;
//void dmpDataReady() {
//  mpuInterrupt = true;
//}

// put your setup code here, to run once:
void setup() {
  //join I2C bus
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 48; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif
  //initialize serial communication
  Serial.begin(115200);
  while(!Serial); //common for Leonardo issues

  //initialize the mpu
  Serial.println("Call MPU6050 Lib to initialize devices...");
  mpu.initialize(); //initialize I2C device by using MPU6050 library

  //verify connection
  Serial.println("Tesing device connections");
  Serial.println(mpu.testConnection() ? F("MPU6050 connection test successed ") : F("MPU6050 connection test failed"));

//  //wait for begin , uncomment if we need wait user interruption
//  Serial.println("Press any button to begin");
//  while (Serial.available() && Serial.read()); // empty buffer
//  while (!Serial.available());                 // wait for data
//  while (Serial.available() && Serial.read()); // empty buffer again

  //load and configure DMP
  Serial.println("initializing DMP");
  deviceStatus = mpu.dmpInitialize(); //use MPU6050 library to inilisalize the dmp

 //feed offsets
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  //make sure it works
  if (deviceStatus == 0) {
    Serial.println("DMP initialization success, now enable DMP for use");
    //turn on DMP
    mpu.setDMPEnabled(true); //use MPU6050 library to enable DMP)

    //wait for first interrup . currently just leave it false automatically
    mpuInterrupt == false;

    //let main llop know it's ok to use DMP, set dmpRead flag to ture
    dmpReady = true;
    Serial.println("DMP is ready to use.");

    //get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    //ERROR! , device status !=0 when initializing DMP
    Serial.print("DMP initialization failed when using MPU6050 library:");
    if (deviceStatus == 1) {
      Serial.println(" intial memory load failed");
    } else if (deviceStatus == 2) {
      Serial.println(" failed to update DMP configuration");
    } else {
      Serial.print(" unknow error with code: ");
      Serial.println(deviceStatus);
    }
}
}

int ticket = 1;
void printOnlyOnce (String message){
  if (ticket == 1){
   Serial.println(message);
   ticket = 0 ;
  } else {
    return;
  }
}

void loop() {
  //if DMP not ready don't do anything
  if (!dmpReady) {
    printOnlyOnce("MAIN LOOP: DMP disabled");
    return;
  } else {

    //testing overflow
    if (fifoCount == 1024) {
      mpu.resetFIFO();
      Serial.println("FIFO overflow");
    } else {

    //wait for enough avaliable data length
    while (fifoCount < packetSize) {
      //waiting until get enough
      fifoCount = mpu.getFIFOCount();
    }

    //read this packet from FIFO buffer
    mpu.getFIFOBytes(fifoBuffer,packetSize);

    //track FIFO count here is more then one packeage avalible

    //reset fifo count
    fifoCount -= packetSize ;
    Serial.println(fifoCount);

    if (fifoCount > 2) {
        ////// clear fifo buffer
    }
    //display stage
                // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
  }
  }
}

How do you know that the FIFO buffer is your problem?

hi , because I've tested it :)

But what method of testing did you do that isolated the problem to that buffer?

By eliminating other potential problem sources one by one to this one , it took me about 8 hours :)

What if we can increase the size of the FIFo Buffer.
uint8_t fifoBuffer[64]; // FIFO storage buffer

What if I change it to lets say:
uint8_t fifoBuffer[1024]; // FIFO storage buffer

and then change :
if ((mpuIntStatus & 0x10) || fifoCount == 16384) { // I changed 1024 -> 16384
    // reset so we can continue cleanly
    mpu.resetFIFO(); // Resets the FIFO buffer when set to 1 while FIFO_EN equals 0.
    Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
}

Please check these changes.

To prevent overflow problems, please, go to MPU6050_6Axis_MotionApps20.h and modify that line:
0x02,   0x16,   0x02,   0x00, **0x01**                // D_0_22 inv_set_fifo_rate

The value in bold is the objective! Change it to 0x03 or 0x04 or 0x05 to reduce the Hz of rate. I am using 0x03 and not getting error values, junk data, or overflows anymore.

Actually when I tried this it even gave me bad results. The values I read were just scraped. Can't down-vote here but this is a bad approach!


text:
Trying to play audio files on arduino via Usb Host Shield
I want to build a program that will seek audio file inside a USB DOK (DisK On Key/Pen Drive) when it is inserted to the Circuits@Home USB Host shield. After a specified file will be found i want it to be played via the Audio library and the Teensy 3.1 12 Bit Analog Output.
Alternatively, I can use an Arduino MEGA with the shield and the TMRpcm library: https://github.com/TMRh20/TMRpcm/wiki
I've saw that there's a sample with SD card and I've fiddled a lot to get the USB Host Shield 2.0 library to work and succeeded. However I've found a simpler implementation of it in the UsbFat library: https://github.com/greiman/UsbFat
Now basically I need to connect between these two libraries but sadly I've failed to understand how to convert "play_sd_wav.h" to use the UsbFat Library.
Or, more simply put, how do I command a USB pen drive like it is a SD card and pull an audio file from it?
Anyone can help please?
Thank You,
Ziv


text:
bootloader uploading into Atmega328

Here is mine circuit. Intially i used arduino UNO directly for programming. Now i am Using atmega 328 IC for programming. I am trying to connect 32 hall sensor via Mux circut. I wanted to How to upload boot loader or HExfile Here. Will avr pocket programmer satisfy above circuit or i need to add addtional circuit here
AVr pocket programmer

The AVR pocket programmer should work fine. Sparkfun has a good guide for doing this.
Here's the pinout of the Atmega328:

You'll want to connect your programmer as follows (note, these are the pins for the bare Atmega328 chip only. The pin numbers on an Arduino board are different.):

Programmer Pin		Atmega328 Pin
5V			Vcc (7)
GND			GND (8)
MOSI			Digital 11 / Physical 17
MISO			Digital 12 / Physical 18
SCK			Digital 13 / Physical 19
Reset			Reset (1)

Note that the physical pins on the chip are numbered differently than the logical pins. In the table above the "Digital" pin numbers are those colored yellow in the figure, while the "Physical" pins correspond to the black-on-white numbers around the edge.
If you already have the ICSP header connected to those pins (it's not completely clear in the schematic if that is the case), you can connect the programmer to those pins instead. This can be easy if you have a 6-pin ICSP cable with your programmer.
Also, if you are already powering your Atmega328 from some other 5V power supply you can omit the 5V-Vcc pin. However, the programmer and the Atmega328 must share a common ground, so be sure the GND pins are connected.
Connect your programmer to the computer using USB, open the Arduino IDE, select the correct serial port of the programmer, and pick "Arduino Uno" in the "Board" menu. You can program the bootloader by selecting "Burn bootloader" in the Tools menu, or you can simply write your program by selecting "Uploading using programmer" in the File menu.

thanks for information.I wanted to know whether above circuit right or wrong

Uploading Hexfile to your arduino can be done using this application:
http://kmtronic.com/upload-hex-files-to-arduino.html

This is how you upload an Arduino Bootloader on an empty ATmega328 / ATmega328P-PU. Using an Arduino. (No need for a separate ISP Programmer).
From Arduino Uno to other Arduino Uno.

Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port > Arduino Uno.
Upload the ArduinoISP sketch.
Wire your Arduino board to the target as shown in the diagram below. (Note: you'll need to add a 10 uF capacitor between reset and ground.)
Also connect TX from Arduino A to the RX of Arduino B and RX from Arduino A to TX Arduino B.
Select Target Board in Tools > Board > Arduino Duemilanove w/ ATmega328
Select programmer in Tools > Programmer > Arduino as ISP
Use the Burn Bootloader > Arduino as ISP command.
Go to Tools and Select Burn Bootloader. Done.

To upload on a breadboard without External clock.

Download: Breadboard.zip
Put boards.txt in your Arduino directory under Hardware > ATmega328. (For windows usually (C:/Program files/Arduino/Hardware/ATmega/boards.txt))
Close Arduino IDE and reopen it.
Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port > Arduino Uno.
Upload the ArduinoISP sketch.
Hook pin13 from Arduino to pin19 on Chip
Pin12 from Arduino to pin18 on chip
Pin11 from Arduino to pin17 on chip
Pin10 from Arduino to pin1 on chip
pin0 from Arduino to pin3 on chip
pin1 from Arduino to pin2 on Chip
connect 5V from Arduino to pins 7 and 20 on chip
14, connect GND from Arduino to pins 8 and 22 on chip
Select Target Board in Tools > Board > ATmega328 on breadboard (8 MHz internal clock)
Select programmer in Tools > Programmer > Arduino as ISP.
Select Tools > Burn Bootloader. Done.

It's also possible with an Arduino Leonardo but you'll have to change some settings for that.
Note: You will need to put target board to Arduino Duemilanove w/ ATmega328 for programming the new chip (Uploading a code to it) instead of targeting Arduino Uno.

I need to uploaD IT TO empty IC atmega 328

Yes, and since you have an arduino you could use your arduino as ISP for programming your clean/empty chip to burn a bootloader on it and your sketch. Follow the links


text:
Multiple HC-SR04 with one 5v 7805 regulator
I am working on a autonomous track vehicle. I have mounted
3 HC-SR04 sensors
1 Sharp infrared distance sensor
3 infrared led distance sensors
1 Arduino Mega 2560
1 H-bridge Board HG7881
I am trying to use 7.5 v 1700 mAh Nicd battery (also tried 11.1 Lipo 2200 mAh)
For all sensors power (5v) I developed 5v regulator using 7805 which is connected directly from battery as input. The output 5v is going to power distribution board (used from quadcopter extra board) which provides 5v to every sensor.
The real problem starts here when I am not getting correct or nothing in reading from Ultrasonic sensors and my vehicle starts behaving abnormal. I checked that sensor reading is either 0 or wrong. I used both simple and with NewPing library.
I checked when using 7.2v battery the output from 5v regulator is 3.72v.
Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?
My vehicle will not work until sensors provide correct distance reading. I worked successfully with one sensor but with number of these, tired working since many days.

The sensors are 5V so yes, very likely they will behave erratic at 3.7v. Have you measured the current draw from the battery while everything is running? Do you have input/output capacitors? Any thin/long wire being used? All connections are ok? Does any part gets hot? Not a problem but a switching regulator might be more efficient.

What's the voltage into the regulator?

How is the Arduino wired into the sensor schematic?

@Talk2, yes 5v sensors, should I check drawing current from battery by multi-meter just touching +v -v?, yes several thin but strong long wires being used. Yes checked connections to every sensor by multi-meter. Nothing hot just my mind :).

@Dave X, on 7.2v battery, 3.7v. On 11.1 battery it is 5v.

@Majenko, this is not the first time I am using these sensors, this is my third similar project but first time with all so many sensors. I connected ultra sonic on analog pins then tried to change to digital pin but same result. I also replaced one of sensor with brand new and new wires.

quazifarhan  It does not make sense to have 3.7V into the regulator and 3.72 out of the regulator.    Also, regarding your answer to @Talk2 --you measure current by putting a current meter in-line (in between) with the circuit, not across the V+/V- terminals. Put it between the battery's V+ and the regulator's Vin to see the current pulled out of the battery.  Or between the regulator's Vout and the rest of the circuit to see the current delivered to the circuitry.  Or between the regulator's GND and the circuit GND to see the current wasted by the regulator.

Does the Arduino share the same power source as the sensors?

Majenko, Arduino getting full 7.2 or 11.1 from battery to vin pin and parallel connention from battery to regulator. So Regulator and Arduino both connected directly to battery.

You really could benefit from a DC/DC switching power supply.  For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.
That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together?  If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results.  Same goes for the 3rd sensor.

Is this an answer to the question Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?

No.  But it appears that the author was having difficulties phrasing the question.  And that the actual goal was a working "autonomous track vehicle".  In the end I believe this question suffers from the XY Problem.

Your 7805 regulator isn't working, it should have a output of 5v, 3.72v is way off. 2-4% diff from 5V is the normal specification. https://www.fairchildsemi.com/datasheets/LM/LM7805.pdf
Vin should be between 7-20volt even if the datasheet indicate that you can have as low as 5volt in.
Causes could be:

Wrong design
Low battery voltage
Faulty component
Faulty connection


text:
Sketch always appears to show data one iteration of main loop behind
I'm trying to emulate a display similar to an old fashioned mechanical bathroom scale, ie the pointer stays in the middle of a small screen and the scale moves left or right as needed.
I am using an Arduino Nanpo with IDE 1.6.13 My problem is that the display is always one iteration of the loop behind on the screen. For example if the previous value was 49.98 and the new value is 50.00, I would expect the screen to "move" to the right by two increments e.g the screen would show
49.97 | 49.98 | 49.99 then move by one to show 49.98 | 49.99 | 50.00 then move my one again to show 49.99 | 50.00 | 50.01
The code I use is working i.e. the "shifting" is occurring, however the problem is the display always shows the previous value even though I can prove that the current value is being passed to the shift routines. BUT when the next current value is being processed the display THEN shifts to the previous current value which on this iteration is now the previous. In other words the display is always one iteration behind the current value. This is my first post. I also have a video which if the forum rules allow, I can upload which perfectly illustrates the problem. In the meantime here's a snapshot image...
Here's my code:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>

#define cs   10
#define dc   8
#define rst  9

Adafruit_ST7735 display = Adafruit_ST7735(cs,  dc, rst);

int box_y_coord = 25;               // Start of y coordinate for boxes
int box_width = 70;
int box_height = 30;
int box_speed = 2;
int box_offset = 80 - (box_width / 2); // value is currently 45
int shi;
int sli;

bool initialisation_required = true;

int random_frequency;
int current_frequency;
int previous_frequency = 5000;
int shift_in_frequency;

void setup() {

  display.initR(INITR_BLACKTAB);
  display.setRotation(1);           // x begins at left-hand side of the screen, y begins from the top of the screen
  display.setTextColor(ST7735_BLACK);
  display.setTextWrap(0);
  display.setTextSize(2);

  Serial.begin (9600);
  randomSeed(analogRead(0));

  display.fillRect(0,0,160,25,ST7735_YELLOW);  // remove when problem fixed
  display.fillRect(0,55,160,25,ST7735_YELLOW); // remove when problem fixed

  delay(5000); // Give me time to start video

}

void loop() {

  current_frequency = random(4997,5004);
  shift_in_frequency = current_frequency - previous_frequency;
  display.fillRect(0,60,160,80,ST7735_WHITE);
  display.setCursor(2,65);
  display.print("Current:");
  display.print(current_frequency);
  display.setCursor(2,85);
  display.print("Previous:");
  display.print(previous_frequency);
  display.setCursor(2,105);
  display.print("Shift:");
  display.print(shift_in_frequency);
  Serial.print("In main loop - current: ");
  Serial.print(current_frequency);
  Serial.print(" previous: ");
  Serial.print(previous_frequency);
  Serial.print(" shift: ");
  Serial.println(shift_in_frequency);

  if (abs(shift_in_frequency) > 5)
     initialisation_required = true;

  if (initialisation_required) {
     setup_initial_display();
     initialisation_required = false;
  }

  if (shift_in_frequency > 0) { // Frequency rising
      shift_higher(shift_in_frequency);
  }
  else if (shift_in_frequency < 0) { // Frequency falling
          shift_lower(0 - (shift_in_frequency));
          }

  previous_frequency = current_frequency;
  shift_in_frequency = 0;
  delay(3000);

}

void setup_initial_display() { //Runs once only

  // Draw the left-hand box
  display.drawRect(box_offset - box_width,box_y_coord,box_width,box_height,ST7735_BLACK);
  display.fillRect(box_offset - box_width + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
  // Draw in the frequency
  display.setCursor(box_offset - box_width + 6,box_y_coord + (box_height / 2) - 6);
  display.print(int(current_frequency - 0.01) / 100);
  display.print(".");
  if (int(current_frequency - 0.01)%100 < 10)
     display.print("0");
  display.print(int(current_frequency - 0.01) % 100);

  // Draw the central box
  display.drawRect(box_offset,box_y_coord,box_width,box_height,ST7735_BLACK);
  display.fillRect(box_offset + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
  // Draw in the frequency
  display.setCursor(box_offset + 6,box_y_coord + (box_height / 2) - 6);
  display.print(int(current_frequency) / 100);
  display.print(".");
  if (int(current_frequency)%100 < 10)
     display.print("0");
  display.print(int(current_frequency) % 100);

  // Draw the right-hand box
  display.drawRect(box_offset + box_width,box_y_coord,box_width,box_height,ST7735_BLACK);
  display.fillRect(box_offset + box_width + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
  // Draw in the frequency
  display.setCursor(box_offset + box_width + 6,box_y_coord + (box_height / 2) - 6);
  display.print(int(current_frequency + 0.01) / 100);
  display.print(".");
  if (int(current_frequency + 0.01)%100 < 10)
     display.print("0");
  display.print(int(current_frequency + 0.01) % 100);

  // Draw the gauge line
  display.drawFastVLine(79,25,30,ST7735_RED);
  display.drawFastVLine(80,25,30,ST7735_RED);
  display.drawFastVLine(81,25,30,ST7735_RED);
  display.drawFastVLine(82,25,30,ST7735_RED);

}

void shift_higher(int offset) {
  Serial.print("In shift higher - current: ");
  Serial.print(current_frequency);
  Serial.print(" previous: ");
  Serial.print(previous_frequency);
  Serial.print(" shift: ");
  Serial.println(shift_in_frequency);

  shi =  box_width + box_offset; // Is 70 + 45 = 115
  while(shi <= ((offset * box_width) + box_width + box_offset)) { // For example when offset = 1,  limit = 1 * 70 + 70 + 45 = 185

      // Starting box
      display.drawRect(shi - box_width,box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(shi - box_width + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(shi - (box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency) / 100);
      display.print(".");
      if (int(current_frequency)%100 < 10)
         display.print("0");
      display.print(int(current_frequency) % 100);

      // Previous minus one - SR1
      display.drawRect(shi - (2 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(shi - (2 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(shi - (2 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency - 1) / 100);
      display.print(".");
      if (int(current_frequency - 1)%100 < 10)
         display.print("0");
      display.print(int(current_frequency - 1)%100);

      // Previous minus two - SR2
      display.drawRect(shi - (3 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(shi - (3 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(shi - (3 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency - 2) / 100);
      display.print(".");
      if (int(current_frequency - 2)%100 < 10)
         display.print("0");
      display.print(int(current_frequency - 2) % 100);

      // Previous minus three - SR3
      if (offset > 1) {
        display.drawRect(shi - (4 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(shi - (4 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(shi - (4 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency - 3) / 100);
        display.print(".");
        if (int(current_frequency - 3)%100 < 10)
           display.print("0");
        display.print(int(current_frequency - 3) % 100);
      }

      // Previous minus four - SR4
      if (offset > 2) {
        display.drawRect(shi - (5 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(shi - (5 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(shi - (5 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency - 4) / 100);
        display.print(".");
        if (int(current_frequency - 4)%100 < 10)
           display.print("0");
        display.print(int(current_frequency - 4) % 100);
      }

      // Previous minus five - SR5
      if (offset > 3) {
        display.drawRect(shi - (6 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(shi - (6 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(shi - (6 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency - 5) / 100);
        display.print(".");
        if (int(current_frequency - 5)%100 < 10)
           display.print("0");
        display.print(int(current_frequency - 5) % 100);
      }
      // Previous minus six - SR6
      if (offset > 4) {
        display.drawRect(shi - (7 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(shi - (7 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(shi - (7 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency - 6) / 100);
        display.print(".");
        if (int(current_frequency - 6)%100 < 10)
           display.print("0");
        display.print(int(current_frequency - 6) % 100);
      }

      // Draw the gauge line
      display.drawFastVLine(79,25,30,ST7735_RED);
      display.drawFastVLine(80,25,30,ST7735_RED);
      display.drawFastVLine(81,25,30,ST7735_RED);
      display.drawFastVLine(82,25,30,ST7735_RED);

      shi = shi + offset;
  }
}

void shift_lower(int offset) {   // sli decreases

  Serial.print("In shift lower - current: ");
  Serial.print(current_frequency);
  Serial.print(" previous: ");
  Serial.print(previous_frequency);
  Serial.print(" shift: ");
  Serial.println(shift_in_frequency);

  sli = 0;
  while(sli >= 0 - ((offset * box_width) + 25)) {

      // Starting box
      display.drawRect(sli + box_width,box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(sli + box_width + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(sli + (box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency) / 100);
      display.print(".");
      if (int(current_frequency)%100 < 10)
         display.print("0");
      display.print(int(current_frequency) % 100);

      // Next plus one - SL1
      display.drawRect(sli + (2 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(sli + (2 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(sli + (2 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency + 1) / 100);
      display.print(".");
      if (int(current_frequency + 1)%100 < 10)
         display.print("0");
      display.print(int(current_frequency + 1)%100);

      // Next plus two - SL1
      display.drawRect(sli + (3 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
      display.fillRect(sli + (3 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
      display.setCursor(sli + (3 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
      display.print(int(current_frequency + 2) / 100);
      display.print(".");
      if (int(current_frequency + 2)%100 < 10)
         display.print("0");
      display.print(int(current_frequency + 2) % 100);

      // Next plus three - SL2
      if (offset > 1) {
        display.drawRect(sli + (4 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(sli + (4 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(sli + (4 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency + 3) / 100);
        display.print(".");
        if (int(current_frequency + 3)%100 < 10)
           display.print("0");
        display.print(int(current_frequency + 3) % 100);
      }
      // Next plus four - SL3
      if (offset > 2) {
        display.drawRect(sli + (5 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(sli + (5 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(sli + (5 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency + 4) / 100);
        display.print(".");
        if (int(current_frequency + 4)%100 < 10)
           display.print("0");
        display.print(int(current_frequency + 4) % 100);
      }
      // Next plus five - SL4
      if (offset > 3) {
        display.drawRect(sli + (6 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(sli + (6 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(sli + (6 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency + 5) / 100);
        display.print(".");
        if (int(current_frequency + 5)%100 < 10)
           display.print("0");
        display.print(int(current_frequency + 5) % 100);
      }
      // Next plus six - SL5
      if (offset > 4) {
        display.drawRect(sli + (7 * box_width),box_y_coord,box_width,box_height,ST7735_BLACK);
        display.fillRect(sli + (7 * box_width) + 1,box_y_coord + 1,box_width - 2,box_height - 2,ST7735_WHITE);
        display.setCursor(sli + (7 * box_width) + 6,box_y_coord + (box_height / 2) - 6);
        display.print(int(current_frequency + 6) / 100);
        display.print(".");
        if (int(current_frequency + 6)%100 < 10)
           display.print("0");
        display.print(int(current_frequency + 6) % 100);
      }

      display.drawFastVLine(79,25,30,ST7735_RED);
      display.drawFastVLine(80,25,30,ST7735_RED);
      display.drawFastVLine(81,25,30,ST7735_RED);
      display.drawFastVLine(82,25,30,ST7735_RED);

      sli = sli - offset; // was box_speed
  }

}

Here's some serial monitor output (nb not the same time as the screen image previously sent
In main loop - current: 4997 previous: 5000 shift: -3
In shift lower - current: 4997 previous: 5000 shift: -3
In main loop - current: 4999 previous: 4997 shift: 2
In shift higher - current: 4999 previous: 4997 shift: 2
In main loop - current: 4999 previous: 4999 shift: 0
In main loop - current: 5001 previous: 4999 shift: 2
In shift higher - current: 5001 previous: 4999 shift: 2
In main loop - current: 5001 previous: 5001 shift: 0
In main loop - current: 5001 previous: 5001 shift: 0
In main loop - current: 5001 previous: 5001 shift: 0
In main loop - current: 5001 previous: 5001 shift: 0
In main loop - current: 5001 previous: 5001 shift: 0
In main loop - current: 5000 previous: 5001 shift: -1
In shift lower - current: 5000 previous: 5001 shift: -1
In main loop - current: 5001 previous: 5000 shift: 1
In shift higher - current: 5001 previous: 5000 shift: 1
In main loop - current: 4997 previous: 5001 shift: -4
In shift lower - current: 4997 previous: 5001 shift: -4
In main loop - current: 5001 previous: 4997 shift: 4
In shift higher - current: 5001 previous: 4997 shift: 4
In main loop - current: 5003 previous: 5001 shift: 2
In shift higher - current: 5003 previous: 5001 shift: 2

IN all of the above, the screen displays the previous frequency and not the current

I think the problem may lie in the shift procedures as the screen correctly displays the current frequency upon invoking the setup_initial_display procedure. It's almost as if the ST7735 display is not flushing the display in a timely manner?

Put another Serial.print() debug statement within the while() loop of both shift_higher() and shift_lower(). These may be executing more often than you would like. If that doesn't bring anything, reduce shift_higher() and shift_lower() to simply printing the starting box and no while loop.

I've solved the problem. It's because I was using the wrong value in the shift routines, ie I was using current_frequency instead of previous_frequency. After all I want to know what the frequency has changed FROM not TO :slight_smile: On changing that and swapping the calls to higher and lower around, it all works perfectly. Problem solved. Thanks to all for your suggestions.

I'm not sure how to mark this question as solved - any suggestions please?

write an answer and accept it as a solution

I've solved the problem. It's because I was using the wrong value in the shift routines, ie I was using current_frequency instead of previous_frequency. After all, I want to know what the frequency has changed FROM not TO :slight_smile: On changing that and swapping the calls to shift_higher and shift_lower around, it all works perfectly. Problem solved. Thanks to all for your suggestions


text:
Vin12V or 5V power supply: possible mistakes
I would like to run an arduino Mega, used to control several stepper motors in a photo enlarger made in the 90s, where the motor control pcb is missing.
In this instrument there is the power PCB still working, which provides 25V DC for the motors, 5v DC regulated for the electronics, +12/-12VDC for some analog comparators and 24VAC for the main lamp.
I would like to use the 5VDC or eventually the +12V to power the Mega.
I have 2 doubts:

is it better to use the 5v connected to the +5V pin or the 12V connected to the Vin? Following the original logic of the instrument I think it would be better to use the 5V, since it's dedicated to the electronics for the whole instrument system. But I read in arduino's docs that is not advised and it's conflicting with usb power supply. Is it true? Does it mean that I cannot use a USB connection when Mega is connected to the main instrument +5V?
Regarding the load on Arduino: I'm going to control via I2C an LCD 20x4, 3rotary encoders, 3 DRV8871 and 3 TB660 + 3 limit switches. Both DRV8871 and lcd screen can be powered by the +5v power supply, and tb660 is opto isolated, so the only load is on internal pullup resistors
the original motor control PCB is missing because it was damaged. There are some chances that this is due to faulty power supplied by the power PCB or by the transformer. How can I verify that the power pcb is working and providing stable and regulated power both with no load and under load? I fear that simply measuring the output voltage is not enough. (By the way, I measured the voltage with no load and I got exactly 5V, +12 and -12V, instead the 25 +-1VDC was measured 27V)

Thanks for you help

is it better to use the 5v connected to the +5V pin or the 12V connected to the Vin?  ... the question is not answerable until you say what you mean by better

Depends on how much current you need on 5V. Mega has linear voltage regulator and it'll get hot even with 200mA load (12-5)V*0.2A=1.4W of power turned into heat

I'm going to control via I2C an LCD 20x4, 3rotary encoders, 3 DRV8871 and 3 TB660 + 3 limit switches. Both DRV8871 and lcd screen can be powered by the +5v power supply, and tb660 i think is opto isolated, so the only load is on internal pullup resistors, if I'm right

Please [edit] your question when clarifying and answering comments. -- You might want to measure the current needed by your Mega. -- To further check the power PCB, use some high-power resistors (read: light bulbs) to give it some load. For example, your (spare) car's front-light bulb is an actual fine high-power load, while a torch's bulb takes significant power but a lot lower. Select as needed.

Thanks , edited. I'm planning to measure the current needed by the mega. Regarding the power PCB I fear that a light bulb could be too much power, I don't know the power it's able to support, and I especially need to evaluate the 5V, where the 12V  light bulb maybe is not fitting. Is it true that powering the mega through the 5V goes in conflict with the USB power input?


text:
IR sensor does not work well on carpets
I have facing a problem since long and cannot solve it. I built Arduino car and place 2 IR sensors shown in image, to check down distance to avoid falling from stairs. One is at back and other at front. On hard surface they work well but on carpet always give wrong reading like no object there which translates unsafe to move and my car stops. How can we solve this problem? I also tried Ultrasonic but it has same problem on carpets or fabric.
I tested this that on carpet it was giving a big distance reading but when I place a white paper, suddenly it was fixed and detected surface.

Maybe a contact switch may work?  Maybe one of those end stop switches with rollers.

It may highly depend on what type of carpet you have. But you might get away with adjusting the IR's sensitivity.
I believe it's also a good thing to place something between the receiver and transmitter, to avoid them making "contact" directly instead of by reflection.

Paul, the blue thing on IR sensor is for adjusting distance and I tried it but this adjusting will not work here.

You may have noticed that this product is no longer available from well known parts distributors like adafruit.com, sparkfun.com or trossenrobotics.com. I would recommend using a Sharp distance sensor designed for the distances you are interested in:

It is about 10 times the price, but produces a variable voltage that you can read with the Arduino's ADC.  Then you can compensate for floor irregularities in your code.
If you care to experiment, I obsurved that the better distance measurement devices angle the emitter and sensor to light up & observe the same spot at the desired operating distance:

You might try this with your current sensor.  However, it does not appear the manufacture left you enough lead length to make such an adjustment.

Thanks @st2000 for detailed reply. I have 1 sharp sensor after failing with cheap IR sensor and Ultrasound sensor. I am using it for front distance. I came up with few results. Ultrasound sensor failed on fabric objects i-g. sofa or carpet. I used sharp sensor which fails on dark objects like black surface or very shiny steel sheets. Also I read that it will also fail on sun light or very bright light. I know there are some LDR sensors on ebay but cheapest one is C$300 plus. Other lasers are around C$130 plus. Can you provide the name and product # etc. for this. I can check on ebay.

I have never used a LDR so can not recommend a part.  You could combine the ultra sound and Sharp sensor in software to cover more surfaces.  Also, what about micro wave sensors like those found in construction-wall-sensing devices.


text:
How to Control 2-wire Rotary-Gear Linear Actuator
Any ideas how to control a 2-wire DC 5V 10mm Stroke Mini Linear Actuator based Rotary Gear Motor? Most linear actuators (aside from solenoids) are controlled via 3-4 wires. Do I need a separate motor controller for the actuator to control it via an Arduino Uno?

Second the H-bridge suggestion.

I suspect that's little more than a geared brushed DC motor with a fancy "nut" on it. So yes, you will need any standard motor driver rated for the correct voltage / current (an H-bridge).


text:
DIY Watering - Required components
I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen  a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.
My idea is the following:
A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.
The components that I will be using are an Arduino uno and:

DV12 subversive pump
Irrigation watering kit

Also I guess I will need some tube to connect the pump to the watering kit.
I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.

Use an external 12V power supply and switch it with a suitable transistor or MOSFET.

I have some details about running motors etc. from Arduino pins at Driving motors, lights, etc. from an Arduino output pin.
Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:

In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.
Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.

Yes, though getting a MOSTFET setup right can take some care as they are a bit delicate electrically, so someone doing this for the first time may find it easier to use one of those extremely cheap relay boards.  If the pump is going to either be off or on for at least a few seconds at a time this should work just as well - where a MOSFET really recommends itself is when the pump speed is to be controlled by rapidly switching it on and off hundreds to thousands of times a second.

I was about to ask this, I was aware of these Relays, but now I guess I learn something new. I do only care only for On/Off

You can get digital relays which I'm not sure if that is what @ChrisStratton meant. Effectively they would have a MOSFET in them. If you get a mechanical relay you have the issue of adequately driving the relay coil, and installing a flyback diode to protect yourself from that coil.

No, electromechanical.  Small electromechanical relays require very little to drive - and are commonly sold on boards with an isolated driver and flyback diode.  These are conceptually a lot simpler to deal with, and don't have the same ESD fragility, making them a lot more beginner-friendly.


text:
Choosing rangefinder for obstacle-avoiding
I am looking to buy a range finder module for an obstacle avoidance robot.
Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.
In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?
both need 5V
both have max range of 3-4m
Sensor angle HC- 15 degrees, parallax cant find..

@Spiked3 they can both be made to communicate with 3 pins, but do they have the same detection characteristics? It doesn't say they are actually the same hardware/mics.

Odds are pretty good they are real close. I've only used the sr04 with
  4 pins (too lazy to mod) and it was ok. cant say if the parallax is
  better or not. For 4 times the price you'd expect it to be, but so far
  in robotics, price seldom reflect performance in my experience. –
  Spiked3

I've also used the SR (with 4 pins) and it worked great. <2$ on eBay


text:
Matlab to Arduino communication
I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you

Consider sending printable values just as if you had typed them into the serial monitor.  It is not the most efficient solution, but it is one of the simplest, avoiding the format-matching and synchronization challenges of multibyte binary data.

I am analyzing images from webcam and continuously sending data to Arduino. I solved the part of sending data, but the problem is that the Serial.Available() is updated only once. It receives much of the data as one string. I need it to be updated after every sending from Matlab. There is no interrupt with each serial fprintf basically.

Communications on the leonardo is packetized, so data will arrive in chunks that may or may not match your initial message size.

Turns out Matlab needed me to define a '\n' terminator in the serial fprintf function along with the type of data to be transferred. The problem was solved, thank you for the help.

You cannot send larger values because byte only covers the range from 0-255.
To send larger values, you can break your int variable into 2 byte variables. Here's an example:
// On Arduino
int myVar = -123;
byte myVar_HighByte = myVar>>8; // get the high byte
byte myVar_LowByte = myVar; // get the low byte
// x86 compatible machines are little-endian so we send the low byte first
Serial.write(myVar_LowByte);
Serial.write(myVar_HighByte);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'int16')

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)
Edit: On second thought, it might be easier to use a pointer.
// On Arduino
float myFloat = 3.14159265359;
byte* ptr = (byte*) (&myFloat);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr++);
Serial.write(*ptr);

% On MATLAB
s = serial('COM10')
fopen(s)
myVar = fread(s,1,'float')

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.

you can use all C datatypes available, is this case a short is the better option as it is 2 bytes and matlab can handle it with int16

MATLAB can handle a wide range of numeric data types (see link.) The example code above applies to short (int16) data types just as well, but take note that only two bytes are sent instead of four bytes in the case of float data types.

Trivia: Single precision floating point data is usually referred in C++ as float, whereas in MATLAB it's more commonly referred to as single.

I agree with sentences stated up, but what I was trying to say is that there is no need to use int myVar and then shift it into lower and higher bytes because we can simply use short myVar and Serial.write(myVar). The float part is 100% correct.

Thanks for pointing that out. If the OP only needs integers within the range of -400:400, short would do the job. Clearly, I was too eager to provide a more generic solution to handle multi-types.

If you want to send your data directly from Matlab to the Arduino, you can try using the "Matlab Arduino Support package". It lets you read/write pins on the arduino directly from Matlab command line or script just like you would with a VERY LOW END Data Acquisition card.
This has the advantage of removing the burden of managing the serial communication. I don't know how it handles large numbers though.
http://www.mathworks.com/hardware-support/arduino-matlab.html?refresh=true