How to change baudrate of ESP8266 (12e) permanently? IMPORTANT: DO NOT USE AT+IPR=9600! (see update)

I have an ESP8266 12E module that communicates at 115,200 bauds. Since I use it with an Arduino Nano with SoftwareSerial things get messy. So I found that I should reduce the baud rate of the ESP module.

I found this link on how to do it.

I am wondering

Is this a permanent change or do you need to do this every time after the module is powered?
Can I achieve the same by sending the command from the Arduino over SoftSerial? Well, I guess not since I tried and I always get an error on AT+CIOBAUD=9600 or AT+IPR=9600.
I read somewhere that in newer firmware versions of the ESP8266, the baud rate defaults to 9,600. Can anyone confirm this and if so, is it better to flash this newer firmware?

The module's vendor:

Ai-Thinker Technology Co.,Ltd.

I think the current version of the firmware is 0.3.0. If I send  AT+GMR I get:

sending AT+GMR

response: ?AT¥TJÕ¨H(Q�²•ÉÍ¥½¹é‚r¢‚r‚r‚BÕ��Â’‚ŠªŠ¢Ò¢ªÒªÂJm
 SDK versioo:0.3.0
 Ai�½½
 ‚Šj

Again some garbage because of the baud rate which is too high.

Other info on the module:

sending AT+RST
response: ?AT+RST
OK
WRT
"%M
<99CT
 ets Jan  8 2013,rst catse:2, boot lode:(3,7)
load 0x40100000ntail 4
chksum 0x89
ld tail 4
chm3 tail 8 r 0 aM
 ón't use rtc mem dat`
sl��oÌÿ
Ai-Thinker Technology Co.,Ltd.

UPDATE

(*) I used an FTDI232 module to send AT+IPR=9600 to my ESP8266-12E module and I bricked it!

DO NOT USE AT+IPR=9600 ON AN ESP8266(-12E).

I did not manage to recover it so far! I tried re-flashing it but I get Invalid head exceptions.

On a new module I sent the AT+CIOBAUD=9600 command and it worked. Permanently!

My module specs:

AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK

Depending on how recent a version of the AT Instruction Set interpreter your chip has, the two instructions you tried may not be valid ones; they are not listed in Espressif's ESP8266 AT Instruction Set document. Searches for either "CIOBAUD" or "IPR" in the current document (version 1.5.3) return no results.

The baud rate commands are now "AT+UART_CUR" and "AT+UART_DEF" which configure the entire UART for the current session or the current and future sessions, respectively. The manual's prototype for the command is:

AT+UART_DEF=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>
Example:
AT+UART_DEF=115200, 8, 1, 0, 3

I have used these and can confirm that they work.

What I've found using software serial is that it can push 115200 baud well enough to send commands to the device (though I wouldn't build an application that depends on it) but it can only read reliably up to 9600 baud. I've been able to change my devices' baud rates from 115200 baud to 9600 over software serial; you just have to expect garbage coming back and ignore it:

// Set ESP8266 baud rate to 9600. You only need to do this once per device
set software serial baud to 115200;
send "AT+UART_DEF=9600,8,1,0,0";
set software serial baud to 9600;
// From now on, communicate with your device at 9600 baud.


Arduino 4G LTE Shield Is there by any chance a shield that can take an 4G LTE compatible SIM card activated by a carrier and establish a connection?

Googling "4g shield arduino" gave this. It will need a 4G LTE capable SIM, but I guess "it depends" if any 4G LTE SIM will work..


How to configure TinySine 3G module (SIM5320E) for HTTP GET request I recently bought a 'TinySine 3G shield (SIM5320E) 900/2100Mhz' based on Adafruit_FONA libraries to use with Arduino Mega 2560 R3.  It successfully registered with Vodafone AU. Other functionality works (SMS, GPS) but not HTTP/TCP.

I'm following this TCP/UDP section of SimCom tutorial to receive data from a REST API. But I cannot set the APN for TCP as there is no support for AT+CSTT command as it seems.

I can see it's on WCDMA network.

    AT+CREG?
    +CREG:1,1

    AT+CPSI?
    +CPSI: WCDMA,Online,505-03,0x014E,xxxxxxx,WCDMA IMT xxxx,xxx,xxxx,0,12.0,97,12,18,500
    OK

Error comes here

    AT+CSTT="live.vodafone.com"
    ERROR

Is there a way to resolve this issue
 - With the same setup/libraries OR
 - By upgrading libraries/firmware of the module OR
 - Using any other set of commands

Please provide if any of you have a sample code to access a REST API. Appreciate your help very much.

CSTT works on GPRS modules like SIM900. I found a way to get SIM5320E working to download websites. Tested with TeraTerm and used <Ctrl M> and <Ctrl J> instead of '<CR> <LF> OR /r/n' characters.

Network setup

AT+CGDCONT=1,"IP","<your APN>","0.0.0.0"
AT+CGSOCKCONT=1,"IP","<your APN>"
AT+CSOCKSETPN=1

Start HTTP service
You can stop and start service if it's not responding properly.

AT+CHTTPSSTART
AT+CHTTPACT="www.iforce2d.net",80

HTTP GET request

GET /test.php HTTP/1.1  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Host: www.iforce2d.net  <-- don't hit enter, instead hit the below 2 keys
<Ctrl M>
<Ctrl J>
Connection: close  <-- don't hit enter, instead hit the below 4 keys. This is useful when connecting to REST APIs to download the the respective result only.
<Ctrl M>
<Ctrl J>
<Ctrl M>
<Ctrl J>

To end the command and to receive results:

<Ctrl Z>

You will receive a lot of data here.

Stop HTTP service

AT+CHTTPSCLSE
AT+CHTTPSSTOP

You will get the contents of the website. Probably it should contain the data you need (I didn't test the content. May be you will need to tweek the result a bit.)


Power Arduino from 230v with battery fallback I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be

Here's the current setup:

Arduino running off the 9 V battery
A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
Arduino is reading light level from the light meter every 200 ms.
Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.

Problem

In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.

Idea

But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.

I could approach it in two ways:

When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.
If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:

a) have Arduino on all the time, regardless of whether button is pressed or not

b) power Arduino from the doorbell to avoid having to use a battery

Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)

Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?

Or maybe I'm missing some easier, simpler solution here?

This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.

Probably 10 mA of that is the LED, so removing it would help. I have a page about power saving. You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

Example of waking using an LDR

I made up a test like this:

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.

#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precautionary while we do other stuff
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  }  // end of setup

void loop ()
{

  // flash LED 5 times
  for (byte i = 0; i < 5; i++)
    {
    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
    delay (100);
    digitalWrite (LED, LOW);
    delay (100);
    }

  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes high
  attachInterrupt (0, wake, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

  What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.


How to use this confing function For INA3221 current sensor, I found this library, however, I don't understand how to use the INA3221SetConfig() function as defined in the .cpp file link.
void SDL_Arduino_INA3221::INA3221SetConfig(void)
{

      // Set Config register to take into account the settings above
      uint16_t config =
          INA3221_CONFIG_ENABLE_CHAN1 |
          // INA3221_CONFIG_ENABLE_CHAN2 |
          // INA3221_CONFIG_ENABLE_CHAN3 |
          INA3221_CONFIG_RESET |
          INA3221_CONFIG_AVG1 |
          INA3221_CONFIG_VBUS_CT2 |
          INA3221_CONFIG_VSH_CT2 |
          INA3221_CONFIG_MODE_2 |
          INA3221_CONFIG_MODE_1 |
          INA3221_CONFIG_MODE_0;
      wireWriteRegister(INA3221_REG_CONFIG, config);
    }

It seems like the function is called automatically when the .begin() function is called and whatever is defined in the config function is written to the register. The use of | operator confuses me. I tried to comment out the some settings to see if it works but it makes no difference. There isn't any documentation so I am in a fix. Could you please tell how can I change the configuration settings e.g. instead of all the three channels or change the config_mode?

Without looking at the library, you can check yourself if this method (INA3221SetConfig) is called from the begin method (of the same class). Just trace back the methods manually until you find a call to this method.
About the | or 'bit-wise-or' operator (see https://en.wikipedia.org/wiki/Bitwise_operations_in_C), these are used to set bits in a byte/word/long.
Most registers have 8, 16 or 32 bits and with the | operator you can easily set multiple bits at the same time. Each value (e.g. INA3221_CONFIG_ENABLE_CHAN) has a value that is a power of 2 (mostly defined in the form 1 << ..something.. you can add them (with +) or | them together, but | is more clear what the purpose is and repeatedly calling | the same bit twice is not a problem (it still gives the same result).


Difference between FreeRTOS libary (AVR_ATmega328PB_Xplained_mini_GCC) Versus FreeRTOS compatible for Arduino boards from Richard barrey I am researching about different IoT development boards and found that espressif uses IDF framework. When looked at the source code it uses FreeRTOS libraries. I have Arduino Uno and i wanted to use FreeRTOS for programming Arduino Uno. After search i found that FreeRTOS has multiple libraries that supports different micro controllers. Arduino Uno has ATMega328P and FreeRTOS has libraries for ATMega328P (link below)
https://github.com/FreeRTOS/FreeRTOS/tree/master/FreeRTOS/Demo/AVR_ATmega328PB_Xplained_mini_GCC
I also found that libraries created for Arduino family of boards (link below)
https://www.arduino.cc/reference/en/libraries/freertos/
I just wanted to what is the difference between these two libraries?

ATmega328PB is not the same MCU as used by Arduino boards. Those use ATmega328P (no B). ATmega328PB is a mostly compatible successor and offers more timers, built-in touch functionality and more but does not come in large DIP packages. Arduino uses the older ATmega328P.


MQTT PubSubClient connection problem with ESP32 I am experiencing some problems with string in Arduino application with ESP32.
I don't understand why this code works:

mqtt.setServer ("m20.cloudmqtt.com", port);  //is OK

and this does not work does not connect

String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strSBM.c_str (), port);  //no OK

I use library PubSubClient 2.7

Any of you can help me

Many thanks

When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:

PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
    this->domain = domain;
    this->port = port;
    return *this;
}

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.

It is really intended to work with string literals and global constant variables that never change.

If this is the one and only time that you ever set the server you could get away with using strdup() to duplicate the string data on the heap, but without direct access to the domain member variable of the PubSubClient class you have no way to free() the memory again should you ever wish to change the server.

String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strdup(strSBM.c_str()), port);

To make it so you can free the value you need to keep track of it separately:

static char *temp = NULL;
if (temp != NULL) {
    free(temp);
    temp = NULL;
}
temp = strdup(strSBM.c_str());
mqtt.setServer(temp, port);


Midi Program not sending notes I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program:
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;
    const int button5 = 6;
    const int button6 = 7;

int note = 0;

const int c3 = 36;
const int d3 = 38;
const int e3 = 40;
const int f3 = 41;
const int g3 = 43;
const int a3 = 45;

void setup() {

  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
  pinMode(button3,INPUT);
  pinMode(button4,INPUT);
  pinMode(button5,INPUT);
  pinMode(button6,INPUT);

  Serial.begin(31250);

}

void loop() {
  int button1State = digitalRead(button1);
  int button2State = digitalRead(button2);
  int button3State = digitalRead(button3);
  int button4State = digitalRead(button4);
  int button5State = digitalRead(button5);
  int button6State = digitalRead(button6);

  if (button1State == HIGH) {
    note = c3;
    noteOn(0x90, note, 0x64);
  }
  if (button1State == LOW) {
    note = c3;
    noteOn(0x90, note, 0x00);
  }

  if (button2State == HIGH) {
    note = d3;
    noteOn(0x90, note, 0x64);
  }
  if (button2State == LOW) {
    note = d3;
    noteOn(0x90, note, 0x00);
  }

  if (button3State == HIGH) {
    note = e3;
    noteOn(0x90, note, 0x64);
  }
  if (button3State == LOW ) {
    note = e3;
    noteOn(0x90, note, 0x00);
  }

  if (button4State == HIGH) {
    note = f3;
    noteOn(0x90, note, 0x64);
  }
  if (button4State == LOW) {
    note = f3;
    noteOn(0x90, note, 0x00);
  }

  if (button5State == HIGH) {
    note = g3;
    noteOn(0x90, note, 0x64);
  }
  if (button5State == LOW) {
    note = g3;
    noteOn(0x90, note, 0x00);
  }

  if (button6State == HIGH) {
    note = a3;
    noteOn(0x90, note, 0x64);
  }
  if (button6State == LOW ) {
    note = a3;
    noteOn(0x90, note, 0x00);
  }

}

void noteOn(int cmd, int pitch, int velocity) {
  Serial.write(cmd);
  Serial.write(pitch);
  Serial.write(velocity);
}

You are handling your buttons in completely the wrong way. You are basically saying:

  While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.

  At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.

Instead you need to detect changes in the state of a button.

For example:

void loop() {
    static bool oldButton1 = LOW;

    bool button1State = digitalRead(button1);

    if (button1State != oldButton1) { // It changed from last time
        oldButton1 = button1State; // Remember it for next time
        if (button1State) { // Pressed
            noteOn(0x90, c3, 0x64);
        } else { // Released
            noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
        }
    }

    ... etc for the other buttons ...
}


Is it possible to use SPI on Redbot Mainboard? My students use the Sparkfun RedBot Inventor's Kit for their final design projects. The documentation about this board isn't great. There are connectors to SPI pins (they are not soldered to headers, but they exist, see diagram below); however the bumpers and wheel encoders use pins 10 and 11, which are pins used in SPI communication.

My question is: is it possible to solder headers into that SPI socket and use SPI communication without interfering with the bumpers and wheel encoders (for example if my students want to hook up a 7-segment display to show the RedBot's speed)?

From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.

Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.

If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.

It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.


Unable to connect and configure ESP8266 wifi module with Ardunio Mega I try to connect Ardunio Mega with ESP8266 wifi module. Wiring diagram mentioned below:

I am using Ardunio IDE - For AT command test I was open COM monitor and selected 115200 baud rate and set to Both NL & CR.

But no response from ESP8266 wifi module. Response like "System read Vendor". I have changed different baud rate. But no use of it.

I don't know what I am missing out.

Please help on this.

Thanks,
Shanmuga Raja

Your ESP8266 module is most likely fried now, if your wiring diagram is any indication of your actual hardware setup.

The ESP operates at 3.3V, which means that every pin on it can receive no more than 3.3V as input. And it looks like you've directly connected the ESP's TX pin with the Arduino, without using a level shifter. The Arduino GPIO pins work on 5V logic levels.

Test this module out with a level shifter (resistor divider network, 3.3V zener, level shifter IC; pick your poison). If the ESP still doesn't respond, swap it out with a new one and repeat.


NodeMCU not responding AT after blink app I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.

I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from Espressif download page and flash it with the Espressif Flash Download Tool (Windows) or with esptool.py.


Upload application from Visual Studio 2019 with PlatformIO How upload application from Visual Studio? I can’t find upload process from standard VS in documentation https://docs.platformio.org/en/latest/ide/visualstudio.html

I hate VS Code.

I have final solution for uploading application from VS 2019.

Visual Studio have Tools > External Tools... where is possible add the PlatformIO command for uploading application pio run -v -t upload

After that is possible adding custom button to Toolbar
Fantastic thing is, that during upload you can Stop the process


What SMS can send to switch LED? I have code but I don't know how to send SMS from my Mobile
I mean what the message I can send to switch the Led?
To switch On or Off.
I use SIm900
and use this code

#include <SoftwareSerial.h>

 char inchar; // Will hold the incoming character from the GSM shield
 SoftwareSerial SIM900(7, 8);

 int led = 10;

 void setup()
 {
   Serial.begin(19200);
   // set up the digital pins to control
   pinMode(led, OUTPUT);
   digitalWrite(led, LOW);

   // wake up the GSM shield
   SIM900.begin(19200);
   delay(20000); // give time to log on to network.
   SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
   delay(100);
   SIM900.print("AT+CNMI=2,2,0,0,0\r");
   // blurt out contents of new SMS upon receipt to the GSM shield's serial out
   delay(100);
   Serial.println("Ready...");
 }

 void loop()
 {
   //If a character comes in from the cellular module...
   if(SIM900.available() >0)
   {
     inchar=SIM900.read();
     if (inchar=='#')
     {
       delay(10);

       inchar=SIM900.read();
       if (inchar=='a')
       {
         delay(10);
         inchar=SIM900.read();
         if (inchar=='0')
         {
           digitalWrite(led, LOW);
         }
         else if (inchar=='1')
         {
           digitalWrite(led, HIGH);
         }
         delay(10);
         // SIM900.println("AT+CMGD=1,4"); // delete all SMS
       }
     }
   }
 }

The code appears to be looking for an SMS that says #a0 or #a1. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does SIM900.read() do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.


Reading a photoresistor I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)

I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit?

I could not find my optocoupler in fritzing. This is it:
http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref_=oh_aui_detailpage_o07_s00

This is my plan.

The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.

I based my circuit on this:

But I don't know if it will do the same thing.

Wouldn't this be simpler?

Note: amended answer increases R1 to 10 k.

The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.

I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.

This gives:

For an input voltage of 5 V -> 2.3 V on the Arduino input
For an input voltage of 10 V -> 2.6 V on the Arduino input
For an input voltage of 20 V -> 2.9 V on the Arduino input
For an input voltage of 30 V -> 3.1 V on the Arduino input

This is all within spec for the Arduino.

Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.

3.3 * 0.6 = 1.98

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.


What's the most accurate way to time-stamp analogRead data? I want to sample an Analog sensor as fast as possible, and time-stamp each sample that I take as accurately as possible.

Currently, I'm doing the following:

val = analogRead(SENSOR_PIN);
clocktime = micros();

writeData(val, clocktime); // writes the values to an SD card

I'm wondering if there is a more-accurate way of time-stamping the data from the analogRead call. Put another way, I would like to record the exact time that the analogRead data was collected. My guess is that this is basically impossible on an Arduino, so what technique will let me get as close as possible?

There is no more accurate way of getting time on the arduino, but I would suggest you use millis() instead.

micros() returns microseconds, or millionths of a second, since the arduino was turned on. The issue is that the 32 bit unsigned integer used to store time on the arduino can only count about 70 minutes worth of micros before overflowing and resetting to 0. (see http://arduino.cc/en/reference/micros)

millis() is in thousandths of a second since the arduino turned on, and it will not reset for about 50 days. If you think one thousandths of a second is good enough resolution, it will probably be the better choice.

If you need time to be absolute, as in the current day/hour/minute, you will need to buy a real time clock to plug into the arduino. They are about 20 bucks, and available from all the standard arduino accessory stores like sparkfun, adafruit, ect.

On your question of the order, both commands run so quickly, I can think of no reason it would matter.


serial communication problem with sim7600 with arduino mega I am just sending the AT command to test if the serial communication works, the response I am getting is a flipped ? or a square or rectangle symbol.
I have tested the communication using software provided by waveshare connected through on board usb to uart.

https://www.waveshare.com/wiki/SIM7600E-H_4G_HAT

int PowerKey = 2;
char answer;
void setup()
{
 Serial3.begin(9600);
 Serial.begin(9600);
 pinMode(PowerKey, OUTPUT);
 Serial.println("initializing");
 digitalWrite(PowerKey, HIGH);
 delay(1000);
 digitalWrite(PowerKey, LOW);
}

void loop()
{
  answer = send_at_cmd("AT\r\n");
  Serial.println(answer);
}

uint8_t send_at_cmd(const char* ATcommand)
{
  char response;
  // send test command AT
  Serial3.print(ATcommand);
  Serial.println(ATcommand);
  delay(1000);
  //Check for response from the sim7600E-H
  while(Serial3.available() != 0)
  {
    response = Serial3.read();
  }
  return response;
}

You have change baud rate by at+iprex=9600 before upload your code, because sim7600 set 115200 by default then save your setting by at&w.

hope this help someone.


how to make GPRS/GSM SIM900 shield work with gps neo-6M module using Arduino UNO board I'm a beginer to arduino program.i will like to make a program that will send latitude and longitude on my mysql database.so since 3 days i try to learn how to use all this material(GPRS/GSM SIM900 shield, gps neo-6M).But i only success to make them work alone.i also learn that i cannot use SoftwareSerial for GPRS/GSM SIM900 shield and  gps neo-6M at the same time.
so how can i make GPRS/GSM SIM900 shield and gps neo-6M work together using arduino uno

thank you for you help

I think you are searching for a solution like this Interfacing GSM and GPS Module using Arduino where GPS and GSM modules can run together and receive data at the same time.

I tried bringing up both inside setup() and it blocked the other device. Here is some extract of the code (Note that rx,tx and baud rates may differ according to the modules).

SoftwareSerial gsm(7,8);
SoftwareSerial gps(3,4);

void setup() {
    Serial.begin(9600);
    gps.begin(9600);
    gsm.begin(4800); <--- This stopped receiving GPS updates
}

If you look for an advanced way of handling this situation, you may need to implement some light-weight threads (e.g Protothreads) and assign GPS and GSM modules to run in separate threads, so one device may not block send/receive of the other device. These Arduino forum answers may help for such approach.


Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board? Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board ? Is it possible without another component in between ?

Actually, this is dependent on the datasheet. Assuming it's 7 segment + dot, it will require 8 independent pins to control each of the segment. All of segments are connected to a common anode/cathode which can be connected to a pullup/pulldown.

If we have 4 digit, that means we need 4*8=32 pins, which is a lot for any microcontroller. However, if you map out the internal circuit, you'll find that the segments are multiplexed. (You can do this by touching the pins with a wire connected to a pullup resistor, and another wire connected to ground.

Generally, you'll find that all the segment pins are multiplexed together in such a way that if all anodes/cathodes are enabled, all of the digits show the same display.

So how then can we make use of this information? Here's an idea:

How about turning on each of the digits one at a time (by controlling the common anode/cathode), but doing it quickly?

An example sequence would be as follows:
Set the segments for digit 1, enable the corresponding common anode/cathode for 5ms. Turn off.
Set the segments for digit 2, enable the corresponding common anode/cathode for 5ms. Turn off.
Do the same for digit 3 and then 4.
Repeat.

Controlling in this manner means you only need 8+4 pins=12 which is available on an arduino uno. Refreshing at 4*5=20ms will hardly be visible to our human perception, thanks to persistence of vision.

My answer is really just a starting point. If you spend some time, you can try to put in other smarts which are suited for your application, using even less pins. You should try this as an exercise. ;-)

Edit:
As a precaution, it's important to limit the current running through each of the LED segments so that they can live a long and happy life.

Assuming a forward voltage of 2V, adding a 1k resistor at the common anode limits the current to 3mA. This means adding resistors for all 4 anodes.

The same could work for common cathode displays, as long as the reverse breakdown voltage is not exceeded.

As with all things you find on the net, don't take my word for it. You should do the maths to check.


Arduino read PWM duty cycle value with input (analog / digital) I am working on comparing autopilots like Ardupilot, CC3D, KK2.1.5. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. I have to read 8 duty cycle values with digital/analog input pins. How do I measure duty cycle of 8 PWM signals?  Also, is digital or analogue measurement precise and faster?

Note about attachInterrupt command: According to arduino.cc AtMega328 series have 2 interrupts, Arduino ATmega 2560 series have 7 interrupts.

The code shown in my answer to question 18183, “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of micros() at each change.

Also see my answer to question 19106, “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  My answer to question 32572, “How to detect the direction of a rotary encoder?”, shows another instance.

Digital input, as used in the code mentioned above, takes under  a microsecond ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the for loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.

10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in a webpage at microsmart.co.za can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.


How to use String.substring? I have the following code in which requestLine is always empty and I can't figure out why. request contains a raw HTTP request, and I want to get the first line of the request which contains the method and the URL.

boolean parseRequest(String* request)
{
  int firstEOLAt = request->indexOf('\n');
  if (firstEOLAt < 0)
    return false;
  Serial.println(firstEOLAt);
  String requestLine = request->substring(0, firstEOLAt);
  Serial.println(requestLine);
  // ...rest of the parsing will go here...
  return true;
}

The first println returns 26 as you would expect for the string "GET /ilyen_nincs HTTP/1.1" (25 characters long), but then requestLine is always empty. I wonder why?

GET /ilyen_nincs HTTP/1.1\n is 26 characters long so string indices are from 0 to 25. Since, your second argument in substring(0, firstEOLAt); exceeds the end index of the string, you are running into unexpected behavior as per the documentation and getting an empty string.

  Caution: make sure your index values are within the String's length or you'll get unpredictable results. This kind of error can be particularly hard to find with the second instance of substring() if the starting position is less than the String's length, but the ending position isn't.


Correct Pins for Nodemcu 8266 I am building a small electronic project, and I am incorporating module nodeMcU 8266 in a box.
I would like to know which pins are for "flash" and for "reset"
I know there are 2 buttons on the module for those 2 actions, but I would like to add 2 external buttons for those function on the case of the project, like that I will not need to open the box everytime. I looked on the net, and I guess that for "reset", I must connect to pin "Rst" and pin "Grd", I mean those 2 pin must be shorted, but I prefere to get confirmation before to go further.
And also for the "flash", what are both pins that I must connect the external push button to, to replicate the button present on the module itself.

Also I would like to connect an external LED to the module, following the state of the blue SMD led.
The thing is that there is an SMD blue led on the module, I want to know what are the 2 pins that are similar to the contacts of the blue SMD led.
I want the External LED that I plan to incorporate to the case of the project, to light up when the SMD blue led on the module is on, and when the led to be off when the blue SMD led is off. I want that both follow the same state.
Blue SMD led "On" >>> external led "On"
and
Blue SMD led "Off" >>> external led "Off"

Sorry for the little confused explanation, and thanx in advance for any help and support.

The v0.9 and v1.0 NodeMCU boards have 2 LEDs: One on the AIthinker module, and one on the actual NodeMCU board.

The AIthinker module's LED is connected between Vcc (3.3V) and GPIO2 (labeled D4 on nodeMCU). It turns ON when D4 is set LOW.

The NodeMCU LED is connected between Vcc (3.3V) and GPIO16 (labeled D0 on nodeMCU).  It turns ON when D0 is set LOW.

The pin labeled RST is the Reset signal from the AIthinker module, and is active-high, meaning you connect RST to GND to put the device in a reset state.

The pushutton labeled FLASH is connected between GND and GPIO0 (labeled D3 on nodeMCU). When the this pin is LOW when the ESP8266 comes out of a reset state, the chip is in flash-bootloader mode, meaning it is ready to receive a new sketch. On a NodeMCU, however, the ESP8266 chip is placed in flash mode by the USB chip and the flashing software, so there is not a need to manually press this button.


Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor? Here's my circuit:

And the code:

//pins
const int control1 = 2;
const int control2 = 3;
const int enable = 9;
const int pinDirection = 4;
const int pinOnOff = 5;
const int pot = A0;
//states
int stateOnOff = 0;
int stateOnOffPrev = 0;
int stateDirection = 0;
int stateDirectionPrev = 0;

int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 1;

void setup(){
  pinMode(pinDirection, INPUT);
  pinMode(pinOnOff, INPUT);
  pinMode(control1, OUTPUT);
  pinMode(control2, OUTPUT);
  pinMode(enable, OUTPUT);

  digitalWrite(enable, LOW);
  Serial.begin(9600);
}

void loop(){
  stateOnOff = digitalRead(pinOnOff);
  delay(10);
  stateDirection = digitalRead(pinDirection);
  motorSpeed = analogRead(pot)/4;

  if(stateOnOff != stateOnOffPrev){
    if(stateOnOff == HIGH){
      motorEnabled = !motorEnabled;
    }
  }

  if(stateDirection != stateDirectionPrev){
    if(stateDirection == HIGH){
      motorDirection = !motorDirection;
    }
  }
Serial.println(stateDirection);
  if(motorDirection == 1){
    digitalWrite(control1, HIGH);
    digitalWrite(control2, LOW);
  }else{
    digitalWrite(control1, LOW);
    digitalWrite(control2, HIGH);
  }

  if(motorEnabled == 1){
    analogWrite(enable, motorSpeed);
  }else{
    analogWrite(enable, 0);
  }

  stateDirectionPrev = stateDirection;
  stateOnOffPrev = stateOnOff;

}

As you can see, the switch on pin 5 controls whether the motor is on and the potentiometer controls motor speed. Both work.

However, when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit. It should when pressed change the direction of the motor via the H-bridge. I've tried everything I could, new switches, higher resistance. The only time it read HIGH is when I literally plugged switch out to GND.

Serial shows stateDirection as an unending chain of zeroes.

And finally the schematics from the original project.

Thank you.

**PS: Forgive for lack of comments! But I think a good Arduino programmer should not need comments. **

when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit.

you could have pull-up enabled on that pin: with a nominal value of 50k, 10k pull-down is just on the cusp of making it a logic low.

solution?

1) disable pull-up;
2) use a stronger pull-down;
3) get rid of the pull-down and rely on the pull-up alone.
...


How to automatically reset the nrf24l01+ with code? I have two separate nrf24l01+ connected to two different Arduino UNOs, one as TX and the other as RX. The problem is the connection stops after a while between them.

On the Arduino COM screen I have noticed these things:

TX Side: Completely Frozen (Transmission Stops).
RX Side: Continuously receives the last data repeatedly.

The problem is solved temporarily when the TX MCU (hence the nrf) is restarted .Sometimes even after restarting the TX MCU the RX stops responding and I have to restart the RX as well. Therefore I am trying to find a way to reset my nrfs automatically using software when this situation occurs.

I found the problem occurs because the transmitter is expecting acknowledgment from the receiver which is getting lost somehow, while transmission and the transmitter still waits for ack for the last transmitted data (which it never gets) so it keeps on transmitting the last packet again and again. I saw on forums that its because of the TX buffer getting full after 3 retries or something. I don't exactly know why it happens.

I first tried resetting just the transmitter through code but it was not enough (as already mentioned in the question). So I now reset both the TX and RX using the below code. I have a separate 1 byte reset-counter in the first byte of the array (you may use a single byte variable) which acts as an id for the packet (you may use the internal PID as well).

The below code resets  the TX if transmission fails by checking the return value of write function and resets the RX when it receives the same ack or packet (with the same reset-counter value) more than 2 times (I use a condition to check if the last counter value is different from the current one or not). To reset it using code I use the below algorithm :

Power Down the NRF using powerDown() function.
Re-initialize the nrf for the MCU.
Power Up the NRF using powerUp() function.

Note: I am using TMRH20 RF24 Library.

TX Code

void radio1_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio1.begin();
  delay(100);
  myRadio1.setChannel(96);
  myRadio1.setPALevel(POWERLEVEL);
  myRadio1.setDataRate(DATARATE);
  myRadio1.setAutoAck(1);
  myRadio1.enableAckPayload();
  myRadio1.enableDynamicPayloads();
  myRadio1.setRetries(2, 10);
  myRadio1.setCRCLength(RF24_CRC_8);
  myRadio1.openWritingPipe( addresses1[0]);
}

void loop()
{
  dataTransmitted[0]++;
  if ( myRadio1.write( &dataTransmitted, sizeof(dataTransmitted)))
  {

    if (myRadio1.isAckPayloadAvailable())
    {
      myRadio1.read(&ack, sizeof(ack));
    }
  }
  else
  {
    myRadio1.powerDown();
    \\Serial.println(" 1 Tx1 problem end");
    radio1_init();
    myRadio1.powerUp();
  }
}

RX Code

void radio2_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio2.begin();
  delay(100);
  myRadio2.setChannel(96);
  myRadio2.setPALevel(POWERLEVEL);
  myRadio2.setDataRate(DATARATE);
  myRadio2.setAutoAck(1);
  myRadio2.enableAckPayload();
  myRadio2.enableDynamicPayloads();
  myRadio2.setRetries(10, 10);
  myRadio2.setCRCLength(RF24_CRC_8);
  myRadio2.openReadingPipe(1, addresses2[0]);
  myRadio2.startListening();
}

void loop()
{
      if (myRadio2.available())
      {
        myRadio2.read( &dataReceived, sizeof(dataReceived));
        myRadio2.writeAckPayload(1, &ack2, sizeof(ack2));
        if (prevack2 == dataReceived[0])
        {
          \\Serial.println("RX 2 problem");
          c2++;
        }
        prevack2 = dataReceived[0];
        if (c2 > 2)
        {
          myRadio2.powerDown();
          radio2_init();
          myRadio2.powerUp();
          c2 = 0;
        }
      }
}


how to break out servo.write(angle) after it reach the angle? I used a servo as a grabber so I don't know the angle I need specifically.I need it to break the serve.write(angle) when the grabber holds something.
I used a simple code

#include <Servo.h>
Servo myservo;
void setup() {
  myservo.attach(9);
}
void loop() {
  myservo.write(100);
  delay(500);
  myservo.write(50);
  delay(500);
}

when it holds anything it deos not return to the small angle until I remove the obstacle from its way.

You change the angle in small increments until the sensor triggers:

bool closing = false;
bool openeing = false;
int angle;

void loop(){

    //read touchSensor

    if(sensorHit){
        closing  = false;
    }
    if(closing){
        if(angle <= minAngle) closing = false;
        angle -= 1;
        myservo.write(angle);

    }

    if(opening){
        if(angle >= maxAngle) opening = false;
        angle += 1;
        myservo.write(angle);

    }

}

The to start moving the grasper you set opening or closing to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.


Should I use LLC to power sensors on grid pcb at 4mtr wire length distance? I have setup a grid pcb that further distributes power and receive signal from sensors, I know low voltage can detroit if not damage sensors , so I am thinking to put BD-LLC  to distribute power output to 6 sensors connected to PCB shown below.
[ignore 24 volt power that feeds solenoid it is separate and comes from power adapter not from mega though the wire has same red colour] the 5 volt wire connecting to main connector from other connector is not visible.

And I have Arduino Mega from which I am drawing power 5 volt (using digital multimeter I found it's 4.98 volt). And all sensors are connected to this 5volt parallely.
So the question is should I put this BD-LLC on above PCB to distribute correct power output to sensors ?

Transmitting power over longer distances requires careful consideration. The actual voltage you will get at the remote end depends on two major factors:

The resistance of the wire, and
The current draw of the remote device

If you regulate your 24V incoming power down to 7V for the Arduino and then send the Arduino's 5V over 4m of wire to power your remote board the actual voltage the board will receive depends on the amount of current the board draws.

If this current is tiny then the voltage drop for the wire will be small and can largely be ignored. For instance, you quote about 3Ω resistance for 4m of wire, which to me seems incredibly high (32AWG which is like hair thin is only ~0.5Ω/m), but anyway.  If your board draws 100mA, over your 4m wire, which is actually 8m when you take into account the length of the ground wire ("There and back again - an electron's tale.") you would drop (2*3Ω)*0.1 = 6*0.1 = 0.6V, so your 5V would turn to 4.4V by the time your board sees it. Not only that but the ground wire would be offset at the board end by 0.2V, which may impact LOW logic level detection.

So ideally you need to both minimise and mitigate that voltage drop. And both can be done using a buck regulator at the board and powering it from the 24V supply instead of 5V.

By using a buck regulator you massively reduce the current over the wire (for 24V to 5V you could be looking at around a quarter of the current or even less, depending on the efficiency of the regulator) which reduces the voltage drop on both the power and ground wires. It also guarantees that the board runs at 5V regardless of the current draw of the board.

Here's a diagram:

For digital sensors this loss of voltage could cause damage if any incoming logic signals are above the absolute maximum for the sensor (which is usually a function of the supply voltage, say Vcc + 0.3V). For analog sensors it will affect the values you are reading, since the voltage emitted from the sensor is often a function of the supply voltage, and if that is not what you expect it to be your calculations from the ADC values will be incorrect.

To answer your original question "can I use a LLC to distribute power" the answer is "no". The LLC can allow you to interface logic signals between two different voltage levels, but not affect power at all. And further more it requires that you have both voltages availabe for the LLC to operate, and you don't have both voltages, you only have the 5V minus the wire's voltage drop available, so you can't use it to mitigate any offset in the logic levels either.


Arduino Digital Input. Trigger HIGH by 12V to 36V I want to build a small circuit that will switch a LED on (for arguments sakes) when the cars ignition gets switched on. But I want to make it versatile so I can work with between 12V - 36V (Cars, Trucks, etc). What would be the best to read the Ignition status via the arduino. Know I have thought of an idea by working with voltage divider. Basically taking the principal of reading voltage Instructable Example and working from there. Any thoughts?

Even easier:

input - series 220 ohm resistor, and a 78L05 voltage regulator (check for maximum voltage). This allows you handling like 4..30V and get a solid "1" on digitalRead. (4V input makes like 3V output which is still logic high).


Custom source directory How do you specify a custom location for your sketch?

I want my code to be located in a src folder, but when I try to compile my main.ino, arduino complains "The file main.ino needs to be inside a sketch folder named "main". How do I disable this arbitrary restriction?

I found I could accomplish this using the arduino-builder tool. I created this simple bash script to do the compilation:

#!/bin/bash
CURRENT_DIR=`pwd`
mkdir -p $CURRENT_DIR/.build
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -tools /usr/share/arduino/tools-builder -libraries $CURRENT_DIR/lib -fqbn arduino:avr:uno -build-path $CURRENT_DIR/.build $CURRENT_DIR/src/main.ino


What changed in the new Due? I recently purchased a batch of Due boards and find that they are cosmetically different. After attaching the Atmel-ICE and reading the firmware from both processors, I find that the firmware is different. The green masked one had a sticker indicating a new IDE should be downloaded from arduino.

The back of the board shows silkscreen changes to the logo (DUE in an oval rather than rectangle) but both boards say BOARD MODEL DUE R3-E. The traces appear the same, the placement of parts appears the same, and other than different colored headers the parts are similar. The main processor has the same part number, but distinctly different markings. Internally the processors report the same device signature and revision.

What has changed in the firmware? Are there other changes I've missed? Other than needing an even newer IDE are there changes that will affect my sketches?

If I load the older firmware onto the newer Due processors, should it operate the same, allowing use of the old IDE, and in case my sketches do face a problem with the new version?

The 'new' board with green soldermask and the lighter headers is made by arduino.org.  The old one was probably made by the same company, but prior to the split in the founders.

Right now there is arduino.cc (the original website) and arduino.org (the website set up by the company that split from Arduino).  There is a lot of different perspectives about who really owns Arduino and I won't attempt to weigh in here.

The changes in firmware are still unknown.  It's likely that they are simple strings or response changes so the boards can be differentiated in software.  The new IDE is in alpha, and is yet another attempt to differentiate between the two Arduino groups.  I haven't attempted to program either with either group's IDE, but if I do I'll update this answer with the results.

At least there's a way to visually identify the difference once received - wish they had given them different part numbers so Digikey wouldn't have sent me a mixture...


Can I power my Arduino Uno with a 9V / 990mAh battery? I have a 9V Lion 990mAh battery. I am not sure if I can use it to power an Arduino externally?

Can you please guide me how to understand current specifications of any device?

Thanks and Regards,
Manish

While this answer addresses the specific question it should also prove useful as a link to resources relating to current reduction in other microcontroller projects.

Short:

The "C" rate for a cell is a current in mA numerically equal to the capacity in mAh
eg 1000 mA for a 1000 mAh cell.

In the absence of a specific data sheet a LiIon or LiPo cell is probably safe for maximum charge and discharge rates of C/2 and C.
ie 500 mA max charge rate for a 1000 mAh cell and
1000 mAh max discharge rate for a 1000 mAh cell.

In many cases double those rates will be safe.
Charge rates are seldom higher than C but discharge rates of substantially higher than 2C MAY be safe - see data sheet!.

In your example case, the operating time will be approximately mAh/average_current. Consult the data sheet for your microcontroller and/or measure current drain.

A typical "bare" Arduino with processor, USB IC, LEDs and "glue" components probably draws typically 50 mA and maybe up to 100 mA. Adding external loads can increase this - depending entirely on the load.

At say 100 mA average drain you'd get approximately 900/100= 9 hours operation. Running just the processor and on board components / peripherals you'd probabaly get twice times as long. By targeting low current methods (see refs ate end) you could get MUCH longer.

Most LiIon batteries are rated to charge at up to the "C" rate - ie 990 mA for a 990 mAh battery and to safely discharge at several times as much. Some manufacturers rate their batteries for lower maximum charge rates and this also can vary with the intended cell application. A "high energy" cell is liable to have lower charge and discharge rates than a "high power" cell. This relates to means of construction and to be safe the manufacturer's data sheet should be consulted.

The battery "capacity" rises somewhat as rates decrease below 'C' and fall significantly for rates above C.

Here is an excellent example data sheet for selected Sanyo LiIon cells . These are only examples but give a reasonable idea of what can be expected from a reasonable quality product.

Arduino per pin current limitations

Typical current draw](http://gadgetmakersblog.com/arduino-power-consumption/)

Excellent - Methods of reducing Arduino power consumption  & Related & more

Stack exchange discussion - How much current do you require in Arduino and embedded systems projects?


Searching for a good keypad I'm wanting to make a keypad for my gragedoor. I found one like this but i don't think it is very waterproof.

Now i'm wondering if someone of you know a good keypad that can be used outdoors and can be connected to a arduino (preferably arduino nano).

Hope you can help.

Edit if found this keypad will i be able to program this one with a arduino?
link

The membrane keyboard you have linked (first link) in your question should be water resistant, if not water proof.

We use something similar at my work. You can have the keypad stuck to the outside of the enclosure and then have a rubber seal (or silastic) sealing where the ribbon cable enters the enclosure.

You will notice that the ribbon cable pretty much exits the bottom of the keypad. The better ones to get, if you can find them, are the ones where the ribbon cable exits the keypad further away from the edge (see example image below). That way the adhesive backing of the keypad seals the cable entry into the enclosure.

As far as hooking it up to an Arduino - no problems at all. A 16 key matrix keyboard has 8 connections, 4 for each row and 4 for each column. Every time you press a key, the row and column are shorted together.

The way I would connect it up is to have the rows connected as inputs and the columns as outputs. One by one I would turn one of the columns on (HIGH) and see which input(s) are reading a HIGH. If it is I know that that key (row and column) is pressed. This method will handle multiple keys pressed at once.

There is an walk-through tutorial posted at instructables.com.

The more expensive keypad in your second link and this one both have the option of connecting by PS2. There is an Arduino page on connecting and controlling a PS2 keyboard here.


'Simple' problem. Delay not working? Servo goes to one end, and immediately travels back without a 2s delay inbetween. After it travels back there is a 2s delay before it loops. Why isn't there a 2s delay before the travel back?

Servo testservo;

void setup() {
    testservo.attach(9);
}

void loop() {
    testservo.writeMicroseconds(700);
    delay(2000);
    testservo.writeMicroseconds(2300);
    delay(2000);
}

Your description (“Servo goes to one end, and immediately travels back without a 2s delay... After it travels back there is a 2s delay before it loops”) implies an overall cycle time of 2 seconds, which appears to be inconsistent with the overall 4-second cycle implied by the code shown.

Here are things you can do to debug the problem:

Turn on an LED before one writeMicroseconds() call, and turn it off before the other.  For example, add pinMode(13, OUTPUT); in setup(), and revise loop() as follows:

void loop() {
    testservo.writeMicroseconds(700);
    digitalWrite(13, HIGH);
    delay(2000);
    testservo.writeMicroseconds(2300);
    digitalWrite(13, LOW);
    delay(2000);
}

This may allow you to find out which end the servo is going to.

Besides adding LED signals, try slightly-less extreme times in the writeMicroseconds() calls; eg 1000 and 2000 microseconds rather than 700 and 2300.
See if a neutral servo setting works, eg via code like the following.

enum { LEDpin=13, dtime=2000}
void stest(angletime, tHi, tLo) {
    testservo.writeMicroseconds(angletime);
    digitalWrite(LEDpin, HIGH);
    delay(tHi);
    digitalWrite(LEDpin, LOW);
    delay(tLo);
}
void loop() {
    stest(1000, dtime-50, 50); // Go CCW
    stest(1500, 50, dtime-50); // Middle
    stest(2000, 50, dtime-50); // Go CW
}

When this code runs, the LED should stay on about 2 seconds with the servo fully (or nearly so) counterclockwise.  Then the LED should blip and the servo should move to center position and stay there about 2 seconds.  Then the LED should blip and the servo should stay fully clockwise about 2 seconds.  This three-part cycle should repeat every six seconds.  If it works ok, then try modifying it, eg by changing 1000 us to 700, 2000 to 2300, etc, or by decreasing the dtime value to see how quickly the servo can respond, etc.


RC522 RFID reader doesn't read NTAG216 chip I have an RFID-RC522 module based on the MFRC522 chip. This chip is described in the datasheet as supporting "ISO/IEC 14443 A/MIFARE and NTAG" protocols. I have wired it up to an Arduino Uno using the recommended wiring in the documentation for the MFRC522 library I'm using. I have a sketch that (among other things) polls for presence of a new card:

void setup() {
    lcd.setup ();       // initialise LCD display
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    lcd.println ("Found new card");
    ...
}

This sketch correctly detects the presence of the card that was supplied with the module (I believe this is a Mifare Classic card) but does not detect my NTAG216 implant. Does anyone have any idea why it might be failing to find the implanted chip?

I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:

https://github.com/mxgxw/MFRC522-python/issues/24

and Cotix's link

https://github.com/mj3052/MFRC522-Pi

Give them a lookover and see what they can tell you.

The problem with the PICC_IsNewCardPresent() function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return false. But the other code may give you a clue - you'll have to delve into the library...


I2C Master send reset command to the slave counter My name is Gianni, I live in Olbia Sardinia Italy and I have some experience in electronics.

For several years I have been passionate about Arduino.

They are now engaged in a project to counter with hall sensors.

The slave sends data to the master via I2C, for my project. I'm using the sketch of Gammon which uses a structure enum to send a request to the slave.

I have the need to send a reset command from master to slave.

I edited the sketch and I can see the command on the slave but will not let me use it to reset the counter.

Master code section

   void RstCounter()
  {

  Serial.println ("funzione azzera attivata");
   Serial.println (sensor);
  char key = keypad.getKey();
  if (key !='A')
  {

   char cmdrst = 'a';
   //set=key;

     if (sensor==11)
    {
    sendCommand (CMD_WRITE_D2, 1);

    Wire.beginTransmission(SLAVE_ADDRESS); // testiamo questa istruzione
    Wire.write(cmdrst);
    Wire.endTransmission();

    delay(100);
    Serial.println (cmdrst);
    }

   else
  {
  m=0;
  }

   azzera =true;
  }
   else if (key=='A')
    {
   Serial.println("");
   Serial.println("AZZERA close");
   azzera = false;
   }
     delay(100);
    }

SLAVE code section

#include <Wire.h>

const byte MY_ADDRESS = 42; // address in valore esadecimale

/************  VARIABILI SENSORI **********************/

#define Sensor11 2
int lastValueSensor11 =0;
int ValueSensor11=0;
int contatore11=0;
int counter11;

// various commands we might get
/************  VARIABILI ENUMERATORE **********************/
enum {
    CMD_ID = 1,
    CMD_READ_D2  = 2,
    CMD_READ_D3 = 3,
    CMD_READ_D4 = 4,
    CMD_WRITE_D2 = 5
    };

char command;
int sensor;
char cmdrst;

/************  SETUP **********************/
void setup()
  {
  command = 0;

  pinMode (Sensor11, INPUT);
  digitalWrite (Sensor11, HIGH);  // enable pull-up

  Serial.begin(9600);
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

/************  LOOP **********************/
void loop()
  {
        /************************ CONTATORE SENSOR 1 ***********************/
   ValueSensor11  = digitalRead(Sensor11);

            if ( ValueSensor11 != lastValueSensor11)
               { if ( ValueSensor11 == LOW)
                    {
                      contatore11 = contatore11 + 1;

                        }
                     }
   lastValueSensor11 = ValueSensor11;

/************  I2C RECEIVE **********************/
void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

void sendSensor1 (const byte which)
  {
  int val11 = contatore11;
  Serial.println(contatore11);
  byte buf11 [2];

    buf11 [0] = val11 >> 8;
    buf11 [1] = val11 & 0xFF;
    Wire.write (buf11, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:
     Wire.write (0x55);
     break;   // send our ID

     case CMD_READ_D2:
     sendSensor1 (2);
     break;  // send A0 value

     case CMD_READ_D3:
     sendSensor2 (3);
     break;    // send D8 value

     case CMD_READ_D4:
     sendSensor3 (4);
     break;

     }  // end of switch

  }  // end of requestEvent

void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

Don't do serial prints inside an interrupt service routine (ISR). That is, not here.
Don't do delay inside an ISR.

  if (key !='A')
  {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave a lot.


Why all unset pins of my Arduino Uno are outputting 2 volts? I am new to Arduino and physical computing When I measure the wire coming from any UNSET Arduino uno pin, the result is approximately 2 volts even the "ANALOG IN" pins. Considering that the pins which been set to HIGH and LOW are giving 5 and 0 volts "which is cool".
Is that the nature of Arduino or is that a failure caused by short or anything else?

The electric shocks being felt is due to leakage current from the laptop's switchmode power supply. All unearthed mains powered switchmode plug pack power supplies leak a few micro amps and voltages in excess of 80 volts AC as measured from the plug packs output socket to ground will be observed when measuring with multimeters having 10 meg ohm input impedance.
The solution is to have the GND pin of the arduino board connected to earth. Here in Australia all computer power supplies are grounded via the 3 pin power plug.


Reading/Writing Strings with Bluetooth Windows API I am trying to use my HC05 so my Arduino can communicate with my Windows 10 PC. I have a program written using the Window API for Serial Communication but the problem is it looks like the Arduino/HC05 can only send or the API can only read one character at a time. It is the same with Arduino; I send an entire string with the API and the Arduino has to read/parse it character by character. I was wondering if there was a solution to this problem or if I will need to develop some sort of coding protocol (like space to separate messages) to send messages. (The other issue is that it will take an age to send long messages this way.)

Windows File Reading API
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364232(v=vs.85).aspx

Here is the PC side file.

do {
    // check for data on port and display it on screen.
    ReadFile(file, buffer, sizeof(buffer), &read, NULL);
    int i;
    sscanf(buffer, "%d", &i);
    std::cout << i << std::endl;

    if (read) {
        //WriteFile(screen, buffer, read, &written, NULL);

        //When space seen, add the string to data
        if (buffer[0] == ' ') {
            int convertedDatum = std::stoi(datum, &sz);
            if (convertedDatum < 12) {
                //WriteFile(file, "S " , 2, &written, NULL);
                //WriteFile(screen, "S", read, &written, NULL);
            }
            else {
                //WriteFile(file, "G ", 2, &written, NULL);
                //WriteFile(screen, "G", read, &written, NULL);
            }
            data.push_back(convertedDatum);
            datum = "";

Arduino-side test code

void loop() {

while (true) {
    String sendValue = String(100);
    sendValue.toCharArray(buf, sizeof(buf));

    Serial1.write(buf);
    Serial1.write(' ');
    delay(4000);
}

What I am seeing on the console on the PC which is represented by the screen variable when I debug is when I break at the line

std::cout << i << std::endl;

1-Continue-0-Continue-0
or on the console

1
0
0
0
0
0
...

I am pretty sure that I have seen entire strings sent at once with the Android Bluetooth API so I am not sure exactly if the same can be done with Windows or if the Windows VC++ API's are incapable.

Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.


Enabling keyboard feature on Arduino with CH340G I've seen here that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?

No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.


Converting RGB from color sensor into the Munsell Color System I am hoping I could get some help developing a an idea I have for archaeologists/soil scientists using an arduino and the TCS3200 colour sensor. The idea I have is a simple device which can determine munsell colours with more accuracy and speed. The current conventional method is to use colour chips/swatches found in the Munsell system booklet and match them as close to examples of sediment/soil found at archaeological sites. The problem with doing this method is that it is highly subjective, and time consuming.

My idea is to use the Adafruit TCS34725 to read and detect the RGB colour of the sediment (in the RBG colour space) and convert the data into the Munsell System. I have all the data of what RGB ratio corresponds to each Munsell colour -- which I have downloaded from this site: www.cis.rit.edu/research/mcsl2/online/real_sRGB.xls

My problem is that when I use the sketch provided, I can not figure out how to use the "if" statement to "Serial.print" what the munsell colour corresponds to the RGB colour detected by the sensor.

My ultimate goal is to modify the colour view sketch here see: colorview
I would like to keep the everything provided but change two things, I would like to convert RGB into Munsell using the data provided by the RIT link and also add a screen and button to start the read process and display the colour.

If some one would be willing to help me that would be great!,

I have some thoughts on your task. First of all colorimetry is a science on its own. I know people working in this field for decades with equipment costing many millions of €. They all share some basic wise words. One is: "Because we all see colours we think measuring colous is an easy task. The opposite is true. Many of the best colorimetrists are colour blind." One second is: "Without light there is no colour". I will write on this later.

Colorimetry in fact is a complex matter. Between a colored piece of stone and a numerical value normally lie a lot of transformations and convolutions. And inbetween there are also lurking many error sources.

This said, I'm sure it will be possible to produce somewhat acceptable results with your sensor. Provided you do a proper calibration and add a calibratable light source.

Speaking of light source. A piece of stone can only reflect incident light (except some uranium/radium salts, you don't want to deal with). Pigments are basically LTI-systems (aka passive filters). This means they can only reflect wavelengths which are present in the incident light. And the will reflect a well defined and individual proportion of each wavelength regardless the luminous flux of the incident light. This means, if your incident light contains nearly no blue light then the stone or whatever you want to examine will reflect only the fraction of "nearly no light" it typically does reflect of any amount of blue light.

So the remission spectra of all pigments get shaped (multiplied) by the spectrum of the incident light. Your sensor sees only the reflected light and therefore will give totally different results for one and the same object depending on the incident light. Look up the spectra for daylight and incandescent light and think about the results of your sensor.

To make a long story short, you can only yield reproducable measurements if you supply your own light source along with the sensor. This is in fact the way all colour meters work.
The only other way was to measure the full spectrum of the incident light. Reasonable portable spectroradiometers for this purpose cost 5000 €. So it's better to go for a light source :).

As they are rather affordable I recommend using LEDs to make up a light source for examination. But LEDs suffer from several drawbacks. They tend to change their output spectrum with their chip temperature and ageing processes. So you have to supply a proper calibration procedure for your measuring equipment. And you better do the calibration sequence before every measurement.

You then have to design an apparatus which allows the light from your LED fall onto your samples (stones, sediments or so) but prevents other scattered or direct light to enter your sensor. Otherwise all measurements will be crap.

While this is not a direct answer to your question, I think the topic is important enough to write an elaborate pamphlet.

Update

Now some more words more closely related to your problem.

In general loading a huge excel table into your arduino is not necessarily a good idea, even if a big "if"-code array was possible. Storage is scarce on this platform.

If you combine a lookup table with interpolation, you can save much space. You would have to omit 90% of all datapoints and estimate all in between when measuring. Still the table will be rather big, because you have three degrees of freedom.

Another drawback of big tables and LUT with interpolation is, that it makes calibration difficult. Normally, when you calibrate your sensor, you have to adjust the parameters along the calculation. If you rely on a table, you have to exchange the whole table, regardless if it is something like that excel thingy or a condensed lookup table.

If you go for an analytical solution, as suggested in one comment, the number of parameters you have to update after calibration reduces drastically. Effectively you have to adjust some factors and offsets in the equations for this problem. Of course you will have to learn the ropes of the photometric equations, but you will  have to do that anyway, I think.

Some more words on the design of your appartus. Your idea of a cylinder in front of your probe is good. I recommend to fit it with a rim of black foam rubber, so you can seal light coming from outside. And you have to paint the inside of your cylinder as black as you can. See the interiour of a camera objective for reference.

If it is white you will have multiple reflections and multiple filtering which deteriorates your measurement results vastly.


is any windows application available for accelerometer based computer mouse I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

try "remotemouse.exe"
its a open source application you can modify the codes according to your requirement


Arduino ethernet shield not responding to every request because it is busy I have a simple HTTP server that monitors a serial port and responds to HTTP requests by sending the value. The serial port constantly outputs data, so that apart from a brief moment when the device is initializing the Arduino always has data available. Once a value is retrieved from the RS232 connection it is stored in a buffer. The buffer is overridden when new values are received.

Occasionally the server does not respond to a request. Monitoring through Chrome developer tools reports net::ERR_CONNECTION_RESET
Could it be that the Arduino is busy with processing the serial port when the connection request is made? What I find very difficult to understand is that once in a while the code below will display "Not available". This shouldn't happen because, as stated above, the buffer is always available.

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println("Cache-Control: no-cache, no-store, must-revalidate");
    client.println("Pragma: no-cache");
    client.println("Expires: 0");
    client.println("Refresh: 5");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("");
    client.println("");
    client.print("Value: ");
    if (valueReady()) {
      client.println( getValue() );
    } else {
      client.println( "Not available" );
    }
    client.println("");
    client.println("");

The "Not available" message is really confusing because that should only occur when the Arduino starts. valueReady() will only return false when power is first applied.

The LEDs on the Ethernet shield do not indicate that the Arduino is being reset, but it seems as if the sketch is periodically restarting. Is it possible for a buffer overrun to cause the Arduino to reboot?

The delay was occurring because, in some cases, I was storing the RS232 data into a character array past the initialized length. It looks like it was causing the Arduino to reboot.


ESP8266 cannot connect to an existing network after using AT command I followed this tutorial to connect the ESP8266 to a wifi network using AT commands. I used the below schematics (without the connection between ESP's CPIO 0 and Arduino's Ground):

After that, I was able to follow through the tutorial and got this response in the Serial Monitor:

That means my ESP8266 has successfully connected to my Wifi named W3. However, I decided to switch the mode of my ESP8266 from Network Device (mode 1) to Both network device AND Access Point (mode 3) (at this point I called AT+CWJAP? and can still see that it's connected to W3 wifi). I then was able to see the ESP wifi in my wifi list as (AI-THINKER_4C8CF2) but when I connected to it, I cannot connect to the internet. I'm wondering what the problem is and would appreciate any help.

Note: The reason why I switched to mode 3 is because I want to control an Arduino Pro Mini (instead of Arduino Pro) using NodeJS. I followed another tutorial and I figured that I need to connect to an ESP8266 access point.

I uploaded the StandardFirmataSketchPlus to my Arduino Pro Mini, with the baud rate set to 115200 (which is the same baud rate with my ESP8266). The schematic I used is similar to the one below, except I used a 3.3V Pro Mini and a Lipo battery, instead of a 5V:

The nodejs code is below:

var VirtualSerialPort = require('udp-serial').SerialPort;
var firmata = require('firmata');
var five = require("johnny-five");
var sp = new VirtualSerialPort({
  host: '192.168.1.243' //I got this number from the AT command (STAIP above)
 });

var io = new firmata.Board(sp);

io.once('ready', function(){
    io.isReady = true;

    var board = new five.Board({io: io, repl: true});

    board.on('ready', function(){
        var led = new five.Led(12);
        led.blink(3000);
    });
});

This code is to test the connection between Arduino and Nodejs and when I run this file, it doesn't work.

you have Firmata in Atmega, AT firmware in ESP and the 'blink led' js on computer.

you did not follow the tutorial properly. it requires jonny-five firmware in esp8266


How would you add Arduino WiFi Module using I2C or serial interface? I am new to Arduino prototyping. I bought an Arduino Automatic Smart Plant Watering Kit 2.0 thinking it was a shield to use with my Arduino Uno WIFI Rev 2.  However, it turns out to be a specially designed Arduino board with all of the components integrated together.

While the system works as designed, my goal is to stream the data to IBM Watson Studio, or some other third-party SaaS.

I welcome feedback to understand how it might be possible to integrate the ESP8266 WIFI module using either the I2C or Serial interface. Here is the sample code: https://www.elecrow.com/download/watering_kit.zip I used a Raspberry Pi to get access to the data and use it in a web/mobile application but I'd like to eliminate this element, if possible.

You would connect the ESP8266 to the serial port.  The normal way of working with an ESP98266 is to issue AT command (like an old Hayes modem) through a serial connection. Since you have one of those available on your board it is a simple matter to just wire it directly to it.

Just follow any of the myriad of ESP8266 + Arduino tutorials, substituting the pins in the examples for your serial pins, and use the Serial1 object instead of the SoftwareSerial class that you have to use on an Uno that lacks extra serial ports.


How to control baby swing? I am starting an intresting DIY project of baby swing. My son is 3 month old and we have swing made with ropes in our house where he sleeps. I am looking for any electronic component controlled with arduino to swing it in controlled manner. I thought of servo motor but not sure how will it work. Any suggestions please ?
swing is similer to below

A simple DC motor would work. you have to pulse it in the right moment. for finding out the right moment and the pulse length (you don't want to push it so hard !) you need a simple accelerometer sensor to measure acceleration in specific axis.


millis() replace delay() question // each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12=0;
unsigned long previousMillisLED13=0;

unsigned long previousMillisLED3=0;

// different intervals for each LED
int intervalLED12 = 500;
int intervalLED13 = 5000;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);

   pinMode(3, OUTPUT);

}
void loop() {
   // get current time stamp
   // only need one for both if-statements
   unsigned long currentMillis = millis();

   // time to toggle LED on Pin 12?
   if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
      LED12state = !LED12state;
      digitalWrite(12, LED12state);
      // save current time to pin 12's previousMillis
      previousMillisLED12 = currentMillis;
   }

// time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
      LED13state = !LED13state;
      digitalWrite(13, LED13state);
      // save current time to pin 13's previousMillis
      previousMillisLED13 = currentMillis;
  }
}

My questions:

Didn't see the led12 and led13 have 10 times defferency, almost same intervals, why?
How can I use millis() as simple as delay?
Is that a must to use if?

Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.

For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.

My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().

#include <M5Stack.h> // needed for my board

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12 = 0;
unsigned long previousMillisLED13 = 0;

unsigned long previousMillisLED3 = 0;

// different intervals for each LED
int intervalLED12 = 50;
int intervalLED13 = 500;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
  Serial.begin(9600);
  //  pinMode(13, OUTPUT);
  //  pinMode(12, OUTPUT);
  //  pinMode(3, OUTPUT);
}
void loop() {
  // get current time stamp
  // only need one for both if-statements
  unsigned long currentMillis = millis();

  // time to toggle LED on Pin 12?
  if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
    LED12state = !LED12state;
    // digitalWrite(12, LED12state);
    // save current time to pin 12's previousMillis
    previousMillisLED12 = currentMillis;
  }

  // time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
    LED13state = !LED13state;
    // digitalWrite(13, LED13state);
    // save current time to pin 13's previousMillis
    previousMillisLED13 = currentMillis;
  }
  Serial.print("LED12: ");
  Serial.print(LED12state);
  Serial.print("  LED13: ");
  Serial.println(LED13state);

}


Issues uploading to atmega324pb w/ adruino as ISP I've been having some issues programming a new atmega324pb I have on a custom board. I set up an old adruino UNO as an ISP by uploading the ArduinoISP sketch, setting the programmer to "Arduino as ISP" and then using the "Upload using programmer" option but to no avail. Here is the verbose error message that the console logs:

System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

I think it might be an issue with Arduino possibly targeting a chip other than atmega324pb that I'm using, but I'm not sure. I don't know of any official arduino boards that utilize the 324pb. The main issue that I see is that avrdude can't find the device signature. I've see others mention it might be faulty wiring, but I made sure all connections are intact.

In case anyone was wondering, I solved the problem.
Unfortunately I wasn't able to figure out how to upload it using Arduino as ISP, but I was able to get it to work with an AVR Pocket Programmer from Sparkfun. If you decide to use this, check out this drivers guide. It will It'll save massive headache getting the usb device to be recognized.

IMPORTANT FOR ATMEGA324PB USERS!!!
The atmega324pb is apparently not a default microcontroller in avrdude. You need to add it to the toolchain manually. You can do this by following this blog:
https://hackaday.io/project/9313-uino-mini-super-atmega328pb/log/31003-easy-way-to-a-toolchain-for-the-atmega328pb
It is the same process to add any Microchip microcontroller to avrdude, so this guide will work for the atmega324pb (did it firsthand). From there, you can also add a custom entry to Arduino's boards.txt config file if you'd like to use the Arduino IDE for development. I didn't mind working the command line, but having it in Arduino definitely streamlines the proccess of compiling the .hex and uploading it in one go.

Here is the custom entry I added to Arduino's boards.txt file for the Atmega324pb. All the data was gathered from the datasheet:

####   ATmega324PB    ####
m324p.name=Atmega324pb
m324p.upload.via_ssh=true

m324p.vid.0=0x0424
m324p.pid.0=0x2740

m324p.upload.tool=avrdude
m324p.upload.protocol=usbtiny
m324p.upload.maximum_size=28672
m324p.upload.maximum_data_size=2560
m324p.upload.speed=57600
m324p.upload.disable_flushing=true
m324p.upload.use_1200bps_touch=true
m324p.upload.wait_for_upload_port=true

m324p.bootloader.tool=avrdude
m324p.bootloader.low_fuses=0x62
m324p.bootloader.high_fuses=0xD9
m324p.bootloader.extended_fuses=0x0f

m324p.build.mcu=atmega324pb
m324p.build.f_cpu=1000000L
m324p.build.vid=0x0424
m324p.build.pid=0x2740
m324p.build.usb_product="Arduino m324pb"
m324p.build.board=AVR_m324pb
m324p.build.core=arduino
m324p.build.variant=standard
m324p.build.extra_flags={build.usb_flags}

Note that I set the upload.tool to avrdude, and the upload.protocol to usbtiny since I was using the pocket AVR programmer.

IMPORTANT!!!  The high fuse bit in this config also is 0xD9, instead of the default 0x99. I changed one fuse bit to disable JTAG and regain access to GPIO pins. To my knowledge Arduino wasn't setting fuse bits when uploading with the programmer, but this is an important note to take. If you need to use GPIO pins that share JTAG functionality, run the avrdude command line to set the high fuse bit appropriately. (0xD9 for me).


How to create a serial communication connection between Cubieboard running Android and Arduino I am connecting my Arduino to my Cubieboard that is running Android.

I tested this originally with my android tablet and USB cable. This worked successfully for the most part using the firmata kit but I don't want to use firmata.

I want a basic function library written in Java for use with Unity (eg Library Tutorial Video) to connect to the Arduino via the USB serial port connection much like a connection with my Windows computer.

I'd like basic command functions like:

Connect / Open
Write
Read
Flush
Close

I was thinking maybe of using this library here but I am unsure how to go about this. I know similar discussion have already taken place on the forum claiming it may not be possible, but it is very clear that it is. It has been done many times. All I need to do is send strings with serial after finding the Arduino's COM port and reading from the serial.

Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.

Then of course providing you connect with the right baud rates and so on it should work.


Using a web server with Arduino So I am not new to arduino, however, I am new with web servers. I am working on a project that can control a robotic arm that is at one location and I can be at my house. I know basic HTML, Basic CSS, Basic JavaScript, and a tiny bit of JQuery. Only reason I say basic is because I self taught all these languages to myself using codeacademy. So I have a few questions since I done research on the matter.

Can a project like this be done with just the languages I know? All the tutorials I have looked at say you have to know AJAX and JSON. I have no idea what these are.

Also, for the interface, I need to be able to take the value of the encoders on the robot and view them. I also need a button that will record the value at that point in time of the encoders so I can configure the points and maybe even name them. A box where I can see the points and their coordinates, and finally a box where i can place points in and then execute a sequence.

How tough should this be?

You can use an Arduino Yun: it has a 32u4 microcontroller coupled with a cpu running linux. The linux side already has a webserver: together with the Bridge library, you can use REST-like APIs to control a sketch, or build a web app that uses that APIs.

One example of remotely control an Arduino (although using an Android app instead of html+js) is this. Here is its source code.


Change input reference to 1 - 5 V I am using a sensor which delivers a 4 to 20 mA output.
Converting this with a 250 Ohm resistor to ground I convert this to a 1 - 5 V output.

My question how can I change the 0V reference, so I can use the full spectrum
I found a way to change the 5V reference (analogReference()).
Is it possible to change the 0V reference of a input to 1V?

Any other solution to my problem is welcome as well! (As long as it doesn't involve I2C or anything which lowers my looptime drastically)

The ADC is ground-referenced, and there's no way to change that. The question is if that's necessary. The ADC has a 10-bit resolution, that's good for 1024 different levels between 0 and 5 V. If you convert the 4-20mA with a 250 Ω resistor to a 1-5 V range you still can discriminate between more than 800 different values.

If that's not enough you can use a differential amplifier to subtract 1 V:

By choosing R3 = 1.25 R1 you convert the 0-4 V range to a 0-5 V range.


Extracting high and low bytes from long I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.

#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

The first line i clearly understood like this, please make corrections if i am wrong.

32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

by right shifting last 16 bits we will arrive at

32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

I am not able to interpret the second line.

#define lowWord(w) ((w) & 0xffff)

I would be very grateful if some body explain how the above line of code works?
Thanks.

The second line masks off the top two bytes using a bitwise AND.

When you use a bitwise AND it follows the normal rules for any boolean truth table.  1 & 1 = 1, 1 & 0 = 0...  Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved.  In this way you can extract the lower two bytes out of the four byte long.


analogWrite never outputs a non-zero voltage With a very simple connection of an LED (which can withstand 5V) to ground and to a pin on my Galileo gen2, I can never output a non-zero voltage from the pin via analogWrite, regardless of whether the pin is digital or analog (although PWM digital works)

The LED is in the correct bias and I'm calling pinMode(pin, OUTPUT) before attempting to call analogWrite(pin, 255) (or any 2nd parameter in-between), even though it's not even necessary.
The LED glows if I call digitalWrite(pin, HIGH) on both analog and digital pins, but does not glow at all for analogWrite(pin, 255) with the same configuration and pins, nor does it for any 2nd param in [0, 255]. This holds for whether the call is attempted in loop() or setup().

The only possible way I can get the LED to receive any power from analogWrite is through a digital PWM pin, but I know the other digital pins can still produce square-waves with timers and the analog pins should certainly be able to use PWM.

(So far, I've been to scared of short-circuits to connect the analogWrite output straight into an analog input to read the voltage)

Is there something I don't understand about the underlying board, or am I experiencing some strange malfunction?

Thanks,
Tyson

On most boards, the standard implementation of Arduino's analogWrite() will only ever produce PWM, and only on a specific set of (digital) pins. These are usually pins 3, 5, 6, 9, 10, and 11, although it's slightly different on some boards.

The only official board which has 'true' analog output is the Due (pins DAC0 and DAC1).

If you want any other behaviour (such as outputting PWM on non-standard pins), you'll either need to modify the Arduino implementation, or directly manipulate the microcontroller's special registers. Note though that modifying the chip's configuration could cause other standard Arduino functions not to work as expected.