text:
How to get ip information of arouter/AP with ESP8266
i, I would like to get ip number, DHCP ip range subnet mask information of an external AP/router autonomusly through the ESP8266 sketch, so the ESP8266 code can determine a suitable static ip range to configure. Any example code or references would be appreciated.

All you can do is get what DHCP gives you.

Connect to the AP
Use DHCP to get an IP address
Store the IP, netmask and gateway in variables
Use the netmask to determine the "fixed" bits in the IP address.
Replace the "unfixed" bits of the IP with your own chosen IP portion
Re-set the IP information with your static information.

What you cannot do is determine what the DHCP range is. Only the router knows that, and it doesn't broadcast it.
The proper way of handling it, though, is to get the router to provide a fixed DHCP IP address for the MAC address the ESP8266 has. Most routers have this functionality available.

Thank you for your response Majenko. WHat I want to do is to handle all configuration for connecting to the network by ESP 8266 or an Android app. User should only need to select the AP and enter password. No other configuration should be needed from user. I need to make sure that the ip that I pick does not conflict wit already assigned dynamic or static ip addresses. For example if I configured a router for a specific IP with a MAC address, I cannot reconfigure same IP for another MAC address unless I reset the router to factory settings.

May be I can use the DHCP assigned ip as static IP, I would like to try if it works.


text:
Arduino Leonardo as USB Keyboard with WiFi module
I have two PCs: the first is connected to the Arduino via WiFi, this will instruct the Arduino what keys to send, and the second PC is connected to the Arduino via USB that will act as a USB Keyboard for the PC to receive keystrokes. Is it possible to use Arduino Leonardo as a USB Keyboard connected to a PC with WiFi module connected to another PC? Do I need other components or modules for this to work?
I have searched the possibility of keystrokes and WiFi connection as separate projects but can't seem to find a project that has this scenario.
I also consider using Teensy with WiFi module if it is feasible. If this is not possible, are there any workarounds? Or other devices I can use? Thanks in advance.
EDIT: I am also checking Raspberry Pi Zero as an alternative. Is the project more probable with this or is it better to stick with Arduino?

Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

You want to talk to an Arduino over Wifi.
You want he PC to send commands to the Arduino.
You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

You can use an ESP8226 - the Arduino talks to it via serial (software serial).
You will need an application (c# will be easiest for Windows) that will send data to the Arduino.  You need to design and implement a protocol, using REST may be a good idea.
I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use.  I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable.  Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi.  I'm not sure if you can use it as a HID though.

Further to what @CodeGorilla says:

You don't need SoftwareSerial on the Leonardo - the UART pins 0 and 1 are independent of any other hardware and can be used directly without any interference.
The Arduino IDE has Keyboard examples for the Leonardo built in and full software support for the USB interface acting as HID is built in to the API. No need for any extra libraries on that front.
The ESP8266 has no USB interface. It may be able to bit-bang it, but I don't think anyone has written software to do that (it's a horrible thing to do anyway).

So you would use pins 0/1 to talk to an ESP8266 which would be your WiFi interface. The Leonardo can directly talk "keyboard" with the wired PC.
A better choice of host board may be the Pro Micro 3.3V since it runs at the same voltage as the ESP8266 so you don't have any issues of logic level translation. True, it runs at half the speed of the Leonardo, but you're hardly doing any intensive processing here.

source: Stack Exchange

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

sort: votes


text:
Can I use NodeMCU 12E (ESP8266) as wifi shield for arduino Nano?
Update:
Point 1- I don't want to program ESP, I just want to use it as a wifi shiled. cause I'm not familiar with flashing or writing sketch for ESP, so still feel comfortable with arduino. beside my existing projects need to upgrade to wifi version. Not possible to turn everying into esp instead of arduino.
Point 2- If anyone can provide me a complete working sketch, where arduino sending a value to ESP, ESP receiving it and then sending to some data server (even sparkfun type will do).
I was working on Arduino based project for last couple of months, where I had to read several sesor data (e.g. temp, humidity, light, sound, motion etc) and save these data to a remote mysql server. I was doing well with Arduino Uno and Ethernet shield, where I connect through RJ45 cable to make my Arduino UNO able using internet.
here is the code for that:
#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(1.1.10.);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "007";        // MySQL user login password

// Sample query
char INSERT_DATA[] = "INSERT INTO database (message, sensor_num, value) VALUES ('%s',%d,%s)";
char query[128];
//char temperature[10];

int potPin = 4;
float temperature = 0;
long val=0;

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(200);
    // Initiate the query class instance
    MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
    // Save
    //dtostrf(50.125, 1, 1, temperature);
    sprintf(query, INSERT_DATA, "test sensor", 24, temperature);
    // Execute the query
    cur_mem->execute(query);
    // Note: since there are no results, we do not need to read any data
    // Deleting the cursor also frees up memory used
    delete cur_mem;
    Serial.println("Data recorded.");
  }
  else
    Serial.println("Connection failed.");
  conn.close();
}

void loop() {
  val = analogRead(potPin);
    temperature = (val*0.0048828125*1000);
    delay(2000);
}

Later, I found it's not convenient to use a whole bunch of cable around, so I was thinking to make it wireless. At beginning I was thinking of RF24OL but it also can't connect internet directly. Then I found ESP8266 module which can directly connect to wifi.
Now, I bought some ESP8266 12e (not ESP-01), which got one USB port to connect with computer, which made things way more sipmle comparing previous versions of ESP. I also installed ESP supporting files on my Arduino IDE, tested and it's working fine.
But, the problem is, whenever I upload the code only for ESP(like connectiong to wifi), it compile and upload proerply.
Like this code works:
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);

}

void loop() {
  digitalWrite(BUILTIN_LED, LOW);

  delay(500);
  digitalWrite(BUILTIN_LED,HIGH);
  delay(300);

}

this also works fine,
/*
 *  This sketch trys to Connect to the best AP based on a given list
 *
 */

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti wifiMulti;

void setup() {
    Serial.begin(115200);
    delay(10);

    wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

    Serial.println("Connecting Wifi...");
    if(wifiMulti.run() == WL_CONNECTED) {
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }
}

void loop() {
    if(wifiMulti.run() != WL_CONNECTED) {
        Serial.println("WiFi not connected!");
        delay(1000);
    }
}

That means, my Arduino IDE, ESP8266 12e all got no problems. But whenever I add something more, like DHT11 library, it shows error compiling.
this code doesnt compile:
#define SSID       "Itead_1(Public)"                //type your own SSID name
    #define PASSWORD   "27955416"                                //type your own WIFI password

#include "uartWIFI.h"
#include <SoftwareSerial.h>
WIFI wifi;

extern int chlID;        //client id(0-4)

// for yeelink api
#define APIKEY         "3a362e99d6f1daf974561163a8c99a85" // replace your yeelink api key here

//replace the device ID and sensor ID for temperature sensor.
#define DEVICEID0       15483 // replace your device ID
#define SENSORID0       26660 // replace your sensor ID

//replace the device ID and sensor ID for humidity sensor.
#define DEVICEID1       15483 // replace your device ID
#define SENSORID1       26661 // replace your sensor ID

char server[] = "api.yeelink.net";   // name address for yeelink API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 5*1000; // delay between 2 datapoints, 5s
String returnValue = "";
boolean ResponseBegin = false;

int DHT11PIN=25;                        //Connect D25 to data pin of DHT11

int humidity;
int temperature;

int post_number;

void setup()
{

  wifi.begin();
  bool b = wifi.Initialize(STA, SSID, PASSWORD);
  if(!b)
  {
    DebugSerial.println("Init error");
  }
  delay(8000);  //make sure the module can have enough time to get an IP address
  String ipstring  = wifi.showIP();
  DebugSerial.println(ipstring);                //show the ip address of module

}
void loop()
{
  char message[400];
   // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if((millis() - lastConnectionTime > postingInterval)) {

  //read dht11
  int chk = dht11_read(DHT11PIN);
  if(chk==0)
  {
        if(post_number==0)
        {
                sendData(DEVICEID0,SENSORID0,temperature);
                post_number++;
        }
        else
        {
                post_number = 0;
                sendData(DEVICEID1,SENSORID1,humidity);
        }

  }

  }

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if(wifi.ReceiveMessage(message))
  {
      DebugSerial.println(message);
  }

  delay(10);

}

// this method makes a HTTP connection to the server:
void sendData(int device_id,int sensor_id,int thisData) {
  // if there's a successful connection:
  if (wifi.ipConfig(TCP,server, 80)) {
    DebugSerial.println("connecting...");
    // send the HTTP PUT request:
    String cmd;
        cmd = "POST /v1.0/device/";
        cmd += String(device_id);
        cmd += "/sensor/";
        cmd += String(sensor_id);
        cmd += "/datapoints";
        cmd += " HTTP/1.1\r\n";
        cmd += "Host: api.yeelink.net\r\n";
        cmd += "Accept: *";
        cmd += "/";
        cmd += "*\r\n";
        cmd += "U-ApiKey: ";
        cmd += APIKEY;
        cmd += "\r\n";
        cmd += "Content-Length: ";
        int thisLength = 10 + getLength(thisData);
    cmd += String(thisLength);
        cmd += "\r\n";
        cmd += "Content-Type: application/x-www-form-urlencoded\r\n";
        cmd += "Connection: close\r\n";
        cmd += "\r\n";
        cmd += "{"value":";
        cmd += String(thisData);
        cmd += "}\r\n";

        DebugSerial.println(cmd);

    wifi.Send(cmd);
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    DebugSerial.println("connection failed");
    DebugSerial.println("disconnecting.");
    wifi.closeMux();
  }
}

int getLength(int someValue) {
  // there's at least one byte:
  int digits = 1;
  // continually divide the value by ten,
  // adding one to the digit count for each
  // time you divide, until you're at 0:
  int dividend = someValue /10;
  while (dividend > 0) {
    dividend = dividend /10;
    digits++;
  }
  // return the number of digits:
  return digits;
}

int dht11_read(int pin)
{
        // BUFFER TO RECEIVE
        int bits[5];
        int cnt = 7;
        int idx = 0;

        // EMPTY BUFFER
        for (int i=0; i< 5; i++)
        {bits[i]= 0;}[/i]

[i]        // REQUEST SAMPLE[/i]
[i]        pinMode(pin, OUTPUT);[/i]
[i]        digitalWrite(pin, LOW);[/i]
[i]        delay(18);[/i]
[i]        digitalWrite(pin, HIGH);[/i]
[i]        delayMicroseconds(40);[/i]
[i]        pinMode(pin, INPUT);[/i]

[i]        // ACKNOWLEDGE or TIMEOUT[/i]
[i]        unsigned int loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == LOW)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == HIGH)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT[/i]
[i]        for (int i=0; i<40; i++)[/i]
[i]        {[/i]
[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == LOW)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                unsigned long t = micros();[/i]

[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == HIGH)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                if ((micros() - t) > 40) bits[idx] |= (1 << cnt);[/i]
[i]                if (cnt == 0)   // next byte?[/i]
[i]                {[/i]
[i]                        cnt = 7;    // restart at MSB[/i]
[i]                        idx++;      // next byte![/i]
[i]                }[/i]
[i]                else cnt--;[/i]
[i]        }[/i]

[i]        // WRITE TO RIGHT VARS[/i]
[i]        // as bits[1] and bits[3] are allways zero they are omitted in formulas.[/i]
[i]        humidity    = bits[0]; [/i]
[i]        temperature = bits[2]; [/i]

[i]        int sum = bits[0] + bits[2];  [/i]

[i]        if (bits[4] != sum) return -1;[/i]
[i]        return 0;[/i]

So, I decided to use ESP and arduino nano together. so that, ESP will work as wifi shiled to connect to internet, like ethernet shield was doing before, arduino will handle parts of sensors data reading and so on. I tried to connect to internet through connecting RX-TX and TX-RX between Arduino-ESP, but it doesn't work. I uploaded wifi connecting script to ESP and it connects to wifi properly, then i uploaded sensor data reading and saving to mysql script to arduino, then conneted arduino tx & rx to esp rx & tx. but arduino can't connect to internet.
Now, my problem is, how I can use ESP8266 12e NodeMCU only as ethernet shield so that my arduino can connect to internet and upload data to my sql server? My ESP will only act as a wifi shield, i don't want to configure esp to read sensor data, cuase it got lack of GPIO pins, most importantly it doesn't work as smoothly as arduino does. So please don't suggest me to use only esp with sensors, because i also wanted to upgrade my existing projects to wifi which done with ethernet shields.
Thanks in advance

If you are trying to send data to the server then I think that connecting tx-tx and rx-rx should maybe work. Or else you could write a code that reads Arduino's messages and sends it to the server.

I tried with both way, doesn't work. And don't know how to write code to esp that will read from arduino, or other way arond. do you have any working code sample? @ Sagnik Pradhan

I don't really have.

@hypocrite420 - The connections should be Tx to Rx not Tx-Tx.

It sounds like you have installed your own custom firmware into the ESP8266 and then are expecting to still be able to communicate with it as if it had AT firmware installed? Or have you written your own software in your sketch to manage the transfer of data from the Arduino to the ESP8266 for the ESP8266 to forward it on through the internet to your chosen server?

@Code Gorilla i tried bot Tx-TX and TX-RX, but no luck.

@Majenko first of all, this ESP can be done everythig as like other arduino. before that you have to add supportng scrits to Arduino IDE. then u can code like arduino. e.g, u can write blinking code same way as do2 arduino, compile and upload. when u upoad ur code, it overwrite existing firmwire on ESP. in my case, it works well when i try to connect or scan wifi networks. but doesn't work when i try to read data from dht11 sensor. so what i did, i put data reading code to arduino & wifi connection code to esp. i was expecting my arduino would b able to connct to server this way, but not

I know exactly what the ESP8266 is. If you look through the bundled examples in the ESP8266 core you'll find at least one written by me.  To use the ESP8266 with an Arduino board you have to have firmware installed in the ESP8266 that communicates with the Arduino. Normally the ESP8266 comes preinstalled with this firmware, called the "AI Thinker AT Firmware". Or you can write your own firmware to communicate between the two boards. Installing some random firmware that scans WiFi access points and connects to one will not allow communication with the Arduino because you haven't...

...written ESP8266 firmware that will communicate with the Arduino.

@hypocrite420 - Does the DHT library you are using work with an ESP?

@Majenko my bad, I'm pretty new and no idea whom i was talking with. sorry for that. btw, I thought u r the right guy to ask then. let me come to the point: No, i didn't write anything that will communicate between arduino and ESP. i just thought it would work like ethernet shield do, that's why connected TX-RX and RX-TX. however, i searched for codes and found a few with allow to talk between them. but i'm not clear to upload my data into mysql server where should i write my code, also how i would communicate? it would look like: Sesnore->arduino->esp8266->mysql. just don't know exact way.

The simplest method is to install the AI Thinker AT firmware and follow one of the many Arduino -> ESP8266 tutorials. Don't talk to MySQL - talk to a website which then performs the MySQL transactions for you (PHP, for example).

@Code Gorilla no, it's not. otherwise i would use esp directly skipping arduino nano part.

@Majenko my ESP exact version is NodeMCU 1.0 (ESP8266 12e), which got usb port to connect. I saw tons of tutorial where esp reading several sensors data and sending to webserver, buy in my case I'm getting always error "NodeMCU 1.0 compiling error". any idea or suggesstion to get rid of that? [i found a tutorial and followed it two remove older version folder from ..\Arduino15\packages\esp8266\hardware\esp8266 directory, but still having same error.] do i need to change sensor library file designed for ESP?

If it is just do get the values from the DHT to the SQL Server, the are a lot of sketch exambles out there using just the NODECPU

OK you have made it very clear that, you want to use the ESP as a serial to WIFI bridge.  You have a Node-MCU ESP12 board, which is normally configured for programming using Luna.

You need to have the correct firmware for this "AI Thinker AT Firmware" and you need to find the correct tool chain for loading this on your board.  It would be easier to but an ESP7 (or lower) to be honest that already comes with the correct firmware.
You want to communicate with the ESP from the Nano.  To do this you will need to use Software Serial on the Nano and cross connect the software serial port to the ESPs serial port.  You must not connect to the nano's serial port, you need this to program the nano.
To configure the ESP to talk to a wireless network you will need to send it AT commands (from the nano) these will need to be part of the setup of you program.  Technically this is programming the ESP, but I'm guessing you'll be OK with this.
Now you can add in your DHT-11 sensor and library and it will work.

However
You would find it so much easier to download the board support package for the ESP, take one of the Web server/client examples and add the DHT-11 code to that.  You'll find, since it is all written in the same dialect of C++ as the Arduino uses, very easy.  In fact the biggest problem you will have is finding something to weight the USB cable down to stop it from rolling the Node-MCU over.
BTW your code doesn't compile because you have left the italic mark-up tags in when you copied it off the website.  Try removing all the [i] and [/i] tags.

Gorila Thx a lot, I was exactly looking 4 somethng as specific as u mentioned. Let me search each steps as well try&see wht happened. Feels ur answer is more informative and very specific. beside everything let me answer few points based on ur steps: 1) I think the board got pre-installed firmware, and I used arduino IDE to program it instead of Luna. Tried ESploere to upload some .lua files, but for some unknown(to me) reasons failed. 2) Made sense. 3) my ESP working fine for conn. wifi or even the first code to send data to mysql server, just was not working when added dht11 library.

I was looking for sample and got two other threads whre which aimed to achieve similar goal: (1) https://arduino.stackexchange.com/questions/17787/communication-via-ip-adress-with-arduino-ide-and-esp8266?rq=1  (2) https://arduino.stackexchange.com/questions/35908/communication-between-two-esp8266?rq=1

UPDATE: If someone looking for easier solution: I got something better, where seems I don't need to use AT command everytime after flashing once: http://www.instructables.com/id/ESP8266-Wifi-Add-on-for-Arduino-Made-Simple/

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


text:
Arduino serial plotter with independent Y axis, is it possible?
The Arduino IDE has a built in functionality that allows the user to plot a value (such as temperature) over time.
I would like to plot two variables with different ranges on the y-axis (pressure in the range of thousands and temperature which varies from 20°C to 40°C).
I could make it work to have both being plotted, but the range differences does not allow me to see small changes in one/both quantities. Is there a way to two, or more, Y axis each one with its own scale?

No. The Arduino Serial Plotter only supports one Y axis.
An alternative would be to capture the data into a file as CSV data and use some other software to plot it - you could import the data into Excel / LibreOffice, or (as I prefer for quick graphing) use something like GnuPlot (or whatever is similar for your chosen OS).
For instance, this is a GnuPlot configuration for plotting two independent axis datasets and the results:
set datafile separator ","
set terminal png enhanced size 1360,768
set output 'testCharge.png'
set ytics nomirror
set ylabel "Current (A)"
set y2label "Voltage (V)"
set y2tics nomirror
plot "testCharge.csv" using 3 smooth bezier title "Current" w l, \
     "testCharge.csv" using 4 title "Cutoff" w l dashtype 2, \
     "testCharge.csv" using 2 smooth bezier title "Voltage" w l axes x1y2

The data I use is formatted thus:
Phase,Voltage,Current,Cutoff
0,3.58,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.61,1.098,0.033
0,3.61,1.098,0.033
... etc ...

And the results:
Incidentally, that's me charging a Li-Ion battery and monitoring the voltage and current.

The Serial Plotter from within the Arduino IDE is quite limited. Not to mention the lack of documentation on the Arduino website. So, no the Serial Plotter cannot do what you require.
However, there is a very good selection of serial data plotter programs over at this question: Serial data plotting programs


text:
cannot get low power with Adafruit Trinket
I want to get as low power use during sleep as possible with an Adafruit Trinket. Based on results presented on various places in the internet (blogs etc), I expect to be able to go down to 50 - 100 micro amps on the ATTiny85 of the Trinket. I am aware of the fact that using a board such as Trinket may add a bit of consumption, and I physically removed the power LED and the power regulator. I am feeding 5V directly on the 5V pin.
I am using the simplest sketch I can think about for low power, with nothing connected to any pin:
#include <avr/sleep.h>          // library for sleep

#define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC (before power-off)

void setup() {
  // put your setup code here, to run once:
  delay(10000);

  // power_all_disable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  adc_disable();
  sleep_enable();
  sleep_mode();

}

void loop() {

}

But I cannot get less than around 1.3 milli amps consumption during sleep. Do you know what may be the cause of using ~1mA instead of ~100 microA? Any idea how I can decrease this further?
Edit 1: it should be even much less than ~50 - 100 micro Amps: ATtiny85: Power consumption vs clock speed ; even though this the libraries are maybe primary intended for the ATMega328P, it looks like it should work also with ATTiny85 as well: http://www.technoblogy.com/show?KX0
Edit 2: I had an ATMega328P-based Adafruit Metro Mini lying around. I took away the ON LED, and then using exactly this sketch, feeding power directly on the 5V pin of the Metro Mini, leads to a power consumption of around 150 micro Amps during sleep, which is more like what I expect. Strange it is 10 times more with the ATtiny while it should have been less (?). Am I missing something or is it maybe just broken library on ATtiny? This is a bit ironic, as I went for the lesser ATtiny85 based board for saving current compared with the ATMega328P...

Are you waking from sleep? Are you taking into account the 10 seconds at the start when it's running on full power?  Put something in loop() that could indicate that it's woken up (maybe turn on an LED or something).

I know that it is awake for the first 10 seconds (then power consumption is about 13 mA), after this period the power consumption drops to the 1.3 mA I was mentioning. ;)
I could of course wake it up with the watchdog, but I do not think this is the point of this sketch; I only want to measure sleeping power consumption, so I think getting it to sleep in the setup and letting it sleeping is ok. I also got it to sleep in the main loop in another sketch, get similar results.

A trinket uses an ARM core processor.  Getting the power down is not trivial.  You probably have hours of reading the Atmel then the ARM core specifications before you start in on designing your own "sleep / low-power" Arduino libraries.  At which point you can start contributing back to the effort of improving the ARM BSP software for Arduinos as they are (were?) full of bugs.

@st2000: ok, that sounds a bit strange as http://www.gammon.com.au/power gets to the micro-amps domain while using just the standard libraries (and I think the same chips architecture), but I may be missing something?

Sorry, my bad, the trinket uses an Atmel ATtiny85.  Still, your link to the power web page says it is intended for the Atmega328P.  Also, I am not sure the BSP is the same for these 2 processors.  You might check on that to make sure you are not up against using 2 different version of sleep libraries.  One for each processor.

No problem ;) I agree, the link to Nick Gammon says it should be for ATMega328P, but I use it with ATtiny. However, it looks like this code should work also on the ATtiny: http://www.technoblogy.com/show?KX0 https://forum.arduino.cc/index.php?topic=372982.0

If you're serious about low power, you should probably look directly to the device data sheet and verify that everything you don't need is turned off, like ADCs, voltage references, etc.  Divide the clock if possible.  Shut down clocks you don't need.  Also, at tiny currents, you have to worry about power being supplied or taken by I/O pins, and things like the burden voltage of your meter.  Often it's hard to get a meter to both pass the run current and measure the sleep current!

Ok, fair enough for the need to go through the datasheet for very low power. But still, it is a bit strange / sad i cannot get to the 100s of microamps domain.

Please have a look at the schematics:
https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit_products_trinket5.png?1378223478
The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5[V] - 3.6[V])/1500[ohm] = 0.0009333... ~= 0.001 [A].
Even though I'm not completely sure without making some tests, that seams plausible to me.
EDIT
(Answer to the OPs comment below.)
The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits  the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us  by Ohms Law that the current through the  resistor is:
I = U / R
I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.

Mmmh, it looks like this diode is going against the polarity provided by the +5V and is here only to protect the pin or something like this, right? It should not be able to draw current from the 5V I think (?).

@Zorglub29:  I've edited the answer in reply.

Many thanks for the explanation, you are definitely right :) Very strange that 1) the drawings are using the 'wrong' symbol 2) they use such a circuit on a 'low power' board. Will contact Adafruit. Why do you think they decided to use a set voltage on this pin?

I guess they use the USB connetion to a 5V controller that has no native USB port. It is common to limit the Voltage on the D- and D+ pins of the USB connect to stay within the specifications. As far as I know does Adafuit recomment to use the newer M0 (ARM) Trinket. (Guess why! ;-) ) My favorit microcontrollers are the MSP430 / MSP432 series from Texas Instruments. That's real low Power. ;-) And the Energia IDE is nearly the same as the Arduino IDE. (Although I use an Eclipse based IDE, so I have not much experience). I heard the STM32 s (e.g Blue Pill) are also very low power devices.

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


text:
Problem with using multi-node nRF24l01+ with Arduinos
I have 3 nodes in my system. One centralNode and two sensor nodes (right and left).
Sensor nodes transmit data to the centralNode and receive from it.
centralNode may transmit to both nodes and receive from them.
I'm using an Arduino nano for central node and Uno and Mega for sensor nodes. I'm using nRF24's base module (with regulators and caps and all) but one node does not have base module (Although I've given it a descent 3.3 V and bypass caps).
Here is my problem:
1- It seems the centralNode can't detect which nodes data it is receiving. I can sometimes get it to work using different delays for sensorNodes but again, on reset it messes up the data.
How can I detect which data's reading the centralNode is receiving?
2- How can I use radio.available(??)
I've put 0, 1 , 2 and pipe addresses in ?? but it does not work (prints garbage data)
radio.available's API
Here are the codes:
centralNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is centralNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 6
#define CSpin 7

RF24 radio(CEpin, CSpin);
byte addresses [][6] = {"1Node", "2Node", "3Node"};

int rightNodeCount = 0;
int leftNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the central node"));
  printf_begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[0]);
  radio.openReadingPipe(1, addresses[1]);
  radio.openReadingPipe(2, addresses[2]);
  radio.startListening();
  radio.printDetails();
}

void loop() {
  if (radio.available()) {
    radio.read(&rightNodeCount, sizeof(rightNodeCount));
    radio.read(&leftNodeCount, sizeof(leftNodeCount));
  }
  //  if (radio.available(1)) {
  //    radio.read(&leftNodeCount, sizeof(leftNodeCount));
  //  }
  Serial.println("centralNode is reporting:");
  Serial.print("centralNode address : ");
  Serial.println((char *)addresses[0]);

  Serial.print("rightNode address : ");
  Serial.println((char *)addresses[1]);
  Serial.print("rightNodeCount = ");
  Serial.println(rightNodeCount);

  Serial.print("leftNode address : ");
  Serial.println((char *)addresses[2]);
  Serial.print("leftNodeCount = ");
  Serial.println(leftNodeCount);

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(500);
}

rightSensorNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is rightSensorNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 7
#define CSpin 8

RF24 radio(CEpin, CSpin);
byte addresses [][6] = {"1Node", "2Node", "3Node"};

int rightNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the right node"));
  printf_begin();

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[1])

  radio.printDetails();

}

void loop() {
  rightNodeCount++;
  Serial.println("Sending data to centralNode");
  Serial.print("rightNode address : ");
  Serial.println((char *)addresses[1]);
  Serial.print("rightNodeCount = ");
  Serial.println(rightNodeCount);
  radio.write(&rightNodeCount, sizeof(rightNodeCount));

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(1000);
}

leftSensorNode:
/*
   Testing multi-node functionality of nRF24l01+
   This is leftSensorNode code

   BOM
   1 Arduino Nano centralNode
   1 Ardiuno Uno rightSensorNode
   1 Arduino Mega leftSensorNode
   3 nRF24l01+
*/

#include <SPI.h>
#include "RF24.h"
#include <printf.h>

#define CEpin 7
#define CSpin 8

RF24 radio(CEpin, CSpin);

byte addresses [][6] = {"1Node", "2Node", "3Node"};

int leftNodeCount = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("This is the left node"));
  printf_begin();

  radio.begin();
  radio.setPALevel(RF24_PA_MAX);

  radio.openWritingPipe(addresses[2]);

  radio.printDetails();

}

void loop() {
  leftNodeCount++;
  Serial.println("Sending data to centralNode");
  Serial.print("leftNode address : ");
  Serial.println((char *)addresses[2]);
  Serial.print("leftNodeCount = ");
  Serial.println(leftNodeCount);
  radio.write(&leftNodeCount, sizeof(leftNodeCount));

  Serial.println("---END OF REPORT---\n\n\n\n");
  delay(1000);
}

Have thought about embedding an ID into the transmission and appending each transmission with a checksum?

@Andyaka 1- Good idea but I have already 32 byte limitation in packet transmission. 2- I think nRF24 does have default CRC checksum.

Without an ID, you cannot reliably detect the transmission source or do you have a cunning plan that you haven't mentioned?

@Andyaka I guess TMRH's RF24 library's available() method does take this issue into account. I don't know how to use it.  http://tmrh20.github.io/RF24/classRF24.html#ace7dd139fabc16b77cb8325faa07620f

You could use the pipe addresses as the ID for a small number of nodes by using a different one for each.

Each sensor point should send its address to the central point and this is how the central point knows the source of the message. Then after the central point receives a message, after if (radio.available()) command receive the data just once (not twice) and then use another if statement to determine which sensor has sent a message (by reading the sent address) and then print.
pseudo code:
if (radio.available())
{
    radio.read(&RXbuffer, sizeof(RXbuffer));
    if(RXbuffer.address == sensor1_address)
    {
        print "this is sensor 1"
        print RXbuffer.address;
        print RXbuffer.data;
    }
    else if(RXbuffer.address == sensor2_address)
    {
        print "this is sensor 2"
        print RXbuffer.address;
        print RXbuffer.data;
    }
}

In your code (inside if (radio.available())) you are trying to receive rightNodeCount and lefteNodeCount eventhough at that time just one of them was received.
EDIT:
It seems that RF24 uses dedicated pipes to know the source of the information. The following code should work:
pseudo code:
unsigned char pipe_num;

if (radio.available(&pipe_num))
{
    radio.read(&data, sizeof(data));

    if(pipe_num == 1)
    {
        print "this is sensor 1";
        print data;
    }
    else if (pipe_num == 2)
    {
        print "this is sensor 2";
        print data;
    }
}

Thanks but in this method, you are sending an struct I guess? As I said, nRF has 32 Byte limitation in each packet so it would be wasteful use of bandwidth. I'm suspecting that this issue can be solved using radio.available(&pipeNum) method but I don't know how...http://tmrh20.github.io/RF24/classRF24.html#ace7dd139fabc16b77cb8325faa07620f

Here I have used a structure as an example (pseudo code). You can create a union data type to be able to use a structure and an array interchangeably. Or you can use just a simple array. It depends totally on your application.

I have edited my answer to use pipes. It should work. If not feel free to share and inform us of your progress.

It seems finally I got it. Actually it seems the client should not pass the desired pipeNum to the available(&pipeNum) method. You first declare a uint8_t pipeNum; then the available method fills the pipe number it is listening to into the pipeNum variable. Do you also confirm this?

@Zeta.Investigator Oops it seems that pipeNum is filled automatically. It is loaded by the number of the pipe that has received the message. So you are right. Look at the code above.


text:
Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
Unable to flash Arduino when TXD pin of HC-6 Bluetooth module is connected to Arduino RXD pin?
I get the following error:

Flashing with command:C:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/bin/avrdude.exe -CC:/Users/home/.arduino-create/arduino/avrdude/6.3.0-arduino9/etc/avrdude.conf -q -q -patmega328p -carduino -PCOM4 -b57600 -D -Uflash:w:C:/Users/home/AppData/Local/Temp/arduino-create-agent051272951/sketch_jun10a.hex:i
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

Most* Arduino devices are flashed through a bootloader which communicates over the serial pins. If you've connected another device to those pins, that communication may fail. You may need to disconnect the device while you flash the Arduino.
(*: The exceptions are the 32u4-based devices, like the Leonardo and Micro. These communicate directly over USB.)


text:
Motor shield code
I am working on a project using an Arduino Uno and a motor driver shield to move a car with an IRremote. But the vehicle is only moving forward and backward. I want it to move left and right. Kindly help.
This is the code:
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(3); // Right motor connected to port 3
AF_DCMotor leftMotor(4); // Left motor connected to port 4
IRrecv irrecv(11);
decode_results results;
#define Straight 0x1FED827
#define Right 0x1FE708F
#define Left 0x1FE30CF
#define Back 0x1FEF00F
#define brake 0x1FE48B7

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch (results.value) {
    case Straight:
      moveForward();
      break;
    case Right:
      turnRight();
      break;
    case Left:
      turnLeft();
      break;
    case Back:
      moveBackward();
      break;
    case brake:
      Stop();
    }
    irrecv.resume();
  }
  delay(100);
}

void moveForward() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnRight(){
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);
  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void moveBackward() {
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(BACKWARD);
}

void Stop(){
  leftMotor.setSpeed(0);
  rightMotor.setSpeed(0);
}

What is the problem? Is it that you don't receive the code, that the car doesn't steer, that the motors stop working, ...? Moreover I'd highly suggest you not to use delays, but.. whatever

You need to check if the Right and Left vars are defined correctly. Use serial monitor to show exaclty the value sent when you try to turn right or left.

the power that the motor sheild is providing to the motor in insufficient and the car is not moving.but it making a noise and the serial monitor is giving the correct hexadecimal numbers.

kindly help !!!!!

@SwathiM Sorry but... If you already discovered that "the power that the motor sheild is providing to the motor in insufficient", why are you asking help about the code? Do you think that changing some variables you will be able to move it? First of all let it move, then try to control it. If with a simple "move forward" sketch it doesn't work it's a setup problem. Check the batteries (empty batteries do not have the power to move the motors), check the motor voltage rating (you can't move a 24V motor with 4 AA batteries = 6V), ...


text:
Write your own program to control Arduino Uno
Is it possible to write a program to control the Arduino Uno, without using
the Arduino IDE?

Do you mean without the IDE or using other IDEs?

In addition to alternate ways to write "Arduino" programs you can also directly target the ATmega328 without using the Arduino stuff at all.  Though as a practical matter, the easiest way I've been able to ask someone got get avr-gcc and avrdude installed for such a project is to ask them to install the Arduino IDE and then look in the directory where a given version puts the compiler and flashing tool.

Possible duplicate of What are the other IDEs for Arduino?

Possible duplicate of Running Arduino IDE in terminal?

Or is the question, if it's possible to make a program on a PC, to communicate with the Arduino, without the Serial Monitor inside the Arduino IDE?

I would like to integrate the Arduino into an existing control system. Therefore I need to communicate with it without having to use / run the Arduino IDE.

You can program the Arduino hardware without using the Arduino IDE. Using avr-gcc and a handful of other tools, including make and avrdude, you can compile and download to the target Aduino hardware. You can even dispense with the Arduino bootloader, and program the hardware using the common ICSP interface. To do this, you need a hardware programmer, but you can make another Arduino into one very easily. Using this method frees up the space used by the bootloader for your own code. Naturally, you use the editor of your choice. For a bit of a taste, have a look at the Adafruit page on programming a trinket (technically not an Arduino, but the methods still apply).

I assume you mean the Arduino IDE?
Yes there are many options, for example plugins for Eclipse or Microsoft Visual Studio.
This link show others like:

CodeBender
Electron
Stino
GEdit
Komodo

Personally use normally the default Arduino IDE, but I don't like the fact you can use just a few files before it does not fit In the top bar, so than I use the Visual Studio plugin VisualMicro.

Most of the time I wrote code for arduino on codeblocks.
The other times on sublime text.
So the answer is yes.


text:
looking for a very accurate and sensitive accelerometer
For a research type project, we are looking for a very accurate and sensitive accelerometer (preferably 6-axis). The average range of the acceleration that we need to record is about 0.0003g (g=gravitational acceleration=9.81m/s2). The minimum sampling rate of measurements should be about 250Hz. We have no electronic engineering background and so we are looking for a readily available module that can be simply installed and connected to a data processor (eg Raspberry pi or a similar one) for recording data. we need to use these sensors for one of our mechanical engineering projects.
Your comments and help are appreciated.
Thanks.
M.

You may find Robotics Stackexchange more useful for this question.  Copy your question there, then delete it here.

I'm voting to close this question as off-topic because questions seeking recommendations for specific products or places to purchase them are off-topic as they are rarely useful to others and quickly obsolete. Instead, describe your situation and the specific problem you're trying to solve.


text:
No ports available
Heyy everyone!!! I have just started working on arduino uno board and for the first week it was working fine but yesterday when I plugged in the usb cable the port option in IDE turned gray(showing no ports).
I tried to update drivers by following commands as given on  forum but arduino.inf file was not there under the drivers folder.
Also mega 16u2 ic on my board gets hot as soon as I connect it with usb . Tx and Rx LEDs are constantly glowing and 13 pin led  glows just for a short time then goes off.
It would be of great help if someone can solve my problem:)

Also mega 16u2 ic on my board gets hot as soon as I connect it with usb .

Your board is electrically damaged and must either be replaced or be repaired by someone able to change out one or more failed surface mount components.
The time of those able to do so is commercially priced above the value of this board, so generally it would only be repaired by someone able to do so themselves, where time spent on a hobby project doesn't necessarily have the same economic value as time spent on paying work.


text:
ESP8266 library / function for IR remote control
I am using IRremoteESP8266 for reverse engineering Hitachi AX-M76E mini stereos IR controller. I want to read the signal that the remote sends and send the same hexas to the stereos with IR led.
Please let me know if this is wrong site but I am trying to find out one thing on that IRremote library that is missing on it: code and protocol for Hitachi. There are even example code for Sony and other well known marks but Hitachi is missing.
Receiving IR is universal:
void loop() {
  if (irrecv.decode(&results)) {
    // print() & println() can't handle printing long longs. (uint64_t)
    // So we have to print the top and bottom halves separately.
    if (results.value >> 32)
      Serial.print((uint32_t) (results.value >> 32), HEX);
    Serial.println((uint32_t) (results.value & 0xFFFFFFFF), HEX);
    irrecv.resume();  // Receive the next value
  }
  delay(100);
}

With this loop I am able to fetch IR hex codes from remote control but with the next code I still cannot wake any action on stereos:
void loop() {
  Serial.println("NEC");
  irsend.sendNEC(0x00FFE01FUL, 32);// put the received hexa here
  delay(2000);
  Serial.println("Sony");
  irsend.sendSony(0xa90, 12, 2);
  delay(2000);
}

What you see every manufacturer uses their own protocol. I tested NEC because its protocol seemed to match what I received, still I did not succeed.
What may be the correct code, if I rewrite the sendNEC function so that I get the Hitachi one?

Now when I look this again, it seems that the problem is that the result code is 64 bit and NECsender parametr is 32. I have to verify that. Code that I received was longer than that I used in example.

HI, did you get solution of this problem. I'm using the same library to get the Panasonic AC remote IR code. It returns the different-different code for Same On/Off button with encoding protocal as UNKNOWN. I also get the Time line data, which is raw data.
Can I get the raw data from IR code?


text:
ESP8266 cannot read POST parameters
I'm working on a simple REST server. I made method to handle http://<esp8266_IP>/test. The GET method works like a charm and I got the response. Then I tried to send a POST with a JSON data (I used PostMan) but I cannot read anything.
Searching online I read ESP8266 library cannot parse JSON and in that case I can found plain text into server.arg("plain"). I tried that but no success
How can I read the data into the POST method?

ESP8266WebServer server(80);
...

void handleTest()
{
    if (server.method() == HTTP_GET)
    {
        ...
    }
    else if (server.method() == HTTP_POST)
    {
        String message = "POST\nHeaders:\n";
        for (uint8_t i = 0; i < server.headers(); i++)
        {
            message += server.headerName(i) + ": " + server.header(i) + "\n";
        }
        message += "\nRequest params:\n";
        for (uint8_t i = 0; i < server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }
        server.send(202, "text/plain", message);
    }
}
...
void setup()
{
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    if (MDNS.begin("esp8266")) {
        Serial.println(F("[Server] MDNS responder started"));
    }

    server.on("/test", handleTest);
}

Please show your code.

i'm not sure it can do that, aside from uploading files...

@MarkSmith I don't think it will be usefull, btw I paste a section of code in my question.

Instead of using below in handleTest()
else if (server.method() == HTTP_POST)

try using below in setup()
server.on("/test", POST, handleTest);

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


text:
Arduino as a real device to computer
Suppose we have a computer mouse , now when we connect it to a computer then  computer understands it is a mouse which is been connected to it. Same thing happens for keyboard and many other devices. As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.
Let me to talk about one of my projects where I build a device driver for my own device. Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.
As we all know that the arduino library provides support for Mouse and keyboard which works fine. Mouse operations are performed without a custom driver.
Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.
I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.
Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.
Or if I think of building my own library then how I should start?
One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?
I know it is a out of the box question but still if you help me, I will be grateful to you.

Try Google - look for something like Arduino zero HID - I know I have seen people do such things.  (HID is Human Input Device)

Yes, I know there are several headers including HID for usb interfacing in library but without proper documents difficult to understand. But still I will give a try. If you have any useful links regarding this please mention those in comment

https://www.google.com/search?q=arduino+zero+hid

As per my understanding, the mouse has a microcontroller and a TTL serial converter which is programmed a certain way that enable computer's default mouse driver to understand the instructions coming from the connected device.

No, the mouse's microcontroller is a USB device.

Like arduino send serial instructions to a port say COM3 and the driver which is a java program reads those instructions and performs accordingly.

No, that is the application you are talking about. The driver is what you install in Windows to make COM3 appear (that is, in any version of Windows before windows 10. Every other operating system, and Windows 10, has the driver built in already).

Now what I want is when arduino connects to a computer it gets detected as a Joystick or as a pendrive or something like that.

There is no support for that in the Arduino API.

I go through different header files of mouse and keyboard which are present in arduino library but those are very complex and without proper documentation hard to understand.

Even with proper documentation and understanding of how USB works it's hard to understand.

Can you tell me where I could find study materiel regarding the existing library? Arduino website provides documentations only on different methods not on how it works.
Or if I think of building my own library then how I should start?

Don't. Trying to do what you want without an in-depth understanding of how USB works is nigh on impossible.  I understand how USB works and struggle with writing USB driver code for microcontrollers.
Instead invest in a device that already does what you want (such as a Teensy 3.x), or move away from Arduino and use a professional environment with professional tools and examples to work with.

One more thing where I can find the information regarding the protocols that a conventional device like mouse, keyboard, pendrive, CD-ROM follows during communication (like the code or the algorithm that is burn into the microcontroller of the device) ?

From the USB Implementer's Forum Inc.

http://www.usb.org/developers/docs/devclass_docs/

Mouse or pendrive have a special type of microcontroller which are capable of direct communication to pc ? if so then is their any programmable microcontroller in market?

Yes, and there are plenty. Any of the Arduino boards based around the ATMega32U4 (such as the Leonardo) are that kind of microcontroller. The "serial" interface chip on the Uno is that kind of microcontroller (it is capable of being reprogrammed so it looks like a completely different device, and if you google around you will find people that have done it).

What is the difference between actual driver and my java program which reads COM port?

The driver is what makes the COM port. Your program is what uses the COM port.
[USB device]---->[USB)- Driver -(COM3]<-----[Your program]

Thank you for your valuable advice. Couple of more thing to clarify...

Mouse or pendrive have a special type of microcontroller which are capable of direct communication to pc ? if so then is their any programmable microcontroller in market? 2) What is the difference between actual driver and my java program which reads COM port?

See my edits...

you talked about teensy. just guide me whether I am going in right the direction or not. In teensy there is one method namely USB: Raw HID, now if I know how mouse does request and respond and code the teensy as per the mouse communication protocol then I am done

Raw HID is the basis of the mouse protocol. Over that is laid a "HID Report" that describes the data. The same thing is done for both keyboard and joystick as well. Teensyduino (the Teensy 3.x API) has Mouse, Keyboard, Joystick, etc objects to use: https://www.pjrc.com/teensy/td_mouse.html

On top of Raw HID teensy library provide different device support. can you suggest me a web site where I can find communication protocols of different devices. Actually my intention is to design a device which apply brute-force attack for fingerprint devices. Like what we do with keyboard. Computer understand it is a keyboard and the device generates and send different keystrokes.

I linked it in my answer already.

Let us continue this discussion in chat.

There's always someone who doesn't like answers to questions like "I want to do X incredibly complex thing and I have absolutely no knowledge of understanding of what it is or how it works" that consist mainly of "Don't waste your time, use something more suitable that already does it". I do wish they wouldn't downvote because of that. It really gets my goat (and I have a lot of goat to get...). To whoever downvoted: if you think USB is a simple enough system to just "hack in" some extra functionality without knowing what USB really is (I mean, the OP didn't even know what a driver was) ...

... then by all means go ahead and show us how it's done. Don't just go around downvoting answers because you don't agree with the fact that they say not to do something. I have spent years studying USB and still know next to nothing about it. By now I know enough to debug the protocol and trace what is happening, craft descriptors, HID reports, choose endpoint types, etc. Writing the state machines to handle it at the low level required is another matter. It's a nightmare. I am an "expert". This kind of thing is not something a beginner can possibly even begin to ...

... contemplate attempting. Especially when there are already Arduino-compatible devices that already do what the OP wants.

sorry but i didn't get your point

@SiddharthaSadhukhan It's not aimed at you - it's aimed at the n00b that downvoted a perfectly reasonable answer.

I appreciate your help and like to thank you for that. And I am asking you to send me some other useful links regarding this if you have such.

You could start here: http://www.usbmadesimple.co.uk/index.html


text:
Pins are not switching
I am trying to make pins 13, 12, 10 and 9 to switch between high and low. That is, when pin 13 is high, pin 12 should be low, then pin 10 should be high and pin 9 should be low.
Code:
 unsigned char driver[4] ={13, 12, 10, 9};
 String mystring = "";
 void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   for(int i = 0; i < 4; i++){
     pinMode(driver[i], OUTPUT);
   }
 }

 void backward(){
   digitalWrite(driver[0], HIGH);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], HIGH);
   digitalWrite(driver[3], LOW);
 }

 void forward(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], HIGH);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], HIGH);
 }

 void STOP(){
   digitalWrite(driver[0], LOW);
   digitalWrite(driver[1], LOW);
   digitalWrite(driver[2], LOW);
   digitalWrite(driver[3], LOW);
 }

 void loop() {
   // put your main code here, to run repeatedly:
   while(Serial.available()){
     delay(10);
     char mychar = Serial.read();
     if(mychar == '\0')
       break;
     mystring += mychar;
   }

   if(mystring == "F" || mystring == "f"){
     forward();
     mystring = "";
     Serial.println("moving forward!");
   }

   else if(mystring == "B" || mystring == "b"){
     backward();
     mystring = "";
     Serial.println("moving backward!");
   }

   else if(mystring == "S" || mystring == "s"){
     STOP();
     mystring = "";
     Serial.println("stopped!");
   }

   else
     mystring = "";
   }

When I test it, there is no switching, that is when moving backward, pin 13 is high throughout, pin 12 is low throughout, pin 10 is high throughout, and pin 9 is low throughout

Also posted at https://stackoverflow.com/q/44594985.

What line ending are you using in your IDE? Because if it is other than 'no line ending', you are also sending a new line, carriage return or both. Those control caracter get included in mystring.
Better to be safe and filter out control caracter. Try this:
String mystring = "";

void setup() {
  Serial.begin(9600);
}

void loop() {

  while (Serial.available()) {
    delay(10);
    char mychar = Serial.read();
    if (mychar == '\0')
      break;

    if (isAlpha(mychar)) {
      //  Doesn't include control caracters in mystring
      mystring += mychar;
    }
  }

  if (mystring != "") {
    Serial.print("***"); Serial.print(mystring); Serial.println("***");
    if (mystring == "F") {
      Serial.println("mystring is equal to 'F'");
    } else {
      Serial.println("mystring is not equal to 'F'");
    }
    mystring = "";
  }
}

Yes, but at that point, why even bother wiht the expensive String concatenation and comparison when you can simply compare the individual characters one at a time as received?  Carry out the appropriate actions on the condition of expected ones, and ignore the others.

You are right; no need for string concatenation, but I want to show the minimal change that solve the problem.


text:
Programmatically activate a specific Arduino
If I have multiple Arduinos plugged into the same computer, is there a way that I can control them both with the same script while also being able to select which one I want to control programmatically?
For instance, the pseudo code may look something like:
stop controlling Arduino2; // Make sure Arduino 2 is not listening
start controlling Arduino1; //Make sure Arduino 1 is listening
set pin 10 high; //Set pin 10 on Arduino 1 to high
stop controlling Arduino1; // Make sure Arduino 1 is not listening
start controlling Arduino2; // Make sure Arduino 2 is listening
set pin 10 high; // Set pin 10 on Arduino 2 high
Windows OS
Currently using Arduino built in language, open to using anything though.

What OS are you on? What scripting language are you using?

Each Arduino will appear as a distinct serial device to programs on the host.  It would be easiest to have something which "finds" all of them, and then keeps track of which is which so that it can talk to the desired one.  Giving each a unique response to a "who are you?" query would help.


text:
RadioHead Library custom configuration for RFM96 LoRa
I have a pair of Adafruit RFM96W LoRa Transceiver Breakouts and want to use them with the RadioHead library.
My pair of radios works if I use the example sketches from the adafruit tutorial, but I want to change their default configuration.
From the Datasheet of RFM96:

For maximum flexibility the user may
  decide on the spread spectrum modulation bandwidth (BW),
  spreading factor (SF) and error correction rate (CR).

I want to configure the BF, SF and CR. I also want to be sure that the radios are working with the LoRa Modulation and that CRC is enabled.
And how to set Header-Settings?
I did find the method rf.setModemConfig() which gives the capability to change the configuration to library-pre-defined ones, which is not what I want. I want to try different combinations of settings.
I did find the method rf.setModemRegisters() but I did not understand how to use it.
Any solution is welcome.

Parameter in RH_RF95.h
const RH_RF95::ModemConfig myProfile =  {
  RH_RF95_BW_62_5KHZ | RH_RF95_CODING_RATE_4_5,
  RH_RF95_SPREADING_FACTOR_1024CPS};

rf95.setModemRegisters(&myProfile);


text:
How do I pull up D1-D6 using 10k ohm resistors?
I'm using push buttons to control CR servos (button1=turn CW; button2=turn CCW). How do I pull up D1-D6 and what does that do exactly? I can't find a tutorial that explains it well enough how to use the resistors.

Why do you need to pull up six inputs if you only have two buttons?

use pinMode(D1, INPUT_PULLUP) and save your resistors for something else.

@MarkSmith I've got multiple servos.

Typical Atmel AVR inputs can “float” when left open, that is, may drift high or low.  The idea of a pullup or pulldown resistor is to give an otherwise-open input a definite value – high if pulled up, low if pulled down.
The values of pullup and pulldown resistor values are a tradeoff:   You can use high values to minimize the current that a sensor device must overcome when it switches values, and to minimize power loss in a battery-powered device.  Or you can use low values to get faster switching when you release the input.
There are built-in pullup resistors on most AVR inputs.  (But A6 and A7 on some models of ATmega328's don't have pullups.)  To use a built-in pullup, initialize the input pin with (for example) pinMode(mypin, INPUT_PULLUP) instead of pinMode(mypin, INPUT).
To sense the state of a simple normally-open switch, you would connect one side of the switch to an input, and the other side to ground.  Initialize the pin to be a pulled-up input: eg, pinMode(mypin, INPUT_PULLUP).  Regard the switch as not-pushed when digitalRead() shows HIGH, and  pushed when it shows LOW.
If you really want to use external pullup resistors, connect the switch as above – one side to ground, one side to a pin – and connect a resistor between +5 V and the pin.  That is, one end of a resistor and one side of a switch will connect to the input pin.  In this case, use either INPUT or INPUT_PULLUP as the pinMode setting; it makes no big difference because the internal pullup resistor has a fairly high value, eg 40 KΩ.

Do you think for this Thing - https://www.thingiverse.com/thing:239105 - I can use internal pull-up resistors? It's telling me to use external, but I don't understand why. Thanks for your help!

I don't know what D2-D6 (which that page refers to as having pull-ups) are used for in that project.  If it's switch or rotary encoder inputs, internal pullups should be fine.   If it's I2C, maybe not.  Anyhow, I didn't find a link to a circuit diagram that might reveal how D2-D6 are used.  Do you have a circuit diagram or a link?

The trouble is that there isn't a circuit diagram. D2-D6 are going to the buttons and joystick on a shield (https://www.sparkfun.com/products/9760). When you press those buttons or move the joystick CRservos will move clockwise or counter-clockwise.

That sparkfun.com/products/9760 page says internal pullups are ok:  “The momentary push buttons are connected to Arduino digital pins 2-6; when pressed they will pull the pin low (utilizing the internal pull-ups of the Arduino)”

That's great! Did not see that. There doesn't seem to be any benefit to using external pullups.


text:
Setting ESP8266-01 up with AT commands
I am facing for the first time with the ESP8266-01 module, so sorry if will write any stupid things.
I bought this module and I wanted to check its parameters through AT commands. Following some guide and wiring schemas found on the web I finally hook the ESP8266 up with an Arduino Uno (as in the picture below. The resistors are 220ohm each and the capacitor is 100uF) in order to print out to the serial monitor the AT commands and responses.
I uploaded the following code to Arduino Uno:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(6, 7);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(57600);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }

  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

But when I open the serial monitor (with both NL and CR selected and baud rate set to 9600) I got no response!!
If I try to send simple AT or AT+GMR commands, it returns to me nothing or random characters.
Does anyone please could tell me what I am doing wrong?

Try different common esp8266 baud rates. Different versions use different baud rates.

Also I know for a fact I have answered this very same question twice this month already.

This question is over a year old - have you solved your issue yet?

@Filipppo, please don’t just edit your title to say “solved”. That’s not helpful to anyone. If you solved it, please post the solution as an answer.

For future readers of this question, see my answer to a similar question, about Software Serial, ESP8266 modules and baud rate.

We faced similar problems when using ESP8266 for the first time, Following approach to the problem was fruitful

ESP8266 is 3.3v compatible so to avoid problems make a simple adaptor circuit to make it compatible with 5v Arduino (find details here)
First thing you need to do is check and confirm if you are able to communicate with your ESP module, you can use any USB to TTL interface and connect ESP Module directly with your computer/laptop. (explained in detail here)
Use ESP8266 configuration utility, it will speed up the ESP Module setup and help get the desired product develop faster. (explained in detail here)

Hope it helps.


text:
Shift Register 74HC595 circuit working weirdly
I built the circuit from the arduino ShiftOut tutorial, but it is not working as expected. I made a simulation model and that one isn't working either.

The code I used is from the tutorial:
// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Any idea as to what's wrong?

I presume that you are referring to this tutorial, and this code.
The clockPin of Arduino should be connected to pin 11(SH_CP) of 595, dataPin to pin 14(DS), and latchPin to pin 12(ST_CP).
Swap the values of clockPin and latchPin in your code, and you should be good to go.
// SH_CP; 11
const int clockPin = 10;
// DS; 14 (not 15)
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 9;


text:
Serial source code
Serial is documented on the Reference pages, but seems to receive special treatment (no need to include header), and there does not seem to be any file with the Source code.
Stream is the base class for Serial and inherits from the Print class.
There is source for Stream.h
LiquidCrystal_I2C also inherits from the Print class, and I was planning to write code which outputs to either LiquidCrystal_I2C or Serial; there are many options, but I was looking for Serial to explore its inner workings.

The HardwareSerial.cpp file is located in ...hardware/arduino/avr/cores/arduino, if that is what you are looking for

@Fauzan There is no Serial class in the location above, which is where I found the other source.

Serial is an instance of class HardwareSerial.

@Majenko Where is it defined? I cannot even find the symbol Serial anywhere?

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L143 is where Serial is defined. On AVR MCUs with built-in USB it is defined here https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/USBAPI.h#L152.

Serial is an instance of the HardwareSerial class.  It is defined in HardwareSerial0.cpp:
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

HardwareSerial is a child of Stream as defined in HardwareSerial.h:
class HardwareSerial : public Stream
{
    ....
};

Stream is a child of Print as defined in Stream.h:
class Stream : public Print
{
    ....
};

Print is a top-level class with no inheritance.
Serial is not a class. It is an instance of a class. That is, it's an object that has been constructed from the class definition. Anything you access member functions of using a . is an instance of a class (aka an object) not a class itself. Anything you access member functions with :: is a class using static member functions.
Examples:
Serial.println(); // Call the println() function in the Serial object
Wire.beginTransmission(0x34); // Call the beginTransmission function in the Wire object
Foo::bar(); // Call the static function bar() in the Foo class.


text:
Power supply to L293D motor driver
I am new to Arduino. I'm making a line-following bot. I need to power my L293D module. I know that I can supply 9/12V directly with a battery but I am not sure whether I can supply 5V directly from the 5V pin of the Arduino or I have to use something like an IC 7805.
I am confused because I read that the L293D can cause currents up to 600 mA but the max current for an Arduino Uno pin is only 50mA. This question might seem too novice but it would be of great help if someone could explain me about this or the concept in general.
Thanks in advance.

You should probably not be using an L293 in a new design at all - it has high internal losses and has been obsolete for at least a decade.  Whatever you use, the motor power must not be routed through the Arduino board at all.  Do not use a small 9v battery for motors; likely you should use between 5 and 8 AA cells.

Where do people get this 50mA number from?

"Do not use a small 9v battery for motors; likely you should use between 5 and 8 AA cells. " Can you please tell the reason behind this ??

@Majenko sorry it was a mistake that was for 3.3V pin.i confused it with 5V pin

9V PP3 batteries have only about 150mAh. AA have nearer 2000mAh.

Ohh so more power capacity ...Right .thankyou

Check the L293x datasheet.
The L293D IC has two power supply pins. Pin 16, VCC1, is to power the IC itself, ei., its internal logic. Pin 8, VCC2, is to power the motors.
The maximum logic current (ICC1 MAX) drawn by the driver IC at pin 16 is 60mA. Thus, provided you do not have other things connected to the Arduino that can take the current draw above the limit, it is safe to connect VCC1 of the driver IC directly to the Arduino's 5V pin.
The maximum current you can draw from the 5V pin is around 400 mA, or 900 mA, when the Arduino is powered by an external power adapter.
The maximum current sourced or sinked by each driver input pin (xA) is 100 μA, and by enable pins (EN), it is 10μA, which is well within the limit of the Arduino digital pins, 40mA (not 50 mA!). So you can also safely connect Ax and EN directly to the Arduino.
Coming to the last point, the maximum power current supply by driver outputs (xY) is 600 mA. You cannot source or sink more than 600 mA from the 1Y, 2Y, 3Y and 4Y pins. All of this current will be drawn from pin 8 (VCC2), which is connected to the power supply for the motors, which can be a 9V battery. Note that ICC2 MAX is 1.2 mA. Thus, if the supply voltage of the motors is 5V, you must use another voltage source, like 7805 and not the 5V pin of the Arduino to provide VCC2.
To summarize,

You can connect pin 16 of L293D to Arduino's 5V pin.
You can connect pins 1, 2, 7, 9, 10, 15 of L293D to Arduino's digital pins.
You cannot connect pin 8 of L293D to Arduino's 5V pin.

You cannot connect pin 8 of L293D to Arduino's 5V pin.
Why is that? If Arduino's 5V pin can provide 900mA with external source? The motor draws up to 600mA.
Also, what exactly is ICC2max?

Thankyou for your answer made a lot of doubts and misconceptions clear. Just to clear things out icc2 max is current from pin 8 of L293D and it's max value is 1.2A instead of 1.2mA right? Or am I making a mistake here ?

900mA if you don't mind cooking the 5v regulator...


text:
PCM audio, PROGMEM sounds through speaker, multiple clips (using speaker_pcm)
I downloaded the PCM Audio speaker_pcm (see link below) and it worked easily with the supplied Mac startup chime. I also got my own sounds parsed properly via a combination of sox and wav2c incantations as described. However, when I tried to store and play two or more (very short e.g. 150ms, 8K) sound clips in sequence, I couldn't seem to get it to work. It only sounds like it is playing the last clip in order. I only modified the code (see below) from the original to address the multiple clips. My pointer dereferencing seems to be working (it plays the last clip in sequence), but it won't play a group of them. What am I doing wrong?
(You can download the 01.h 02.h 03.h files from my website, pete dot zelchenko dot com slash 2017 slash the file name. I can't post lots of links here. You can also create your own using the incantations about sox and wav2c in the documentation below, but it takes time. The three files are the words "one" "two" "three" and that's it.)
/*
 * (PCM Audio speaker_pcm downloaded from http://playground.arduino.cc/Code/PCMAudio)
 *
 * speaker_pcm
 *
 * Plays 8-bit PCM audio on pin 11 using pulse-width modulation (PWM).
 * For Arduino with Atmega168 at 16 MHz.
 *
 * Uses two timers. The first changes the sample value 8000 times a second.
 * The second holds pin 11 high for 0-255 ticks out of a 256-tick cycle,
 * depending on sample value. The second timer repeats 62500 times per second
 * (16000000 / 256), much faster than the playback rate (8000 Hz), so
 * it almost sounds halfway decent, just really quiet on a PC speaker.
 *
 * Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
 * (analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
 * for the pulse width modulation, breaking PWM for pins 11 & 3.
 *
 * References:
 *     [links]
 *
 * Michael Smith <michael [at] hurts.ca>
 */

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 8000

    /*
     * The audio data needs to be unsigned, 8-bit, 8000 Hz, and small enough
     * to fit in flash. 10000-13000 samples is about the limit.
     *
     * sounddata.h should look like this:
     *     const int sounddata_length=10000;
     *     const unsigned char sounddata_data[] PROGMEM = { ..... };
     *
     * You can use wav2c from GBA CSS (OR use EncodeAudio? http://highlowtech.org/?p=1963):
     *     http://thieumsweb.free.fr/english/gbacss.html
     * Then add "PROGMEM" in the right place. I hacked it up to dump the samples
     * as unsigned rather than signed, but it shouldn't matter.
     *
     * [link deleted]
     * mplayer -ao pcm macstartup.mp3
     * sox audiodump.wav -v 1.32 -c 1 -r 8000 -u -1 macstartup-8000.wav
     * sox macstartup-8000.wav macstartup-cut.wav trim 0 10000s
     * wav2c macstartup-cut.wav sounddata.h sounddata
     *
     * (starfox) nb. under sox 12.18 (distributed in CentOS 5), i needed to run
     * the following command to convert my wav file to the appropriate format:
     * sox audiodump.wav -c 1 -r 8000 -u -b macstartup-8000.wav
     */

    //#include "sounddata.h"
    #include "toolow.h"
    #include "toohigh.h"

    #include "01.h"
    #include "02.h"
    #include "03.h"

    int      ledPin   = 13;
    int      speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

    volatile uint16_t sample;
    byte lastSample;

    int sounddata_length;

    /*int sounddata_length;
    signed char *sounddata_data[10000]; */

    void stopPlayback()
    {
        // Disable playback per-sample interrupt.
        TIMSK1 &= ~_BV(OCIE1A);

        // Disable the per-sample timer completely.
        TCCR1B &= ~_BV(CS10);

        // Disable the PWM timer.
        TCCR2B &= ~_BV(CS10);

        digitalWrite(speakerPin, LOW);
    }

    unsigned int sounddata_addr;

    // This is called at 8000 Hz to load the next sample.
    ISR(TIMER1_COMPA_vect) {
        if (sample >= sounddata_length) {
            if (sample == sounddata_length + lastSample) {
                stopPlayback();
            }
            else {
                if(speakerPin==11){
                    // Ramp down to zero to reduce the click at the end of playback.
                    OCR2A = sounddata_length + lastSample - sample;
                } else {
                    OCR2B = sounddata_length + lastSample - sample;
                }
            }
        }
        else {
            if(speakerPin==11){
                OCR2A = pgm_read_byte(sounddata_addr + sample);
            } else {
                OCR2B = pgm_read_byte(sounddata_addr + sample);
            }
        }

        ++sample;
    }

    void startPlayback(int clip)
    {

    signed char *sounddata_data[10000];

        switch (clip) {
          case   1:  sounddata_data[0] = &s_01_data[0]; sounddata_length = s_01_length; break;
          case   2:  sounddata_data[0] = &s_02_data[0]; sounddata_length = s_02_length; break;
          case   3:  sounddata_data[0] = &s_03_data[0]; sounddata_length = s_03_length; break;

        }

    sounddata_addr = sounddata_data[0];

        pinMode(speakerPin, OUTPUT);

        // Set up Timer 2 to do pulse width modulation on the speaker
        // pin.

    *  // Use internal clock (datasheet p.160)
        ASSR &= ~(_BV(EXCLK) | _BV(AS2));

        // Set fast PWM mode  (p.157)
        TCCR2A |= _BV(WGM21) | _BV(WGM20);
        TCCR2B &= ~_BV(WGM22);

        if(speakerPin==11){
            // Do non-inverting PWM on pin OC2A (p.155)
            // On the Arduino this is pin 11.
            TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
            TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2A = pgm_read_byte(&sounddata_data[0]);
        } else {
            // Do non-inverting PWM on pin OC2B (p.155)
            // On the Arduino this is pin 3.
            TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
            TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2B = pgm_read_byte(&sounddata_data[0]);
        }

        // Set up Timer 1 to send a sample every interrupt.
        cli();

        // Set CTC mode (Clear Timer on Compare Match) (p.133)
        // Have to set OCR1A *after*, otherwise it gets reset to 0!
        TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
        TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

        // No prescaler (p.134)
        TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set the compare register (OCR1A).
        // OCR1A is a 16-bit register, so we have to do this with
        // interrupts disabled to be safe.
        OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

        // Enable interrupt when TCNT1 == OCR1A (p.136)
        TIMSK1 |= _BV(OCIE1A);

        lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
        sample = 0;
        sei();
    }

    void setup()
    {
    // audio pins
        pinMode(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);

        startPlayback(01);
        startPlayback(02);
        startPlayback(03);

    }

    void loop()
    {
      loop();
    }

Which Arduino board ? Arduino Uno ?

I know I'm answering my own question. A lot of rules on stackexchange and dog only knows if this violates one. It looks as if I need to put enough delay after each clip that the clips don't walk on each other. It's that simple. Without the delays, it makes sense that they will just overlap and you'll just hear a high-pitched shriek. I put a delay(250) in for these short clips just to test, but you can calculate the necessary delay for each clip after startPlayback() of each clip, based on the length of the given clip.

I think it's just a case of startPlayback() being asynchronous. It doesn't block; it doesn't wait for playback to finish. It just sets up the 8000 Hz timer interrupt and returns.
The original code calls stopPlayback() when it runs out of samples. You could change that block (under if (sample >= sounddata_length)) to have it cycle on to the next clip, rather than stopping.
(Note: I'm the original author of the PCM sample but it's been quite a while so take this with a grain of salt. Surprised it still works with newer boards. Have fun!)

The Mega2560 apparently has to use pin 10 instead of pin 11 for PCM output.  It would be better if this were defined in the main sketch instead of the library.


text:
Output of Hex of ino
I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?  Can I see the output or anything ? Can I upload it on arduino ?

Not really...  I mean, if it was mission-critical there might be a way, but in general the effort to do so would be more than simply rewriting the program.

I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?

That is a binary image of the compiled sketch in a hexadecimal notation. You could spend hours disassembling it if you understood the right tools to use.

Can I see the output or anything ?

You can convert it back to a crude form of assembly language maybe, but that is all. Understanding what that means takes skill and knowledge.

Can I upload it on arduino ?

Sure. It's a compiled program ready to be uploaded to an Arduino.
avrdude -D -patmega328p -PCOM3 -b115200 -C/path/to/avrdude.conf -c arduino -Uflash:w:sketchname.ino.hex:i

Thanks, I just few queries regarding uploading the code. I have Arduino Uno and Due so how do I change the command for them and will it harm the Arduino ? And how can I find what the code is doing after uploading it ?

Arduino and Due use completely different programs, and the entire systems are completely different. You can only upload the HEX to the chip it was compiled for.

How will I verify for which system is it for. I have few lines of hex code only.

You won't. You'd need to see the source and know what the compilation options were when compiling.

"a few lines of hex code" is unlikely to be of any use on either board.  You could attempt to disassemble it and see what it might imply as instructions for either system, but it is probably an incomplete fragment.

@Majenko Oh okay.

@ChrisStratton It gives error objdump -d chall.ino.hex : objdump: can't disassemble for architecture UNKNOWN!

Disassembling raw files is a pain, you have to specify the architecture as a distinct command line option (and you need to use an avr or arm objdump, not the one for the host system!), may need to tell it about or translate the input format, etc.   And as I said before, if you only have a few lines it's unlikely to yield anything interesting.

@ChrisStratton I got around 400 lines after disassembling it ! . I don't know what to do now. Can I convert it into C program ?

No. Now you need to learn assembly language. Welcome to the world of real embedded system programming.

What are you trying to do anyway? You have some binary, you don't know what device it's for or what it does. Why are you interested in it? What are you REALLY trying to do?


text:
Comparing 2 char converted from a array
I wrote this little program to test converting and comparing 2 char with each other. With some help from here i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:
char code[4] = {'1','2','3','4'};
char strcode[5];
char pass[4] = {'1','2','3','4'};
char strpass[5];

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    memcpy(strcode, code, 5);
    strcode[4] = '\0';
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
    memcpy(strpass, pass, 5);
    strpass[4] = '\0';
    Serial.println(strpass);
    Serial.println("donepass");
    if (strpass == strcode)
    {
        Serial.println("yes");
    }
    else
    {
        Serial.println("no");
    }
}

I get this in my serial monitor:
1234
done
1234
donepass
no

Why is this not equal to each other?

You cannot compare char arrays with ==. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.
C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).
Comparing two char array variables with == is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.
There's various functions for doing that depending on how you want to compare.
strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

All return 0 for a == b, a negative number for a < b and a positive for a > b.
The "n" variants (e.g., strncmp) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).
The "case" variants are case insensitive comparisons - that is "foo" matches with "Foo" and "foO".


text:
Access I2C sensor from Arduino Uno as slave
I connected Raspberry Pi 3 to an Arduino Uno through I2C. The Arduino Uno uses the I2C as slave.
When I connect AM2320 sensor (temperature and humidity) to the Arduino Uno, I am getting the response that the sensor is offline.
I tested the sensor on Raspberry Pi 3 and it is working fine. On the Raspberry Pi the address is 0x5c. On most libraries, the address is 0xb8. I have the same result when I tried these 2 addresses.
Do I have problem because Arduino Uno is working as slave?

Two comments and a request. C1) rPI is powered at 3.3V, while the arduino uno is powered at 5V. What pullup voltage are you using on the I2C lines? Remember that 5V is too much for the rPI, and 3.3V should be not enough for the arduino.... C2) 0x5C and 0xB8 are essentially the same address. I2C have 7bit addresses, while the last bit of the first byte is the read/write one. So the proper address is, in binary, 1011100 (saved as 101 1100, or 0x5C), but arduino saves it with the R/W bit too (1011 1000, or 0xB8, for more easiness). R1) remember to choose an answer if it answers your question

You can do it. A single device like the Arduino can be both a slave and a master.
It's explained in great detail by Nick Gammon in http://www.gammon.com.au/i2c in the paragraph Communicating with other devices

Indeed, I2C slaves cannot communicate with one another.
There are some obscure capabilities for devices to switch role, but that is likely to introduce lots of complications.
You might look at using bit-banged (or "soft") I2C on other digital pins and move the peripheral's I2C lines there instead o the hardware I2C pins connected to the pi.  For example, a web search quickly found something that claims to do this at:
https://github.com/felias-fogg/SoftI2CMaster
No idea if that particular one will work for you, but there are others as well.
Or you can re-design your scheme so that the pi reads the sensor, and if necessary writes the values of interest to the Arduino.

I had may be a bad connection but I can read the sensor AM2320 on Arduino-
Uno and send the value back to Raspberry Pi.
Arduino side:
#include am2320
#define SLAVE_ADDRESS 0x04
Wire.begin(SLAVE_ADDRESS);
AM2320 th;
Wire.write( (int)(th.t * 10)); // th.t is for temperature which I send
integer

Raspberry side:
import smbus
bus = smbus.SMBus(1)
address = 0x04
number = bus.read_byte(address)

Raspberry Pi and Arduino Uno seems to work good together with and I2C sensor on Arduino side. Thanks for you time to help me and I will go to the link you propose.


text:
Wierd Issue with PWM pin
I'm trying to run two of my motors through PWM. Here's my code -
#include <Servo.h>
int Lm = 11;
int Rm = 10;
int incomingByte = 0;
int pos = 0;
Servo myservo;
void setup() {
  pinMode(Rm, OUTPUT);
  pinMode(Lm, OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(2,OUTPUT);
  myservo.attach(3);
  Serial.begin(9600);

}

void loop() {
  blinkers();
  if (Serial.available() > 0) {
                incomingByte = Serial.read();
  }
  if(incomingByte == 49){
    analogWrite(Rm, 128);
    analogWrite(Lm, 128);
  }
   else if(incomingByte == 48){
    analogWrite(Rm, 0);
    analogWrite(Lm, 0);
    myservo.write(0);
  }
  else if(incomingByte == 50){
    analogWrite(Rm, 0);
    analogWrite(Lm, 128);
    delay(500);
    analogWrite(Lm, 0);
  }
  else if(incomingByte == 51){
    analogWrite(Rm, 128);
    analogWrite(Lm, 0);
    delay(500);
    analogWrite(Rm, 0);
  }
  else if(incomingByte == 52){
    for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}

void blinkers(){
    digitalWrite(7, HIGH);
    digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(7, LOW);
  digitalWrite(2, LOW);
  delay(100);
}

Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use digitalWrite instead, both motors work fine.
I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -
void setup() {
  pinMode(10,OUTPUT);

}

void loop() {
  analogWrite(10, 128);
  delay(100);
  analogWrite(10, 0);
  delay(100);

}

This code worked perfectly fine.
So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...
Can anyone tell why is this happening?

It is a timer conflict.
The Servo reference says: "...use of the library disables analogWrite() (PWM) functionality on pins 9 and 10..."
This is a picture of the pinmapping of the Arduino Uno: PighiXXX - Uno.
Pin 9 en 10 uses OC1A en OC1B for PWM, that is Timer1. You can't use PWM on them when the Servo is used.
Pin 11 uses OC2A for PWM, which is Timer2.
I suppose it will work if you choose another PWM pin for analogWrite. Timer0 is used for millis and therefor the PWM frequency will be different (pin 5 and 6). That is mentioned in the analogWrite reference. In most cases that is not a problem.
Pin 3 is a normal PWM pin.
This is a common problem. The documentation is not always clear about the use of timers and other parts of the microcontroller. Many times the source code has to be read to see what is used. In the end, you need more experienced Arduino users to spot the conflict.

Yeah I had no idea that something like this would be the reason... Thanks for the answer @Jot


text:
Arduino nano as HID Keyboard
I'm a bit of a noob in the Arduino area but I found an Arduino nano I bought a long time ago sitting on my shelf and collecting dust,
so I taught "why not make a project". I game a lot of racing games so I wanted to make a simple ignition button with it, but every time I tried to compile or verify it, it says

Keyboard not found. Does your sketch include the line #include "Keyboard.h"

did you include the keyboard library from the Sketch menu?

@dandavis - that would not be possible or at least not meaningful, as there is no such library for a nano.

@ChrisStratton: good call.

Unlike and official Arduino Uno, which uses a re-programmable ATmega16U2 for an USB to UART interface, a Nano uses an non re-porgrammable FTDI chip.

A typical Nano has no hardware support for this - so you could only do it by a means such as software-approximate USB, or by adding a USB device interface chip.  As the answer suggests, there are better platform choices.

Maybe this question might help you. https://arduino.stackexchange.com/questions/76557/how-can-i-make-my-arduino-uno-press-space-on-my-laptop-keyboard/76570#76570

Arduino Nano I am not sure. But I am sure that you can do it with Arduino UNO.
https://www.youtube.com/watch?v=tvqA-JcTQNg

Get yourself a Arduino Leonardo, Micro or Pro Micro (or Due, Zero, M0). Those can emulate a keyboard.
Start with reading the Arduino Keyboard Mouse reference.
The Arduino Nano can not use the Arduino Keyboard Mouse library.
Since many years, there is a library called "V-USB" that requires some extra hardware and makes it possible for a ATmega328p microcontroller to act as an USB device. It is not something for a beginner.
A few years ago, Arduino has changed the way the USB is used. The NicoHood HID library makes use of the new possibilities. It makes it possible for example to have extended features for a USB keyboard, like the media keys.
For a normal keyboard and mouse, the Arduino Keyboard Mouse library will do. It will be perfect for a ignition button. But you have to buy one of those boards (Leonardo, and so on).

or a teensy board

The solution to get a board that has built in USB support is not preferred for someone who just wants to use the boards they already have.  It is possible to use a board that can communicate with your computer over serial, such as the Arduino Nano, to send data to a Python program which can then turn the input from the Arduino into keyboard presses, etc. using libraries.
For this approach, you would need to know python.
The libraries to use are:
pyserial - communication with Arduino
pynput - control the computer's keyboard
threading (comes with python) - allow pyserial and pynput to work simultaneously