body:
Problem in getting -5 V with Arduino.

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

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

    void loop() {
      digitalWrite(13, HIGH);
      delay(20);
      digitalWrite(13, LOW);
      delay(20);
    }

Above code is generating below digital signal:

[![puredigi][1]][1]

I want this type of digital signal output:

[![digiwithn][2]][2]

I read this for generating negative -5 V signal:

https://electronics.stackexchange.com/questions/10322/what-is-negative-voltage

but not able to understand very well WRT Arduino.

Also read this:

https://arduino.stackexchange.com/questions/19435/negative-voltage-how-do-i-scale-a-0-to-5-v-signal-to-10-v-to-10-v

seems to much complicated circuit diagram with TL802.

**My questions:**

1. How do I get above digital signal?
2. I was wondering if we can use some 1 microF capacitor or transistor to generate negative signal? (simplest way)

  [1]: https://i.stack.imgur.com/GGNoF.png
  [2]: https://i.stack.imgur.com/sruN8.png

title: Generating digital positive (+5 V) and negative (-5 V) signal?

Answers: 1

body:
It is not so easy to create a -5v power supply using a capacitor or transistor.

 A very easy way is to use an additional Wall wart power supply to create -5 volts (while still using your original +5 volt power supply).

For the additional (new -5 volts power supply), use the two wires (positive and negative to create your -5 volts).   The positive lead goes to your board ground, and the negative lead becomes your -5 volts.

EDIT 1  :   Make certain that the Wall wart that you use is isolated from the mains voltage (line voltage you plug it into).  Most Wall warts are isolated,  but check to be sure.

Then you need level translation, which can be done with an op-amp and a couple of resistors  :

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

You have not mentioned what frequency (data rate) you need.  This circuit is not fast, so for high frequency or high data rates, the circuit could be improved.

  [1]: https://i.stack.imgur.com/4JGOJ.jpg


body:
I use the Arduino IDE 1.6.9

What I want is a DMX Receiver which receives 1 channel and displays it on the serial monitor. When I try to compile the code, I get the following error:

    C:\Users\Helyx\AppData\Local\Temp\build25a76891c667e0896ec10beb77bd0478.tmp/core\core.a(HardwareSerial0.cpp.o): In function `__vector_25':

    D:\Programme\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial0.cpp:48: multiple definition of `__vector_25'

    sketch\DmxReceive.ino.cpp.o:C:\Users\Helyx\Documents\Arduino\DmxReceive/DmxReceive.ino:26: first defined here

    d:/programme/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Fehler beim Kompilieren.

Any ideas?
Here is my code:

    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <stdio.h>

    #define F_CPU 16000000

    #define DMX_BAUD 250000
    #define DMX_LOST_TIMEOUT 8000

    volatile unsigned char dmx_buffer[10];
    volatile unsigned int dmx_lost = DMX_LOST_TIMEOUT;

    volatile unsigned int dmx_adresse = 1;

    ISR (USART0_RX_vect)

    {
    static unsigned int dmx_channel_rx_count = 0;
    static unsigned char dmx_valid = 0;
    unsigned char tmp = 0;

    tmp =  UDR0;

    if(UCSR0A&(1<<FE0))
    {
     if(dmx_channel_rx_count > 1)
     {
       dmx_lost = 0;
     }
     dmx_channel_rx_count = 0;
     dmx_buffer[0] = tmp;
     if(dmx_buffer[0] == 0)
     {
       dmx_valid = 1;
       dmx_channel_rx_count++;
     }
     else
     {
       dmx_valid = 0;
     }
     return;
    }

    if(dmx_valid)
    {
     dmx_buffer[dmx_channel_rx_count] = tmp;
     if(dmx_channel_rx_count < 514)
     {
       dmx_channel_rx_count++;
     }
     return;
    }
    }

    ISR (TIMER2_COMPA_vect)

    {
     if(dmx_lost<DMX_LOST_TIMEOUT)
     {
       dmx_lost++;
     }
    }

    void setup()
    {

    EICRA |= (1<<ISC11)|(1<<ISC10); //The rising edge of INT1 generates an interrupt request
    EIMSK |= (1<<INT1); //External interrupt request 1 enable

    //Init usart DMX-BUS
    UBRR0   = (F_CPU / (DMX_BAUD * 16L) - 1);
    UCSR0B|=(1 << RXEN0 | 1<< RXCIE0);
    UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
    sei();//Globale Interrupts Enable

    TCCR2A |= (1<<WGM21);
    TCCR2B |= (1<<CS22|1<<CS21|1<<CS20);
    TIMSK2 |= (1<<OCIE2A);
    OCR2A = F_CPU/1024/1000 - 1; //Tick 1ms
    Serial.begin(57600);

    DDRC = (1<<PE3);
    PORTB |= 0x3F;
    PORTC |= 0xFF;
    PORTC &=~(1<<PE3);

    }

    void loop()
    {

    if(dmx_lost==DMX_LOST_TIMEOUT)
    {
      dmx_buffer[dmx_adresse] = 0;

    }
    Serial.print(dmx_buffer[dmx_adresse]);
    }

title: Error when using USART with Arduino Mega 2560

Answers: 2

body: The compiler/linker is providing the answer. There are at least two definitions of the ISR for UART0 RX. One in your code and one in HardwareSerial.

body:
If I understand you correctly, you want to receive serial data (in DMX format) on one serial port, and then display that data on the serial monitor (using a different serial port).

The Arduino Mega 2560 is an excellent choice, because it has [4 hardware UARTs][1].

Alas, there is really only 3 hardware UARTs that you can actually connect to external hardware. USART0 (the Mega pins labeled "TX0" and "RX0") are *already* connected to the USB interface; the Arduino calls that USART "Serial." (without a number).

I avoid connecting anything to the "TX0" or "RX0" pins on the Mega, so I can use "Serial." (USART0) for sending debugging messages to the serial terminal over the USB cable.

    // doesn't compile
    ISR (USART0_RX_vect)
    {
        // ...
    }
    // ...
    void loop()
    {
        // ...
        Serial.print(dmx_buffer[dmx_adresse]);
    }

This looks inconsistent to me.
One part of your program is trying to use USART0 ("Serial.") for sending and receiving messages to the serial monitor on the PC.
Another part of your program is trying to use the same USART0 ("Serial.") for sending and receiving messages on the DMX network.

Have you tried connecting the DMX interface to the other available hardware USARTs -- perhaps USART1 ("Serial1.", the pins labeled TX1 and RX1), or USART2 ("Serial2.", the pins labeled TX2 and RX2), or USART3 ("Serial3.", the pins labeled TX3 and RX3)?
Then your code would look more like other people recieving DMX on an Arduino Mega -- [(a)][2], [(b)][3], [(c)][4], etc.:

    // the ISR setup that the other DMX-on-Arduino-Mega people use:
    ISR( USART3_RX_vect ){
        // ...
    }
    // ...
    void loop(){
        // ...
        Serial.print(dmx_buffer[dmx_adresse]);
    }

  [1]: http://www.arduino.cc/en/Reference/Serial
  [2]: http://forum.arduino.cc/index.php?topic=50696.0
  [3]: http://github.com/phoeve/NPCC_DMX/blob/master/npcc_dmx_servo_mega
  [4]: http://github.com/rad1o/l0unge-sender/blob/master/arduino_dmx/libraries/Conceptinetics/Conceptinetics.cpp


body:
I have an Arduino Leonardo that can turn a relay off and on and the click is audible on the relay -this is simply done by making one of the control wires HIGH in the program code to turn the relay on and make the same control wire LOW to turn the relay off. In this way it can turn a set of relays on and off. By varying the patterns of on and off timings to the relay it make distinct sounds-it reminded me of a piezoelectric speaker for some of the programmed values. At fast on or off puling this 6V relay makes a buzzing noise. I was wondering if the sound emitted from the relay could be used as a crude speaker- I'm not talking about a quality speaker- just good enough to recognise a melody or speech. So my question
I was thinking the problem maybe be simplified if a set of relays is used buzzing at a certain frequency-corresponding to tones heard in the human voice to make it sound like speech. Im no expert in acoustics.

My questions are

1) is  it theoretically possible to use the clicking noise from a set of relays only to act as a a crude speaker (so hear a crude known melody or a crude speech)?

2) Is there such a circuit (if so what is it exactly and the theory of how it works) that can be built with an arduino?-so it only used the noise from a relay to act as a crude speaker.

I personally think it possible it would be an interesting circuit to build as I have not seen a relay used like this before. I just think it sounds interesting that music or speech can possible be made by a circuit without using a speaker type component. Maybe there's another non-speaker component (i.e. a component that was not originally designed to make a sound) that can be used instead of a relay.

I'd love to know the answers.

Update
I started on this. And the relays do make different tones-thats as far as I got.
So music seems to be possible; something like a famous melody of a song. I havent got any ideas yet for a another component instead of a relay.

title: Can an a Arduino make music or speech without a speaker?

Answers: 2

body:
Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.

To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.

A function that takes agreements of pitch and duration, something like:

     note(hz, ms)

would give you a fairly easy way to describe the music you wanted to play.

Just for fun, here are a few examples of "speakerless devices" making music:

* [Floppy disc drive music][1]
* [Lotus F1 car plays Happy Birthday][2]

[1]: https://youtu.be/OUzDwCX1sKY
[2]: https://youtu.be/Tr4zb-HHZs4?t=30s

body:
The operate/release time for a [typical relay](http://www.omron.com/ecb/products/pdf/en-g5v_2.pdf) is 10ms/4ms - that means it takes 14ms for the contacts to close and open again. 14ms equates to a maximum 'click' frequency of 71Hz.

Typical rates of cycles-before-failure are in the region of 100,000  minimum - but at a rate of 5 cycles per second. This will rapidly decrease as you increase the switching rate.

Furthermore, as alluded to in the above datasheet, must-operate and must-release voltages increase as the number of completed cycles moves into the tens-of-thousands. Thus, if you were to find a relay that switched fast enough you will eventually (and maybe only after a 100 seconds of non-continuous operation) run its operating voltage above a level that can be achieved.

----------

Due to the maximum switching frequency of a relay you **cannot** use one, or many, to synthesise speech. Speech is an incredibly complex mixture of frequencies, the majority of which are well above those that can be produced by switching a relay on and off.

----------

*Music* is a loose term. Simply switching the relay on and off once per second is technically a rythym, and therefore music. Different relay models will have different 'clicks' - the smaller the contacts the higher the click will be in pitch (logically speaking, that is). A collection of *different* relays could definitely create music, akin to percussion, but by their *individual clicks* and **not by the rapid switching thereof**.


body:
I have a Funduino Joystick Shield (See here [Funduino on Gearbeast store][1]) which has some Bluetooth pins.

Does anyone know what pins they are connected to, and has anyone successfully connected to a BT HC-05 device using SoftwareSerial?

  [1]: http://www.gearbest.com/boards-shields/pp_236610.html?currency=GBP&gclid=CKvOx76k0soCFUieGwodKTcD-w

title: Funduino Joystick Shield with Bluetooth

Answers: 1

body:
Well, it turns out that the tx/rx for the board are connected to the standard pins 0 and 1 on the Arduino.
To use this, you can simply use Serial.write.
Of course, remember to take of the module when trying to upload your code.....


body:
I know it's possible (in theory) to reprogram the VID PID details back into a chip. It is however way beyond me.

Recently I learned that Microsoft distributed a piece of malicious software as part of their Windows update service. This virus was written by the FTDI chip makers to brick any chips such as the CH341's found in many cheaper Arduinos et al.

The virus attacked my CH341A serial to USB chip by writing 0's to the VID PIC and probably other locations. This makes the hardware 'Unknown' and even if you have the correct driver software, the device is never associated with it.

Does anyone know a solution to get the zeroed information back into the CH341A?

title: Reprogram CH341A chips VID PID etc

Answers: 2

body:
What you call a “virus” is, more properly, malware.  FTDI's driver that bricked fake FT232R chips was withdrawn from Windows Update in October of 2014.  (See, for example, discussion at [epanorama.net](http://www.epanorama.net/newepa/2014/10/23/on-counterfeit-usb-serial-chips/), [sparkfun](https://www.sparkfun.com/news/1629), and [hackaday](http://hackaday.com/2015/02/08/unbricking-a-counterfeit-ftdi-chip/).  The hackaday article, “Unbricking a counterfeit FTDI chip”, has links to an article about unbricking counterfeits.)

The CH341A is not a fake FT232; it is a cheaper alternative that requires a different driver.  The driver is not automatically installed by Windows. Several web pages I've seen about it suggest downloading from Chinese-language web pages, which is a gamble if you don't understand what the page says.  [However, English-language [driverscape.com](http://www.driverscape.com/download/usb-serial-ch341a) seems to have a CH341A driver at the moment.  I don't know if it works or whether it is free, and anyway have no Windows machine to test it on.]

body:
Here's the guide I used to correct the problem :-

## HOW TO FIX THE USB-FTDI PROBLEM

(on arduino nano, usb ttl, ft232, ...)

There must have been a production of faulty ftdi drivers (version 2.12.0.0 or later) on august 2014 that makes some arduino boards and other usb devices not readable from the computer. The problem is random, meaning that it is possible to program the arduino a couple of times and then it comes out the ftdi problem, at that point the board isn't accessible anymore.

Once you come up with this problem, upgrading/downgrading the drivers, the IDE or the bootloader is just a waste of time, as the ftdi driver installed leaves some wrong data. This guide followed step by step will completely fix the driver problem thus making your board working again.

### Step 1: check if you have a faulty ftdi chip driver

Not every ftdi chip has faulty drivers, so the first step is to check the chip's driver version. In order to check the version you need a software like usbview or usbdeview (both freeware and don't need any installation). Run the software and look for the "USB serial converter" device which is the one related to the ftdi driver, then read the vendor-id and the Product-id whose values should be 0x0403 for the vendor and 0x6001 for the product. The goal is to modify that 0x6001 value with 0x0000, and to do that we need some other software.

### Step 2: modify values

Unplug your arduino nano or usb device. In order to modify the driver values you need CDMUninstaller (no installation needed). Fill the vendor and product fields with the values found with usbview (0403 and 6001) and click 'add', finally click 'remove devices'.

### Step 3: download the 2.10.0.0 ftdi driver

Go to the ftdi website and download the 2.10.0.0 virtual driver choosing between 32 or 64 bit version, voiding the 'setup executable' file: just download the folder. After downloading the folder, we have to overwrite some files inside of it. Click [FTDI.rar][1] to download the files already modified, and place them inside the 2.10.0.0 folder overwriting the old ones.

### Step 4: connect your arduino board

connect your arduino board, and stop windows from looking for new drivers. Go to device manager and look for FT232 USB device, then right click on it, select Properties and click on update drivers. Manually select the place in which scan for the new drivers and choose the 2.10.0.0 driver folder with the modified files. Now windows will prompt you saying that it can't certificate the new drivers. Ignore the alert and proceed with the installation. Once installation has finished, windows should recognize the connected board as 'USB recuperacion'.

Close the window and go to device manager, and look for the COM ports device. The connected device is now showing up like USB recuperation by ElectroHobby.es

### Step 5: modify the chip eeprom

This is the last step and you need to restore the initial vendor and product values inside the ftdi chip eeprom. In order to do that you need to download and install Ftprog, click on the magnifing glass icon, select 'USB device descriptor' and again select 'custom pid'. Finally click on 'ftdi default'.

A new window shows up and you just need to check flag the device list and then click on 'program'.

  [1]: http://www.electrohobby.es/Archivos/ModificadosFTDI.rar


body:
I am new to microcontrollers and just become confused trying to solve the following problem:

An ATmega32 chip is connected to four on/off switches (SW0-SW3) and 4 LEDs (LED0-LED3). SWi is connected to PAi.  LEDi is connected to PA(4+i).

How will I code in such a way that turning a switch on, turns the corresponding LED on? For example, turning SW1 on will turn LED1 on. **I am confused in the part that after taking input what will I send to port A**? Multiple switches can be switched on at the same time.

**For clarification:**

    switch0 is connected to PA0
    switch1 is connected to PA1
    switch2 is connected to PA2
    switch3 is connected to PA3

    LED0 is connected to PA4
    LED1 is connected to PA5
    LED2 is connected to PA6
    LED3 is connected to PA7

title: Switching LED on and off using microcontroller

Answers: 1

body:
A common approach is, to read the input pin, check the read value and then write to the output pin.
As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.

So in your arduino sketch you could write:

    loop()
    {
      uint8_t pin1=digitalRead(PA0);
      if (pin1==HIGH)
      {
         digitalWrite(PA4, HIGH);
      }
      uint8_t pin2=digitalRead(PA1);
      if (pin2==HIGH)
      {
         digitalWrite(PA5, HIGH);
      }
      // and so on
    }

I assume you have already done the prerequisites in your setup() routine.


body:
Ok so forgive me for being an amateur but I'm having a situation that's driving me nuts.

I have a sensor that I have to cycle between +5VDC and +1.4VDC every 60 seconds. I'm using an ATTiny85 with the 8Mhz internal clock fuse set.

What I was hoping was to use a 2N7000 N-Channel MOSFET to control the cycling of the voltage. So my thought is to have +5VDC on the Drain and a PWM signal on the Gate with the + side of the sensor connected to the Source. I am thinking that using PWM and adjusting the duty cycle on the Gate will allow me to adjust the voltage that is seen at the Source but what I'm seeing is a variation of +1.4VDC @28% duty cycle and +3.6VDC at 100% duty cycle.

I can't figure out why +3.6VDC is the best I can do. The PWM is coming from PB1 on the ATTiny85 and the +5VDC is coming from the main voltage source that also feeds the ATTiny85. The current draw of the sensor is 140mA max.

[![Schematic][1]][1]

Ok so I haven't had any luck using a BJT or a single component to perform this voltage change so I started on a different approach using two 1N7000, with one being in an inverter configuration.  My though is the pin from the MCU will go high, which will turn on both FET's, with one supplying 5V and the other sinking to ground.  When the MCU pin goes low, both FET's turn off, which stops the 5V flow and the sink to ground, which then will allow the path through a voltage divider into my sensor at 1.4V.  The issue I am having is the second FET is smoking, and by that I mean the sucker heats up like crazy and one even let the smoke out!  I cannot for the life of me figure out WTF I am missing in this configuration.  Here is the new schematic and Q1 is the FET that is smokin.

[![Version 2][2]][2]

  [1]: https://i.stack.imgur.com/Iv3Px.png
  [2]: https://i.stack.imgur.com/bzTeI.png

title: Use MOSFET to Change Voltage With PWM

Answers: 1

body:
Using a N-type transistor as a high-side switch is inefficient unless you have some way of driving the gate above the positive rail. The most you can reasonably expect at the source is the gate voltage minus the gate threshold voltage, VGS(th). The typical threshold voltage of the 2N7000 as given in the datasheet is 2.1V, which means that it is a bit remarkable that you are able to get a voltage as high as you have (5V - 2.1V = 2.9V).

The way to fix this is to switch to a P-type transistor (and flip it around) since its threshold voltage is negative.


body:
I would like to introduce myself as a student from Czech Republic. I'm currently I'm working on a Meteostation project.

I've got Arduino set up, with plenty of weather sensors, as well as WH1080 sensors connected.

Right now, I'm only able to read the data via serial port on computer with Arduino IDE or show it on my 20*4 display.

Because of the distance between source of data and recipient of data, wireless data transfer is unsuitable for my application.

I found these MAX 485 modules on eBay for cheap:

[![max485 module][1]][1]

I quickly got 2 pieces, as well as 5v-3.3v logic level shifter, as I was concerned about different logics on Raspi. I don't know much about Raspi and their pins, as the only thing I ever used with them was DS3231 real time clock module.

Now, the thing I'm trying to achieve is this - I want to be running a bunch of sensors at roof of our house, and have the Arduino send the data to Raspi over the rs485 (on request? as the sensor loop would be like 10-15min so maybe communicate on interrupt?)

What I'm planning to do with the data on the raspi would be running a software like WeeWx or wfrog to process them and possibly render a local website, that I could make public as port forwarding (I have public IP).

However, there are few questions I have, hopefully its not too much to ask

1. How would the wiring look like? I was unable to find any dumb-proof tutorial online, as I don't know whether or how to use the logic level shifter.

2. If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?

3. If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

Thanks in advance for any kind of response, as this is at the moment causing me headaches, as I'm unable to do this on my own. I don't expect anyone to do all the work for me, maybe just point me in the right direction.

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

title: Arduino sending data over MAX485

Answers: 2

body:
Ok, one simple step which might help you to get going.

**The no-brainer**

There is an RS232 link between your Arduino and the PC. (Of course, it might not be a real RS232, it can be the USB, and over the USB the PC sees the arduino as a serial port what you can write from Arduino. So far so good.

You can easily extend the USB with passive expansion cords, as well as with active USB expansion cords, easily getting an extra 30m. Of course it is not an RS485, but comes at no further thinking.

**The RS485**

RS485 is basically a clever variant of a serial port, which allows you sending your data over up to 1.5km twisted wire pair.

 * get an USB-RS485 adapter for your PC or Raspberry side. These are widely available, e.g. http://usb-rs485.eu/?cms=eu85xl&gclid=CjwKEAjwq6m3BRCP7IfMq6Oo9gESJACRc0bNkhzTSQU3wUW_5tebRZDD-zAqflcvcFOq9V8nmZIlRhoCvyPw_wcB
 * get an RS485 driver chip such as MAX485 (I prefer LTC485, that works straight from 5V, costs like 1 EUR) for your Arduino side.
 * you'll need two ardino pins - serial read and write, therefore you may prefer an Arduio supporting also Serial1 - so a TxD and RxD wire from the board. When you write to this serial port instead of Serial, the data comes out from the TxD pin of the Ardino panel, instead of going to the PC via the USB.
 * now, if you can have a simplex system - i.e. only Arduino talks to the PC or Raspberry - then it makes your life a lot easier. Then you only need the TxD from the Arduino, and connect it to the DI of the RS485 driver chip. Connect RE and DE and connect both of them to 5V. That's all.
 * if you want a two direction communication between the Arduino and PC, that makes things a bit more complicated. RS485 is a half-duplex thing, so your Arduino needs to control when it wants to talk to the line or listen. For that you need a separate pin to be connected to RE and DE together. Put it to 1 to write, 0 to read from the RS485 lines. Note that Arduino is having write buffers, so it will be a little tricky to know exactly when to switch back to listening after writing. Solving this properly worths of a separate question :)
 * connect A of the MAX485/LTC485 to the A of the USB RS485 interface. Connect B to B. Now you're almost there... Connect also GND of the Arduino to the GND of the RS485 interface. (Although you can see many examples on the net of using only two wires, A and B, in the real life you either need a common GND, or an additional overvoltage protection circuit made of four zener diodes to have it running well forever.)
* you're advised of using a twisted pair wire for A and B. This is not a requirement though, you can go well with any wires. One of my friend used a garden fence made of metal as A, and the soil as B, which worked well for 50 meters :) However for 1.5Mbit, 1km you definitely need a twisted pair
* Note that if you go with long wires (over 50 meter) and higher speed (over 9600 bps), you need to have line-terminator resistors. This means a simple 120 ohm resistor connected between A and B on the PC side. Another 120 ohm resistor to be connected at A and B on the MAX 485 side - so the two farthest end of the long communication wire.

Now the software side:

* The USB RS485 interface will look like just a regular serial port for the PC (e.g. COM9) or Raspberry. So you can read and write the RS485 bus just like a standard com port.
* On the Arduino side, you can use the Serial1 (or equal) to write data out to the MAX485, which drives the wires.
* I suggest again to start with a simplex system, i.e. Arduino only writes data, the PC just reads data.
* Note that you have to use exactly the same bit rate on Arduino as well as on the PC side. Watch out when you open up the terminal.

body:
> How would the wiring look like? I was unable to find any dumb-proof
> tutorial online.

I found [this][1] tutorial to be pretty usefull.

There really isn't much to it, I suggest trying a short range before going full range.
It's a "half duplex bus system" the ends of the bus should have a "end termination resistor", usually 120Ohms, between the A and B signal.
Since it's half duplex, the Pi and Arduino can't talk at the same time.
You'll have to pull the DE and RE pins high when you want to transmit (and keep them low for receiving).

Basic sketch would be something like:

    #define TXEnablePin 13

    void setup(){
      Serial.setup(9600);
      pinMode(TXEnablePin,OUTPUT);
    }

    void loop(){
      String data = "";
      Unsigned int sensorValue1 = Sensor.getValue();
      Unsigned int sensorValue2 = Sensor.getValue();
      data += str(sensorValue1) + ":" + str(sensorValue2) + ";\r\n";
      send(data);
      delay(10000);
    }

    void send(String data){
      digitalWrite(TXEnablePin,HIGH);
      delay(1);
      Serial.send(data);
      Serial.flush();//Wait for everything to be transmitted, before disabling transmitter.
      digitalWrite(TXEnablePin,LOW);
    }

> I don't know whether or how to use the logic level shifter.

These things are pretty straight forward. You should actually be able to figure it out yourself (given you have the power of the internet).

LV to 3.3V of Pi
GND to GND of Pi
GND to GND of Arduino
HV to 5V of Arduino

Then, whatever 5V signal you want to connect to HVx and whatever 3.3V signal you want to connect to LVx

    Example:
    Arduino-TX -> HV1
    Arduino-RX -> HV2
    Pi-TX -> LV2
    Pi-RX -> LV1

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

> If I can read the data over serial port, would it be just a plain text
> (as shown on PC in Arduino ide serial monitor), or has each value its
> address that I could then easily accessing to a variable then being
> used to process the weather data?

It would be ASCII (plain text) if you send strings.
You could make different types of requests.

Like; If you send: "Temperature" to the Arduino, it will respond with: "TEMP:10" or something.

But the easiest thing would be to send all values of all sensors in a combined string every 10 seconds or so. And let the Raspberry Pi unpack that string.

> If I'm completely wrong in something, or there's some completely
> different way how these things are being done by more experienced
> people, I'd love to hear some suggestions.

I think it's pretty good that you actually already know of the existence of RS485 and why you'd want to use it.

But I also feel that you feel a little uncomfortable with the project as it is.
It's important to handle problems one by one, to avoid getting overrun by problems.
Try to make it working over (short) USB first. Then try a short RS485 link and eventually try a long RS485 link. You can then more easily spot where the problem is. Use facts from multiple tutorials, to boost the confidence you have in the system ;). It may just work if you wire it as said. If it doesn't work, you can always post a question.

If possible, it may also be worthwhile to follow some tutorials on Arduino (get a starter kit and book with tutorial projects?). Within these tutorials they give examples of problems and show what there is to solve them. Without throwing yourself into a dark pit of a project.

  [1]: http://arduino-info.wikispaces.com/SoftwareSerialRS485Example
  [2]: https://i.stack.imgur.com/GUmhB.png


body:
I have a question regarding _potentiometer example_:

https://www.arduino.cc/en/Tutorial/AnalogReadSerial

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

If I turn the potentiometer to the marginal position and have 5V at A0 (and almost zero resistance at the pot), what limits the current flowing through the circuit?

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

title: Arduino potentiometer example: what limits the current?

Answers: 2

body:
A0 input is high impedance, so very little current is flowing into A0. The value is so small that you can simplify that it flows only from +5V through the potentiometer to GND.

For some applications, when you are measuring high-impedance sources (a source that can deliver very little current) this simplification may not be correct.

You can find more detailed explaination in Atmel application note:

http://www.atmel.com/images/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf

body: Assuming A0 is set to **input** then it is a high-impedance input. That is, the input has a high resistance, and only consumes enough current to "sample" the voltage.


body: In my application all of the Arduino Uno LEDs will be invisible inside an enclosure, so I wish to provide panel-mounted Tx and Rx LEDS just replicating their on-board counterparts. Is there a way to drive any of the digital outputs to replicate those LEDs? I seem to recall that the Tx and Rx LEDs are driven directly from the FTDI logic, does this preclude hacking their states and sending them to two digital outputs? How could this be done? I could de-solder the LEDs and hardwire the panel LEDS to their pads, but I think this should be a last resort.

title: Replicating Tx and Rx LEDs

Answers: 3

body: The easiest thing to do would likely be to use an Arduino that does not have an on-board serial connection such as the Pro Mini and then add a separate USB-UART bridge with either bare pads you can solder panel-mount LEDs to or mounting holes that will allow you to mount it with the LEDs aligned to holes on the enclosure.

body:
The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).

If you look closely you'll see there are 4 pad near the chip, JP2 in the [schematic](https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf). You could solder some wire to it to connect your leds. You could then slightly modify the [firmware running on the ATMega16u2](https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2), and [upload it using DFU](https://www.arduino.cc/en/Hacking/DFUProgramming8U2).

I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.

In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change `DDRD` and `PORTD`, to `DDRB` and `PORTB` in [LED.h](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/firmwares/atmegaxxu2/arduino-usbserial/Board/LEDs.h).

body:
Personally I would wrap all serial reading and writing in my own functions which, as well as doing the reading and writing, turn on an LED on any chosen GPIO and set a timer variable which is then used in the main loop to turn the LEDs off after a short period (otherwise they flicker too fast to be properly seen).  Something like:

    uint32_t readLedTimer = 0;

    // Call instead of Serial.read();
    int mySerialRead() {
        if (Serial.available()) {
            digitalWrite(13, HIGH);
            readLedTimer = millis();
            return Serial.read();
        }
        return -1;
    }

    // Call from loop();
    void cancelLeds() {
        if ((readLedTimer > 0) && (millis() - readLedTimer > 20)) {
            readLedTimer = 0;
            digitalWrite(13, LOW);
        }
    }

Of course, replicate (with a different LED) for the any Serial.write or Serial.print functions you may want to do (use may use *overloading* to pass different variable types to similar functions).

Another option is to directly modify the serial reading and writing routines within the Arduino AVR core to do the same thing, but that gets rather tricky when you update the IDE or want other people to use your code to build these widgets of yours.


body:
Hello I have an Arduino programme that has a string with the words hello in it.
I can add characters and other strings to the end of that one using:

       String test = "hello";
       test+=" jack";

it would then say "hello jack"
The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

title: Arduino subtracting chars from strings

Answers: 3

body:
You may use [remove()][1] method to remove last character.

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

    String s = "1234567890";
    while(s.length() > 0) {
        int lastIndex = s.length() - 1;
        s.remove(lastIndex);
        Serial.println(s);
    }

body:
> I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

This is how you could do that. Avoid using String and putting the string constants in program memory.

    // A buffer for the message
    const size_t MSG_MAX = 16;
    char msg[MSG_MAX];

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

    void loop()
    {
      static int len = 0;
      // Check if it is time to create the initial message
      if (len == 0) {
        strcpy_P(msg, (const char*) F("hello"));
        strcat_P(msg, (const char*) F(" jack"));
        len = strlen(msg) - 1;
      }
      // Otherwise shorten the message
      else {
        msg[len--] = 0;
      }
      // And print current message
      Serial.println(msg);
      delay(2000);
    }

body:
You are best of learning about C-style strings rather than the String class. The String class can eventually fragment dynamic memory.

To shorten a string a simple method is to move the "string terminator" inwards by overwriting the last byte of the message with zero, like this:

    const size_t MSG_MAX = 20;
    char msg [MSG_MAX];

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      strcpy (msg, "hello");  // initial message
      strcat (msg, " jack");  // concatenate more stuff
      }  // end of setup

      void loop ()
        {
        if (strlen (msg) > 0)
          {
          Serial.println (msg);  // display current message
          msg [strlen (msg) - 1] = 0;  // move null-terminator in
          delay (1000);
          }  // end of any message left

        }  // end of loop

Results:

    hello jack
    hello jac
    hello ja
    hello j
    hello
    hello
    hell
    hel
    he
    h


body:
I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7

I tried the [AVR -> DMX source code from Ulrich Radig][1] and also the layout for the RS-485 transmission.

I modified the code to fit the ATMega2560 but when I upload the code nothing happens.

The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?

Any idea?

Here is my circuit:

[![Photo of breadboarded RS-485 circuit][2]][2]

Here is the source

    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <stdio.h>

    #define F_CPU 16000000
    #include <util/delay.h>

    #define DMX_BAUD 250000
    #define DMX_BAUD_BREAK 80000
    #define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
    #define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

    volatile unsigned char dmx_buffer[512];

    //############################################################################
    //DMX Senderoutine
    ISR (USART_TX_vect)
    //############################################################################
    {
      static unsigned int  dmx_channel_tx_count = 0;
      static unsigned char dmx_tx_state = 0;

      switch (dmx_tx_state)
      {
        case (0):
          UBRR0   = DMX_BAUD_BREAK_UBBR;
          UDR0 = 0; //RESET Frame
          dmx_tx_state = 1;
          break;

        case (1):
          UBRR0   = DMX_BAUD_UBBR;
          UDR0 = 0; //Start Byte
          dmx_tx_state = 2;
          break;

        case (2):
          _delay_us(10);
          //Ausgabe des Zeichens
          UDR0 = dmx_buffer[dmx_channel_tx_count];
          dmx_channel_tx_count++;

          if(dmx_channel_tx_count == 512)
          {
            dmx_channel_tx_count = 0;
            dmx_tx_state = 0;
          }
          break;
      }
    }

    void setup() {
     //Init usart DMX-BUS
     UBRR0   = DMX_BAUD_UBBR;
      DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
      UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
      UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
      sei();//Globale Interrupts Enable
      UDR0 = 0;//Start DMX

    }

    void loop() {
      // put your main code here, to run repeatedly:
        dmx_buffer[4]=255;
        _delay_ms(1000);
        dmx_buffer[5]=255;
         _delay_ms(1000);
        dmx_buffer[6]=255;
        _delay_ms(1000);
        dmx_buffer[4]=0;
        _delay_ms(1000);
        dmx_buffer[5]=0;
         _delay_ms(1000);
        dmx_buffer[6]=0;
         _delay_ms(1000);

    }

  [1]: http://www.ulrichradig.de/home/index.php/avr/atmega8-experimentierboard/avr---dmx
  [2]: https://i.stack.imgur.com/AA6Cx.jpg

title: Problem with sending DMX

Answers: 1

body:
> The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a *huge* problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.


body:
I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:

    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
     static SPISettings settings;
            ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
         SPI.endTransaction();
             ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
         SPI.beginTransaction(settings);
             ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
         SPI.beginTransaction(settings);
                              ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
       settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
       ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
       settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                         ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
       SPI.beginTransaction(settings);
           ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
       SPI.endTransaction();
           ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
         case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                  ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
         case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                      ^
    make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
    Make failed with code 2

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:

    #include <Wire.h>

So my minimal code to reproduce the error is:

    #include <Wire.h>

    void setup(){
    }

    void loop(){
    }

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?

I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

title: SPISettings was not declared in this scope

Answers: 2

body:
Try a later version of the IDE. Try making a completely new sketch (don't just delete things from your current one). It looks to me like it is trying to compile things it shouldn't.

> /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp

That doesn't seem relevant to your empty sketch.

body:
If fixed this by deleting this built-in library

    /usr/share/arduino/libraries/SD

but then I received the error:

    /usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
      Serial1.begin(9600);

so I deleted these libraries as well:

    /usr/share/arduino/libraries/Robot_Control
    /usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.


body:
I can't flash my ESP8266 (ESP-01). I have 3.3 V and ground connected, Rx to Tx and Tx to Rx on my USB to serial adapter. I also have GPIO0 connected to ground too.

I am using an external power supply but the USB adapter and power adapter share a common ground.

I'm using a Mac and ESP tools to flash it, and it has worked before.

The command I am using is:

    sudo ./esptool.py --port /dev/tty.wchusbserial1410 write_flash 0x00000 AT22SDK10020150320boot12.bin

But the response is:

    A fatal error occurred: Failed to connect to ESP8266

This make me think something is wrong with receiving data from the ESP because when attempting to connect, the ESP's blue LED flashes.

My USB to serial adapter works fine though as I've tested it with my Arduino.

title: Flashing ESP8266

Answers: 0


body:
[![enter image description here][1]][1]Anybody here have tried connecting multiple MPU9250 into multiplexer. Anyway, I've used the HD74LS151 as the substitute for the 74HC4051 multiplexer. I already tried running the program and just followed how it is connected as it is connected like in the picture. Please see the attached image in here.

Right after running the code I just only got zeros on the output. I hope someone could help me figure out what's going on with my program or  the connections of my pins.

And here is the code I used:

        #include <I2Cdev.h>
        #include <MPU6050.h>

        // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE    implementation
        // is used in I2Cdev.h
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
        #endif

        // class default I2C address is 0x68
        // specific I2C addresses may be passed as a parameter here
        // AD0 low = 0x68 (default for InvenSense evaluation board)
        // AD0 high = 0x69
        MPU6050 mpu_0(0x68);
        MPU6050 mpu_1(0x68);
        MPU6050 mpu_2(0x68);
        MPU6050 mpu_3(0x68);
        //MPU6050 accelgyro(0x69); // <-- use for AD0 high

        int16_t ax_0, ay_0, az_0, ax_1, ay_1, az_1, ax_2, ay_2, az_2, ax_3, ay_3, az_3;
        int16_t gx_0, gy_0, gz_0, gx_1, gy_1, gz_1, gx_2, gy_2, gz_2, gx_3, gy_3, gz_3;

       // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
      // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
     // not so easy to parse, and slow(er) over UART.
     #define OUTPUT_READABLE_ACCELGYRO

     // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
     // binary, one right after the other. This is very fast (as fast as possible
    // without compression or data loss), and easy to parse, but impossible to read
    // for a human.
    //#define OUTPUT_BINARY_ACCELGYRO

     #define LED_PIN 13
     bool blinkState = false;

     //Mux control pins
     int s0 = 5;
     int s1 = 6;
     int s2 = 7;

     //Mux in "SIG" pin
     int SIG_pin = 0;

     const int MPU=0x68;

     void setup() {

      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);

      //    delay(5);
      //    Wire.begin();
      //    Wire.beginTransmission(MPU);
      //    Wire.write(0x6B);  // PWR_MGMT_1 register
      //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
      //    Wire.endTransmission(true);
      //    delay(15);
     //
     //    digitalWrite(s0, HIGH);
     //    digitalWrite(s1, LOW);
     //    digitalWrite(s2, LOW);
    //    delay(5);
    //
    //    Wire.begin();
    //    Wire.beginTransmission(MPU);
    //    Wire.write(0x6B);  // PWR_MGMT_1 register
    //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    //    Wire.endTransmission(true);
    //    delay(15);

    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(38400);

    // ================= MPU: 0 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_0.initialize();
    Serial.println("Testing device connections #0 ...");
    Serial.println(mpu_0.testConnection() ? "MPU6050 connection #0 successful" :      "MPU6050 connection #0 failed");
    delay(5);

    // ================= MPU: 1 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_1.initialize();
    Serial.println("Testing device connections #1 ...");
    Serial.println(mpu_1.testConnection() ? "MPU6050 connection #1 successful" :  "MPU6050 connection #1 failed");
    delay(5);

    // ================= MPU: 2 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_2.initialize();
    Serial.println("Testing device connections #2 ...");
    Serial.println(mpu_2.testConnection() ? "MPU6050 connection #2 successful" : "MPU6050 connection #2 failed");
    delay(5);

    // ================= MPU: 3 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_3.initialize();
    Serial.println("Testing device connections #3 ...");
    Serial.println(mpu_3.testConnection() ? "MPU6050 connection #3 successful" : "MPU6050 connection #3 failed");
    delay(5);

    // use the code below to change accel/gyro offset values
    /*
    Serial.println("Updating internal sensor offsets...");
    // -76 -2359 1688 0 0 0
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");
    accelgyro.setXGyroOffset(220);
    accelgyro.setYGyroOffset(76);
    accelgyro.setZGyroOffset(-85);
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");
    */

    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
    // read raw accel/gyro measurements from device
    //    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    // these methods (and a few others) are also available
    //accelgyro.getAcceleration(&ax, &ay, &az);
    //accelgyro.getRotation(&gx, &gy, &gz);

    // ================= MPU: 0 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_0.getMotion6(&ax_0, &ay_0, &az_0, &gx_0, &gy_0, &gz_0);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#0\ta/g:\t");
        Serial.print(ax_0); Serial.print("\t");
        Serial.print(ay_0); Serial.print("\t");
        Serial.print(az_0); Serial.print("\t");
        Serial.print(gx_0); Serial.print("\t");
        Serial.print(gy_0); Serial.print("\t");
        Serial.println(gz_0);
      #endif
      delay(5);

    // ================= MPU: 1 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_1.getMotion6(&ax_1, &ay_1, &az_1, &gx_1, &gy_1, &gz_1);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#1\ta/g:\t");
        Serial.print(ax_1); Serial.print("\t");
        Serial.print(ay_1); Serial.print("\t");
        Serial.print(az_1); Serial.print("\t");
        Serial.print(gx_1); Serial.print("\t");
        Serial.print(gy_1); Serial.print("\t");
        Serial.println(gz_1);
    #endif
    delay(5);

    // ================= MPU: 2 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_2.getMotion6(&ax_2, &ay_2, &az_2, &gx_2, &gy_2, &gz_2);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#2\ta/g:\t");
        Serial.print(ax_2); Serial.print("\t");
        Serial.print(ay_2); Serial.print("\t");
        Serial.print(az_2); Serial.print("\t");
        Serial.print(gx_2); Serial.print("\t");
        Serial.print(gy_2); Serial.print("\t");
        Serial.println(gz_2);
       #endif
       delay(5);

       // ================= MPU: 3 =================
       digitalWrite(s0, HIGH);
       digitalWrite(s1, HIGH);
       digitalWrite(s2, LOW);
       delay(5);
       mpu_3.getMotion6(&ax_3, &ay_3, &az_3, &gx_3, &gy_3, &gz_3);
       #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#3\ta/g:\t");
        Serial.print(ax_3); Serial.print("\t");
        Serial.print(ay_3); Serial.print("\t");
        Serial.print(az_3); Serial.print("\t");
        Serial.print(gx_3); Serial.print("\t");
        Serial.print(gy_3); Serial.print("\t");
        Serial.println(gz_3);
        #endif
        delay(5);

       //    #ifdef OUTPUT_BINARY_ACCELGYRO
         //        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax &    0xFF));
         //        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
         //        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
          //        Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
          //        Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
         //        Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
         //    #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
       }

Cheers!

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

title: Multiple MPU9250 using Multiplexer

Answers: 1

body:
Your concept sounded sensible enough so I gave it a try-out.

[![Multiplexed I2C][1]][1]

First point is: The master always generates the clock so we don't need to multiplex that. We only need to multiplex the data (SDA).

Code snippet:

<!-- language-all: lang-C++ -->

    // the multiplexer address select lines (A/B/C)
    const byte addressA = 6; // low-order bit
    const byte addressB = 5;
    const byte addressC = 4; // high-order bit

    int selectTarget (const byte which)
      {
      // select correct MUX channel
      digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
      digitalWrite (addressB, (which & 2) ? HIGH : LOW);
      digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
      }  // end of readSensor

All you have to do is call `selectTarget(n)` where `n` is 0 to 7, and you redirect SDA to the desired chip. I suggest a 4.7k pull-up on the target side so that the line is pulled high when not selected.

I tested it out and it seems to work OK.

---

The beauty of this setup is that you can multiplex 8 devices (eg. sensors) which happen to have the same I2C address, with only one additional chip. And, you can get 16-channel multiplexers if you want to take this further. Of course, in the code you still have to select the correct I2C address for the chip.

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


body:
I recently got to work with Arduino and I want to get parallel input from 5 LDRs and at the same instance I need to light a LED corresponding to that LDR if the resistance got high.

I read about a finite state machine, but I couldn't understand how it works.

Is it the only way for this type of problem or are there any other way?

title: Can I do parallel processing in Arduino?

Answers: 1

body:
You do not need parallel processing or finite-state machines for that:

    // Vector with digital pin numbers for LEDs (with resistor to ground)
    const int LED_MAX = 5;
    const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

    // Vector with analog pin numbers for LDR (with pullup resistor)
    const int LDR_MAX = 5;
    const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

    // Analog value or lower when to light the LED
    const int THRESHOLD = 200;

    void setup()
    {
       // All LED pins should be digital output pins
       for (int i = 0; i < LED_MAX; i++)
         pinMode(LED[i], OUTPUT);
    }

    void loop()
    {
       // Read all LDRs and set LED pins according to threshold
       for (int i = 0; i < LDR_MAX; i++)
         digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
    }

But if you really want to describe this as multiple tasks you could use the [Simple Scheduler library][1]:

    #include <Scheduler.h>

    const int THRESHOLD = 200;

    template<int LED> void setup()
    {
       pinMode(LED, OUTPUT);
    }

    template<int LED, int LDR> void loop()
    {
       digitalWrite(LED, analogRead(LDR) < THRESHOLD);
       yield();
    }

    void setup()
    {
       Scheduler.start(setup<2>, loop<2, A0>);
       Scheduler.start(setup<3>, loop<3, A1>);
       Scheduler.start(setup<4>, loop<4, A2>);
       Scheduler.start(setup<5>, loop<5, A3>);
       Scheduler.start(setup<6>, loop<6, A4>);
    }

    void loop()
    {
       yield();
    }

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler


body:
I am rewriting a set of LED manipulation functions to be more object oriented, and I have found that, mysteriously, my global variable memory space has been over consumed, despite a reduction of the use of global variables.

I played around with a number of things, and found something curious.

Here is a fragment of a function that does not live in an object, and is called directly from `loop()`:

    Animation *getNewAnim(int index)
    {
        switch(index)
        {
            case 0:
                return new RedClouds();
            case 1:
                return new TwoLayerClouds();
            case 2:
                return new LavaLamp1();
            case 3:
                return new Bubbles1();

            ...  (20 or so more cases)
         }

This is a function that lets me switch between display modes based on the value of `index`.  Only one of these objects is ever created at a given time; I delete the old one before calling this, so there will never be multiple instances in use simultaneously.

Now the curious thing is that if I remove a few of these return statements, collapsing the block into something like this:

    Animation *getNewAnim(int index)
    {
        switch(index)
        {
            case 0:
            case 1:
            case 2:
            case 3:
                return new Bubbles1();
    }

The amount of global memory space used falls considerably.

My hypothesis is that the Arduino build environment is pre-allocating space for each of these objects in the global memory space before the program is even run, rather than doing so dynamically as needed.

Is my hypothesis correct?  And if so, is there any way to tell the build environment not to do this, as I'd rather use the same memory for my new object that was used by the old one.

To clarify: When I build I see this sort of output:

    Sketch uses 6,550 bytes (21.3%) of program storage space. Maximum is 30,720 bytes.
    Global variables use 1,167 bytes (57.0%) of dynamic memory, leaving 881 bytes for local variables. Maximum is 2,048 bytes.

When I refer to "global memory" I am referring to the Global variables number on that output.  I'll also note that when I compile with the second example, the program storage space reported also falls dramatically.

**NEW HYPOTHESIS**

Here is what I think may be going on.  When I omit the classes from the switch statement, the compiler seems to optimize them out of the codebase, which is what I expect, and is consistent with seeing the program storage space shrink.  Each class has a method that returns it's name.  This method contains an embedded string, and I now believe that this string is stored in the global variable space.  Therefore, if the class is included, more global variable space is consumed to hold the name, and if it is optimized out, less is consumed.  This theory is consistent with all the facts I have, and makes more sense than my previous hypothesis.

title: Understanding global variables on Arduino

Answers: 1

body: I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries.  It's a wrapper for malloc https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino


body: I am using a GSM module sim800. My module responds to the output given by my PIR sensor and sends sms according to it. My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

title: Using Rx and Tx pins(0 and 1) on Arduino Uno for GSM

Answers: 2

body:
You have a choice.

Always:

* GND => GND
* +5V => +5V

Then, either:

* TX => RX (0)
* RX => TX (1)

and use the hardware UART "Serial", but that then means that uploading new code to your Arduino becomes an arduous task since the usage pins 0 and 1 will interfere with that.  So the other option:

* TX => Any pin
* RX => Any pin

And then use [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) to set up a secondary "bit banged" serial port on the two pins you choose.

body:
> My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

TX => RX, RX => TX, that is Arduino TX to module RX, and TX to module RX. If you want to use [Serial][1] the pins are 0 for Arduino RX, and 1 for Arduino TX.

If you want to use [SoftwareSerial][2] you decide which pins to use (check the documentation for valid pins on your board).

    // Use software serial with pin 2 for rx and pin 3 for tx
    SoftwareSerial gsm(2,3);

Cheers!

  [1]: https://www.arduino.cc/en/Reference/Serial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialConstructor


body:
As mentioned in the title I'm facing a problem in printing strings in the LCD. It's printing actually weird characters.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    void setup() {
      lcd.begin(16, 2);
      Serial.begin(9600);

      lcd.print("hello, world!");
    }
    void loop() {

     lcd.setCursor(0, 1);
      lcd.print(millis()/500);
    }

You can find the output of the LCD in the picture below:

[![LCD error !!][1]][1]

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

title: LCD is not printing strings, only integers with Arduino

Answers: 1

body:
Whenever I use an LCD display I make sure to use the I2C backpack.  It takes actual effort to hook it up wrong if you use them.  So if this were me, I would desolder all those pins and get one.

Here is a good description of how they work:
https://learn.adafruit.com/i2c-spi-lcd-backpack/overview


body:
I had attatched a GSM module to my arduino Uno board. The power had been switched on. The GSM 5V pin was connected to my board. I was still midway with my work so for some reason I gave an external power supply to my GSM module. Now smoke started coming out of my Uno board and a burning smell came from it. I immediately switched off the power supply. But now I am unable to burn sketches to my Arduino. It is showing error: Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
On opening the serial monitor it says: Board at COM3 not detected.

Link from wher I bought the GSM module: http://www.ebay.in/itm/GSM-Module-SIM800-Quadband-better-than-SIM-900-or-SIM900A-Modem-with-SMA-Antenna-/252053758680?hash=item3aaf9322d8

title: Problem with my arduino board

Answers: 1

body:
Oops.

You let the [Magic Smoke™](https://en.wikipedia.org/wiki/Magic_smoke) escape from your Arduino.  Your Arduino is now somewhat dead.  Depending on *what* died it may be repairable by replacing components, or it may be beyond resurrection and it'll be easier to buy a new one.

Now - why did it happen?  Looking at the board in your link it should have been OK with the 12V power you provided, since it has its own regulator on board that can supposedly take up to 12V.  So one of two things may have happened:

1. What you thought was 12V was actually higher than 12V and the regulator didn't cope with it.
2. You connected the power backwards, so -12V was pumped straight through everything.

There seems to be no polarity protection on the board as far as I can see, and many regulators, if connected backwards, will just pass the power straight through with little or no change to it.  So my money is on having connected the power backwards.  Now, that might not be your fault, since on that site I can see no mention of which polarity the power connector uses - whether it is pin-positive or pin-negative.  The normal way (the way the Arduino board uses) is pin-positive, but that is not always the case.

Either way, the Arduino is now dead, and the GSM module may be dead as well. In fact the whole lot may be dead.


body: I wanted to know if my GSM sim800 is working or not. A mishap occured while I was experimenting around with my GSM module and I arduino uno. The link to the module which I bought: http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW I want to know ow can I check if my module is fine?

title: How to check if a GSM module is working or not?

Answers: 1

body:
Power it up and check the 'status' light.  If it blinks with a 1 blink per second cycle, it is attempting to connect to the network.  If it connects, it does a slow blink at 1 blink/3s, it made the network connection.

I don't know if your board does an auto-power-on, but you might need to push the power button or reset button.


body:
I have 4 dot matrix displays, every one of them connected to an i2c and accessible with `0x70`, `0x71`, `0x72` and `0x73`. All these work just fine when I address them apart. What I want to achieve is a scrolling text throughout all 4 displays. How can I do this? Are there any libraries around that already do this? (I did not find any).

Basically, this is my code:

    #include <Wire.h>
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"

    Adafruit_8x8matrix matrix[4];

    void setup() {
      Serial.begin(9600);
      Serial.println("4x(8x8) LED Matrix Test");
      matrix[0].begin(0x70);
      matrix[1].begin(0x71);
      matrix[2].begin(0x72);
      matrix[3].begin(0x73);
    }

title: scroll text through multiple i2c connected dot matrix displays

Answers: 1

body:
This is what I found behind the link @mikael-patel posted, and with a little configuration it does exactly what I want. Basically the `scroll()`-method handles anything neccessary.

    #include <Wire.h>
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"

    #define NUM_MATRICES 2
    Adafruit_8x8matrix matrix[NUM_MATRICES];

    void setup() {
      Serial.begin(9600);
      Serial.println("8x8 LED Matrix Test");

      for(uint8_t m=0; m<NUM_MATRICES; m++) {
        matrix[m].begin(0x70 + m);
        matrix[m].clear();
        matrix[m].setTextSize(1);
        matrix[m].setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
        matrix[m].setTextColor(LED_GREEN);
      }
    }

    void loop() {
      scroll("Hello World!");
    }

    void scroll(char* text) {
      int scrollPositions = (strlen(text) * 8) + 32;

      for (int x=(8 * NUM_MATRICES); x>=-scrollPositions; x--) {
       for(uint8_t m=0; m<NUM_MATRICES; m++) {
        matrix[m].clear();
        matrix[m].setCursor((x - (m * 8)), 0);
        matrix[m].print(text);
        matrix[m].writeDisplay();
       }
       delay(80);
      }
    }


body:
Uploading a sketch to an ESP8266 board fails with:

    error: failed reading byte
    warning: espcomm_send_command: can't receive slip payload data
    warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

...or:

    espcomm cmd: receiving 2 bytes of data
    warning: espcomm cmd: no final C0
    warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

This is on OS X with a PL2303HXD USB-to-Serial cable, using the latest official Prolific signed [OS X El Capitan-compatible drivers][1].

  [1]: http://prolificusa.com/pl-2303hx-drivers/

title: Upload with esptool fails with "espcomm_send_command: can't receive slip payload data"

Answers: 1

body:
This is [a known issue][1] with [the included esptool][2], and for the Arduino IDE there are quite a few blog posts to be found on this problem. But most are outdated, and are not applicable when using [PlatformIO][3] with some other IDE. So, February 2016:

**Install [esptool.py](https://github.com/themadinventor/esptool)**

- `git clone https://github.com/themadinventor/esptool/` (or download the ZIP file)
- `cd esptool`
- `sudo python setup.py install`

**When using Arduino IDE**

- Open `~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/platform.txt`.
- Find the line `tools.esptool.upload.pattern` and disable that by prefixing with a hash. Check that your version only mentions `-ca 0x00000`, not `-ca 0x10000` as well (like in most outdated blog posts):

        # tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"

- Add the following, referring to the `esptool.py` you installed above and also using different command line parameters:

        # Fix for espcomm_send_command: cant receive slip payload data
        tools.esptool.upload.pattern="/path/to/new/esptool.py" --port "{serial.port}" --baud {upload.speed} write_flash 0x00000 "{build.path}/{build.project_name}.bin"

- Restart the IDE.

(One might be tempted to just change `tools.esptool.path` and `tools.esptool.cmd` instead, but beware that the command line parameters need changing as well.)

**When using PlatformIO**

You will find the same `platform.txt` file somewhere in `~/.platformio/packages/framework-arduinoespressif/platform.txt`, but that file is not used for the upload. [Instead][4]:

- In `platformio.ini` add:

        # ...or whatever your port is named
        upload_port = /dev/cu.usbserial
        extra_script = /path/to/platformio_extra_script.py

- Create a new file `/path/to/platformio_extra_script.py`:

        # Custom settings, as referred to as "extra_script" in platformio.ini
        #
        # See http://docs.platformio.org/en/latest/projectconf.html#extra-script
        # See https://github.com/platformio/platformio/issues/426

        from SCons.Script import DefaultEnvironment

        env = DefaultEnvironment()

        # Must be full path, or use
        # https://docs.python.org/2/library/os.path.html#os.path.expanduser

        env.Replace(
            LOCAL_UPLOADER="/Users/arjan/path/to/new/esptool.py",
            LOCAL_UPLOADERFLAGS=[
                "--port", "$UPLOAD_PORT",
                "--baud", "$UPLOAD_SPEED",
                "write_flash", "0x00000",
            ],
            UPLOADCMD='$LOCAL_UPLOADER $LOCAL_UPLOADERFLAGS $SOURCE'
        )

  [1]: https://github.com/igrr/esptool-ck/issues/9
  [2]: https://github.com/igrr/esptool-ck
  [3]: http://platformio.org
  [4]: https://github.com/platformio/platformio/issues/426


body:
I am powering a UNO through the 5V pin. I am using a tftlcd shield (2.8" mcufriend.com) on it.

To be able to use the shield with I2C I had to snip the RST leg from the shield. That was done because the shield used A4 which was required for I2C.
 When I power the UNO through the USB port the program starts correctly and a bitmap is loaded onto the screen. When I power up from the 5V pin or the power adapter, the screen remains white. I have to manually press the reset button on the UNO and then the program loads the bitmap.

The ladyAda examples had this to say;

    #define LCD_CS A3 // Chip Select goes to Analog 3
    #define LCD_CD A2 // Command/Data goes to Analog 2
    #define LCD_WR A1 // LCD Write goes to Analog 1
    #define LCD_RD A0 // LCD Read goes to Analog 0
    #define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

Does that mean I should solder the lcd RST pin to the RESET on the UNO? (if so I am not sure how I can do that without taking the lcd shield to pieces).

title: Manual reset is required on power on

Answers: 1

body:
It isn't clear from the description whether your setup has a hardware problem or a software problem.  For example, the rationale for “I had to snip the RST leg from the shield” is unclear.

The comment in ladyAda's example, “Can alternately just connect to Arduino's reset pin”, means that it's suitable to hardware-reset the LCD at the same time the Arduino does a hardware reset.  If the “RST leg from the shield” that you snipped is the LCD reset pin, as opposed to a pin driven by the small tactile reset switch on the 2.8" mcufriend shield, you probably should restore that pin.  In other words, unsolder and remove the stub of the pin you snipped off, insert a new pin, and solder it in place.

Note, just reinstalling the pin might make things work.  It's possible the LCD is sitting there in a permanently-reset  state, due to its RST input hanging open.  It's also possible the library is already driving RST properly but that drive isn't getting through, due to the missing pin.  Whatever the case may be, with the pin in place you should be able to software-reset the LCD by pulsing A4.  (Ie, with consecutive `digitalWrite()` commands, in `setup()` and before shield initialization, take A4 high and then low, or vice versa.)

*Edit:* If A4 isn't available for resetting the LCD (due to its use as the SDA signal for I2C, per comment) you might try adding a jumper wire from the shield's LCD_RS pin (above A4) to an available pin, and adjust the `#define LCD_RESET` statement accordingly.

In general, to add a jumper wire, strip about 5 mm of each end of a short piece of #30 [wire-wrap](https://en.wikipedia.org/wiki/Wire_wrap) wire.  Form a small hook at each end.  Hold a hook onto the solder of the pin you wish to attach to and briefly heat the solder, letting the hook sink into the solder.  If you don't have wire-wrap wire, use a single strand from some old stranded cable (eg, mouse or keyboard).  Use thin heatshrink tubing or a bit of stripped-off cable insulation to insulate the jumper.  To keep pins in place while soldering, seat the pins being worked on into an old disk-drive connector, or another shield, or if you have nothing else, an Uno.

In your particular case, an mcufriend shield on an Uno, no pins are available unless you co-opt one of the SD-card-slot signals.  But before doing that, it's probably worthwhile to try your original idea of wiring to the Uno's RESET pin.  Your jumper would run from J3's second pin (A4) to J4's last pin (Reset), installed on the LCD side of the shield.  You should be able to see the trace between the Reset pin and the Reset switch, when identifying the Reset pin.


body:
I would like to upload my code to the Arduino Mega 2560.

 1. The USB is fried hence I have to use the FTDI
 2. I've a FTDI cable, but it has only 4 wires, Vcc,GND,TX,RX

How do you upload, as the ATmega is not responding to anything?

title: Upload Code on Arduino Mega using FTDI Cable

Answers: 1

body: FTDI cables usually have RTS which is used to bring `Reset` low. If you only have four pins, press the Reset button on the board the moment you start the upload.


body:
The code below works fine when  one IMU (MPU9250). What I want to know is how can I edit this code to work perfectly with two IMU (MPU9250) in one arduino board ?

Hope someone can help me. THANKS :)

<!-- language: c -->

    ////////////////////////////////////////////////////////////////////////////
          //
          //  This file is part of RTIMULib-Arduino
          //
          //  Copyright (c) 2014-2015, richards-tech
         //
         //  Permission is hereby granted, free of charge, to any person           obtaining a copy of
        //  this software and associated documentation files (the "Software"), to deal in
        //  the Software without restriction, including without limitation the rights to use,
       //  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
       //  Software, and to permit persons to whom the Software is furnished to do so,
       //  subject to the following conditions:
       //
       //  The above copyright notice and this permission notice shall be included in all
      //  copies or substantial portions of the Software.
      //
      //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
      //  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
      //  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
      //  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
      //  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
      //  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

      #include <Wire.h>
      #include "I2Cdev.h"
      #include "RTIMUSettings.h"
      #include "RTIMU.h"
      #include "RTFusionRTQF.h"
      #include "RTPressure.h"
      #include "CalLib.h"
      #include <EEPROM.h>

      RTIMU *imu;                                           // the IMU object
      RTPressure *pressure;                                 // the pressure object
      RTFusionRTQF fusion;                                  // the fusion object
      RTIMUSettings settings;                               // the settings object

      //  DISPLAY_INTERVAL sets the rate at which results are displayed

      #define DISPLAY_INTERVAL  300                         // interval between   pose displays

     //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

     #define  SERIAL_PORT_SPEED  115200

      unsigned long lastDisplay;
      unsigned long lastRate;
      int sampleCount;

      void setup()
      {
      int errcode;

      Serial.begin(SERIAL_PORT_SPEED);
      Wire.begin();
      imu = RTIMU::createIMU(&settings);                        // create the    imu object
      pressure = RTPressure::createPressure(&settings);         // create the  pressure sensor

      if (pressure == 0) {
      Serial.println("No pressure sensor has been configured - terminating");
        while (1) ;
       }

       Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu-   >IMUName());
       Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());
       if ((errcode = imu->IMUInit()) < 0) {
       Serial.print("Failed to init IMU: "); Serial.println(errcode);
       }

       if ((errcode = pressure->pressureInit()) < 0) {
       Serial.print("Failed to init pressure sensor: ");
       Serial.println(errcode);
       }

       if (imu->getCalibrationValid())
       Serial.println("Using compass calibration");
       else
       Serial.println("No valid compass calibration data");

        lastDisplay = lastRate = millis();
        sampleCount = 0;

        // Slerp power controls the fusion and can be between 0 and 1
        // 0 means that only gyros are used, 1 means that only accels/compass are used
       // In-between gives the fusion mix.

       fusion.setSlerpPower(0.02);

       // use of sensors in the fusion algorithm can be controlled here
       // change any of these to false to disable that sensor

        fusion.setGyroEnable(true);
        fusion.setAccelEnable(true);
        fusion.setCompassEnable(true);
        }

         void loop()
         {
         unsigned long now = millis();
         unsigned long delta;
         float latestPressure;
         float latestTemperature;
         int loopCount = 1;

          while (imu->IMURead()) {                                // get the latest data if ready yet
          // this flushes remaining data in case we are falling behind
          if (++loopCount >= 10)
             continue;

          fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
          sampleCount++;
          if ((delta = now - lastRate) >= 1000) {
          Serial.print("Sample rate: "); Serial.print(sampleCount);
          if (imu->IMUGyroBiasValid())
          Serial.println(", gyro bias valid");
          else
          Serial.println(", calculating gyro bias");

            sampleCount = 0;
            lastRate = now;
           }
           if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
            lastDisplay = now;
           //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());
                      // gyro data
            //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());
                         // accel data
           //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
              // compass data
            RTMath::displayRollPitchYaw("Pose:",   (RTVector3&)fusion.getFusionPose()); // fused output

            if (pressure->pressureRead(latestPressure, latestTemperature)) {
                Serial.print(", pressure: "); Serial.print(latestPressure);
                Serial.print(", temperature: ");
            Serial.print(latestTemperature);
            }
            Serial.println();
            }
            }
            }

EDITED CODE:

           #include <Wire.h>
           #include "I2Cdev.h"
           #include "RTIMUSettings.h"
           #include "RTIMU.h"
           #include "RTFusionRTQF.h"
           #include "RTPressure.h"
           #include "CalLib.h"
           #include <EEPROM.h>

           RTIMU *imu;                                           // the IMU object
          RTPressure *pressure;                                 // the pressure object
          RTFusionRTQF fusion;                                  // the fusion object
          RTIMUSettings settings;                               // the settings object

          //  DISPLAY_INTERVAL sets the rate at which results are displayed

          #define DISPLAY_INTERVAL  300                         // interval between   pose displays

         //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

         #define  SERIAL_PORT_SPEED  115200

        unsigned long lastDisplay;
        unsigned long lastRate;
        int sampleCount;

        // ================= MPU: 1 =================

       RTIMU *imu1;                                           // the IMU object
       RTPressure *pressure1;                                 // the pressure object
       RTFusionRTQF fusion1;                                  // the fusion object
       RTIMUSettings settings1;                               // the settings object

       unsigned long lastDisplay1;
       unsigned long lastRate1;
       int sampleCount1;

       const int CS_MAX = 2;
       const int CS[CS_MAX] = { 7, 8 };

       void setup()
       {
      for (int i = 0; i < CS_MAX; i++) {
      pinMode(CS[i], OUTPUT);
      digitalWrite(CS[i], HIGH);
      }

      int errcode;

      Serial.begin(SERIAL_PORT_SPEED);
      Wire.begin();
       imu = RTIMU::createIMU(&settings);                        // create the imu object
      pressure = RTPressure::createPressure(&settings);         // create the pressure sensor

      if (pressure == 0) {
      Serial.println("No pressure sensor has been configured - terminating");
      while (1) ;
       }

       Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu->IMUName());
       Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());

      for (int i = 0; i < CS_MAX; i++) {
      digitalWrite(CS[i], LOW);
      if ((errcode = imu->IMUInit()) < 0) {
      Serial.print("Failed to init IMU: "); Serial.println(errcode);
      }

      if ((errcode = pressure->pressureInit()) < 0) {
      Serial.print("Failed to init pressure sensor: "); Serial.println(errcode);
      }

      if (imu->getCalibrationValid())
        Serial.println("Using compass calibration");
      else
        Serial.println("No valid compass calibration data");

      lastDisplay = lastRate = millis();
      sampleCount = 0;

       // Slerp power controls the fusion and can be between 0 and 1
       // 0 means that only gyros are used, 1 means that only accels/compass are   used
      // In-between gives the fusion mix.

      fusion.setSlerpPower(0.02);

      // use of sensors in the fusion algorithm can be controlled here
      // change any of these to false to disable that sensor

       fusion.setGyroEnable(true);
       fusion.setAccelEnable(true);
       fusion.setCompassEnable(true);
       digitalWrite(CS[i], HIGH);
       }

       int errcode1;
       Serial.begin(SERIAL_PORT_SPEED);
       Wire.begin();
       imu1= RTIMU::createIMU(&settings1);                        // create the imu object
       pressure1 = RTPressure::createPressure(&settings1);         // create the pressure sensor

        if (pressure1 == 0) {
        Serial.println("No pressure sensor has been configured - terminating");
        while (1) ;
        }

        Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu1->IMUName());
        Serial.print(", pressure sensor "); Serial.println(pressure1->pressureName());

        for (int i = 0; i < CS_MAX; i++) {
        digitalWrite(CS[i], LOW);

        if ((errcode1 = imu1->IMUInit()) < 0) {
        Serial.print("Failed to init IMU1: "); Serial.println(errcode1);
        }

        if ((errcode1 = pressure1->pressureInit()) < 0) {
         Serial.print("Failed to init pressure sensor1: ");
         Serial.println(errcode1);
         }

         if (imu1->getCalibrationValid())
        Serial.println("Using compass calibration");
        else
        Serial.println("No valid compass calibration data1");

        lastDisplay1 = lastRate1 = millis();
        sampleCount1 = 0;

        // Slerp power controls the fusion and can be between 0 and 1
        // 0 means that only gyros are used, 1 means that only accels/compass are used
        // In-between gives the fusion mix.

        fusion1.setSlerpPower(0.02);

       // use of sensors in the fusion algorithm can be controlled here
       // change any of these to false to disable that sensor

         fusion1.setGyroEnable(true);
         fusion1.setAccelEnable(true);
         fusion1.setCompassEnable(true);

         digitalWrite(CS[i], HIGH);
         }
         }

         void loop()
         {
         unsigned long now = millis();
         unsigned long delta;
         float latestPressure;
         float latestTemperature;
         int loopCount = 1;

          while (imu->IMURead()) {                                // get the   latest data if ready yet
          // this flushes remaining data in case we are falling behind
          if (++loopCount >= 10)
            continue;

           fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
            sampleCount++;
            if ((delta = now - lastRate) >= 1000) {
            Serial.print("Sample rate: "); Serial.print(sampleCount);
            if (imu->IMUGyroBiasValid())
                Serial.println(", gyro bias valid");
            else
                Serial.println(", calculating gyro bias");

            sampleCount = 0;
            lastRate = now;
            }
            if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
            lastDisplay = now;
            //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());

             // gyro data
             //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());

             // accel data
            //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
            // compass data
              RTMath::displayRollPitchYaw("Pose:",
              (RTVector3&)fusion.getFusionPose()); // fused output

             if (pressure->pressureRead(latestPressure, latestTemperature)) {
                Serial.print(", pressure: "); Serial.print(latestPressure);
                Serial.print(", temperature: ");
                Serial.print(latestTemperature);
            }
            Serial.println();
            }
            }

           unsigned long now1 = millis();
          unsigned long delta1;
          float latestPressure1;
          float latestTemperature1;
          int loopCount1 = 1;

          while (imu1->IMURead()) {                                // get the latest data if ready yet
          // this flushes remaining data in case we are falling behind
          if (++loopCount1 >= 10)
            continue;

          fusion1.newIMUData(imu1->getGyro(), imu1->getAccel(), imu1-  >getCompass(), imu1->getTimestamp());
          sampleCount1++;
          if ((delta1 = now1 - lastRate1) >= 1000) {
            Serial.print("Sample rate: "); Serial.print(sampleCount1);
            if (imu1->IMUGyroBiasValid())
                Serial.println(", gyro bias valid");
            else
                Serial.println(", calculating gyro bias");

            sampleCount1 = 0;
            lastRate1 = now1;
        }
        if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
            lastDisplay1 = now1;
          //          RTMath::display("Gyro1:", (RTVector3&)imu1->getGyro());
          // gyro data
          //          RTMath::display("Accel1:", (RTVector3&)imu1->getAccel());
          // accel data
          //          RTMath::display("Mag1:", (RTVector3&)imu1->getCompass());
            // compass data
            RTMath::displayRollPitchYaw("Pose1:", (RTVector3&)fusion1.getFusionPose()); // fused output

            if (pressure1->pressureRead(latestPressure1, latestTemperature1)) {
                Serial.print(", pressure: "); Serial.print(latestPressure1);
                Serial.print(", temperature: "); Serial.print(latestTemperature1);
            }
            Serial.println();
        }
    }
}

title: How to connect two IMU in one arduino board?

Answers: 1

body:
Before editing the code to support an additional MPU9X50 you will need to figure out a way to address them on the I2C bus. Hopefully the MPU9X50 module you are using has a pin named AD0.

There are two basic solutions to multiple MPU9X50.

The first solution is to use the two different addresses. AD0 pin LOW on one and AD0 pin HIGH on the other. The sketch above would require two instances (imu), one for each module/address.

The second solution, which works for several modules, is to hold the AD0 pin LOW for the module that is addresses and all other HIGH. The setting must be handled by a digital pin. One for each module. They will be used as chip/module select. Below the example code assumes that the MPU I2C address is with the lowest bit LOW.

In the setup() initiate these pins to output mode and high. The example code uses pin 7 and 8.

    const int CS_MAX = 2;
    const int CS[CS_MAX] = { 7, 8 };

    void setup()
    {
       ...
       for (int i = 0; i < CS_MAX; i++) {
         pinMode(CS[i], OUTPUT);
         digitalWrite(CS[i], HIGH);
       }
       ...
    }

Set the digital pin LOW for the module you want to address before calling an MPU library function and back to HIGH afterwards.

    digitalWrite(CS[0], LOW);
    imu->someMemberFunction();
    digitalWrite(CS[0], HIGH);

If several functions are called in a block it can be convenient to run all of them per module. An example section from the setup:

    for (int i = 0; i < CS_MAX; i++) {
      digitalWrite(CS[i], LOW);

      if ((errcode = imu->IMUInit()) < 0) {
        Serial.print("Failed to init IMU: ");
        Serial.println(errcode);
      }

      if (imu->getCalibrationValid())
        Serial.println("Using compass calibration");
      else
        Serial.println("No valid compass calibration data");

      digitalWrite(CS[i], HIGH);
    }

Cheers!


body:
I have question about microphone and generating sound signal. I have microphone in my intercom at home. It is simple analog microphone, not digital.

What I want is to connect arduino analog output to the microphone and generate some signal that will be heard like a voice at least few words.

Is it possible to do this ? Or it would be quite hard ?

Please suggest the easiest way to implement this.

title: How to generate Analog Signal (Voice) to the microphone

Answers: 0