text:
Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10
I want to send my Arduino's sensor data to a MySQL database, using XAMPP and phpMyAdmin. I have been using an ESP8266 for the wifi connection. But I am unable to send the value. And actually I have to send four values, but for the time being I am sending only one value. So also please tell how to send multiple values. I have written the PHP file and saved in to Apache's htdocs.
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <SPI.h>
IPAddress ip(192,168,8,1);
char ssid[] = "ZONG MBB-E8372-B67D"; // your network SSID (name)
char pass[] = "08522547"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
int photocellPin = 4; // Analog input pin on Arduino we connected the SIG pin from sensor
int photocellReading; // Here we will place our reading
char server[] =  "192.168.8.1";
// Initialize the Ethernet client object
WiFiEspClient espclient;
SoftwareSerial soft(2,3); // RX, TX

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  soft.begin(115200);
  // initialize ESP module
  WiFi.init(&soft);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }
  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
}

void loop() {
  photocellReading = analogRead(photocellPin);
  // Fill the sensorReading with the information from sensor
  // Connect to the server (your computer or web page)
  if (espclient.connect(server, 80)) {
    espclient.println("GET /write_data7.php?"); // This
    espclient.println("value="); // This
    espclient.println(photocellReading);
    // And this is what we did in the testing section above.
    // We are making a GET request just like we would from our browser
    // but now with live data from the sensor
    espclient.println(" HTTP/1.1"); // Part of the GET request
    espclient.println("Host: 192.168.8.1");
    // IMPORTANT: If you are using XAMPP you will have
    //to find out the IP address of your computer and put it here
    // (it is explained in previous article). If you have a web page,
    // enter its address (ie.Host: "www.yourwebpage.com")
    espclient.println("Connection: close");
    // Part of the GET request telling the server
    // that we are over transmitting the message
    espclient.println(); // Empty line
    espclient.println(); // Empty line
    espclient.stop();    // Closing connection to server
  } else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

Following is the PHP code:
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'connected_car_1');
define('DB_USER','Maryam1');
define('DB_PASSWORD','telecom1213');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql,$con);
mysql_close($con);
?>

And this is my serial monitor output:

I am very new to coding in Arduino as well as PHP and databases. So kindly tell me what I am doing wrong. And do I have to provide the IP address of the server, ie. 127.0.0.1? If yes, then where?

Nice SQL injection attack vulnerability there. (http://yoursite.com/yourpage.php?value=');+drop+database+connected_car_1;--Will people never learn? Hint : Use PDO.

I am not uploading on a webpage. I am uploading on mysql. That is the comment in the code for if you want to upload it on a webpage, but iam not doing that.

You have a piece of PHP code there. That is a web page. It accepts GET parameters.

then how should i upload the arduino reading on mysql?

Through a web page, like you have created. Just learn, right from the beginning, best practices. Your web page, if it were ever public, would be a huge security risk.

I have to submit it after 1 week..so can you help and give some hints so that i learn fast?

Your problem looks to not be anything to do with MySQL, XAMPP, or anything like that. You seem to have a basic inability to communicate on the WiFi network. All those "Timeout" messages should tell you that much at least.  Get the network connection working first and then work on interfacing with MySQL.

i have googled to much already but found this code working much more better to connect to a wifi network. Can you give me some good links?

Step one: run some of the examples that come with your WiFi library to confirm that you can connect to your network correctly. There's huge numbers of warnings and errors in your output that tell me that something is fundamentally wrong with your setup. The ESP8266 is not a simple board to use with an Arduino.

Isn't GET the wrong verb to use when writing to a web server?

#include (avr/pgmspace.h) ^ compilation terminated. exit status 1.
Compile error card NodeMCU 1.0 (ESP-12E Module).

Its not very clear what this "Answer" is for, please can you edit it to clarify or delete it.

@LookAlterno - I know, I was trying to be subtle :)

192.168.8.1 should be your PC IP. Where your apache should be running. You can check it by visiting http://192.168.8.1/write_data7.php and see if the server is ok or not. Then you can try access from another machine to make sure no firewall is blocking you

Not sure how PDO would prevent SQL injection. After error checking data use mysql_real_escape_string()

You should write the PC IP, for example: 192.168.1.53, because 127.0.0.1 is the IP used only for phpmyadmin and the database inside your computer.


text:
Moisture sensor data will not output data to Serial Monitor?
I am making a Soil Analysis system with an Arduino Uno, but I have run into a problem and was wondering if /r/learnprogramming could help!
The moisture sensor section of my code will not output the data to the Serial Monitor in Arduino 1.7.1 IDE. I am not sure why it's not working. Running the moisture sensor code by itself works, and I just copied and pasted that code into my combined code file since I'll I am running 4 sensors at once with my Arduino Uno.
These are the four values I need to output data on one baud rate:

pH value
EC
DHT temperature reading
Moisture Sensor Value
I am currently missing Moisture Sensor Value when I run Combined1.ino

Here is the Combined1.ino code of the code from four sensors together that's uploaded to the Arduino:
Combined Code Link
Moisture Sensor Link
Any help would be much appreciated!

/r/learnprogramming? Are we Reddit now?

Your second print section will always fail.
You have:
if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator

However, a bit before then you have:
if(millis()-printTime>=printInterval)
{
  printTime=millis();

So millis() - printTime can never be greater than printInterval since you have just set printTime to millis(). So millis() - printTime will always be somewhere between 0 and printInterval - 1.
Consider combining your different printing routines into one single printing routine so you are comparing (and changing) the printTime only once.

I got it to work. There is something happening with the DHT22 section that when the DHT22 is not connected, it fails and ends the loop. I just moved my moisture sensor code above that and it is now working. I will see if I can clean it up using this advice.

source: Stack Exchange

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

sort: votes


text:
Writing a float to a BLE characteristic. What data format?
I am currently working on a python-based Bluetooth Low Energy client for OS X and I got stuck while trying to write a remote float characteristic value.
First of all: my setup is an Arduino 101 with integrated BLE module and a Macbook. On the Arduino side the code is working well, I can read and write BLE characteristic's from a BLE explorer app on my phone.
Also I did achieve to read out the characteristics float values in my python script on the Macbook. Yet I did not fully understand what exactly I am doing. After requesting the characteristic's value from the peripheral, the peripheral answers and I get what I think is binary data? I could manage to unpack the data to a float by using.
     def characteristic_to_float(data):
        float_value = struct.unpack('f', data)[0]
        return float_value

The received floats are correct. But I couldn't get my python code to properly write a float value to the peripheral. I tried this:
    a_number = 5.3

    def float_to_characteristic(float_value):
        val = struct.pack('<f', float_value)[0]
        return val

    characteristic_1.write_value(float_to_characteristic(a_number))

The python code itself will run through without an error, but the Arduino doesn't receive the data. I am sure of that, because I implemented a function on it that sends out a Serial print when a characteristic has been written.
Remember the characteristics are read & write and I could verify this by using my phone. I think I got something wrong with the struct.pack thing, since I can't find any information about what data format is needed...
Does someone know how I can pack or convert the float to the right data format? Unfortunately the lib I use (Adafruit BluefruitLE) does not have a documentation.
Thanks!

Try packing and then unpacking the value entirely in python as a test.  Try sending the packed value from the arduino back to it directly as a test.  Figure out how to dump the bytes of the packed value as hex from python for verification, etc...

I could solve the issue by taking another look in the documentation of the struct lib in python. I tested different pack and unpack methods and wondered where the [0] in my code came from (I did copy it from somewhere). So what I found working for my setup simply is:
def float_to_characteristic(float_value):
       val=struct.pack('<f',float_value)
       return val

When I send this packed value through BLE the Arduino will accept it.

Two solutions came to my mind if am gonna do your thing,
1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- > "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)
2) calculate the number of decimal digits and send it with the number something like:
5.3 ---> 53 and one decimal point, you would send it as
53:1 and then unpack it and reconstruct it
the second solution would be better for me since i have to send it as 2 things
number: decimal point
and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions)
SimpleSerialExtractor

I used this way:
define a BLE format descriptor (0x2904)
Attach the descriptor to the characteristic
struct BLE2904_Data {
  uint8_t m_format;
  int8_t m_exponent;
  uint16_t m_unit;
  uint8_t m_namespace;
  uint16_t m_description;
} __attribute__((packed));

struct BLE2904_Data desc1;   // must remain valid memory for ArduinoBLE

  desc1.m_format = 0x14;  // float
  desc1.m_exponent = 0x0;
  desc1.m_unit = 0x2728;  // voltage
  desc1.m_namespace = 1;
  desc1.m_description = 0x10f;

  BLEDescriptor voltageLabelDescriptor("2904", (uint8_t*)&desc1, sizeof(desc1));
  batteryLevelCharacteristic.addDescriptor(voltageLabelDescriptor);

The 2904 descriptor sets the data type see here for more details:

authors: Сергей Анисимов

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

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


text:
In-application programming for the Arduino Uno
I would like to know if it is possible to read from and write to the microcontroller's (Arduino Uno's ATmega328P) flash memory using a program or "bootloader" previously stored in the flash memory (or the EEPROM memory) itself.
If it is possible, can it be done using the Arduino IDE?

@Wossname. Is it possible to separately access the ATmega328P on an Arduino so as to use the tools you have mentioned?

@Wossname. My Arduino Uno board is the same as the image at this link: http://d2rormqr1qwzpz.cloudfront.net/photos/2013/06/12/48912-arduinouno_r3_front.jpg


text:
Arduino Nano (clone) not recognized
Asking here cause I ran out of options in searching. My Arduino Nano clone isn't recognized by my computer anymore. It was, until I plugged into a Windows machine, that did not recognize it... and now even my Linux Mint distro doesn't detect the Nano at all. Here's the thing, though: the green power LED still lights up and, if I connect my DC motor to it like I used to before, the LED turns off and the motor is powered only a little bit, with less speed than if it were powered by a 1.5V battery.
My voltimeter reads a 2.18V out of the 5V pin.
Here's all I did: uploaded a sketch to power a 5v motor, it worked, unplugged the Arduino, took it home to my Windows machine on the casing I got it from my school, plugged it there, then it didn't detect anything. Go back to the lab today, plug it in, doesn't detect it there either.
From there, I've replaced USB cables, tried different USB ports, checked with lsusb and dmesg, tried finding it using the FTDI tool (the chip underneath is FTDI), then tried powering it from a phone charger, but the voltage readings at the 5v pin still are around 2.18V with that. Nothing seems to give this little thing an output greater than 2.18V.
The only thing I haven't tested is powering it through the VIN pin.
I came across other questions of similar problems but nothing that seems quite like mine... since they all either are able to detect the device but it is displayed as an unknown device or can't recognize the device at all but their power LED does not turn on.
Any ideas on what is going on?

When powered by a USB port, the 5v should be coming fairly directly from the USB, possibly via a diode.  So that suggest a problem with the diode, failure of the connector or PCB or its solder, or an overload (perhaps from a damaged chip) causing the USB VBus itself to sag, or an issue with the measurement itself.

How is/was you motor wired up?

This is why you should not power motors from an Arduino's power supply, regulator, or even simply power nets.

Just talking.. Have your flywheel diode been there? Meaning across the Motors terminals?
Because if not that might have broke something.

It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.

This answer pointed me towards a ton of other people experiencing the same problem (usually after accidentally shorting the 5V and ground pins) and this is exactly what it turned out to be for me as well. It seems to be commonplace with clones. Replacing the diode in question (which protects the USB port in the event of an external power supply also being connected) fixed the problems for me.

Apart from 5V pin, the rest sounds like your FTDI clone chip might be bricked. Check your device VID (under Device Manager -> Device Properties -> Details tab -> under Property select Hardware Ids). If VID and/or PID is 0000 than it is.
It is possible restore the original VID/PID (thus recover the Arduino). Google for "Fix bricked FTDI", there are many instructions like this: http://internetofhomethings.com/homethings/?p=987
Most of these cheap Arduino Nano clones have also fake FTDI IC and at some point FTDI (the vendor) released new driver which bricks such clones by setting VID/PID of the chip to 0. This effectively makes the IC undetectable / incompatible with original FTDI drivers. That is why it is not recognized on a PC where it was working earlier.
http://hackaday.com/2016/02/01/ftdi-drivers-break-fake-chips-again/
After recovery, make sure to use older FTDI driver.

What was your schema? did you try to control 5V motor from arduino directly.
Now assuming that
$ lsusb

doesn't show something like:
Bus 002 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

It is generaly a bad idea to control any mechanical (magnetic) device without using transistor and maybe a diode to protect against current in an opposite direction
standard DC motors can generate quite a nice voltage if turned mechanically (during transport) or even current increase if motor is blocked when powered.
TO me it sounds like you have burned your chip. USB on most computers has got an over-current protection resulting in lover voltage if something you connect has very low resistance.
2.8volt is more then enough to lit-up green LED on a damage MCU, but probably not to power the FTDI chip wired for 5V

Standards compliant USB ports will only supply 100mA unless a higher current is negotiated by USB.
I suspect that you problem is the USB serial (Chinese Nano clones often have cheap chips). This happened to one of my Nano clones.

I'll go to the maintenance lab tomorrow at my school, and see what they tell me. It's rather strange, since this is the second Nano that has some problem on my end.

It may be caused by the cable. In my case it was. Not all cables have data wires.

The OP indicated that it worked before so... how should the cable change (except mechanical cutting/breaking which would probbly affect other lines too)


text:
Accessing configuration registers of OV7670 cam on i2c
I am a new user of Aurdino and want to interface OV7670 camera with aurdino uno which uses i2c mode of communication.I want to check the configuration of the device control registers and set them as per requirement. In this case, OV7670 is my slave device.
     How can I access a particular register inside the slave device?(The parameters for commands like wire.begin() etc., include slave address but not the address of the registers inside a slave device.)

I think this belongs on the Arduino SE

Thanks - my comment is meant to suggest that this question be migrated to the Arduino StackExchange site.

To communicate with the OV7670:

SIOC => SCL
(pulled up to 3.3V)
SIOD => SDA
(pulled up to 3.3V)
RESET => 3.3V
PWDN => GND
XCLK => Clock signal is necessary (at least 10 Mhz)
Vcc => 3.3V
GND => GND

The XCLK needs at least 10 MHz according to the datasheet, but from other accounts, it seems that's not a hard limit. You can get a 4 MHz clock from the Uno using its timer0; check out this post on how to do it. After this, you can write a small sketch along the lines of:
Wire.begin();
Wire.beginTransmission(0x21);
Wire.write(0x12);  // software reset
Wire.write(0x80);
Wire.endTransmission();
delay(500); // wait for reset to complete

Wire.beginTransmission(0x21);
Wire.write(0x01);  // u now read from reg 0x01
Wire.endTransmission();
Wire.requestFrom(0x21, 1);
while (Wire.available() == 0);  //block till u get something
while (Wire.available())
  Serial.println(Wire.read(), HEX);

You can place everything in setup() after including the Wire library and setting up the XCLK clock signal. If all goes well, 80 should be printed in the serial monitor and this will confirm that you're now communicating over the SCCB with the camera.
I should warn you that while others have used the Uno to grab images from the OV7670, the process is moderately complex, especially for a beginner, and it's not what the Uno is intended for; all you'll be able to do is grab frames and pass them on to some TFT screen or your PC and even then you'll get at most 5 fps, I think, with QVGA or QCIF output. You'd be better off with some ARM dev board, one running Linux perhaps. Good luck.

Take a look at the datasheet - that will show you the correct waveforms / transactions for this. However, something like this should work (assuming 8-bit addresses and registers)
// reading

Wire.beginTransmission(address);
Wire.write(reg); // set address to read from our requested register
Wire.endTransmission(false); // repeated start
Wire.requestFrom(address,(unsigned char)1);  // just a single byte
if(Wire.endTransmission()!=0){
    // put error code here
}
readValue = Wire.read();

// writing

Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(value);
if(Wire.endTransmission()!=0){
    // put error code here
}


text:
Which (Official) Arduino IDE to use?
I have bought an Arduino UNO that turned out to be the Italian version (Arduino SRL) not the American one (Arduino LLC).
Now when I go to arduino.org and arduino.cc, they both have different versions of the IDE!
So, which one should I use (if they are even different) ?

Neither. Use UECIDE ;)

Seriously though, the real answer is "It depends which side of the argument between the two Arduino parties you are on". Personally I am on the side of the .CC camp, so I would recommend to use the .CC version. Someone on the side of .ORG would recommend the .ORG version to use.

Possibly unnecessary warning: if you are expecting to have a coding experience similar to other IDEs, you might be surprised that there are "magic" includes rules and what would normally work in a typical GNU-like project might not work. This is meant to simplify the life to beginners, but not everyone likes it. The alternative is to use a plain Makefile and your favorite means to deal with Makefile - based projects.

.CC are open and welcoming. .ORG are sneaky and underhanded. For instance they create the same IDE but with a higher version number, so it appears newer than the .CC version. They also include (or have attempted to include) code to stop you being able to use non-.ORG boards.

Personally I would use the Arduino.CC version. However I'm going to close this question as being primarily opinion-based. Sorry about that.

You can use both IDEs no matter of the origin of the UNO even fake ones runs with the IDEs.
The arduino.org IDE is just a fork of the arduino.cc.
But arduino.org has many Board which are only run with the .org IDE.


text:
Arduino RS232 Shield with SD Card conflict
I have an Arduino Mega with a Ethernet2 Shield + RS232 Shield
SD Card works well with Ethernet2 Shield, but it get a conflict when I add the RS232 Shield.
Both hardware use the same PIN:
#define RS232_DIR_PIN     4 // RS232 Shield
#define AMS_SS_SD         4 // Ethernet Shield

 pinMode(RS232_DIR_PIN, OUTPUT);             //Set RS232 direction pin as output
    digitalWrite(RS232_DIR_PIN, LOW);           //Set RS232 chip as receiver

    //Set SPI to Read SD Card
    pinMode(AMS_SS_HARDWARE, OUTPUT);
    digitalWrite(AMS_SS_HARDWARE, HIGH);

I dont need both running at same time, but I dont know how to make only one work at a time.

You will need to physically modify one of these to use different pins.

@ChrisStratton, do you know wich pin I could use for them? for Arduino Mega

Probably any available I/O, it's more a mechanical issue of what you can access.

@ChrisStratton, it worked, just moved the RS232 Pin to 5 physically. Set this as an answer. thanks


text:
Get value from a website using Yún and a RPi
I have a project that requires opening a door remotely. I'm using an arduino Yún and a raspberry pi.
 I have a switch connected to the RPI and i'm sending it's value to a web server. How can I get the value from the website to the arduino, so that it can process it and see if an order to open the door is issued?
Thanks for any help :)

Do you want to do it from the Linux portion or the AVR portion of the Yun?

I want to check the remote value (located on a web-site) using AVR.

You need to use the Process library that comes with the IDE.
That allows you to execute commands on the Linux portion of the Yun from within your Arduino code, and get data back from it.
You use that class to execute the curl command in Linux to fetch the content of a web page and return that content to the AVR code where you can deal with it.
If the content of the web page is complex it may be worth passing the output of curl through some other Linux based commands first (such as grep and cut or awk) to clean it up and reduce the amount of text you have to deal with at the AVR end.


text:
Getting POST data into a char array
I'm using Energia to program TI's CC3200 MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.
I'm trying to get the CC3200 to act as a Webserver which when successfully starts up serves up a page with two fields for the username and password that the user needs to fill. Now I'm able to see that the two fields are being successfully POST'd (through Serial.write but only when the code to get it into buffer is not present) but I was hoping someone can help me get this content into a character array (called buffer declared before the setup loop begins).
The code in the section //Here is where the POST data is does not seem to be working as I see garbage values in buffer and in the Serial.write. How do I get these POST values into buffer OR even better how do I split the two field values and store them into two separate character arrays?
void loop()
{
  // listen for incoming clients
  WiFiClient client = server.available();

  if (client) {
    //Serial.println("Client connected");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected()) {
      while(client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

            // Here is where the POST data is.
            Serial.println("Post data: ");
            int ctr = 0;
            while(client.available())
            {
            Serial.write(client.read());
            buffer[ctr] = client.read();
            ctr++;
        }
        Serial.println("Buffer: ");
        Serial.write(buffer);
        Serial.println();

        //Serial.println("Sending response");
        // send a standard http response header
        client.println("HTTP/1.0 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: keep-alive");
        client.println();

        //form added to send data from browser and view received data in serial monitor
        client.println();
        client.println("<!DOCTYPE html>");
        client.println("");
        client.println("");
        client.println(" <FORM action=\"\" method=\"POST\">");
        client.println("
");
        client.println("    Username:");
        client.println("    <INPUT type=\"text\" name=\"uname\">

");
        client.println("    Password:");
        client.println("    <INPUT type=\"text\" name=\"pwd\">

");
        client.println("    <INPUT type=\"submit\" value=\"Submit\">");
        client.println("
");
        client.println(" </FORM>");
        client.println("");
        client.println("");

        client.println();

        client.stop();
        }
        else if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    //Serial.println("Disconnected");
    Serial.println();
  }
}

What sort of garbage data are you seeing?

In this loop
while(client.available()) {
    Serial.write(client.read());
    buffer[ctr] = client.read();

you're using client.read() twice, so the buffer gets only every second character.
A solution could be:
while(client.available()) {
    int c = client.read();
    Serial.write(c);
    buffer[ctr] = c;

Thanks! This code worked great!
int ctr = 0;
while(client.available())
{
buffer[ctr] = client.read();
ctr++;
}

Any idea why this loop runs twice? I see two outputs of the buffer. Is it once when I enter the URL and hit Enter and the second when I hit Submit?


text:
Character array weirdness
I'm using Energia to program one of TI's MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.
I'm building a simple UDP packet sender and receiver app. The MCU starts up and connects to the local Wifi network and waits for a packet from another device on the same network.
This packet is collected in a char array char packetBuffer[16];
I want to split this array into two separate arrays each of 8 elements. These are char lampCmdRead[8]; and char pwdReadBuffer[8]; Now the network bit works great. I can send the packet through my desktop and receive it on the MCU. However when I split this array I see that the pwdReadBuffer shows the same contents as packetBuffer even though they are of different sizes. How is this possible?
Here is the code:
char packetBuffer[16];
char lampCmdRead[8];
char pwdReadBuffer[8];

// This is code from the 'void loop()' section
int packetSize = Udp.parsePacket();

if(packetSize) {
 int len = Udp.read(packetBuffer, 16);
 if (len > 0) packetBuffer[len] = 0;
 Serial.println();

 Serial.println("packetBuffer:");
 Serial.println(packetBuffer);
 Serial.println();

 for(ctr = 0; ctr < 8; ctr++) {
   pwdReadBuffer[ctr] = packetBuffer[ctr];
 }
 if (len > 8) pwdReadBuffer[len] = 0;

 for(ctr = 0; ctr < 8; ctr++) {
   lampCmdRead[ctr] = packetBuffer[ctr+8];
 }
 if (len > 8) lampCmdRead[len] = 0;

 Serial.println("pwdReadBuffer:");
 Serial.println(pwdReadBuffer);
 Serial.println();

 Serial.println("lampCmdRead:");
 Serial.println(lampCmdRead);
 Serial.println();
}

And here is the output:
Received packet of size 16
From 192.168.1.101, port 55056

packetBuffer:
2qZ@X51Rredledon

pwdReadBuffer:
2qZ@X51Rredledon

lampCmdRead:
redledon

You're overflowing your buffers.

Also you're not terminating your strings properly.

if (len > 8) pwdReadBuffer[len] = 0;

This line is unsafe.  You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write outside of the target buffer, with unpredictable results.
You make a related mistake here:
if (len > 8) lampCmdRead[len] = 0;

First the test should be >= but again, such a value would be beyond the end of the target buffer.
Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.
If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage.  And of course you need to only use in-range indices to access the elements.

This behavior (where contents of pwdReadBuffer print out the same as those of packetBuffer) is occurring because you haven't properly null-terminated your strings.
After you copy the first 8 characters of packetBuffer to pwdReadBuffer the statement if (len > 8) pwdReadBuffer[len] = 0; gets executed.  It sets pwdReadBuffer[16] to 0, ie, references out of array bounds.
Apparently lampCmdRead is allocated directly after pwdReadBuffer, so when you copy the next 8  characters of packetBuffer to lampCmdRead, they are being copied, in effect, to pwdReadBuffer[8] ... pwdReadBuffer[15], so that the println prints a 16-character string,
2qZ@X51Rredledon.
For each of your three arrays, allocate an extra byte for a null terminator.


text:
Converting an array of uint8_t to a char array
I'm trying to convert this array uint8_t data[] in the code below to a character array to be printed in the serial monitor. However, when I run this code I see a blank screen. What am I doing wrong?
Serial.begin(115200);
uint8_t data[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05};
Serial.println((char*)data);

In what way do you want to "print" it? Converting it to char * just makes the compiler think it's a string, which it isn't. Those aren't the ASCII values of printable characters.

When you cast as char *, println thinks you are passing it a string. It will try to print it as a string and stop on the first 0x00.
You can use Serial.write to send the array as integers (no conversion):
Serial.write(data, sizeof(data));

If you want to send the ASCII representation of these numbers, use a loop. Serial.print will convert:
int count = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < count; i++) {
    Serial.print(data[i]);
}
Serial.println();

A quick Q: Why are you dividing sizeof(data) by sizeof(data[0])? Wont just sizeof(data) suffice?

sizeof(data) gives you the size of the array in bytes. What I did gives the number of items in the array.

To print numbers, integers have to be converted to ASCII code.  To accomplish this add 0x30 to each value.  Note, this (only) works for numbers between 0 and 9 as the ASCII value for zero is 0x30.  Good code will check to make sure only the values 0 through 9 are being processed.
When creating a character string you need to identify the end using the NULL character.  Before using an array of characters, set the array position after the last desired character equal to NULL or 0x00. Terminating the string is explained further in this article.


text:
Extracting a specific sequence of characters from an array
I have a character array called storebuffer that contains data from a POST submission and its in the format ssid=abcdef&pswd=ghijk. I wanted to extract everything after ssid= into one array called acqSSID and the portion after &pswd= into another array called acqPaswd. I tried using this but it does not seem to be working. MAX_STORE_BUFFER_LEN is 255. Can anyone help?
int ctr = 0;
for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
{
  if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
  {
    break;
  }
  acqSSID[ctr] = storebuffer[ctr];
}

Serial.print("acqSSID: ");
Serial.println(acqSSID);
Serial.print("ctr: ");
Serial.println(ctr);

You can simply chop it up in place without requiring more than a few extra bytes of RAM using strtok():
char storebuffer[] = "ssid=abcdef&pswd=ghijk";

// Slice it into two parts around the &:
char *lefthalf = strtok(storebuffer, "&");
if (lefthalf != NULL) { // We found a & and split the string OK
    char *righthalf = strtok(NULL, "&");

    // Now you can slice each half around the =
    char *ssidtag = strtok(lefthalf, "=");
    char *ssid = strtok(NULL, "=");
    char *pswdtag = strtok(righthalf, "=");
    char *pswdtag = strtok(NULL, "=");

    Serial.print("SSID: ");
    Serial.println(ssid);
    Serial.print("Password: ");
    Serial.println(pswd);
}

The existing string gets chopped up and the pointers point to different places:
ssid\0abcdef\0pswd\0ghijk
^     ^       ^     ^
1     2       3     4

1: ssidtag
2: ssid
3: pswdtag
4: pswd

Rather than acqSSID[ctr] = storebuffer[ctr];, say (eg) acqSSID[ctr-5] = storebuffer[ctr];.  Also, after the break but before printing acqSSID, say acqSSID[ctr-5] = 0; to terminate the string.
Note, rather than coding a literal 5, you might say enum { acqOffset=5 }; up front, and subsequently use acqOffset in place of the literal.


text:
Atmega328p ISP won't work
I have a grbl board that runs on an Atmega328p. On the board I have also provided the ability to control the stepper drivers through an external control step and dir signals. The schematics are shown here. For the sake of simplicity, the Atmega328p's ISP part of the schematic is shown. Now since the datasheet for the MCU says that when its not powered, the MCU pins should not see voltages more than Vcc+0.5V and less than -0.5V. Which is why the control signals from the Atmega328p are OR'd with the external signal inputs. The limit and spindle signals are buffered through a dual buffer.
Now on another revision of the board without this added feature of being driven from an external control logic, everything works great. However, on this board, I'm not able to program the Arduino bootloader using the ISP header (using a Pocket AVR programmer). I'm was not sure if these OR chips and the buffer were interfering somehow which is why I removed them from the board and I'm still not able to program the Atmega328p with the Arduino bootloader. To eliminate a kaput programmer as the cause for the issue, I tried using the programmer on the earlier version board and everything works great there.
TL;DR, ISP programming won't work on this board and I'm not sure if the added OR and buffer chips are interfering. Any help would be appreciated.
The schematics:

My guess: MISO-D12-LIM-Z is driven stronger by NLWZ16 than by programmers MISO. Try to add 1K resistor between NLWZ16 output and MISO line.

@KIIV Ah I see, so that the ISP programmer gets priority. However, when the ISP is connected, there is nothing on the input of the NLWZ16. Which means there is nothing on the output of it as well and it really is not driving the MISO line.

That doesn't mean its output is disconnected. It's driving low or high level or it's catching interferences and it's random. Anyway there is no HI-Z (It is not Tri-State buffer nor open collector ...)

@KIIV You were right and that worked! Thanks.


text:
Reading a .csv file element wise
I'm fairly new to arduino programming and C/C++. I would like to read a .csv file element wise, and send each element via. a nRF24L01 tranceiver to a raspberry pi. Right now I'm able to read the .csv file with Serial.write(<file>.read()). I was wondering if there's a way to read each element one at a time, if so how would i do that?
My thoughts (Pseudo code-ish):
loop through every element in .csv file {
    save the current element to X.
    send X to raspberry pi (I already have a function for sending)
}

I hope someone can help. Thanks in advance.

Take a look at this post. Since the file is csv, you can construct a similar approach using a sscanf on each line you read.

Are all your CSV values all numeric, or do you have textual data in there as well?

The read() method works character-wise, not element-wise. Then you
have to rethink your algorithm to loop over characters:

store each character in a buffer
send the whole buffer (i.e. a single element) when you see a delimiter

Example:
const size_t BUFFER_SZ = ...;
char buffer[BUFFER_SZ];
size_t pos = 0;    // current write position in buffer
int c;

// While we can read a character:
while ((c = <file>.read()) != -1) {

    // If we get a delimiter, then we have a complete element.
    if (c == ',' || c == '\n') {
        buffer[pos] = '\0';         // terminate the string
        raspberry.println(buffer);  // send to the RPi
        pos = 0;                    // ready for next element
    }

    // Otherwise, store the character in the buffer.
    else if (pos < BUFFER_SZ-1) {
        buffer[pos++] = c;
    }
}

Here the buffer is sent as a string. If you want to parse it into a
number, you can use sscanf.
This code assumes Unix text-file conventions, i.e. each line of the file
(including the last one) being terminated by an LF character. You may
have to adapt if your file is different.


text:
I need more memory!
I am trying to make a RBB Arduino based project and I only need 3 pins. In the future I may use one to two more. I wanted to use an ATtiny85 however my code is 13,270 bytes and it would not fit. So I decided to use an ATtiny84 but it also would not fit, it will fit on an ATmega328p but I do not want to use one because i want to keep the project relatively small and I for sure do not need that many pins. Does anyone know of a chip that has a lot of memory but not many pins, or some other solution. Thank you, any help is appreciated.

Have you tried Atmel's parametric search tool yet?

AFAIK, 8 KiB of flash is the most you can have on an AVR in a DIP
package with less than 28 pins. If you do not mind soldering
surface-mount parts, the 328P is available in TQFP and VQFN packages,
significantly smaller than the DIP version.
Otherwise you could try to optimize your program to fit in 8 KiB.
The Arduino libraries are often inefficient size-wise, and in many
instances you can save quite a lot by rewriting the parts that you need
on top of just avr-libc. Note that
this libc is always linked to your program by the Arduino IDE.

Ok, I tried to optimize my code but could not get it much smaller. I guess my best option is to use a TQFP version, I didn't think about that. Thank you.

There are a few ways to optimize your code and reduce the size. Have a look on this document from Atmel. I've used some tips to reduce the size of my bootloader once.
http://www.atmel.com/images/doc8453.pdf
For the AVR family I'm not familiar with any option. You could use a small QFN package for the atmega328p as well... You might find some small ARM with much more memory and small size.


text:
Bluetooth module is neither sending nor receiving data at baudrate(115200)
Im sending data between my arduino and android via bluetooth, using a simple chat app called "Bluetooth Terminal" . the code work perfectly at baudrate(9600) but I need to increase the speed to that of (115200) but nothing gets transmitted, or at least visible, anymore.
here's my code
#include <SoftwareSerial.h>

const int TXD = 3;
const int RXD = 4;
SoftwareSerial mrBlue(TXD, RXD);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mrBlue.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:

  if (mrBlue.available() > 0) {

    String data = mrBlue.readString();
    Serial.println(data);

  }

  if (Serial.available() > 0) {

    String data = Serial.readString();
    mrBlue.println(data);
  }

  delay(20);
}

Software serial is not working good with 115200 speed because of too much CPU usage. When I'm using only the bluetooth communication in Arduino, I'm connecting HC-05 (for example) to hardware serial pins and everything works fine.
If you want to increase the speed you must also change it in AT mode.

Software serial is really limited because it needs relatively precise timing, full attention of CPU and there can't be any interruptions from other sources.
You can see source code for better understanding how it works.
And if you need faster communication, you should get board with more hardware serials.


text:
how to use an object of a class within that same class?
I want to write a tree data structure made up of Nodes, but I'm having a problem with my Node.h class as each Node need to have a reference Variable to other Nodes,it's children. which ends up giving me the following error

"field 'child' has incomplete type"

so I thought to myself if I was to #include "Node.h" within my Node.h class which gave another error

"#include nested too deeply

how can I have reference to my child Nodes within my node class

With a forward declaration.

thanks, I'm new to c++ so i didn't know that . anyways, i define my child node as Node* child; is this correct?

Yes node* is a pointer.  Always make sure you initialise a pointer to NULL though, and check to see if it is NULL before you do anything to it.
And don't forget to free the memory when you have finished with it.  And never mix new/malloc and delete/free

You will need to forward declare the class and add a pointer to it from within  the class.  i.e.
class CElement;  // Forward declaration

class CElement
{
public:
    CElement();
    ... // Other functions
private:
    CElement *m_NextElement;
};

Just to be clear you can't have your class as a member variable, it has to be a pointer or a reference.  This is because:

You can't use a type that hasn't been fully defined.
You would end up with your class consuming an infinite amount of memory, because every node would contain a node, which contains a node, etc...

You don't actually need to pre-declare the class the way you did on your first line: the class CElement is known about by the time the compiler gets to the CElement *m_NextElement; line

Also, check your "Just to be clear" line: you say "you can have your class as a member variable" - you mean "you can't". If you want you can have it as a reference - you imply you can't.

@Matt thanks, I added the forward declaration to my Node class. while i did manage to solve this I'm having a lot of trouble understanding when to use * or -> and new keyWord

@JohnBurger - Thanks, good spot.  My fingers were traveling faster than my brain.  Hopefully corrected them now.

@Matt Why do you think you can't have it as a reference? It may not be useful (in this instance), but it's certainly legal.

@Raed Its difficult to guess your code, but assuming this is a simple class, I don't think you need to use a * except in the declaration of variables where it declares a pointer.  In the code pointer will give you the data that is pointed to by pointer, which you can access with ->.  You use new to allocate memory CElement pNewObject = new CElement(); and delete pNewObject should be all you need.  However I would recommend that you check that pNewObject has been allocated after the new and before the delete calls.  if (!pNewObject) // If not allocated report error.

@Raed: About "understanding when to use * or ->": *pointer means the thing pointer points to. It could be a simple entity like a number, or a whole bunch (tech term, heh) of entities like an array or a struct or a class. pointer->foo means the member named foo within the thing pointer points to. (In this case the "thing" would have to be a struct, a union, or a class, to have named members).

If you have a class like this:
class Node {

public: // Methods

    inline Node() :
           left(nullptr),   // No children yet!
           right(nullptr) {
    } // Node()

public: // Variables (normally this should be private, but for this example...)

    Node *left;
    Node *right;

}; // Node

Node root; // The root of the tree

You now have a class that has two members, both pointers to Nodes. Obviously there's going to be more data in there - strings or whatever - but let's ignore that for now.
I've also created the root of the tree - note that I didn't use new! It's a file variable that is always accessible, and there's not an * in sight (except inside root...).
What are left and right? Pointers to the children. They are not the children: just pointers to them. As soon as any Node is created (after the constructor has finished), the Node has no children - both pointers are nullptr.
So (ignoring any attempt to sort the children into place) you could now do the following:
void AddChildren() {
    Node sister;           // Create a sister
    Node brother;          // Create a brother
    root.left = &sister;   // Point to sister
    root.right = &brother; // Point to brother
} // AddChildren()

Note you couldn't do node.left = sister; - you're not trying to put sister inside root, you're only trying to point to sister with one of root's children. So you take sister's address with the & operator.
Only... as soon as AddChildren() exits, both sister and brother are destroyed (they're local to the function, so get destroyed as the function leaves) - but root is still pointing to where they used to be! It doesn't know that they are dead!
That is why you call new. It creates the object on the heap rather than the stack, and the object stays around until explicitly destroyed with delete. Only, new returns a pointer to the object, not the object itself. So:
void AddChildren() {
    Node *sister = new Node();  // Point to new object on the heap
    Node *brother = new Node(); // Point to new object on the heap
    root.left = sister;         // Already a pointer! Just copy it
    root.right = brother;       // Already a pointer! Just copy it
} // AddChildren()

Or, perhaps easier:
void AddChildren() {
    root.left = new Node();  // Point to new object on the heap
    root.right = new Node(); // Point to new object on the heap
} // AddChildren()

Now, how do you access the different fields inside Node? It depends on whether you're accessing them through an object or through a pointer:

Through an object?
With ., like root.left above
Through a pointer?
Using ->, such as ptr->left

So finally, how can you use it for real?
// TraverseTree is going to call a function that looks like this:
typedef void TraverseFn(const Node &node);

// Traverse a (sub)tree, calling the passed-in fn() on each Node.
void TraverseTree(Node *node, TraverseFn *fn) {
    if (node == nullptr) { // Nothing to traverse!
        return;
    } // if
    TraverseTree(node->left, fn);  // Trees love recursion!
    fn(*node);                     // Call the passed-in fn with node
    TraverseTree(node->right, fn); // More recursion!
} // TraverseTree(Node)

And you can call the above with:
// A function to print the contents of Node
void PrintNode(const Node &node);

// Traverse the whole Tree, from root, calling PrintNode at each Node
TraverseTree(&root, &PrintNode);

Beware! Do not pass! Here be dragons!
(or at least pointers to member functions...)
Personally, I would have put TraverseTree() inside Node:
class Node {

public: // Methods to call with Traverse()

    // Print this Node
    void Print();

public: // Traverse

    // This is the type of the function that Traverse will call
    typedef void TraverseFn();

    // Note we're passing in a pointer-to-member-function!
    void Traverse(TraverseFn Node::*fn) {
        if (left != nullptr) {
            left->Traverse(fn);
        } // if
        (this->*)fn();
        if (right != nullptr) {
            right->Traverse(fn);
        } // if
    } // Traverse(fn)

}; // Node

If you do that, you'd print out the tree like this:
root.Traverse(&Node::Print);


text:
Arduino as an automation controller
I am considering using an Arduino as a controller for a water treatment system and would love to hear your opinions. All it has to do is open/close a water gate (by starting/stopping a motor) at predefined times. It would have to...

Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)
Log data which would be easily retrievable
Ideally, be able to connect to a cell network and send/receive packets. I believe there is a shield for this
Consume MINIMAL POWER. All it has to do is flush once every few days, log data, and possibly receive data from shield/usb. It would be running off of a solar panel and battery. In winter it could run out of power.

And thats pretty much it! Can this project be done with an Arduino? I would greatly appreciate any advice and recommendations!

Where's the power for the motor coming from? Staying on the cellphone network 24/7 would consume quite a lot of power (think of your phone and how often you have to charge it). If you have enough power to operate a motor powerful enough to open a gate, there should be some over for the Arduino. See my page about power.

The power for the motor also comes from the the battery(which comes from the solar panel). I'm getting the feeling that power is going to be the limiting factor here... And thank you for that link I feel it will be very helpful!

If there is enough power to run the motor, there is enough power to run the Arduino. If you have a clock chip on board with a lithium cell battery backup (as clock chip boards normally have) then you could survive a few days of insufficient power. When the sun comes out the Arduino can power up, and then decide if it is time to turn on the motor.

Does the arduino do this automatically? Or is this something I will program the avr chip to do?

Do what automatically? Everything it does you need to program it to do.

Does the arduino automatically run on the internal battery when input power is low i mean

I was referring to the clock chip shown in the photo in my answer. Those chips are designed to switch to the clock battery backup if there is not enough power to the chip's Vcc pin. The Arduino however does not have an internal battery.

Have a look at my Temperature and humidity sensor - battery powered. That works from 3 x AA batteries, and has been going for a few years. I think I replaced the batteries once. It keeps track of the time, and logs data to the disk (SD card).

I don't have room to describe the whole project here, but the general idea is that the processor sleeps most of the time (consuming around 6 µA). Now this particular project doesn't turn on a motor, but adding a solid-state relay should be all you need to do that.

Be able to connect to a phone using a usb cable. The phone would act as a UI to change settings and water flush times on the Arduino (via a custom app)

I think this will take a lot of power, keeping the phone active. One possible thing to try would be to power up the phone (eg. using another relay) during a certain "window" of time (eg. 6 pm to 7 pm). Then you would know to try to configure the device during that time.

I was thinking of having an app that people could download, then when they went to the site plug in their phone to the arduino there. It seems like it could be a way to avoid having a display running, except when somebody connects their phone. It would be very power intensive when connected though

If they are going to be onsite anyway, some sort of configuration screen might be easier. Eg. a LCD display to show various options, and a keypad to enter data.

So first of all, if the voltage of your systems is too high, arduino cannot provide that on its own. Arduinos can only provide 5v out with the rail. So you could use a relay shield, an add on board to stack on top of it, or just plain old relays with some soldering. Now, for connectivity, try this thing. http://www.annikken.com/andee/ It is relatively easy to learn, and you can build a decent UI without the need for coding an app. I think you can get them for ~30$. However, I do not know how well the arduino can run with so many shields. For data logging, a few companies make data logging shields, or you can get an external read/write and wire it up. I have a small, probably 3" by 8" solar panel for my arduino and it is quite unreliable even in low power applications. However, if you have a good one, that is cool. Best of luck -Peter

I have not had a chance to play with the battery yet, so I don't know what I will need. I will keep the relay shield in mind. The andee shield looks interesting too I'll check it out!


text:
Set EEPROM from PC before program
I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.
All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?
Thanks for your help!
-sam

No, strings loaded from EEPROM take SRAM, not flash.

The simplest way would be to have two sketches.
One that will store all the strings into EEPROM.
After that you can upload the second actual sketch that uses the values stored in EEPROM.
You only need to upload the first sketch if any of the strings change.
There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.

I think here is a confusion about the three types of memory. EEPROM, FLASH and SRAM are completely separate. EEPROM is like your file storage. FLASH contains you program and static values. SRAM is the memory the program is working with.
Static values are loaded from FLASH into SRAM upon start unless you declare your static content not to load automatically by using the according Macro PROGMEM. In that case it does not eat up your SRAM until you manually read it from FLASH into SRAM. #include <avr/pgmspace.h> is used for this (pgmspace.h).
EEPROM is not loaded automatically and therefore must be read explicitly. #include <avr/eeprom.h> contains all the functionality (eeprom.h).
I'm not sure about the Arduino IDE but with avrdude you can program the EEPROM separately without having the values been predefined in your program. The third example in the AVRdude manual shows how to flash the program, eeprom and fuses at once.

thanks I'll check out the avrdude example! that may be what I am looking for

You don't need two sketches:
#include <avr/eeprom.h>

char e2str[] EEMEM = "Hello, world!\n";

void setup()
{
    Serial.begin(9600);
    uint8_t *ptr = reinterpret_cast<uint8_t *>(e2str);
    while (true)
    {
        char c = eeprom_read_byte(ptr++);
        if (c == '\0') break;
        Serial.write(c);
    }
}

void loop() {}

Compile (Sketch>Verify/Compile) the source above and you should find file named <sketch-name>.ino.eep in project's build directory.
For Arduino Nano, you can just run avrdude with -U eeprom:w:<path-to-eep-file>:i option before Sketch>Upload.
For Arduino Uno, however, you must first program it's EEPROM using programmer, since Optiboot doesn't support writing to EEPROM. Or you can burn it with Arduino Nano bootloader once (Tools>Board>Arduino Nano, Tools>Processor>ATmega328, Tools>Burn Bootloader) and then use the procedure for Arduino Nano. (Arduino Uno and Nano bootloaders use different baud rates).


text:
Arduino as wireless network host
I have a rather simple question, which I cannot seem to find the answer to online.
I would like to host a wireless network using an arduino. Other devices could connect to and communicate with the arduino. Could I do that with a shield like this?
Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?
Thank you!

While not impossible, this is generally a bad idea - a classic Arduino is desperately short on memory and computational resources to manage network communication with one other station, let alone several.  There are far more capable alternatives out there at lower prices - esp8266, router chipsets, etc.

Yes!
You can absolutely do the above said task with the shield that you provided information about.
All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!
Then you'll have to replace the SSID and Password with your WiFi's password.
Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.
Note the IP Address and open any browser on any device of your choice.
NOTE-
Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.
You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.
Here's the link to the detailed explanation from arduino.cc itself.
Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"
Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).

Can a device connect directly to the arduino? Rather than both connecting both devices to an existing network, I would like to broadcast a network FROM the arduino.

Yes ! Absolutely but not with this shield. That requires both the device and the Shield to support ad hoc wireless mode, most of the devics do have the ad hoc conectivity but the Shield does not! So you have to find another shield for that and then it would work! But as far as this shield is concerned This is the only possible way to set up a server!

It looks like the ESP8266 supports this! Thank you :)

If my answer helped you then you can upvote/ mark it correct answer Thank you :)


text:
Average response time of Esp8266 module
I'm planning a project where I'd like to control an RC car with Arduino and an Esp8266 module.
A software running on a computer would read the input from an USB analog controller and send the data to the Esp8266 module through the wifi network, and the Arduino would read this data and send signal to the ports accordingly.
What I'd like to know is: would ping/delay be an issue? Considering a dedicated wifi network for this, so the only devices connected to it would be the computer and the Esp8266 module.
I need to know what is the average response time of the Esp8266 module before I buy it, because if it is too high I'll think of something else since for this project I'd need a reasonably high response time.

we can't say what your "average response time" will be, because it depends on your physical environment and how many other wifi devices you are surrounded by that are on (or close to) the channel you choose. My opinion is, as you are only using the ESP as a serial-to-wifi bridge, there are better devices you can attach to an arduino for radio communication - although this would make the (sending) computer side more complicated

I'm pretty sure it can be made to work.
I have a home server with several devices attached to it, including 2 ESP8266 modules - one at home and one in my office. All devices connect using permanent TCP connection and respond to my custom "ping" requests over that connection. Typical round-trip response times are bellow 50ms and often bellow 10ms. There are occasional "hickups" of 100+ms, but they are rare and could be a result many factors. Note that these 2 ESPs are programmed in Lua, which is not optimal efficiency - I was just lazy and the tasks they do are simple enough to not matter.
Most probably if you start an HTTP server on the ESP and bombard it with HTTP requests every time you move the joystick it would be horribly laggy. But with a plain old TCP connection or even a consistent flow of UDP packets I'm pretty sure you will get good results.
Also, I would ditch the Arduino and use only the ESP - you should have no problem controlling two motors (most probably via motor driver board or chip) and perhaps a servo from the ESP directly. This would eliminate the additional lag of serial communication and parsing the serial data. It would also reduce the cost and size of the project.
Having that said, other solutions, like bluetooth or even RF modules should also work, but you asked whether the ESP can do it - and my answer is yes.

It was a bit tricky since both answers were stating two different things. I'm going to accept yours because the TCP connection hint was a big help. My module is coming this week, so I'm finally going to be able to test it out. Unfortunately bluetooth is out of the question, since I need analog input for the speed control, and bluetooth analog controllers are quite pricey.

I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.
Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.

If you use websocket it will have a really good response time.
It is a test about it:
https://www.youtube.com/watch?v=8ISbmQTbjDI
I use it for a quadcopter controller.


text:
Brushless motor "jiggles"
When I run my code, the ESC makes some noises, different on the high pulse and low pulse, then it begins to jiggle for a bit when it gets to the loop. Here is the code:
#include <Servo.h>

#define MAX_SIGNAL 2000
#define MIN_SIGNAL 1000
#define MOTOR_PIN 10

Servo motor;

void setup() {
  Serial.begin(9600);
  Serial.println("Program begin...");
  Serial.println("This program will calibrate the ESC.");

  motor.attach(MOTOR_PIN);

  // Wait for input
  while (!Serial.available());
  Serial.read();

  Serial.println("Now writing maximum output.");
  motor.writeMicroseconds(MAX_SIGNAL);
  delay(2000);

  // Send min output
  Serial.println("Sending minimum output");
  motor.writeMicroseconds(MIN_SIGNAL);
  delay(2000);

}

void loop() {
  motor.writeMicroseconds(MAX_SIGNAL);
}

Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: http://robots.dacloughb.com/project-2/esc-calibration-programming/
You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?

I have seen that diagram and my connection is exactly like that. I think the power is the problem. How can I tell how much power is needed? Currently I am using a common square 9V battery.

can you provide us the model of the ESC you have? And if possible the motor model if any. That 9V may be the cause of that yes. I've searched a little more and came across this similar topic. In there they address two possible cause which can also be one of yours, the UBEC and the 9V. Take a look please, hope it helps. If motors came with some datasheet or similar, it could specify how much current it needs.

@DSchana this topic also describes similar problem as yours rcgroups. In the end the user also says he used a 9V with sucess but it quickly run out


text:
How do I create a 9 bit number based on values from 9 digital inputs?
I have 9 pins that are inputs from 9 IR LEDs. I want to combine all their results into one 9 bit number.
example:
pin1 = high,
pin2 = high,
pin3 = high,
pin4 = low,
pin5 = high,
pin6 = low,
pin7 = low,
pin8 = high,
pin9 = low
9 bit number = 111010010

https://www.arduino.cc/en/Reference/Bitshift

As far as I know, the minimum variable size is 1byte = 8 bits, so there is no bit type.

In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.
If the pins correspond to different ports on your micro, you basically do this:
Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.
Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)
unsigned int ir_inputs = 0

ir_inputs = PORTB; //just reads the register directly
ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

something like that
actually you could put it into a function
unsigned int getIRinputs(void){
    return (unsigned int)PORTB|((PORTC & 0x04)<<6);
}

Easy done
Even if you had the inputs on 9 separate ports the principle is the same.
Read, Shift, OR

Something like this:
typedef union NUM_9_BITS_t {
    unsigned int U;
    struct NUM_9_BITS_FIELD {
        unsigned int BIT0 : 1;
        unsigned int BIT1 : 1;
        unsigned int BIT2 : 1;
        unsigned int BIT3 : 1;
        unsigned int BIT4 : 1;
        unsigned int BIT5 : 1;
        unsigned int BIT6 : 1;
        unsigned int BIT7 : 1;
        unsigned int BIT8 : 1;
        unsigned int BITO : 23;
    } BITS;
} NUM_9_BITS;

NUM_9_BITS num;

num.BITS.BIT0 = digitalRead(PIN0);
num.BITS.BIT1 = digitalRead(PIN1);
num.BITS.BIT2 = digitalRead(PIN2);
num.BITS.BIT3 = digitalRead(PIN3);
num.BITS.BIT4 = digitalRead(PIN4);
num.BITS.BIT5 = digitalRead(PIN5);
num.BITS.BIT6 = digitalRead(PIN6);
num.BITS.BIT7 = digitalRead(PIN7);
num.BITS.BIT8 = digitalRead(PIN8);

Serial.print(num.U);

+1 for the struct. Could you explain why you use 23 and not 7? As an int is only 16-bits. Is 32-bit the minimum size of a union or something?

Thats a perfectly valid approach but seems like a lot lines for something that just needs basic logic and bit shifting.

As @KiraSan said, You need something larger than a byte for 9 bits. However:
int tally;
tally=0;
for (char pin=1; pin<=9; pin++) {
    if (digitalRead(pin)==HIGH) {
        tally|=1<<(9-pin);
    }
}

This is done from memory and is untested, if anyone spots any errors, let me know.
Explanation: tally is the sum (you should do something with this at the end, obviously, or it has no effect). It is defined and set to 0. Then, for each pin (1-9), read the pin; if the pin is high: take the number '1', and double it (9-pin) times; so if pin=9, it is doubled 0 times; for pin=2, it is doubled once (for a total of 2), and so forth. Set this bit on the tally.
Note that this reads digital pin 1 (which happens to be the second pin, the first being pin 0) - this should be marked as "tx" to set in the first bit, not the one referred to as "pin1" (which might be a constant or a variable, and therefore could point to any given pin). This method also assumes the pins are in order - you could easily change it to start from 0, or 7, but they have to be in order.
If you want arbitrary pins, or variable pins, you might try this:
const PIN_COUNT=9;
char pins[PIN_COUNT]={13,2,5,4,3,6,7,8,9};
int tally;

tally=0;

for (char pin=0; pin<PIN_COUNT; pin++) {
    if (digitalRead(pins[pin])==HIGH) {
        tally|=1<<pin;
    }
}

Changes: add PIN_COUNT as a constant at the start, set the order of the pins (which can include any digital pins, including repeating a given pin if you feel so inclined, even after the start of the code.). You can also change them by doing: pins[0]=1; - note that they are numbered from 0-8 for 9 pins. Since they now start at 0, the line with << is now adjusted accordingly, as is the line that starts with for....

authors: محمد يحيى الجدره


text:
Interrupt on Analog Port - ESP8266 w/ Arduino
I'm trying to implement interrupts in my program. It essentially is constantly reading a photo-resistor and if it exceeds a certain threshold, we should send an update to our database. I'm struggling to understand how to do interrupts on a analog pin. I've tried reading this but honestly, it doesn't make much sense. Could anyone give me some advice? Here's out code.
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Initally send out false state
  sendState("18:FE:34:F4:D0:AF", false, false);
}

void loop() {

  if(analogRead(A0) < 20) {
    sendState("18:FE:34:F4:D0:AF", false, true);
    lastState = true;
    Serial.println("Waiting....");
    delay(15000);
  } else if(lastState == true){
    sendState("18:FE:34:F4:D0:AF", false, false);
    lastState = false;
  }

}

void sendState(String address, boolean lights, boolean occupied) {

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String lightsStr = (lights) ? "true" : "false";
  String occupiedStr = (occupied) ? "true" : "false";
  String json = "{\"MACAddress\":\"" + address + "\", \"occupied\":" + occupiedStr + "}";

  String postData;
  postData += "POST /sensor HTTP/1.0 \r\n";
  postData += "X-Parse-REST-API-Key: " + API_KEY + "\r\n";
  postData += "Content-Type: application/json \r\n";
  postData += "Host: " + String(host) + " \r\n";
  postData += "Content-Length: " + String(json.length()) + "\r\n\r\n";
  postData += json;

  // Send the postdata to the server.
  client.print(postData);

  delay(1000);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("Closing connection!");
}

Interrupts are a tricky concept to get, you have to be mindful of so many things (in bigger projects).
Have a quick look on youtube for some tutorials, there are a heap out there.
Having said all that, your code above isn't using interrupts at all. And you have these big delays, does the code work as published?
I would suggest you rework the code into more of a state machine and have a single loop. ditch all the delays (except for your setup, that's fine) and go along the lines of:
setup
set a variable for current timer value and have a constant defined for your update interval
loop

read sensor (consider constantly reading, or reading it more often than the information is sent, and average it out)
anything on the serial port?

go read it

check timer against old timer and interval
interval exceeded

send averaged value

using interrupts
You could use interrupts but the thing to consider is that they can be run AT ANY TIME. your code must be interrupt-able which whilst isn't too hard, needs special consideration in relation to delays, reading 16bit values, not having delays in the interrupt, status register changes, a whole host of others.
There are two types of interrupt, those that are driven by a change in input and those that are time based. You don't really want the change in state on this one because you would normally want to monitor it constantly anyway, but it is certainly doable.
In both time based and external input, you would have the interrupt set a flag that gets acted upon in your main loop.
sorry for not providing more info at this time, screaming kids :(

You can use the inbuilt analog comparator to generate an interrupt when a certain threshold is reached. Example circuit (reference voltage on D7, voltage under test on D6):

Example code for the Uno:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

The incoming voltage is on the AIN0 (positive) pin which is pin 12 on the actual chip, and D6 on the Arduino board. The reference voltage (negative) pin is pin 13 on the chip, and D7 on the Arduino.
My example does not address the issue of transmitting the results, but that is the easy bit. You might need to build in a test so that you don't transmit the information thousands of times a second.

I need wifi capabilitiy is this available for any esp microcontroller?

@LucaZiegler - this is not relevant to this question. I suggest you ask your own question, preferably after searching to see if it has already been answered here.

But the title is 'Interrupt on Analog Port - ESP8266 w/ Arduino'

@LucaZiegler The abbreviation "w/" means "with" not "wifi". The basic question was "I'm struggling to understand how to do interrupts on a analog pin.". Not "how to do WiFi".
Look, comments on questions are for clarifying the question. Asking about WiFi capability on ESP microcontrollers is a new topic, and I suggest you make your own question about it. That is, IF that has not already been answered.

I believe the reason for Luca's comment is that the question refers to the ESP8266 but your code example is for the Uno; the comment as I understand it is "I need WiFi capability, will this code also work on an ESP microcontroller?".

*shrug* - my code is for the Uno, and it does not have WiFi in it (the code). Asking about WiFi on the ESP controller seems to be quite a leap. In fact, one that really requires a new question.

As far as I understand, the question is not asking about WiFi - the asker is simply stating that they are using an ESP microcontroller due to the WiFi capability of said microcontroller.
As such the question is as simple as "Will this work on an ESP microcontroller?" to which the answer is "no", as the registers you have used are not present on an ESP8266/ESP32.

"I need wifi capabilitiy is this available ..." - perhaps, but I took "this" to mean WiFi not "the code above for interrupts".

The joys of ambiguity when using written communication!


text:
Audio Visualizer (not working properly)
Parts

Arduino Uno R3 (Atmega328 - assembled)
Adafruit Bicolor LED Square Pixel Matrix with I2C
Backpack
Electret Microphone Amplifier - MAX4466 with Adjustable Gain
Half-size Breadboard
Breadboarding wires

Description
I have been following the build guide for the "Piccolo Music Visualizer" on the Adafruit website (https://learn.adafruit.com/piccolo?view=all), using all of the same components and code (following the guide exactly as shown). I first tested the 8x8 matrix to see if it was working properly, and it works beautifully. The problems started when I wired up the electret microphone...
In regard to how I wired this to the breadboard, I followed the example for the R3 on the Adafruit guide (since that's my current version):
Note
The files (code) used for this project are found here: (https://github.com/adafruit/piccolo). The ffft file is supposed to be saved to the library (this worked for me). The Piccolo file is supposed to be saved to the Sketchbook (this did not work for me - kept giving error messages when trying to reference it). I instead copied the code found in the Piccolo file, and saved it as a new sketchbook file. Let me know if this might be the cause of the problem. This is my first arduino project, so I am still trying to figure out how the IDE works.
Problem
The electret microphone is supposed to pick up audio and the LED matrix should display a waveform based on the loudness and frequency of the audio. Instead, I only have 2 bars on the bottom left lighting up (the effect is static - wont respond to volume or frequency changes). Oddly, when pulling out the microphone from the breadboard, the waveform begins displaying as it should, but in a glitchy/unstable form. I figured the problem was with the adjustable gain on the microphone, but no matter how much I adjust the screw only the 2 bars are affected and still static (when adjusted to the left only green LED, in middle is green and orange, to the right is red/orange/green on the matrix).
A little confused as to what the problem could be... is the microphone broken, code malfunctioning, wiring incorrect, etc.
Pictures to reference (DropBox link):
- See comment below for link (must have 10 rep to use more than 2 links in post)
(zip file contains 3 pictures: "wiring", "when_on", "pulling_out_mic")
Photos are over 2MB so I couldnt upload here.

DropBox: https://www.dropbox.com/s/22uojp0w0u039kc/SE_Arduino_Problem.zip?dl=0

Check your soldering on the microphone board header pins; sounds like a dry joint.

@CharlieHanson How would I fix a dry joint? I don't see any problems with the soldering, but I could be wrong.

Just add more solder; the more the merrier. The fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.

@CharlieHanson You were right, it works perfectly now! Thanks so much! Post your comment as an answer and I'll accept it.

It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.
Try adding more solder; the more the merrier.


text:
How Master and Slave concept works with Bluetooth?
From what I understand the master has primary control over the slaves and communicates with them. A master must always be present as well, and can be connected to (up to) 7 slaves.
Question

If I have 2 arduinos with Bluetooth communicating with each other
from within a radius of 80 meters or less, which arduino do I set as
the master and which do I set as the slave? (what dictates which one should be set as master, etc.)

I want both arduinos to be able to transmit data to one-another (where neither has privilege over the other), so in my mind this is more like two slaves communicating. Both devices have the same controls on them and will effect the other devices the exact same way.

How does the communication process work exactly, and how should more
arduinos be addressed if they are to be added with similar
privileges?

Well, master/slave concept for Bluetooth resides on the protocol, not in the communications. On few words, this means Bluetooth Master is who has the ability to initiate connection with a peripheral (or slave), but onces connected both master and slave basically can interchange information without restriction (limited by application). If your bluetooth module or implementation has a SPP (serial port profile https://developer.bluetooth.org/TechnologyOverview/Pages/SPP.aspx) once the master finds and connect to the slave, information can flow in both ways like a chat (actually, chat application is the most common usage example of bluetooth modules)


text:
Using a phone battery as a power source possible?
Use
I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The goal is to have the most compact and long-lasting battery possible for my arduino projects.
Note
I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.
Question
I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.
Also:
Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (http://www.gammon.com.au/power); If utilizing his methods on different batteries are better than using a phone battery please let me know...)
If Possible...
Does it make sense for something like a:

LED suit (lasting 12 hours)
Portable gaming system (lasting 8 hours) - similar to: (https://www.adafruit.com/products/2510)
I Know this is for Raspberry Pi
BlueTooth Speaker (lasting 6 hours)

etc...

There's nothing inherently special about phone batteries; they're usually just Li-ion/Lipo batteries with an integrated thermistor.

@IgnacioVazquez-Abrams - I understand that, but I'm primarily interested in them for their low profile. Like the new iPhone and Samsung smartphones. Would it make sense to add these to an Arduino as a power source? (i.e. are there any implications to using them)

It makes sense to use a Li-ion battery as a power source for a microcontroller. It makes slightly less sense to use one with a bog-standard Arduino Uno or Mega due to all the other stuff on the board.

@IgnacioVazquez-Abrams - Are you saying that the "other stuff" draws too much power to make sense for a Li-ion battery?

The boards are fine for prototyping, but once you're done with that you should move to a breakout board or bare MCU.

@IgnacioVazquez-Abrams - So a breakout board or MCU would help with the compact designs I'm looking for, but are these incapable of being powered by certain batteries? (just trying to understand; sorry if questions are naive)

The MCU itself can only handle a specific range of supply voltages. This range is given in the datasheet.

Sounds like a good solution.
Just note that most cellphones use Lithium batteries. Those are typically around 3.7 volt. They require some special way of charging, or they may explode or catch on fire. They also get damaged if discharged too much.
These batteries may have some protection circuitry inside them. This would be ideal in your case, as it protects against over-discharge, and accidental shorts.
An alternative would be the cells used in notebooks called 18650s. These are available with protection and without. The advantage is that you have a standard size. You can buy battery holders for them. That way you can easily exchange batteries. You can also combine cells to create higher voltages.
As for the runtime; you can make a rough calculation of it.

Thanks for the advice! I hadn't thought of using the batteries found in notebooks. I also appreciated the calculator.

I've done this before, but not very practical as a bare "flat-pack" outside its case presents other "issues", the battery "may" catch fire if punctured or shorted too long.  (read fire hazard when punctured) Lithium fires are like thermite, you can't put them out, tossing water on it will only make it worse.
Then there's the voltage mismatch (unless you're using a DUE). A POL  boost converter is needed for best efficiency to get 5-5.2V from a 3.7V cell. And a specialized charging IC is needed so that you don't overcharge/over-rate the current charging the pack. (constant-voltage/constant-current regulator type is needed). I think Adafruit has a lithium breakout board for the 3.7V lithium cell charger, it's for their lilypad stuff i think.


text:
delay() vs delayMicroseconds()
I just started using Arduino and so far I've used both delay() and delayMicroseconds(). I was wondering what the difference between these two is, because it seems to me that they're the same.

From the documentation:

delay()
Description
Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

So... milliseconds vs. microseconds.

Wow. Can't believe I missed that.


text:
Why is Serial.print working when nobody receives the data?
I have a kind of theoretical question. Let's have an Arduino Uno connected through USB that does a lot of Serial.print-ing. Then I disconnect it and I don't see anything on the Serial monitor, but the Arduino is still working. I can judge by the blinking lamps and so on.
Now I see that all printing goes through HardwareSerial::write from the Arduino core. There is this statement:
  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  // ???: return 0 here instead?
  while (i == _tx_buffer->tail)
    ;

It means that if the output buffer is full, the Serial.print will hang there eternally. However this doesn't happen. I guess somebody is consuming the data and to be more precise in ISR(USART_UDRE_vect). It seems as the only place where within interrupt _tx_buffer->tail can be changed. Otherwise the code would loop endlessly in HardwareSerial::write. This interrupt USART_UDRE_vect should be raised only when the Data Register is empty.
My question is - who is consuming the sent data? Is that done by some USART_to_USB drivers? Or am I missing some part of the picture?
Regards,
Boyan

Ignacio's answer is half right. | Right: Either the UART bridge is consuming the data - presumably into its own buffer or there is no "flow control" & the Arduino is sending "blind". | Partially wrong inasmuch as: If it can't YOU care as  your code would hang. || It doesn't so it can. || If you want to stop it from hanging even if the buffer is full you could do a non hanging test and do a check using millis() N ms later where N is somewhat less than a character time (or longer if you don't mind the buffer partially emptying before you restart.

atmega 328p datasheet, section 20.6.3:

The Data Register Empty (UDREn) Flag indicates whether the transmit
buffer is ready to receive new data. This bit is set when the transmit
buffer is empty, and cleared when the transmit buffer contains data to
be transmitted that has not yet been moved into the Shift Register
...
When interrupt-driven data transmission is used, the Data Register
Empty interrupt routine must either write new data to UDRn in order to
clear UDREn or disable the Data Register Empty interrupt, otherwise a
new interrupt will occur once the interrupt routine terminates.

the USART Data Register Empty vector is run when the hardware for USART serial has taken the byte in the register and sent it, not when a receiving device has polled and "taken" it. Once copied into the shift register and sent out of the chip nothing knows if there was another device to "hear" it or not. Some systems may have hardware flow control and wait for a CTS (clear to send) signal on a different wire, but the arduino does not.
You may also notice that if interrupts are not currently enabled (preventing USART_UDRE_vect from ever occuring) the HardwareSerial::write routine will manually poll the correct condition and run the interrupt handler when appropriate to cycle data through and prevent a deadlock.

Brett - It's apparent that you'll be aware of the following - mainly for completeness". I'm not aware of the specific implementation here and I'm sure that what you say applies, but in general a UART can if desired implement the equivalent of RTS/CTS (DTR/...) so that a hearer is needed.

The USB-UART bridge is, if it can. And if it can't, no one cares. A UART is asynchronous, hence it doesn't care if anyone consumes it; as long as it has sent the data, that's all it cares about. There can be additional checks to see if the other side is able to receive data, but that is not implemented on the Uno.


text:
Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino
I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

Did you include a fixed resistor to form a voltage divider network with the velostat?

You need to use a matching resistance to create a voltage divider.

Could you put some more details on your answer? Maybe the OP does not know what a voltage divider is?

I am using 10k resisrtor to form a voltage divider circuit at the end


text:
Wemos D1 mini fatal exception
I'm trying to flash a Wemos D1 mini ESP8266 board with the blink sketch, but get an error. The built in LED turns off when flashing starts.
Sketch uses 247872 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28000 bytes (34%) of dynamic memory, leaving 53920 bytes for local variables. Maximum is 81920 bytes.
warning: serialport_set_baudrate: baud rate 921600 may not work
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I tried changing the programming speed to most of the other options.
If I open the serial monitor and set the baud rate to 74880, I get the following message repeatedly.
Fatal exception (0):
epc1=0x400cd530, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

Is the board dead, or is there a way of reflashing it without using the serial port?

How are you powering the board?

warning: serialport_set_baudrate: baud rate 921600 may not work try a lower baudrate (115200 is safe) because your code isn't uploading error: espcomm_upload_mem failed - perhaps you got a partial upload at some time which is causing the fatal exception on boot -

Flashing with the serial port is the only practical option. The flash chip can be removed, and it can be flashed off board, but that isn't practical.
Has the board ever worked? Have you used other RSP8266 boards before or is this the first you have? Do you have a different USB cable you can try? Marginal power can cause unpredictable operation.

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


text:
Serial.readString() not working becaue of outdated IDE?
I've searched google honestly but can't find an answer nor changelogs for Arduino that might be the answer.
Basically I'm trying to use Serial.readString() to input commands to the Serial Monitor but it shows an error that readString is not a member of 'HardwareSerial'.
I am using Arduino 1.0 as IDE because the device I'm using (Aceduino) seems to have a custom IDE derived from 1.0 so I'm not sure if it will work with newer IDE versions. Wondering if that was what's causing the eror

Stream::readString() is available since version 1.0.1. See:

the changelog, and
the corresponding commit.


text:
How to run stepper motor at its maximum speed
I am running a stepper motor using arduino and IC l293d. What is the maximum possible speed of rotation that I can achieve with the IC and what should be the applied voltage for the same? Earlier, I got the optimum rotation with a step size of 30 at 7V. I want to increase the step size. What should I do?

I want to increase the step size. What should I do? - Change the motor for one with a bigger step size. The step size is a function of the motor - how far it moves with each step - not a function of voltage, current, software, cheese...

If you are asking these types of questions you might consider using an H bridge and a DC motor in place of the stepping motor controller and stepping motor..

It would be informative to review the numerous stepper motor questions at electronics.stackechange.com (do not post another) and the many online resources which explain this.

As this link states:

Stepper motors are normally used for positioning, and are not known
  for their speed.

However, the link is to an on line stepping motor speed calculator.
As for the size of the step, this is a function of the way the stepping motor is built.  Some controllers / stepping motor combinations can do half steps or micro steps.  Disable these feature for the fewest number of steps per revolution.
These are some of the basic concepts which deal with practical stepping motor applications.  As speed increases, other factors come into play.  For example, resonance and inductance.
In this paper resonance is discussed:

If a rigidly mounted stepping motor is rigidly coupled to a
  frictionless load and then stepped at a frequency near the resonant
  frequency, energy will be pumped into the resonant system, and the
  result of this is that the motor will literally lose control.

The paper also discusses the effect of the stepper motor's coil inductance:

An important consideration in designing high-speed stepping motor
  controllers is the effect of the inductance of the motor windings. ...
  The inductance of the motor winding determines the rise and fall time
  of the current through the windings. ...

The speed of the stepper motor (assuming you measure it in RPM) will depend on many factors. I am not sure how the "30 step size at 7V" you mention is relevant.
IMHO, the most important parameters are
1) physical parameters of motor (steps per revolution, rated voltage, motor intetia)
2) Load on the motor
3) software implementation
Normally you shouldn't be able to affect 1( if you are looking like most arduino's developers you should be looking at things like this. i.e. 200 steps per revolution, 5-12VDC and a few tens to hundreds of g*cm^2 or motor inertia.) or 2 (although with higher loads lower velocities can be achieved, normally you select the motor based on the load and not vice versa).
Therefore you are left with Software implementation. Things here can get messy very quickly depending on how experienced you are and what you want to do.
e.g. The arduino Stepper library is simple and you can set parameters but it is blocking (i.e. you can't do anything else until movement is completed, or interrupts are used).
If you want to get your hands dirty (and your head messed up ;-/ ) you can looks at

Arduino timers
micros(), and millis() for updating the steps yourself. (Have a look at here and here - shameless plug)
pin registers (for increasing speed) here.

My experience is that normally you can get up to 150 [rpm] easily. Theoretically you should be able to go higher but the uC should be doing pretty much nothing else.


text:
Need help with on off switch to power arduino.
I am trying to add an on and off power switch to my arduino project.  My project is running off a 9v battery and I would like to save as much power as I can.  There might be a better why that I don’t know.  I added SLEEP_MODE_PWR_DOWN to my project and from what I can tell, the arduino enters sleep mode.  I am having a hard time getting the arduino to wake from sleep mode.  Am I able to do this from a full power down?  I have been reading this link. http://www.gammon.com.au/forum/?id=11497  and others.

It would also be helpful to know what else are you powering in your project (sensors, modules etc.), their part numbers and their typical and maximum current consumption.

Is there a problem with an actual switch? You could store state in NVRAM...

Since you are using an Arduino Uno board, putting the MCU (the ATmega328P-PU) to sleep won't save you much battery juice. Putting the MCU to sleep won't make a difference because the voltage regulator on the Uno will waste a lot more power than anything else on the board. The ON LED will also draw significant amount of current on that board.
To really save power you should look into getting an Arduino board that has a more efficient voltage regulator, or use no regulator at all by changing your 9V battery by, say, 4 NiMH AA cells.
Here's some more information about the issue for you to look at: What are (or how do I use) the power saving options of the Arduino to extend battery life?

And the usb-to-serial chip on the Uno will also consume power.

I will end up moving off the arduino board and just use what is needed down the line.  I have read about this being an issue.

There is a very good write-up on how to save power, use sleep mode etc, at: http://www.gammon.com.au/power
This includes step-by-step examples of what was done to save power, and how much power was saved, including examples on how to go to sleep and wake back up.