body: The X-axis is fixed and nothing gets plotted on the X-axis. It has its own divisions and they are automatically set by the Arduino IDE. The Arduino IDE still has to do some improvements to its software so that the X- axis can be adjusted and plotted too! This is my experience so far and corrections are welcome!


sender: user

message:
Brownout with Arduino Nano

[![enter image description here][1]][1]
I'm making an RC car with the Arduino Nano. I'm using RF433 as  wireless communication with 2 motors and L293D as the motor driver. I use 4 1.5V batteries to power the Arduin and another 6V battery pack to power the motors, and a joystick with an Arduino Mega to send commands through the RF433 to the Arduino Nano.

I've written a program that sends specific digits when the joystick is in a certain position, i.e. when the joystick is "bent" to the front it sends a "1", a "2" is sent when the joystick is bent towards the back, and so on.

**My problem is this:**

When I bend the joystick towards a certain direction, the RC car moves accordingly without problem; However, when I bend the joystick towards another direction the RC car doesn't respond.

I took a look at what the RC car was receiving, and I've noticed that after the first command was sent (when I bend the joystick towards a certain direction), no more commands get to the RC car (in other words the Arduino Nano), and this occurs occasionally. I think this means the Arduino Nano "froze" after the first command.

  [1]: https://i.stack.imgur.com/8RwqP.jpg

sender: assistant

body:
You have *at least* three problems here:

1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino *even before* it gets loaded down by a motor, and it only gets worse under load

2) L293/L297 and similar **bipolar** bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip.  Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.

3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway.  You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).

Granted, you may well have other issues as well, such as errors in your software.


message:
Why does my code or Serial Monitor hang with analogRead?

I have the following code in loop() to collect values from an electret microphone

    for(int i=0; i<sampleSize; i++){
      analogVal[i]= analogRead(ADC_Pin);
      sumOfSquares= sumOfSquares+sq(analogVal[i]);
    }
    Serial.print("Sum of squares: ");
    Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.

My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

body:
Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.

I suppose, that `analogVals[]` is declared as `int` and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome `48 bytes` for all your others variables (including `int i` in the for cycle and `Serial` outside it) and stack for calling functions (like `analogRead` and `sq`) and all theirs variables and functions and arguments.

So `int i` = 2B, `Serial` = 2B, `sumOfSquares` = 2B, `"Sum of squares: "` = 17B of what I see takes anothe `23 bytes` of those `48 bytes` leaving us with only **25 bytes** for all else.

I bet, that you try to use more REAM, than you have and so your `stack overflows` and

 1. destroys some variable content on the vay

 2. is overwriten by assigning to some variables, which then leads to all sort of problems.


message:
Power bank turns off spontaneously

I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?

Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

body:
I can't see this helping.

It could only help if your power bank switched off its output when the current  drawn dropped too low - but unless your  circuit's current consumption drops after two hours, which you don't mention, that is unlikely to be the reason it's switching off.


body:
You have a couple of options, depending on how much you want to dive into electronics.

 - Find/buy a new powerbank that does not auto-shutoff
 - Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
 - Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.


body: Expanding @jose can u c first suggestion I did a little research and found that Voltaic Systems sells power banks with an option to disable auto-shutoff mode. There may be others. I found two of their power banks offered on Amazon. The blurb in the Amazon listing explicitly mentions using it with Arduino and Raspberry Pi.


body: As the company Voltaic has been mentioned I feel that it would be helpful if I warned you of that company. We are after all trying to offer solutions and if you follow the advice of the person who suggested Voltaic then I know from first hand experience that the thing turns itself off even when the auto shutdown mode is disabled. Though this may not be an end solution I know that by helping you to avoid useless information I can keep you on track and help you towards your solution. In detail : I'm a chauffeur and I bought a Voltaic for this specific reason and guess what? It switches off even when auto shutoff mode is disabled. I wanted my customers to be able to charge their devices as quick as poss and with as little complication as poss. I'm thinkin bout puttin a led fibre optic charging cable in so there is always a tiny power usage from the LED near the big USB jack. At least then also the cable wld be more 'look at me, look at me' I'm thinkin the problem comes either from an auto time out or from the completion of the charging of the power bank which is itself on a dribble charge from the car's electrics.


message:
ADC with better performance

I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

body:
> I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.

even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.

precision is another matter.


body:
[ADS7835][1] from Texas Instrument.

> can be interfaced with Arduino Mega or Raspberry Pi

It is interfaced through SPI, 12 bit data, and up to 500kHz throughput rate.

  [1]: http://www.ti.com/lit/ds/symlink/ads7835.pdf


message:
SIM808 module restarting repeatedly

I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

body:
Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.

Use a 5A power supply and that should solve the problem.

I have never tried it but "super capacitors" *might* work, providing the extra power when its needed, it depends how long you need the 3A for.


message:
Need help with my project

Can anyone give me the full code of my project because my code is not working?

My aim is that when the Z axis of an accelerometer is below 370 and a pushbutton connected to a pin 2 becomes high, then pin 13 turns high and remains high.  When the Z axis is above 370 and pushbutton is high then the pin 13 goes low and remains low.

P.S I am also a noob to Arduino

Here is my code :

    const int ledPin = 13;
    const int threshold = 370;
    const int pull_up_resistor = 12;
    const int pull_down_resistor = 11;
    const int groundpin = A1;
    const int powerpin = A5;
    const int xpin = A2;
    const int ypin = A3;
    const int zpin = A4;

    int pushButton = 2;

    void setup() {

      pinMode(ledPin, OUTPUT);

      Serial.begin(9600);

      Serial.begin(9600);

      pinMode(pushButton, INPUT);
      digitalWrite(pushButton, HIGH);
      Serial.begin(9600);

      pinMode(groundpin, OUTPUT);
      pinMode(powerpin, OUTPUT);
      digitalWrite(groundpin, LOW);
      digitalWrite(powerpin, HIGH);
    }

    void loop() {

      int buttonState = digitalRead(pushButton);

      Serial.println(buttonState);
      delay(100);        // delay in between reads for stability

      Serial.print(analogRead(xpin));

      Serial.print("\t");
      delay(100);
      Serial.print(analogRead(ypin));

      Serial.print("\t");
      delay(100);
      Serial.print(analogRead(zpin));
      Serial.println();

      delay(100);

      if (buttonState = 0) {
        digitalWrite( ledPin, HIGH);
      }
      if (buttonState = 1) {
        digitalWrite (pushButton, LOW);
      }

    }

body:
Use some formatter before posting it here. For example here is great one, written by [KrzaQ] edit: didn't noticed that was fixed by Mark

Next thing to do is keep your code clean. Three times you initialized Serial communcation. Why?
You should also first initalize Serial then set pinModes into state and then put digitalWrite. It helps reading the code.

**Example:**

    Serial.begin(value);
    pinMode(x,x);
    pinMode(y,x);
    pinMode(z,x);
    digitalWrite(x,x);
    digitalWrite(y,x);
    digitalWrite(z,x);

More readable, isn't it?

Next step: Pull-up and pull-down resistors... It is not thing you need to set in your code. It is hardware connection of 1 resistor, sometimes capacitor and device. There is no use for it in your device.
Read about them here: [Pull-up/pull-down]

Next thing: You **must not** define your outputs as power pins and treat them like one. AVR's have limited power output from each pin and by doing so you can fry it very quickly.

If I understand your sentence correctly you need to save your angle values into variable like this (pseudo code, you have to adjust it to your case no one will write it for free):

    int xvalue, yvalue, zvalue, button;
    void setup(); // all setup should go here do not skip this like me here
    void loop() {
      xvalue = analogRead(xpin);
      yvalue = analogRead(ypin);
      zvalue = analogRead(zpin);
      if (button == 1) {
        if (zvalue > 370)
          digitalWrite(ledPin, HIGH);
        else
          digitalWrite(ledPin, LOW);
      } else
        actionWhenPushButtonIsZero();
    }

If you think about what I wrote and focus on your task I am sure that everything will work in your device. THINK first then ask next questions.

[KrzaQ]: http://format.krzaq.cc/
[Pull-up/pull-down]: http://www.resistorguide.com/pull-up-resistor_pull-down-resistor/


message:
How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data?

I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.

<!-- language-all: lang-cpp -->

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include "Timer.h"

    Timer t;

    // Data wire is plugged into pin 10 on the Arduino
    #define ONE_WIRE_BUS 10

    // Setup a oneWire instance to communicate with any OneWire devices
    OneWire oneWire(ONE_WIRE_BUS);

    DallasTemperature sensors(&oneWire);

    DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

    void setup(void)
    {
      // start serial port
      Serial.begin(9600);
      // Start up the library
      sensors.begin();
      // set the resolution to 10 bit (good enough?)
      sensors.setResolution(insideThermometer, 10);
      int tickEvent = t.every(3000,doTempReading);

    }

    void loop()
    {
        t.update();
    }

    void printTemperature(DeviceAddress deviceAddress)
    {
      float tempC = sensors.getTempC(deviceAddress);
      if (tempC == -127.00) {
        Serial.print("Error getting temperature");
      } else {
        Serial.print("C: ");
        Serial.print(tempC);
      }
    }

    void doTempReading()
    {
      delay(2000);
      Serial.print("Getting temperatures...\n\r");
      sensors.requestTemperatures();

      Serial.print("Inside temperature is: ");
      printTemperature(insideThermometer);
      Serial.print("\n\r");
    }

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.

I have done a lot of research and tried several different techniques and can't understand how to go about it.

What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?

Thanks in advance for any help.

body:
I know this is old but to help out newcomers:

Here's a place you can begin https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5

The wiring depends on which arduino board you are using and the model of your HC-05 BT module. mine uses 4 pins VCC (5v) GND (ground) TX --> TX and RX --> RX

You should be able to google the wiring for your module, and connect to the raspberry pi after you install bluetooth on raspberry pi

    sudo apt-get install bluetooth bluez blueman

    sudo reboot

Navigate to new bluetooth interface in menu bar through

 - preferences
 - bluetooth

Add new device, turn arduino on with BT module plugged in and make sure your HC-05 module is blinking red, and you should see a pair connection named HC-05 on raspberry pi. Password is 1234


message:
Can an Arduino emulate a USB mass storage device?

**Question:**

Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?

Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?

This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.

Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?

**Research:**

I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?

**Possible Solution:**

The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?

**Diagram:**

Arduino USB Port -> USB Cable -> Embedded Device USB Port
Arduino GPIO -> USB Module -> USB Cable -> Embedded Device USB Port

Requirements:

Connection via USB cable between Arduino and an embedded device's USB port.
Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

body: The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947


message:
Connecting to the Sparkfun Redboard on Mac OS X Sierra

I'm trying to connect to my Sparkfun Redboard (Arduino UNO compatible) on Mac OS X 10.12.3 (Sierra). The board comes with a USB mini to USB A FTDI cable. The board lights up and gets power over USB, but I don't see the right USB serial port in the Arduino IDE (I only see the Bluetooth port).

I've installed the [VCP FTDI drivers][2] v2.3 to no avail. When that didn't work, I also installed the CH340 CH341 drivers (but I doubt I need those). Rebooting the computer didn't help either.

I can only load the FTDI VCP v2.3 drivers using an explicit command `sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext/`. When I run `kextstat | grep FTDI`, I get:

     155    0 0xffffff7f83892000 0x7000     0x7000     com.FTDI.driver.FTDIUSBSerialDriver (2.3) ECC3AF36-431D-370D-86F2-5237785E9CF8 <127 41 5 4 3 1>

But it still doesn't show up in the Arduino IDE.

I've heard that Apple's own USB FTDI drivers (AppleUSBFTDI) could [cause problems][3], but it seems these are never loaded. If I try to unload the Apple FTDI driver (`sudo kextunload –b com.apple.driver.AppleUSBFTDI`), I get the following:

    (kernel) Kext com.apple.driver.AppleUSBFTDI not found for unload request.
Failed to unload com.apple.driver.AppleUSBFTDI - (libkern/kext) not found.

Any tips are welcome. Thanks!

  [1]: https://i.stack.imgur.com/SNdab.png
  [2]: http://www.ftdichip.com/Drivers/VCP.htm
  [3]: https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac

body:
I'm using MacOS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever.

Some people have reported problems using the manufacturer (FTDI) drivers that they had already installed **after** upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and relying on the default Apple FTDI drivers [uninstalling the conflicting drivers and relying on the default Apple FTDI drivers][1] instead. It's worth a try.

OTOH, the CG340 driver doesn't currently work under Mac OS Sierra. Fortunately, Adrian Mihalko patched the driver and made it [available at GitHub][2], along with some troubleshooting instructions.

  [1]: https://forum.arduino.cc/index.php?topic=427825.0
  [2]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
  [3]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html


message:
Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?

I have:

 1. An Digispark clone (with no Arduino bootloader)
 2. A USB -> TTL serial device
 3. A development breadboard
 4. Avrdude

I want to burn [the micronucleus bootloader](https://github.com/micronucleus/micronucleus) to the chip.

Is this possible, are there instructions?

ISP programmer is in the post but I'm not expecting it for 3 weeks.

body: Short answer, no. You can burn a bootloader onto the chip using a programmer, and then the bootloader does the serial communication magic so you can upload your sketches via serial or even low-speed USB (if your bootloader knows how to do USB bit-banging). But you can burn the bootloader only through SPI.


body:
you can't program your hardware with just USB to tty converter you need a programmer for that now instead of buying expensive programmers you can buy an Arduino board and use it as ISP (In System Programmer) here is the link describing the whole process.

  [Adruino as a  ISP][1]

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


body:
No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.

Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a _qualified yes_.  Another Arduino can do this -- search the web and find many examples.

You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.

Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb


message:
How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?

I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library `VirtualWire` and It works very well for this code:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[7] = {'h','e','l','l','o',' ','!'};
      vw_send((uint8_t *)msg, 7);
      vw_wait_tx(); // Wait until the whole message is gone
      delay(1000);
    }

I was wondering if I want to send some `string` or `int` data how I can do that.
I tried to use it for string data but I couldn't because the `Input` of function `vw_send(...)` is char and I couldn't use `int` or `string`.
finally I run this code:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[11]="Hello there";
      vw_send((uint8_t *)msg, 11);
      vw_wait_tx(); // Wait until the whole message is gone
    delay(1000);
    }

 and I could send Hello there !, but I'm looking for the correct way for sending `string` and `int`.

body: Have a look at the Easy Transfer library.  I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules.  In essence the EasyTransfer library transmits the data as a structure with the same format on each module.  The structure can contain any data type.


message:
3.3v inductive proximity sensors

I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?

I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.

body:
I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the [TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V](http://hackaday.com/2016/12/05/taking-it-to-another-level-making-3-3v-and-5v-logic-communicate-with-level-shifters/) article at hackaday.com for a circuit explanation.  See [gearbest.com](http://www.gearbest.com/other-accessories/pp_241590.html?currency=USD&vip=760186&gclid=CMPxtdWqoNICFUq5wAodEKwP3g) and [sparkfun.com](https://www.sparkfun.com/products/12009) and [Adafruit](https://www.adafruit.com/product/757) for inexpensive modules.

Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.


message:
HTTP post request in JSON Format using SIM900 module

I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:

    {("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

I don't know what the error is and how to fix it. Please help me to fix this.

    #include<SoftwareSerial.h>

    SoftwareSerial client(2,3);

    String testReading="{  \"testID\" : 1,  \"testLevel\" : 1, }";

    void setup() {
      Serial.begin(9600);
      client.begin(9600);
      delay(1000);
      if(client.available()) {
        Serial.print("Connected");
      } else {
        Serial.print("Not Connected");
      }
      checkSignal();
      connectGPRS();
      postData();
      delay(1000);
    }

    void loop() {
      if(client.available()) {
        checkSignal();
        connectGPRS();
        postData();
        delay(1000);
      }
    }

    void connectGPRS() {
      client.println("AT+CGATT?");
      delay(1000);
      ShowSerialData();
      client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(1000);
      ShowSerialData();
      client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
      //Using Indian Standard Vodafone Sim and so APN is www
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=1,1");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=2,1");
      delay(1000);
      ShowSerialData();
    }

    void checkSignal() {
      client.println("AT+CSQ");
      delay(1000);
      ShowSerialData();
    }

    void ShowSerialData() {
      while(client.available()!=0)
        Serial.write(client.read());
    }

    void postData() {
      client.println("AT+HTTPINIT");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CID\",1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPDATA=99,10000");
      delay(1000);
      ShowSerialData;

      client.println(testReading);
      delay(1000);
      ShowSerialData;

      client.println("AT+HTTPACTION=1");
      delay(10000);
      while(!client.available());
      ShowSerialData();
    }

body:
Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

     #include<SoftwareSerial.h>

    SoftwareSerial client(2,3);

    String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

    void setup()
    {
      Serial.begin(9600);
      client.begin(9600);
      delay(500);

      if(client.available())
      {
        Serial.print("Connected");
      }
      else
      {
        Serial.print("NotConnected");
      }

      //initSIM();
      connectGPRS();
      connectHTTP();
    }

    void loop()
    {

    }

    void connectGPRS()
    {
      client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=1,1");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=2,1");
      delay(1000);
      ShowSerialData();
    }

    void connectHTTP()
    {
      client.println("AT+HTTPINIT");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CID\",1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
      client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
      delay(1000);
      ShowSerialData();

      client.println(reading);
      delay(1000);
      ShowSerialData;

      client.println("AT+HTTPACTION=1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPREAD");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPTERM");
      delay(1000);
      ShowSerialData;
    }

    void ShowSerialData()
    {
      while(client.available()!=0)
      {
      Serial.write(client.read());
      delay(100);
      }
    }


body:
    client.println(reading);
    delay(1000);
    ShowSerialData;

The above line of code would result in an error.


message:
How to properly use interruptions with twi (I2C)

I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.

In the [datasheet][1], page 262, 24.9.2, bit 0, I can read that I have to set the `TWIE` flag to one to be able to catch the interruption.

So, I started to write this code :

<!-- language: c++ -->

    //https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

    #include <avr/interrupt.h>

    #define ADDRSHIELD 0xC0//adresse sur 8 bits

    #define TWI_FREQ 100000L
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

    #define START       0x08  //TWI start
    #define MT_SLA_ACK  0x18   //slave ACK has been received
    #define MT_DATA_ACK 0x28   //master ACK has been received

    #define LED0_ON_L 0x6

    #define TWI_STATUS      (TWSR & 0xF8)

    int etat = 0;
    uint8_t currentstep = 0;
    uint8_t _addr;
    uint8_t _data;

    ISR(TWI_vect)
    {
      //I remove the TWINT flag
      TWCR |= (1<<TWINT);

      switch(etat)
      {
        case 0:
          //start has been send, let's check if it's ok
          if(TWI_STATUS == START)
          {
            //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
            TWDR = _addr;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 1;
            //Serial.println(etat);
          }
          else
          {
            etat = -1;
          }
          break;
        //addr has been send
        case 1:
          if(TWI_STATUS == MT_SLA_ACK)
          {
            TWDR = _data;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 2;
            //Serial.println(etat);
          }
          else
          {
            etat = -2;
          }
          break;
        //data have been send
        case 2:
          if(TWI_STATUS == MT_DATA_ACK)
          {
            // disable twi module, acks, and twi interrupt
            TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
            etat = 3;
            //Serial.println(etat);
          }
          else
          {
            etat = -3;
          }
          break;
        //stop condition
        case 3:
          // desactivate internal pullups for twi.
          digitalWrite(SDA, 0);
          digitalWrite(SCL, 0);
          etat = 0;
          //Serial.println(etat);
          //Serial.println("Next");
          break;
      }
    }

    void sendData(uint8_t addr, uint8_t data)
    {
      _addr = addr;
      _data = data;

      i2cSetup();
      //start condition
      TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
    }

    void i2cSetup(void)
    {
      // activate internal pull-ups for twi
      sbi(PORTD, 0);
      sbi(PORTD, 1);

      // initialize twi prescaler and bit rate
      cbi(TWSR, TWPS0);
      cbi(TWSR, TWPS1);

      TWBR = ((F_CPU / 100000) - 16) / 2;
    }

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

    void loop()
    {
      if(etat == 0)
      {
        sendData(0xC0, 0b1010101);
      }
      if(etat == 3)
      {
          Serial.println("Next");
      }
      if(etat == -1)
      {
        Serial.println("Error from start");
        delay(100);
        exit(-1);
      }
      if(etat == -2)
      {
        Serial.println("NACK");
        delay(100);
        exit(-1);
      }
      if(etat == -3)
      {
        Serial.println("DATA NACK");
        delay(100);
        exit(-1);
      }
    }

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.

EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the [datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf), p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).

Thanks for your help,
julien

  [1]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf

body:
After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.

This is my code working :

<!-- language: c++ -->

    //https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

    #include <avr/interrupt.h>

    #define ADDRSHIELD 0xC0//adresse sur 8 bits

    #define TWI_FREQ 100000L
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

    #define START       0x08  //TWI start
    #define MT_SLA_ACK  0x18   //slave ACK has been received
    #define MT_DATA_ACK 0x28   //master ACK has been received

    #define LED0_ON_L 0x6

    #define TWI_STATUS      (TWSR & 0xF8)

    volatile int8_t etat = 0;
    volatile uint8_t _addr;
    volatile uint8_t _data;

    ISR(TWI_vect)
    {
      switch(etat)
      {
        case 0:
          //start has been send, let's check if it's ok
          if(TWI_STATUS == START)
          {
            //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
            TWDR = _addr;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 1;
          }
          else
            etat = -1;
          break;
        //addr has been send
        case 1:
          if(TWI_STATUS == MT_SLA_ACK)
          {
            TWDR = _data;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 2;
          }
          else
            etat = -2;
          break;
        //data have been send
        case 2:
          if(TWI_STATUS == MT_DATA_ACK)
          {
            // disable twi module, acks, and twi interrupt
            TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
            etat = 3;
          }
          else
            etat = -3;
          break;
        //stop condition
        case 3:
          // desactivate internal pullups for twi.
          digitalWrite(SDA, 0);
          digitalWrite(SCL, 0);
          etat = 0;
          break;
      }
      //I remove the TWINT flag
      TWCR |= (1<<TWINT);
    }

    void sendData(uint8_t addr, uint8_t data)
    {
      _addr = addr;
      _data = data;

      i2cSetup();
      //start condition
      TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
    }

    void i2cSetup(void)
    {
      // activate internal pull-ups for twi
      sbi(PORTD, 0);
      sbi(PORTD, 1);

      // initialize twi prescaler and bit rate
      cbi(TWSR, TWPS0);
      cbi(TWSR, TWPS1);

      TWBR = ((F_CPU / 100000) - 16) / 2;
    }

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

    void loop()
    {
      if(etat == 0)
      {
        sendData(0xC0, 0b0010101);
      }
      if(etat == 3)
      {
          Serial.println("Next");
      }

      if(etat == -1)
      {
        Serial.println("Error from start");
        delay(100);
        exit(-1);
      }
      if(etat == -2)
      {
        Serial.println("NACK");
        delay(100);
        exit(-1);
      }
      if(etat == -3)
      {
        Serial.println("DATA NACK");
        delay(100);
        exit(-1);
      }
    }

Thanks a lot to jfpoilpret !


body:
Two observations.

1. The datasheetss does a fairly good job of Laying out the states and required conditions to move forward. Your code simply needs to mimic that. A short cut is to take a look at lpc210x datasheetss as it has fairly simple c code for the state machine implementation in the Isr.

2. What I typically do for slow multi byte transmission, i2c or UART, is to point a pointer to a string to be transmission, load up the datasheetss register and enable the interrupt. In the Isr, test if all the data has been transmission. If yes, turn off the Isr. Otherwise, load up thee next char. The data received can be processed via a callback function.

This approach minimizes user involvement. On a SPI with buffer, it can transmit without interruption.


body:
**Why ?**

The Arduino Mega 2560 is not very fast. The gain by using interrupts is not a lot.

The Wire.endTransmission and Wire.requestFrom wait until the I2C transaction has finished. That might seem a waste of time, but for the slow ATmega microcontrollers, not a lot of time is wasted.

The overhead by more code might even slow it down. A I2C library that is completely in software might even be faster than the original Arduino Wire library. Although the Arduino Wire library uses interrupts, the overhead by the Wire library creates a few extra delays during the I2C transaction.

It took years (it really did) to have a normal working Wire library for ATmega microcontrollers and it still is not very good. For example a hardware problem on the I2C bus could halt a sketch. I have seen a number of custom I2C libraries that run into problems one way or the other.

You can waste less time with:

 1. Make a well designed sketch, using millis instead of delay.
 2. Write a good interface to the sensor. I see a lot bad usage of the Wire library with unnecessary I2C transactions.
 3. Increase the I2C speed to 200kHz or 400kHz with Wire.setClock.
 4. Try to use the SPI bus if possible. For a 3.3V sensor with a SPI interface, a 3.3V Arduino board is the best choice. For example the Arduino Due with ARM M4 or a small board with ARM M0+ processor.
 5. When using the SPI bus with a Ethernet shield, try setting the SPI bus faster.
 6. When using a SD card, try full speed, instead of half speed.
 7. Use the newest Arduino IDE, because the 'lto' optimization was enabled which helps a lot.

Really serious work for better I2C functions has been done for the Teensy. It is still compatible with the Arduino Wire functions, but extra functions have been added that do not wait.


message:
Is there a good Arduino enclosure for that works with the Olimex MIDI shield

I have a MIDI project I put together using an Arduino UNO R3 and the [Olimex Shield-MIDI][1].

[![Omilex Shield MIDI][2]][2]

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.

Has anyone come up with a good solution for Arduino + MIDI projects?  A metal enclosure would be a plus.

  [1]: https://www.olimex.com/Products/Duino/Shields/SHIELD-MIDI/open-source-hardware
  [2]: https://i.stack.imgur.com/DMn6u.jpg

body:
**Your best bet is to 3D print the enclosure.**

There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend [Shapeways][1] as they are fairly reasonable in price and ship worldwide.

If you are a handy DIY person you could use [SketchUp][2] or [Tinkercad][3] to design your enclosure. Also there are many Arduino enclosures on [Thingiverse][4] that you could use as a starting point.

Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.

  [1]: https://www.shapeways.com/
  [2]: https://www.sketchup.com/
  [3]: https://www.tinkercad.com/
  [4]: https://www.thingiverse.com/search/page:1?q=arduino&dwh=475a3e5064c9ae8


message:
Do we really need to upload Arduino bootloader for new Atmega IC

I am using `Atmega328p` in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using `USBasp` programmer. So before uploading code as `upload using programmer`, I will select my arduino board in board select menu and then I will select `USBasp` as my programmer. But I want to know that is it really necessary to burn bootloader on a new `Atmega328p` IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like `Serial.Begin()` etc.

So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

body:
No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.

If you are programming through USBasp you don't even need it on a "normal" Arduino board.

All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.

If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


message:
Problems creating 10Hz pulse wave

I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:

    #define F_CPU 16000000UL
    #include <avr/io.h> //Defines pins, ports, etc.
    #include <util/delay.h>

    int main(void)
    {

     DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
     PORTB |= (1<<PORTB1);

     while(1){

      PORTB |= ~(1<<PORTB1);
      _delay_ms(100);
      PORTB |= (1<<PORTB1);

     }

    }

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?

Still doesnt work
**edit:**

    #define F_CPU 16000000UL
    #include <avr/io.h> //Defines pins, ports, etc.
    #include <util/delay.h>

    int main(void)
    {

     DDRB |= (1<<DDD1);
     PORTB |= (1<<PORTB1);

     while(1){

            PORTB &= ~(1<<PORTB1);
      _delay_ms(100);
      PORTB |= (1<<PORTB1);

     }

    }

body:
Your code doesn't clear anything.
<!-- language: c++ -->

        PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
        _delay_ms(100);
        PORTB |= (1<<PORTB1);  // set PORTB1 pin

And recommended tutorial: [Bit manipulation (AKA "Programming 101")][1] from the AVRFreaks.net

BTW: next issue might be "the pulse is way too fast so it seems there is none"

Try this:

    while(1) {
        PINB = _BV(PINB1); // toggle pin
        _delay_ms(50);
    }

  [1]: http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all


body:
       PORTB |= ~(1<<PORTB1);

change it to:

       PORTB &= ~(1<<PORTB1);

if you want to clear PB1.


body:
You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(50);
        PORTB |= (1<<PORTB1);
        _delay_ms(50); // You need a delay here too.
    }


message:
Can I set arbitrary SPI clock speeds?

I would like to interface an ADC (in particular this one: http://www.linear.com/product/LTC1400) with an Arduino Nano via SPI. The specified max clock speed for the ADC is 6.4 MHz. The Nano can do up to 8 MHz clock speed, but I'm not able to set 6.4 MHz. If I try this

    SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE0));

I get 4 MHz at the clock pin, which means the achievable acquisition rate of the ADC is reduced. Is there a way to get the 6.4 MHz going for maximum acquisition rate with the ADC? Or is there a different approach to get fast data transfer with the ADC (e.g. external clock)?

body:
You are limited to what your microcontroller supports. You could use a 12MHz oscillator to clock your Arduino and set the SCK divider to fOSC/2 = 6MHz (even if it was possible, I wouldn't go higher. Having some margin just to be on the safe side is generally a good advice).

Drawback of this solution is that you lose CPU performance. Please consider also that just collecting ADC data is not enough. You also have to do something with it. Therefore the question should rather be:

"What minimum ADC acquisition rate do I need for my application?"


body:
No, you cannot set 6.4MHz on SPI with a default hardware arrangement.

On the ATMega series of chips the SPI clock is generated by dividing the system clock (8 or 16MHz depending on if you have a 3.3 or 5V board) by one of: 2, 4, 8, 16, 32, 64 or 128.

Looking at [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) (section 25) it may be possible to configure the USART to run in SPI mode which allows a flexible clock speed, though this is not supported by the Arduino API.


message:
Does the reset button clean a programe that you programmed?

does the code clean from arduino if i touch reset button?

body: No, it only causes the microcontroller to start over the existing program/code.


message:
is it possible to power esp8266 with button cell

is it possible to power esp8266 wifi module with button cell for long period(1 year ) real time applications??
 Needs only wifi features (no need of gpio)

what will be voltage and current of the cell??

body:
No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.

The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.


message:
Problem with TIMER in Arduino DUE

I'm writing a code to print/update the value of sensors for each 10 ms, and I decide to use Timer instead of delay function (I'm afraid it's not exactly 10ms with delay function).But when I watch the result on terminal, it stops running at about 0.5s. I guess there is a problem with my code in using Timer because when I remove timer, it prints normally. I debug all day but still cannot find any errors. I guess this is related to memory or pointer or print function.

Please help me :( !!

Here is the code. The code is very long but you can ignore all the unnecessary things:

      #include <DueTimer.h>

      int mod_11k = 12;
      int mod_17k = 13;

      int analog1 = 0;              //output pin of signal 1
      int analog2 = 1;              //output pin of signal 2
      int analog3 = 2;              //output pin of signal 3

      float xf; float yf;
      unsigned long t1;
      unsigned long t2;

    void myHandler(){
        Serial.print(t2-t1);
        Serial.print(" ");
        Serial.print(xf,3);
        Serial.print(" ");
        Serial.println(yf,3);
    }

    void setup() {
      Serial.begin(38400);
      pinMode(mod_11k,OUTPUT);
      pinMode(mod_17k,OUTPUT);
      Timer1.attachInterrupt(myHandler).start(10000);
      digitalWrite(mod_17k,LOW);
      digitalWrite(mod_11k,HIGH);
    }

    void loop() {
        afficherSig(analog1,analog2,analog3);
    }

    void afficherSig(int pin1, int pin2, int pin3){
      unsigned int i;
      float mes[3];
      float mesflt[3];
      float x; float y;
      int  nb_ech = 10000;
      float res = 0.0049;
      float Te;
      float Tbeg;
      float QR1[2],QR2[2] ;
      float *sol1;float *sol2;float *sol3;
      float P1[4];float P2[4];float P3[4];
      float xprec1[2];float xprec2[2];float xprec3[2];
      float *s1_11k;
      float *s1f_11k;

      float H = 80;

                                           //------------------------------>>>
      QR1[0] = 1;
      QR1[1] = 10;
      QR2[0] = 1;
      QR2[1] = 100;
      P1[0] =QR1[0]; P1[1] =0; P1[2] =0; P1[3] =QR1[0];
      P2[0] =QR1[0]; P2[1] =0; P2[2] =0; P2[3] =QR1[0];
      P3[0] =QR1[0]; P3[1] =0; P3[2] =0; P3[3] =QR1[0];
      xprec1[0] =0; xprec1[1] =0;
      xprec2[0] =0; xprec2[1] =0;
      xprec3[0] =0; xprec3[1] =0;
                                          //------------------------------>>>
      t1 = millis();
      Tbeg= millis();
      mes[0]  = res*analogRead(analog1);
      mes[1]  = res*analogRead(analog2);
      mes[2]  = res*analogRead(analog3);

      xprec1[0] = mes[0];
      xprec2[0] = mes[1];
      xprec3[0] = mes[2];
      Te = (millis() - Tbeg)/1000;
      Tbeg = millis();
      sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
      sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
      sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

                                          //------------------------------->>>
     for(i=1;i<nb_ech;i++) {

        P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
        P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
        P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];

        xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
        xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
        xprec3[0] =sol3[0]; xprec3[1] =sol3[1];

        free(sol1);
        free(sol2);
        free(sol3);

        mes[0]  = res*analogRead(analog1);
        mes[1]  = res*analogRead(analog2);
        mes[2]  = res*analogRead(analog3);

        Te = (millis() - Tbeg)/1000;
        Tbeg = millis();
        sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
        sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
        sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

        mesflt[0] = sol1[0];
        mesflt[1] = sol2[0];
        mesflt[2] = sol3[0];                               // Envoie des résultats  à la sortie série

    //Traitment du signal
        s1_11k = traitement1(mes[0],mes[1],mes[2]);
        s1f_11k = traitement1(mesflt[0],mesflt[1],mesflt[2]);

        x = H*s1_11k[0];
        xf = H*s1f_11k[0];
        y = -H*s1_11k[1];
        yf = -H*s1f_11k[1];
        t2 = millis();
      }
    }

    float *Fkalman(float xprec[2],float ymes,float P[4],float QR[2] ,float Te){
                         // Filtre proprement dit
        float *sol = NULL ;
        sol = (float*) malloc (sizeof(float) * 6);
        float xpred[2];
        float Ppred[4] ;
        float Kf[2] ;
        int q = QR[0];
        int r = QR[1];

        xpred[0] = xprec[0] + Te*xprec[1];
        xpred[1] = xprec[1];
        Ppred[0] = q*q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
        Ppred[1] = P[1] + Te*P[3];
        Ppred[2] = P[2] + Te*P[3] ;
        Ppred[3] = q*q+ P[3];
        Kf[0]  = (Ppred[0]/(r+Ppred[0]));
        Kf[1]  = (Ppred[2]/(r+Ppred[0]));

        sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
        sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);
        sol[2] = Ppred[0]*(1-Kf[0]);
        sol[3] = Ppred[1]*(1-Kf[0]);
        sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
        sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
        return sol;
      }

      float *traitement1(float mes1,float mes2,float mes3)
      {
        float *sol11 = NULL ;
        sol11 = (float*) malloc (sizeof(float) * 2);
        sol11[0] = (mes1-mes2)/(mes1+mes2);
        sol11[1] = (((mes1+mes2)/2)-mes3)/(((mes1+mes2)/2)+mes3);
        return sol11;
      }

Here is the result using Timer (stop at about 0.5 second):
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/dhom7.png

body:
As noted in the last part of [Nick Gammon's answer](https://arduino.stackexchange.com/a/14035/3917) to the question [How does the Arduino handle serial buffer overflow?](https://arduino.stackexchange.com/q/1726), if the serial output buffer fills up, serial output blocks, waiting for an interrupt telling it it's ok to send the next byte out the serial port.  When interrupts are turned off, that interrupt is never processed, so the program deadlocks. Don't do Serial prints in an ISR.

Looking at your code, it looks like a typical message has about 20 characters.  <strike>Sending at 38400 bps, or 384 characters per second, it seems to me the buffer shouldn't fill, even if it's small (16 bytes) instead of large (64 bytes).  However, I don't know of another explanation for the behavior you describe.</strike>

Summary:  In your ISR, just store the current time and other relevant data in volatile variables, set a flag in a volatile variable, and in your main loop print stuff and clear the flag (or clear the flag and print stuff) whenever you see that the flag has been set.

---

*Edit 1:* I've struck out some erroneous numbers above.  Here is a correction:  100 sends per second at 20 characters each is 2000
characters per second.  38400 bps of asynchronous data at 10 bits per transmitted byte is 3840 characters per second.  So the raw data rate should be fast enough that the buffer ordinarily doesn't overfill.

---

In the summary above, I suggested that the ISR store the current time and other relevant data in volatile variables and set a flag in a volatile variable.  That is, read `millis()` and store it, perhaps as follows:

    // at file level ...
    volatile unsigned long isrMillis;
    volatile byte isrFlag;

    // in ISR ...
      isrMillis = millis();
      isrFlag = true;

    // in main loop ...
      unsigned long mlMillis;
      ...
      // when flag is true...
      cli();
      mlMillis = isrMillis;
      isrFlag = false;
      sei();
      // Now do stuff with mlMillis
      ...

However, looking at your ISR, perhaps it should go like the following instead:

    // at file level ...
    volatile float xf, yf, xfc, yfc;
    volatile unsigned long t1, t2, tdelt;
    volatile byte isrflag;

    // in ISR ...
    void myHandler(){
      tdelt = t2-t1;
      xfc = xf;
      yfc = yf;
      isrFlag = true;
    }

    // in main loop ...
      // when flag is true...
      isrFlag = false;
      // Now do stuff with tdelt, xfc, and yfc
      ...

Note that if an interrupt occurs while `xf` and `yf` are in the middle of being computed via your Kalman filter or whatever, the statements  `xfc = xf;` and   `yfc = yf;`   may pick up partially-stored results.  You can avoid that problem at least in part by protecting stores of `t1, t2, xf, yf` in the main loop:

      cli();
      xf = someXResult;
      yf = someYResult;
      t1 = someT1Result;
      t2 = someT2Result;
      sei();

In the above I've pointed out a few issues with races and concurrency and suggested technical solutions.  Those suggestions may be quite wide of the mark rather than appropriate.  In general I don't have a precise understanding of what you are trying to do with the software and don't know what redesign should be done to make it coherent.


message:
Identification of IoT

For a school project I Have to make an IoT solution in the retail. We were thinking of a smart clothing hanger. We want to make the hanger smart enough to recognize what clothing is hanging on it. In order to do so the clothing has to be able to send some sort of ID to the hanger.

first thing we thought of was RFID but the hanger next to an one hanger would pick up the signal from the other hanger so that wouldn’t be an option.

Does anyone have any other ideas on what we could try to let the piece of clothing talk to the hanger?

body:
Well I guess the [signal strength could be measured][1] but clothes hanged in wardrobe are too close to each other to distinguish them. Maybe close range NFC?

**I have other solution to be considered.**

Maybe you look at the wrong touchpoint of that interaction. What if the desired action occurs not while it's already hanged but when user put the clothes on hanger? During that, it's not with other clothes (as you grab the hanger in your hand to put the clothes on it).

There are a few things to consider. I guess people put things only on one hanger at once while having clothes in second hand. How many % of users puts clothes on hanger by grabbing it outside of wardrobe (as mundane event/behavior)?

Why it's important?

**During that interaction there is a moment when user tries to pair single cloth with single hanger separated from the rest.**

The hanger could have additional sensor to know when it happens:

 - Magnetic field sensor and small magnet in collar?
 - Capacitive sensor?
 - Accelerometer?

...so the device will know when that interaction occurs and then activate the reading from single rfid tag.

I guess my answer is more about user experience and the aesthetics of interaction but it can give you some clues to finish your project.

  [1]: https://stackoverflow.com/questions/14237110/calculate-distance-to-rfid-tag


message:
Format Integer in Arduino

How to format an integer as 3 digit string? If I give `3` formated string should be `003`

    printf("d\n", 3); // output: 003

This doesn't work in Arduino.

body:
The standard C function `printf` print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.

Instead of `printf`, use `snprintf`. It prints to a char array, which you later can use with `Serial.print`, or whatever other function that take a string.

    void setup() {
      Serial.begin(9600);
      while(!Serial);

      char buffer[4];
      snprintf(buffer,sizeof(buffer), "d", 3);
      Serial.println(buffer);
    }

    void loop() {

    }

Note: all the comments apply to this answers.


message:
ESP8266 Timing question / Do something in 2 seconds even

I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

 1. The MC recieves the signal for trigger by the user on 09:25:18:312
 2. It waits until it is exactly 09:25:19:000
 3. It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!

Edit: Corrected Times.

body:
You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...

The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).

Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.

You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.


message:
Read data from arduino once only serial communications (jSSC)

I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.

Here is Arduino code:

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
     Serial.begin(9600);  // Initialize serial communications with the PC
     while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin();   // Init SPI bus
     mfrc522.PCD_Init();  // Init MFRC522

     //mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

    void loop() {
     // Look for new cards
      String code = "";
     if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
     }
     // Select one of the cards
     if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
     }
      for (byte i = 0; i < mfrc522.uid.size; i++) {
          code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
          code += String(mfrc522.uid.uidByte[i], HEX);
      }
      code.toUpperCase();
      Serial.println(code);
      mfrc522.PICC_HaltA();
    }

body:
Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.

The fault is with the receiving java code, pump test data into that to see what is wrong.


message:
Arduino Nano BME280 weird values

My goal is to measure temperature, pressure and humidity using my Arduino Nano and the BME280 (GY-BME/P280).

[![BME280 back][1]][1]
[![BME280 front][2]][2]

To do this I use [this library][3] from SparkFun and that works almost. What I notice is probably invalid values for temperature and no humidity values at all.

The PINs:

 - GND -> GND
 - VCC -> 3.3V
 - SDO -> D12
 - CSB -> D10
 - SDA -> D11
 - SCL -> D13

I have noticed that I can unplug the VCC pin, it makes to difference to the measurements. I find that odd.
And I have noticed that the results are the same for 5V to VCC.

This is the result, I have tested this with I2C and SPI, it's the same:

    Program Started
    Starting BME280.Program Started
    Starting BME280... result of .begin(): 0x58
    Displaying ID, reset and ctrl regs
    ID(0xD0): 0x58
    Reset register(0xE0): 0x0
    ctrl_meas(0xF4): 0x27
    ctrl_hum(0xF2): 0x0

    Displaying all regs
    0x80:9A 70 90 28 92 2D AF 00 76 6F 7D 67 32 00 93 8C
    0x90:C1 D6 D0 0B CF 18 AD FF F9 FF 8C 3C F8 C6 70 17
    0xA0:00 45 82 00 00 00 00 00 00 00 00 00 33 00 00 C0
    0xB0:00 54 00 00 00 00 60 02 00 01 FF 82 13 4E 08 00
    0xC0:00 87 27 FF 00 00 00 00 00 00 00 00 00 00 00 00
    0xD0:58 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    0xE0:00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    0xF0:00 00 00 0C 27 00 00 58 DD 00 82 72 00 00 00 00

    Displaying concatenated calibration words
    dig_T1, uint16: 28534
    dig_T2, int16: 26493
    dig_T3, int16: 50
    dig_P1, uint16: 35987
    dig_P2, int16: -10559
    dig_P3, int16: 3024
    dig_P4, int16: 6351
    dig_P5, int16: -83
    dig_P6, int16: -7
    dig_P7, int16: 15500
    dig_P8, int16: -14600
    dig_P9, int16: 6000
    dig_H1, uint8: 69
    dig_H2, int16: 0
    dig_H3, uint8: 0
    dig_H4, int16: 0
    dig_H5, int16: 0
    dig_H6, uint8: 0

    Temperature: 24.59 degrees C
    Temperature: 76.26 degrees F
    Pressure: 101121.63 Pa
    Altitude: 18.25m
    Altitude: 59.87ft
    %RH: 0.00 %

My script is almost exactly like the example from the library.

    /******************************************************************************
    I2C_ReadAllData.ino
    BME280 Arduino and Teensy example
    Marshall Taylor @ SparkFun Electronics
    May 20, 2015
    https://github.com/sparkfun/SparkFun_BME280_Arduino_Library

    This sketch configures the BME280 to read all measurements.  The sketch also
    displays the BME280's physical memory and what the driver perceives the
    calibration words to be.

    Resources:
    Uses Wire.h for I2C operation
    Uses SPI.h for SPI operation

    Development environment specifics:
    Arduino IDE 1.6.4
    Teensy loader 1.23

    This code is released under the [MIT License](http://opensource.org/licenses/MIT).
    Please review the LICENSE.md file included with this example. If you have any questions
    or concerns with licensing, please contact techsupport@sparkfun.com.
    Distributed as-is; no warranty is given.
    ******************************************************************************/

    #include <stdint.h>
    #include "SparkFunBME280.h"
    //Library allows either I2C or SPI, so include both.
    #include "Wire.h"
    #include "SPI.h"

    //Global sensor object
    BME280 mySensor;

    void setup()
    {
      //***Driver settings********************************//
      //commInterface can be I2C_MODE or SPI_MODE
      //specify chipSelectPin using arduino pin names
      //specify I2C address.  Can be 0x77(default) or 0x76

      //For I2C, enable the following and disable the SPI section
      //mySensor.settings.commInterface = I2C_MODE;
      //mySensor.settings.I2CAddress = 0x76;

      //For SPI enable the following and dissable the I2C section
      mySensor.settings.commInterface = SPI_MODE;
      mySensor.settings.chipSelectPin = 10;

      //***Operation settings*****************************//

      //renMode can be:
      //  0, Sleep mode
      //  1 or 2, Forced mode
      //  3, Normal mode
      mySensor.settings.runMode = 3; //Normal mode

      //tStandby can be:
      //  0, 0.5ms
      //  1, 62.5ms
      //  2, 125ms
      //  3, 250ms
      //  4, 500ms
      //  5, 1000ms
      //  6, 10ms
      //  7, 20ms
      mySensor.settings.tStandby = 0;

      //filter can be off or number of FIR coefficients to use:
      //  0, filter off
      //  1, coefficients = 2
      //  2, coefficients = 4
      //  3, coefficients = 8
      //  4, coefficients = 16
      mySensor.settings.filter = 0;

      //tempOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
      mySensor.settings.tempOverSample = 1;

      //pressOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
        mySensor.settings.pressOverSample = 1;

      //humidOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
      mySensor.settings.humidOverSample = 1;

      Serial.begin(57600);
      Serial.print("Program Started\n");
      Serial.print("Starting BME280... result of .begin(): 0x");

      //Calling .begin() causes the settings to be loaded
      delay(10);  //Make sure sensor had enough time to turn on. BME280 requires 2ms to start up.
      Serial.println(mySensor.begin(), HEX);

      Serial.print("Displaying ID, reset and ctrl regs\n");

      Serial.print("ID(0xD0): 0x");
      Serial.println(mySensor.readRegister(BME280_CHIP_ID_REG), HEX);
      Serial.print("Reset register(0xE0): 0x");
      Serial.println(mySensor.readRegister(BME280_RST_REG), HEX);
      Serial.print("ctrl_meas(0xF4): 0x");
      Serial.println(mySensor.readRegister(BME280_CTRL_MEAS_REG), HEX);
      Serial.print("ctrl_hum(0xF2): 0x");
      Serial.println(mySensor.readRegister(BME280_CTRL_HUMIDITY_REG), HEX);

      Serial.print("\n\n");

      Serial.print("Displaying all regs\n");
      uint8_t memCounter = 0x80;
      uint8_t tempReadData;
      for(int rowi = 8; rowi < 16; rowi++ )
      {
        Serial.print("0x");
        Serial.print(rowi, HEX);
        Serial.print("0:");
        for(int coli = 0; coli < 16; coli++ )
        {
          tempReadData = mySensor.readRegister(memCounter);
          Serial.print((tempReadData >> 4) & 0x0F, HEX);//Print first hex nibble
          Serial.print(tempReadData & 0x0F, HEX);//Print second hex nibble
          Serial.print(" ");
          memCounter++;
        }
        Serial.print("\n");
      }

      Serial.print("\n\n");

      Serial.print("Displaying concatenated calibration words\n");
      Serial.print("dig_T1, uint16: ");
      Serial.println(mySensor.calibration.dig_T1);
      Serial.print("dig_T2, int16: ");
      Serial.println(mySensor.calibration.dig_T2);
      Serial.print("dig_T3, int16: ");
      Serial.println(mySensor.calibration.dig_T3);

      Serial.print("dig_P1, uint16: ");
      Serial.println(mySensor.calibration.dig_P1);
      Serial.print("dig_P2, int16: ");
      Serial.println(mySensor.calibration.dig_P2);
      Serial.print("dig_P3, int16: ");
      Serial.println(mySensor.calibration.dig_P3);
      Serial.print("dig_P4, int16: ");
      Serial.println(mySensor.calibration.dig_P4);
      Serial.print("dig_P5, int16: ");
      Serial.println(mySensor.calibration.dig_P5);
      Serial.print("dig_P6, int16: ");
      Serial.println(mySensor.calibration.dig_P6);
      Serial.print("dig_P7, int16: ");
      Serial.println(mySensor.calibration.dig_P7);
      Serial.print("dig_P8, int16: ");
      Serial.println(mySensor.calibration.dig_P8);
      Serial.print("dig_P9, int16: ");
      Serial.println(mySensor.calibration.dig_P9);

      Serial.print("dig_H1, uint8: ");
      Serial.println(mySensor.calibration.dig_H1);
      Serial.print("dig_H2, int16: ");
      Serial.println(mySensor.calibration.dig_H2);
      Serial.print("dig_H3, uint8: ");
      Serial.println(mySensor.calibration.dig_H3);
      Serial.print("dig_H4, int16: ");
      Serial.println(mySensor.calibration.dig_H4);
      Serial.print("dig_H5, int16: ");
      Serial.println(mySensor.calibration.dig_H5);
      Serial.print("dig_H6, uint8: ");
      Serial.println(mySensor.calibration.dig_H6);

      Serial.println();
    }

    void loop()
    {
      //Each loop, take a reading.
      //Start with temperature, as that data is needed for accurate compensation.
      //Reading the temperature updates the compensators of the other functions
      //in the background.

      Serial.print("Temperature: ");
      Serial.print(mySensor.readTempC(), 2);
      Serial.println(" degrees C");

      Serial.print("Temperature: ");
      Serial.print(mySensor.readTempF(), 2);
      Serial.println(" degrees F");

      Serial.print("Pressure: ");
      Serial.print(mySensor.readFloatPressure(), 2);
      Serial.println(" Pa");

      Serial.print("Altitude: ");
      Serial.print(mySensor.readFloatAltitudeMeters(), 2);
      Serial.println("m");

      Serial.print("Altitude: ");
      Serial.print(mySensor.readFloatAltitudeFeet(), 2);
      Serial.println("ft");

      Serial.print("%RH: ");
      Serial.print(mySensor.readFloatHumidity(), 2);
      Serial.println(" %");

      Serial.println();

      delay(10000);

    }

  [1]: https://i.stack.imgur.com/iIuyk.jpg
  [2]: https://i.stack.imgur.com/4e6Bb.jpg
  [3]: https://github.com/sparkfun/SparkFun_BME280_Arduino_Library

body:
The photo of the board shows that it is for BM E/P 280. It can take either the BME280 chip which does temperature, pressure and humidity, or the BMP280 chip which only does temperature and pressure.

The Register 0xD0 contains an ID which has a value of 0x60 for the BME280 and 0x58 for the BMP280.

Your output shows the ID as 0x58 which means you have a BMP280 temperature pressure chip.

I have been sold one of these, claiming to be a BME280 chip. I shall be asking for a refund.


body:
I'm after getting a batch of these myself...

I can't get it working with the Adafruit libraries, but it will work with the SparkFun Ones

To get data... the wiring is, well, nonstandard.

I can't get it to work in SPI mode, but it will work in I2C mode
I'm using an Arduino mega so the pin layout is different from an uno.

Pin no|Label|Arduino pin

Pin 1 |VCC  |3.3V

Pin 2 |GND  |GND/Ground

Pin 3 |SCL  | The SCL pin, on a mega its digital 21

Pin 4 |SCA  | The SCA pin, on a mega its digital 20

Pin 5 |CSB  |Do not connect

Pin 6 |SDO  |3.3V

Weird as it sounds, it needs to be connected to power on 2 separate pins


body:
The breakout board photo shows that it is not the original BOSCH BME280 sensor. The dimensions are off. The original is square. This is how it should [look like.][1]

  [1]: https://www.bosch-sensortec.com/bst/products/all_products/bme280


message:
How to connect a digital sensor through SPI

I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections ([user guide][1]):[![enter image description here][2]][2]

I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.

Code:

    //modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

    #include <SPI.h>

    const int ID = 0x00;
    const int FIFO = 0x11;
    const byte READ = 0b11111100;
    const byte WRITE = 0b00000010;

    const int dataReadyPin = 6;
    const int chipSelectPin = 7;

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

        // put your setup code here, to run once:
        SPI.begin();

        // initalize the  data ready and chip select pins:
        pinMode(dataReadyPin, INPUT);
        pinMode(chipSelectPin, OUTPUT);

        delay(100);
        readRegister(ID);
    }

    void loop() {
        if (digitalRead(dataReadyPin) == HIGH){
            Serial.println("data ready");
            delay(500);
        }
    }
    void readRegister (byte thisRegister){
        byte inByte = 0 ;
        Serial.println(thisRegister, BIN);

        thisRegister = thisRegister<< 2;
        byte dataToSend = thisRegister & READ;
        Serial.println(thisRegister, BIN);
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(dataToSend);
        inByte = SPI.transfer(0x00);
        Serial.println("data: ");
        Serial.println(inByte);
    }

  [1]: http://www.analog.com/media/en/technical-documentation/user-guides/EVAL-ADXL354-355-UG-1030.pdf
  [2]: https://i.stack.imgur.com/0gpi1.png

body:
You're shifting your address too far.

* Read should be 0b00000001 not 0b00000010.
* Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

----

    byte readRegister (byte thisRegister){
        byte inByte = 0 ;
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer((thisRegister << 1) | 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }

    void writeRegister (byte thisRegister, byte value){
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }


message:
Making the speaker play a certain frequency of sound

I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

    digitalWrite(buzzer, LOW);
    delayMicroseconds(1000000 / frequency);
    digitalWrite(buzzer, HIGH);
    delayMicroseconds(1);

What could be the problem?

body:
Have you looked at the [Tone library][1]?  That does what you want, with some other niceties besides.

Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:

    digitalWrite(buzzer, LOW);
    delayMicroseconds(500000 / frequency);
    digitalWrite(buzzer, HIGH);
    delayMicroseconds(500000 / frequency);

  [1]: https://www.arduino.cc/en/Reference/Tone


message:
Two-way communication on multimaster I2C bus

I'm trying to send data both ways between an Arduino Mega 2560 slave and 2  Arduino Nano Zero (ATSAMD21G).

This example is a simplified setup and code. There will be more masters along with passive slaves on the bus (LCD, EEPROM).

[Code and results (txt files)][1]

My code is working fine with one master only and the slave active on the bus (data is sent both ways every 2s). I however notice missing transfers to the masters when more than one master is active. The 2 masters to slave transfers are working properly (once the 2 masters are on, the data is received by the slave every 2s from each master).

Is this problem due to collision? How can I handle it?

  [1]: https://github.com/kb-/Arduino-I2C-2way-anydata/tree/f78aa10354f7706d1aa32f49d3bc647600f2b4ee

body:
> notice missing transfers to the masters when more than one master is active.

Because you didn't provide a way for the master's to know of a transmission ISS in progress. Lack of conflict resolution. A problem with all multimeter transmission.

A simpler approach is for the slave to signal a transmission from the master. That can be done via a slave requestion pin from the slave to the master.


body:
The code had several issues leading to a constant flow of wrong data (with correct data in the middle) between the master that won the bus arbitration. This made it keep the bus too long and eventually give it away to the second master at a random time, with missed transfers from the second master in between. The second master was then behaving the same and so on.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`. Avoid slow code in `receiveEvent`!

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

These fixes solved the busy bus problem. I figured these out after asking question #35092

The bus speed also had to be reduced because 800 kHz was too fast for the Mega 2560 (but worked between 3 Nano).

The slave has to send the data destined to both masters to each of them because `requestEvent` can't tell which master is asking for data. The data is then filtered on each master to only keep the relevant information.

The data is now being transferred both ways between the 2 Nano masters and the Mega slave at the correct interval, without corrupt data.

[fixed Slave code][1]

[fixed Master 1 code][2]

fixed Master 2 code in the same repo (I'm limited to 2 links post)

[1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/ff9b47bdb17c137731882ec3b1b53c34afd91193/Slave_test_i2c_data/Slave_test_i2c_data.ino
[2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/7e63e0aaeb7f2a60aad23f67b06f30f55774ce6e/Master_test_i2c_data/Master_test_i2c_data.ino


message:
If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)

I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

 1. How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
 2. How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

body:
On a basic level, the 5v of the USB port is regulated by the power supply of the external device, be it a computer USB port or a USB type charging module. When you are using the power jack on the Arduino, you can provide a range of voltage, from 7v (recommended minimum) to as much as 20v. This input power passes through a voltage regulator to provide the regulated 5v necessary to operate the Arduino.

Voltage is not "used up" by the Arduino, but you may have little reserve power for additional devices which are tied into the 5v bus.

Consider that voltage can be viewed in a manner similar to water pressure, while current can be compared to the volume of water flowing. If you have a 1000 mA power supply and the Arduino uses 500 mA, you have still available 500mA at 5v for other uses.

You can experience voltage drop in a circuit, depending on the way components are connected. That's more advanced than necessary for this discussion.

This is a very basic overview and details will vary from one model Arduino to another.

Also note that one should not apply 5v to other pins marked 5v as it bypasses the regulator and can damage the board or other devices attached.


body: You might be mixing up voltage and ampereage. The Arduino takes in from 5volts up to 12, and uses a regulator to bring higher voltages down to 5V. Milliamps (mA) is the measure of what is drawn per circuit part. The Arduino itself only draws around 25 of these, which if running off of USB, leaves around 475mA that other things can draw.


body: You can supply five 5V directly to the 5V pin, which is effectively what the USB interface does. The quoted 7 to 12V is only if you are using the power jack. That converts it down to 5V which is what the processor needs.


body:
Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is **where do those 5V come from**. Basically, from 2 possible sources:

 1. **USB**. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.

 2. **Barrel connector (wall adapter)**. It accepts 7-12V and brings it down to 5V using a [linear regulator][1] whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, **preference is given to the wall adapter**. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.

This is done not only for convenience purposes (so you have more current available), but also for **protection**. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.

I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.

[![Arduino UNO power supply][2]][2]

  [1]: http://www.onsemi.com/pub_link/Collateral/NCP1117-D.PDF
  [2]: https://i.stack.imgur.com/tEqgz.png


body:
@enric blanco made a good description. I just point out the strange difference between USB (5V) and barrel connector (7-12V).

The barrel connector has to accept different power supplies (with different voltages), moreover they may need voltage regulation; thus arduino needs a "regulator" after the barrel connector. There are different composants that can do it. This simple one will provoke a minimal loss of voltage. That is why you have to input more than 5V.

There are other components (buck/boost) that could accept input voltage from 3V to 12V and always provide 5V as output, but they are more expensive (5$).


body:
No, you don't have to input more than 5V at the raw pin while exactly 5V is output at the VCC pin (at least with the Pro Mini).
How this is done I have no idea.


message:
Hacking old car dvd monitors with arduino

I got this old junk LCD from my car. The DVD function stopped and the LCD holder on the top of the car broke, so I took it.

Is there any documentation or advice I could use to get this working with an Arduino mega or clone of similar power? I couldn't find anything after looking through Google.

I.e. I'm looking for a way to get a pinout or idea of what those wires on the jack are so that I might be able to get text and/or basic graphics on the screen. Maybe to make an Arduino PC or something idk.

Any advice on either figuring out the connections by hand and how to get a simple connection to the Arduino to get bsic stuff working or a place I can find pinout and such or where someone else has done something similar would be helpful.

[![enter image description here][1]][1]

**Update 2**
A quick Google search reveals that it's made by sharp I believe. I'm looking into it.

**Update**
Here's is the back. It's got quite a few numbers on it. Maybe one of those can help?

Top Numbers:
D 09399847
LQ070T5CRQ2 46009355

And the one on the bottom:
K4013TP

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/CQMvP.jpg
  [2]: https://i.stack.imgur.com/UprEI.jpg

body:
Your best bet is to try to take the casing off until you find a company name so that you can get a lead on where to look for documentation. Because until you find out more about how that screen works, it's a black box to you and you don't know what to put in it. No one else will be able to help you until you provide more information to this extent because no one else can hold it in their hands, and the photo of the socket that you showed us doesn't look like a common display format either.

Also, you're very unlikely to make a PC-type thing out of this. That depends on the power of the computer behind the display and an arduino isn't that powerful. You want a Pi. Or maybe I'm misunderstanding what you want. You could easily get a scrolling text type thing going or maybe even a game (if you figure out how to make it work).

Edit: I just looked up a sample LCD screen and it has 6 signal pins and power and ground. Yours looks like it has a lot more. So you definitely have some digging to do.


body:
I realize this is an ancient question, but just in case someone else has one of these things, I'll share what I know. I have one of these Sharp LCDs that I typically use as a monitor for a Commodore 64. I believe mine was originally from a rear seat DVD player in a Ford Explorer.

Looking at the rear of the unit, with the two connectors on the bottom, the leftmost connector is CN2 and the rightmost is CN1. I know nothing of CN2, but here's what I know about CN1:

 Pins 1 through 15, from left to right:

 1. NTSC composite video in
 2. ground
 3. ground
 4. ?
 5. +12VDC in
 6. ?
 7. ?
 8. ?
 9. ?
 10. ?
 11. ?
 12. +12VDC in
 13. +12VDC in
 14. ground
 15. ground

I'm sure the other pins have additional functionality, but I'm not aware of it. Hopefully this helps someone.

EDIT: I found the datasheet in my files: https://byteshiftmusic.com/media/Sharp_LQ070T5CRQ2.pdf


message:
Problem with transmitting 2 byte data in correct way

I'm using Atmel Studio with Atmega328P.

I'm trying to send the decimal number 876 continuously from the micro-controller. This was just to learn.

To send 876 I need two bytes which is:

0x036C = 00000011 01101100

So I manipulated a code and here is what I use now:

    #include <avr/io.h>
    #define F_CPU 16000000
    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

    void USART0Init(void)
    {
     // Set baud rate
     UBRR0H = (uint8_t)(UBRR_VALUE>>8);
     UBRR0L = (uint8_t)UBRR_VALUE;
     // Set frame format to 8 data bits, no parity, 1 stop bit
     UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
     //enable transmission and reception
     UCSR0B |= (1<<TXEN0);
    }

    int main (void)
    {
     //Initialize USART0
     USART0Init();

     while(1)
     {

      UDR0 = 0b00000011;
      UDR0 = 0b01101100;

     }

    }

The problem is at the receiving side the data comes as:

01101100
00000011
00000011
.
.
.

Here is the screen shot of the binary data at the receiving end:
[![enter image description here][1]][1]

However it should be received correctly as two byte chunks 00000011 01101100.

And here you can see the problem of the data being received as uint16(not only 876 as desired):
[![enter image description here][2]][2]

How can I fix this and receive the data properly as two bytes with correct order as 876?

  [1]: https://i.stack.imgur.com/E9RzA.png
  [2]: https://i.stack.imgur.com/k3XnI.png

body:
First, you want to determine what you are trying to send. Send data in binary form is rare.

Secondly, you want to wait for each transmission to send before starting the next one.


body:
The data sheet for the 328P - section 24.7.1 - contains an example of waiting for the transmission to complete before sending another byte.

When sending serial data, you determine the order of bytes and will need to reassembly in the correct order on receipt.  You can use bit shift operators to move the bytes back into the correct location.  If you send the most significant byte first (MSB) and then the least significant byte (LSB), putting them back into a 16 bit integer would look something like:

uint16_t result = (MSB << 8) | LSB;


body:
Your code has a fundamental error: when you write "UDR0 = 0b00000011;", the CPU does not wait until the transmission is complete - that would be terribly wasteful, in terms of time. It just write to the transmit data buffer. Furthermore, if the transmission was not ongoing yet, that instruction also starts transmission (assuming the USART is properly initialized, as it is in your case). However, if a transmission is ongoing, and the data buffer is not empty, this write instruction might be either ignored or it might overwrite the data on the buffer.

Therefore, with your code, you're continuously writing two bytes (at a very high speed, because that loop would result in very few asm instructions), without checking if actually you can write to the transmit data buffer register. This will result in most of the bytes being "randomly" ignored, with some other being randomly picked and trasmitted.

Before sending any data, you must check if the data register is empty:

    while ( !(UCSR0A & (1 << UDRE0)));
    UDR0 = firstByte;
    while ( !(UCSR0A & (1 << UDRE0)));
    UDR0 = secondByte;

Where firstByte and secondByte are either the numeric values or two 8-bit variables.

Instead of the two "while" statements, you can use the built-in macro:

    loop_until_bit_is_set(UCSR0A, UDRE0);


message:
Question about configuration EEPROM or Flash

I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).

This 'setup file' needs be stored in the Arduino.

Now I thought of the following alternatives:

- Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
- Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
- Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
- Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

body:
> Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

> Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

> Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

> Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.

The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

> To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can `seek()` straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.


message:
Arduino WiFi/ESP8266 WiFi Password Changed

I am working on a project for a friend who is not very tech savvy involving an ESP8266. It will need to be connected to his WiFi network.

The issue is that he occasionally changed the password to his WiFi network. Since I will not be able to access this device at a moments notice, it needs to be able to adapt to a change in the password. Is this possible with the ESP8266, or should I switch to an Arduino WiFi board, or is something more powerful necessary?

body:
Yes that's possible.

Just don't hard-code the password: store it in EEPROM.

A common way of doing it if for the ESP to present a wifi access point which serves a configuration page when it cannot successfully connect to another access point.  Store the SSID and password in EEPROM.


body:
The [WiFiManager][1] library was written for exactly this purpose.

  [1]: https://github.com/tzapu/WiFiManager


message:
LCD isn't working with if statement

#include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #define trigpinyellow 10
    #define echopingreen 9
    #define Grove_Water_Sensor 8
    void setup()
    {
        Serial.begin(9600);
        pinMode(trigpinyellow,OUTPUT);
        pinMode(echopingreen,INPUT);
        pinMode(Grove_Water_Sensor, INPUT);
        lcd.begin(16, 2);
    }

    void loop()
    {
        long duration,distance;
        digitalWrite(trigpinyellow,LOW);
        delayMicroseconds(1000);
        digitalWrite(trigpinyellow,HIGH);
        delayMicroseconds(1000);
        digitalWrite(trigpinyellow,LOW);
        duration=pulseIn(echopingreen,HIGH);
        distance = (duration/2) / 29.1;
        Serial.println(distance);

        if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) >=20  )
        {
            lcd.clear();
            lcd.print("water_came");
            lcd.setCursor(0, 1);
        }
        if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) <=8 )
        {
            lcd.clear();
            lcd.write("Tank_is_full");
        }
        if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) >=20 )
        {
            lcd.clear();
            lcd.print("Fill The Tank PLEASE");
        }
        if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) <=8 )
        {
            lcd.clear();
            lcd.print("Tank_is_FULL");
        }
    }

body: Every time you instantiate digitalread(), you poll the pin. Here, you're polling pins 8 times every loop. Instead, poll the two pins at the start of the loop to update the variable, and then do your math and make your decisions afterward. Right now you're doing math with your distance variable, and then overwriting the variable during your if conditionals. Not sure if that's what you intend. You're also creating the variables duration and distance every single loop. instead, create those variables globally and just update them every loop.