body:
I was thinking of buying another Arduino, and the Leonardo looks appropriate.

However I am confused! The [Comparative Tables](http://www.arduino.org/product/boards/comparative-table) seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)

There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?

I assume I can use the Uno Prototyping shield on the Leonardo.

title: Arduino Leonardo model differences

Answers: 1

body:
At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.

Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.

The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.

It's still the same chip, and still connected up in the same way.


body:
I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug

    int LED3 = 5;
    int LED4 = 6;

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

    int intervalLED3 = 500;
    int intervalLED4 = 500;

    void setup() {
        pinMode(LED3, OUTPUT);
        pinMode(LED4, OUTPUT);

          digitalWrite(LED3,LOW);
          digitalWrite(LED4,LOW);

    }

    void loop() {
      //unsigned long currentMillis = millis();
          for(int P=0;P<6;P++){
            //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
                analogWrite(LED3, 127);
                analogWrite(LED4, 254);
            delay(500);
                  //previousMillisLED3 = currentMillis;

          //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
                analogWrite(LED3, 254);
                analogWrite(LED4, 127);
           delay(500);
                 //previousMillisLED4 = currentMillis;
          }
    }

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

title: Millis...alternate flash

Answers: 3

body:
You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.

The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.

But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.

body:
Well, the for loop is useless. Then you need to plan your time cycle. For instance what you want is

    time(ms)  LED3  LED4
       0       127   254
     500       254   127
    1000 -> back to 0

So implement this. One way can be the one suggested by st2000:

    int LED3 = 5;
    int LED4 = 6;

    // just one tracking, since there is only one sequence
    unsigned long previousMillis=0;

    int endOfPhase1 = 500;
    int endOfPhase2 = 1000;

    void setup() {
     pinMode(LED3, OUTPUT);
     pinMode(LED4, OUTPUT);
     digitalWrite(LED3,LOW);
     digitalWrite(LED4,LOW);
    }

    void loop() {
     unsigned long currentMillis = millis();

     if ((currentMillis - previousMillis) < endOfPhase1) {
      analogWrite(LED3, 127);
      analogWrite(LED4, 254);
     }
     else if ((currentMillis - previousMillis) < endOfPhase2) {
      analogWrite(LED3, 254);
      analogWrite(LED4, 127);
     }
     else
      previousMillis += endOfPhase2;
    }

Just a small note about this: I tend to prefer summing the period instead of setting previousMillis to millis because this way small errors do not accumulate.

This way is the simplest, but the state machine oriented is the one I suggest you, since it is more powerful and you will reuse this a lot of times. Moreover it will detect the "change" of state, thus avoiding the continuous analogWrite (in the previous code the analogWrite instructions are executed a lot of times).

Just define a state machine as two states (state 1, where LED3 is 127 and LED4 is 254, and state 2, where LED3 is 254 and LED5 is 127). The transitions will be after 500ms in each state, but I'll make two separate constants so you can trim them later. Usually each state has a function to be performed when you enter the state, a function to run continuously, a function when you exit and one or more transitions. The way to perform this is

 1. calculate if there is a state change
 2. if there is, perform the exit functions of the previous state and the enter functions of the next state
 3. advance to the new state
 4. perform the actions to be done continuously in the new state

In our case just state transition, enter and advance should be implemented. Usually you use a switch case on a variable holding an index for the state. In this case, for instance,

    int LED3 = 5;
    int LED4 = 6;

    // just one tracking, since there is only one sequence
    unsigned long previousMillis=0;

    int state1duration = 500;
    int state2duration = 500;

    uint8_t state;

    void setup() {
     pinMode(LED3, OUTPUT);
     pinMode(LED4, OUTPUT);
     digitalWrite(LED3,LOW);
     digitalWrite(LED4,LOW);

     state = -1; // Invalid state, used to force a transition at startup
    }

    void loop() {
     unsigned long currentMillis = millis();

     // Check the transition
     uint8_t nextState = state;
     switch (state)
     {
     case 1: // Transition for state 1
      if ((currentMillis - previousMillis) >= state1duration)
      {
       nextState = 2;
       previousMillis += state1duration;
      }
      break;
     case 1: // Transition for state 2
      if ((currentMillis - previousMillis) >= state2duration)
      {
       nextState = 1;
       previousMillis += state2duration;
      }
      break;
     default: // When unknown state, go to state 1
      nextState = 1;
      break;
     }

     // If there is a change, perform the enter functions
     if (nextState != state)
     {
      switch (nextState) // enter functions of the next state
      {
      case 1: // Entering state 1
       analogWrite(LED3, 127);
          analogWrite(LED4, 254);
       break;
      case 2: // Entering state 2
       analogWrite(LED3, 254);
          analogWrite(LED4, 127);
       break;
      }
     }

     // Advance to the new state
     state = nextState;
    }

This can be more complicated, but believe me, it is not. Once you get what this means you will be able to solve a lot of problems this way.

According to my experience, never try to simplify this to your particular problem, since it will make things more complicated. Just add, when needed, the exit functions (before switch(nextState) put another switch on state) and the execution (after the advancing, put another switch on state) if needed.

body:
The final sub routine...I did move the counter to get a better result. The variable "ditchFlag" is set in an IF statement further up in the sketch.
The duration of the subroutine is a combination of the timers and the number in "count".

    void ditchDim() {
    while (ditchFlag == 1) {            //set to 1 when conditions are met

    unsigned long currentMillis = millis();

    if ((currentMillis - previousMillis) < endOfPhase1) {
        analogWrite(LED3, 127);
        analogWrite(LED4, 254);
    }
    else if ((currentMillis - previousMillis) < endOfPhase2) {
        analogWrite(LED3, 254);
        analogWrite(LED4, 127);
    }else{
      count = (count+1);
        previousMillis += endOfPhase2;
        }
          if (count == 5) {
            count = 0;
            ditchFlag = 0;
            return;
        }
      }
    }

thanks
Doug


body:
I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.

My code:

    randNumber = random(2);

    if(randNumber == 0){
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
    }

    if (btnAddFirst.pressed() && randNumber == 0){
      Serial.println("You did it");
    }
    else {
      Serial.println("u failed");
    }

title: I am making an easy game but something in my code is wrong

Answers: 1

body:
Don't use `delay()`, since nothing can happen (not even reading a button) while that delay is running.

Instead use `millis()` as in the `BlinkWithoutDelay` example sketch.


body: The HC-12 module has 100 possible channels starting at 433 MHz. Can someone tell me how to program the Arduino to use multiple channels at the same time? My goal is to build an RC transmitter with Arduino and an HC-12 module for a quadcopter. Therefore I need 6 channels, like a normal transmitter does. Thanks in advance!

title: Multichannel communication with Arduino and HC-12 transmitter

Answers: 2

body:
I believe you are misunderstanding what it means by channels. The HC-12 can transmit on up to 100 channels, which means different frequencies under the 433 MHz band. For example 433.05 MHz or 433.15 MHz. This is so multiple HC-12 modules can be used next to each other and only the module receiving on the channel of the transmitter will receive the data broadcast.

What you need to do for your quadcopter is send an array of bytes that begins with a constant, followed by the data you need (a packet). Example:

    byte packet[] = {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}

    // in your loop
    packet[1] = ; HOW MUCH THE ENGINE IS THROTTLED
    packet[2] = ; HOW FAR THE CONTROL TO GO FORWARD IS DEPRESSED
    // etc

Iterate through this array writing the data through the serial port to the HC-12. Whenever your receiver detects the constant (in this case 0x00) read the values that follow as the controls for the quadcopter.

body: I'm starting on HC-12 myself and as I understand, you can only access 1 module at a time by selecting each modules individual channel, assuming you have set the modules to separate channels, you cannot receive data from multiple modules even if set to the same channel at the same time, it would just be a jumble of unsortable data. But you may be able to select one channel after another and collect each set of data separately 1 thru 6 and then extract the information you need by using AT+C001,002,etc. Or you could use 1 RX and program the on board arduino to cycle thru the 6 motors sequentially and collect the 6 sets of data that way. this question would be easier to answer with a diagram of you proposed circuit.


body: I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries->rfid-master->bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries->rfid-master->examples->ReadAndWrite->blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

title: How to convert Arduino example sketch to a complete c++ project?

Answers: 1

body:
Basically *.ino is *.cpp without headers. So you can

 - rename it to *.cpp,
 - If you have any functions which are used before they have been defined, provide declarations for each function before its first use
 - `#include <Arduino.h>` on the top
 - `#include <Wire.h>` if you are using Wire and so on

and you have "normal" CPP file.

If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)

You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project

the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there


body:
Arduino: 1.8.0 (Windows 10), Board: "Arduino/Genuino Uno"

c:\program files (x86)\arduino\hardware\tools\avr\bin\../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

title: Win10 64bit, IDE 1.8.0 back to IDE 1.6.13 won't compile anything including Blink. 1.6.12 does compile

Answers: 1

body: Try locating the code file in explorer.exe, go to its properties and check if the system has full access to the file. Just to be sure, run the Arduino IDe as an administrator.


body:
I am trying to find the simplest way to connect multiple (preferably around 10-20) IMU sensors to one controller. There are two constraints: sampling at 60Hz and reasonably simple wiring as I want to put it on clothes.

I am totally new to the Arduino world, please let me know what other details I should provide.

It seems that just having multiple IMUs on the I2C bus would work great, but they usually all come with the same address.

So, the solutions I found so far:

* Using several different IMUs from different companies - hard to find 20 of them
* Using a multiplexer - requires star-like wiring topology.
* Using multiple controllers - inefficient and doesn't seem right.

For now, the solution with a multiplexer seems to me the most reasonable, but is there any other way I am missing? Can I somehow produce IMUs with, say, 16 different addresses and wire them all together to one I2C?

Thanks for your help!

title: Multiple I2C sensors with the same address

Answers: 3

body:
If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's `AD0` pin to a separate digital pin on the Arduino[*]. When you want to read from a specific IMU, set all `AD0`s to `HIGH`, except the one you want to read to `LOW`. All the IMUs with `AD0` set to `HIGH` with have an I2C address of 0x69, whereas the only one on `LOW` will have an address of 0x68.

If you want to read them all, you just go through a loop and set the one you want to `LOW`, the others to `HIGH`, and you're set.

[*] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells [Maple clones for 6 bucks][1]. ElecFreaks [sells them for 9 bucks][2]. You could use the 16 pins at the bottom for the `AD0`s.

This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.

Reference: https://github.com/PaulStoffregen/FreeIMU_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf

  [1]: https://www.itead.cc/iteadmaple.html
  [2]: http://www.elecfreaks.com/estore/efmaple-100-leaf-maple-rev5-compatible.html

body: You can also get I2C Multiplexers such as the TCA9545A that can split one I2C line into 4 buses. I have connected up to 9 MPU9150 on one line with that.

body:
Another way is to use a **software emulation of the I2C interface** so that any of the digital I/O pins may act as an I2C pin. One well-written library you can use for this is **`SoftWire`** by Steven Marple. It can be installed via the Arduino Library Manager or directly from its GitHub repository [here][1].

With this, you can select arbitrary pairs of pins to act as SDA and SCL for each I2C device and then you can communicate with each device individually.

Note that with this method, you need two digital pins for each I2C device. In that sense, I believe @dda's answer is the best in regard to these IMUs in question.

  [1]: https://github.com/stevemarple/SoftWire


body:
I have shift register 74HC595. I added 7 push buttons from Q1-7 and the 8th to ground. On the other side which pin of the register will go to Arduino pin 2? And wich one to the 5v pin?

How can I read one button at a time in the code because on the Arduino it is just 1 pin?

title: Arduino uno shift register

Answers: 3

body:
A shift register is an output device. You won't be able to "Read" 7 push buttons in this way.

A shift register like that is for taking a "series" of bits on one wire and parallelizing them onto 8 wires.

It does not work in reverse. The reverse is called a multiplexer.

body:
You cannot.  The 74HC595 does not have parallel inputs, such as you would need to read from 7 switches.

You need a parallel-in, serial-out shift register, such as a [CD4021B][1].  You can find details on how to use it with an Arduino [here][2]

> How can I read one button at a time in the code because on the Arduino it is just 1 pin?

Basically you "clock in" the data by toggling a clock line - each toggle presents the next bit, which you read in using your one digital input.

  [1]: http://www.ti.com/product/CD4021B
  [2]: https://www.arduino.cc/en/Tutorial/ShiftIn

body:
[Shift registers](https://en.wikipedia.org/wiki/Shift_register) are available in several flavors:

• [Serial-in, Serial-out (SISO)](https://en.wikipedia.org/wiki/Shift_register#Serial-in_Serial-out_.28SISO.29) units like 7491 have serial input and output.

• [Serial-in, parallel-out (SIPO)](https://en.wikipedia.org/wiki/Shift_register#Serial-in_parallel-out_.28SIPO.29) units like 74164 have serial input, parallel output.

• [Parallel-in, Serial-out (PISO)](https://en.wikipedia.org/wiki/Shift_register#Parallel-in_Serial-out_.28PISO.29) units like 74165 or 74166 (etc. – just search for shift register in a [list of 7400 series integrated circuits](https://en.wikipedia.org/wiki/List_of_7400_series_integrated_circuits) or other series) have parallel input, serial output.

Other variations: The 7494, 7495, and 7499 have serial and parallel input, parallel output.  The 7499 also has serial output.  The 7494 and 7499 can shift right or left.  (Most of the models listed earlier only shift one direction.)

Anyhow, by using an appropriate shift register, along with a bunch of resistors and diodes, it is possible to read lots of switches.  As suggested in another answer, you might want to ask about how to do that.


body:
The system voltage on my arduino 101 is published at 3.3V, even though it also has a 5V output pin.

My Seeedstudio touchscreen is supposedly a 5V device. http://wiki.seeed.cc/2.8inch_TFT_Touch_Shield_v2.0/

I believe I've successfully ported the library for this touchscreen to the 101 because it now runs and compiles on both the 101 and the Mega, although it gives erroneous values on the 101. Could it be because of this voltage difference? is there any way to fix it?

Edit- I should add that the 101 is labeled as "5V tolerant".

Edit II: I've found a pretty informative review that explains a little bit about how the 101 is supposed to work with 5V peripherals. I'm not sure though how it could work in cases where a shield does not recognize 3.3V as logic high. Usually 3.3V is right around the cutoff voltage for many circuits. http://www.tweaktown.com/reviews/7706/intel-curie-based-arduino-101-programmable-microcontroller-review/index2.html

title: System voltages: Can I use a 5V touchscreen shield on a 3.3V arduino?

Answers: 1

body:
You'll probably need a fairly common device known as a logic level converter.  One such example, in breakout board form, can be found here: https://www.sparkfun.com/products/12009

There are tons of other options depending on what exactly you need.


body:
Consider a computer monitor hanging on a wall. Next to it is an Arduino Uno with a wifi. Is it possible to create something like this? Using wifi it should be possible to send data (images) to Arduino. This will be output to a monitor, like an image gallery. Images can be any type (videos included).

Is it possible? Where does one start?

Thank you.

title: Show images on a monitor using Arduino via Wifi

Answers: 3

body:
I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.

You'd better look into doing this with something like a Raspberry Pi.

body: What you want is the [GameDuino shield](http://excamera.com/sphinx/gameduino/) which gives you a full VGA experience on your Arduino. Also good for making games with.

body:
For the novice/intermediate, this is going to take way too much time and effort to meet the requirements you have asked with an Arduino Uno (if it is even possible).

May I suggest a [Raspberry Pi][1] instead.

The Raspberry Pi ([depending on the model][2]) has multiple video outputs:

 - HDMI
 - Composite video
 - LCD display

Each of these video outputs require very little effort to get going.

Adding WiFi capability requires just a USB WiFi dongle (and possibly downloading a driver) a bit of set-up and that about it. The RPi 3 (Model B) has on-board WiFi so you won't need the dongle.

What you want is very similar to a digital photo frame, so I would search for people who have already done that using google. I imagine that there would be plenty of free code/software out there on the internet.

All of this is a lot easier on the Raspberry Pi compared to using the Arduino.

----------
[pcDuino][3] is another hardware platform much like the Raspberry Pi that would meet your requirements. The pcDuino is less popular than the Raspberry Pi and so there may be less open source code out there in cyberspace - but it would still be worth a try.

  [1]: https://www.raspberrypi.org/
  [2]: https://en.wikipedia.org/wiki/Raspberry_Pi#Specifications
  [3]: http://www.linksprite.com/linksprite-pcduino/


body:
I currently have an Arduino Ethernet Shield which is Mega Compatible. I've found on the Arduino Ethernet Library https://www.arduino.cc/en/Reference/Ethernet that the Shield uses different Pins on the Arduino Uno and Arduino Mega. How is this possible? The Ethernet shield isn't connected to those pins mentioned.

Arduino Uno:
Pin: 13 - SCK
Pin: 12 - MISO
Pin: 11 - MOSI
Pin: 10 - SS for Ethernet Controller

Pin: 4 - SS for SD Card

Arduino Mega:
Pin: 52 - SCK
Pin: 50 - MISO
Pin: 51 - MOSI
Pin: 53 - SS for Ethernet Controller

Pin: 4 - SS for SD Card

[![Arduino Mega Pins][1]][1]

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

title: Arduino Ethernet Shield on Arduino Mega Pin Usage!

Answers: 2

body:
Those 4 pins D50 to D53 are the ICSP pins which appear twice on the MEGA; the Ethernet Shield uses the second set of connections located in the middle of the Mega board.

The header files gets told (by the Arduino IDE) that the board is a MEGA so the compiler uses those pin numbers to connect.

body:
Firstly, I am assuming you are using an Ethernet Shield similar to the [Arduino Ethernet Shield][1].

Secondly, I assume that you are referring to the following quote on the [Ethernet Library page][2]:

>The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

This communication interface is called SPI.

The Ethernet Shield connects to the SPI interface (ie MISO, MOSI, SCK) using the in-circuit Serial Programming (ICSP) pins which are also connected to the SPI interface pins (ie. pins 50, 51, and 52)

[![Underside of Ethernet shield][3]][3]

As noted in the above quote, pin 53 is not used as the SS pin (but needs to be kept as an output pin and not used). Pin 10 is used instead for the ethernet SS pin on both the Uno and Mega.

  [1]: https://store.arduino.cc/usa/arduino-ethernet-shield-2
  [2]: https://www.arduino.cc/en/Reference/Ethernet
  [3]: https://i.stack.imgur.com/xc9Ro.jpg


body:
Recently I have been experimenting with battery powered sensor (mySensors).

I created node with 3.3V Arduino Pro Mini (ATMega328P @ 8Mhz with nordic radio chip and BME280 sensor) and successfully programed it many times using either USBAsp programmer or serial (to USB) programmer.

I wanted to lower power consumption and so I disconnected power led and burned fuses as follows:
lfuse 62
hfuse DA
efuse 7

It worked successfully and I recompiled the sketch and upload it with USBasp.
I got an error that data cant be verified. It was late in the night so I jumped to Internet and googled it. In one forum I found, post (which I am unable to find again) that stated the he was able to upload sketch when he switched programmer to 5V. (Power was connected to Vcc)

I did that and it worked fine.

Than I tried to make change to sketch and upload it again (on 3,3V) and again got verification error so I unplugged programmer and switched back to 5V.

When I did that, the device stopped answering.

I regularly used this command to check that device responds and see fuses

    avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cusbasp -Pusb

What i did

 1. Checked wiring.
 2. Tried program fuses on blank new arduino - worked (programmer is
    fine)
 3. Measured voltage ok

 4. Measured current (its around 4mA, I see it as the board is not
    sleeping and is actively doing something)
 5. I noticed that when I issue command mentioned above the on board led
    quickly lights up and then goes off again.
 6. I tried to power it from raw, from Vcc and from Vcc on serial hader (picture).
 7. I measured power on Vcc when connected to Raw pin and it reads 3.3V
    so power regulator should be ok.
 8. I used -B10 switch to averdude with no luck

My question is

 1. Is it possible that I burned the ATMega chip?
 2. Is it possible that I see target not answering because of USBAsp is unable to lower programming frequency? (warning: cannot set sck period. please check for usbasp firmware update.)

Please suggest if there is anything I can try before throwing it out.

Thank you.

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

  [2]: https://i.stack.imgur.com/1UM5z.jpg
  [3]: https://i.stack.imgur.com/ltUeM.jpg

**EDIT 2017-01-07**
I was able to brick another board.
I think that the programmer is the cause.

I tried to upload bootloader with fuses from arduino and it failed with verification error.

I was able to burn bootloader from command line after seting fuses and restarting the board.

When I tried to upload the program it I got

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0000
             0x00 != 0x0c
    avrdude: verification error; content mismatch

    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: safemode: lfuse changed! Was 62, and is now 0
    Would you like this fuse to be changed back? [y/n] n
    avrdude: safemode: hfuse changed! Was da, and is now 0
    Would you like this fuse to be changed back? [y/n] n
    avrdude: safemode: efuse changed! Was 7, and is now 0
    Would you like this fuse to be changed back? [y/n] n
    avrdude: safemode: Fuses OK (H:07, E:DA, L:62)

I answered yes because in in earlier attempts it just froze.

Now the board is in same condition as the first one.

Is it possible to revive it?
Thanks.

title: Arduino pro mini (clone) @1Mhz target does not answer

Answers: 1

body:
I am closing this thread.

The board is probably not destroyed, more likely are fused corrupted.
There are ways of reviving ATMega328 chip and program fuses back its called [high voltage programming][1]. You need to probably unsolder the chip or [modify your board][2] (post from tontrack).

Also if you are wondering what to do or not to your Arduino board here is quite interesting page (you wil find it in comment).

I did not found a way how it could have happen but it did.

Anyway Iam done with UsbAsp programmer and ordered AVR pocket programmer. Until it arrives I stop any more attempts.

Hope this helps somebody.

  [1]: http://www.gammon.com.au/forum/?id=12898
  [2]: https://forum.arduino.cc/index.php?topic=282705.15


body: What are the benchmarks (MIPS) of an Arduino Uno (ATmega32P) and Arduino Nano 3.0 (Atmega328) @ 1.6MHz?

title: Arduino Nano 3.0 and Arduino Uno Benchmarks

Answers: 2

body:
Do you mean 16MzHz?

Benchmarks are [here][1].

  [1]: https://www.arduino.cc/en/Products/Compare

body:
ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.

That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle.  A fair number of memory access instructions take 2 cycles.  A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles.  Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow.  For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's [AVR Instruction Set Manual, doc0856 at atmel.com](http://www.atmel.com/images/Atmel-0856-AVR-Instruction-Set-Manual.pdf).

Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.


body:
I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.

Here's my configuration:

- Arduino connected to a computer via USB cable (serial connection working)
- ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
- ESP-01 powered with external battery + capacitor to ensure sufficient current
- I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
- I've tried 3 different ESP modules

Here's how things work:

- Arduino sends back every received UART transmission so that I can monitor the whole thing.
- I can send messages to Arduino from a terminal on the PC and Arduino responds.
- I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
- When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
- When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
- When I connect CH_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd.
invalid
- The baud rate is correct (115200) since I can only read that invalid message on this rate

title: ESP-01 won't start correctly

Answers: 1

body: Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.


body:
Like I said in the subject, I would like to know the equivalent for the instruction:

    PORTB |= 0x01;
    PORTB &= ~0x01;

More precisely I was using it to trigger a fast pulse conversion on my shield-ADC on an Arduino Uno. Now I am using an Arduino Mega 2560.

Can you write the exact same instruction for ATMega2560?

title: Equivalent for PORTB in Arduino Mega 2560

Answers: 2

body:
This code sends a pulse on pin PB0, which on the Uno is equivalent to
digital 8. On the Mega, digital 8 is PH5, thus you would write

    PORTH |= _BV(PH5);
    PORTH &= ~_BV(PH5);

The equivalence between the Arduino pins and the AVR pins is provided in
the [official
documentation](https://www.arduino.cc/en/Hacking/PinMapping2560), but
there are nicer versions at pighixxx.com:

* [Uno pinout](https://web.archive.org/web/20180204145141/http://www.pighixxx.com/test/portfolio-items/uno/)
* [Mega pinout](https://web.archive.org/web/20171005020517/http://www.pighixxx.com/test/portfolio-items/mega/)

body:
The other answer has provided correct information and useful documentation on the question as asked.  This answer uses a slightly more portable method of producing a brief pulse on a given digital pin.

This more-portable method uses some standard (although not well-documented at arduino.cc) functions to get port numbers, port pointers, and bit masks from a pin number.  These functions – [`digitalPinToPort()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html), [`portInputRegister()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/portInputRegister.html), and [`digitalPinToBitMask()`](http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToBitMask.html)– can be used at run time to compute physical ports and pins from Arduino pin numbers.  In some cases the computation could occur at compile time if compiler is smart enough or is allowed to optimize.  But avr-gcc as configured for the Arduino IDE is not so allowed, which is a reasonable default for embedded programming.

This method also uses the fact that an AVR pin – as on most Atmel-based Arduinos – will toggle when you write a 1 to its bit in its input register.  For example, see §14.1 in Atmel doc8271, the ATmega48A/PA/88A/PA/168A/PA/328/P datasheet, which states:
>Three I/O memory address locations are allocated for each port, one each for the Data Register – PORTx, Data Direction Register – DDRx, and the Port Input Pins – PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, **writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register**. ...

---
# Example program

    /*  jiw - Jan 2017 - toggle Arduino digital pin 8 several ways
    Re: http://arduino.stackexchange.com/questions/33033/equivalent-for-portb-in-arduino-mega-2560 */
    volatile uint8_t *portofpin;
    uint8_t bitofpin;
    void setup() {
      pinMode(8, OUTPUT);       // Set pin as output
      portofpin = portInputRegister(digitalPinToPort(8));
      bitofpin = digitalPinToBitMask(8);
    }
    void udelay() {
      delayMicroseconds(5);
    }
    void loop() {
      PORTB |= 0x01;        // Set Uno pin 8
      PORTB &= ~0x01;       // Clear Uno pin 8
      udelay();
      PINB = 1;         // Toggle Uno pin 8
      PINB = 1;         // Toggle Uno pin 8
      udelay();
      PINB = bitofpin;      // Toggle Uno pin 8
      PINB = bitofpin;      // Toggle Uno pin 8
      udelay();
      *portofpin = bitofpin;    // Toggle Arduino pin 8
      *portofpin = bitofpin;    // Toggle Arduino pin 8
      udelay();
    }

---
# Compilation on Uno
`loop()`, from compilation of the example program for an Uno board:

    void loop() {
      PORTB |= 0x01;                // Set Uno pin 8
     10e:   28 9a           sbi     0x05, 0 ; 5
      PORTB &= ~0x01;               // Clear Uno pin 8
     110:   28 98           cbi     0x05, 0 ; 5
      udelay();
     112:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
      PINB = 1;                     // Toggle Uno pin 8
     116:   81 e0           ldi     r24, 0x01       ; 1
     118:   83 b9           out     0x03, r24       ; 3
      PINB = 1;                     // Toggle Uno pin 8
     11a:   83 b9           out     0x03, r24       ; 3
      udelay();
     11c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
      PINB = bitofpin;              // Toggle Uno pin 8
     120:   80 91 00 01     lds     r24, 0x0100
     124:   83 b9           out     0x03, r24       ; 3
      PINB = bitofpin;              // Toggle Uno pin 8
     126:   80 91 00 01     lds     r24, 0x0100
     12a:   83 b9           out     0x03, r24       ; 3
      udelay();
     12c:   0e 94 83 00     call    0x106   ; 0x106 <_Z6udelayv>
      *portofpin = bitofpin;        // Toggle Arduino pin 8
     130:   e0 91 01 01     lds     r30, 0x0101
     134:   f0 91 02 01     lds     r31, 0x0102
     138:   80 91 00 01     lds     r24, 0x0100
     13c:   80 83           st      Z, r24
      *portofpin = bitofpin;        // Toggle Arduino pin 8
     13e:   e0 91 01 01     lds     r30, 0x0101
     142:   f0 91 02 01     lds     r31, 0x0102
     146:   80 91 00 01     lds     r24, 0x0100
     14a:   80 83           st      Z, r24
      udelay();
     14c:   0c 94 83 00     jmp     0x106   ; 0x106 <_Z6udelayv>

As you can see in the above, instead of using read/modify/write sequences to implement `PORTB |= 0x01; PORTB &= ~0x01;`, the compiler produced `sbi 0x05,0; cbi 0x05,0;`, to directly set and then clear bit 0 of register 5, PORTB.  This uses 4 clock cycles total, producing a pulse that's high for 2 cycles.

avr-gcc implemented `PINB = 1; PINB = 1;` via `ldi r24, 1; out 3,r24; out 3,r24`, which takes 3 cycles total and produces a pulse that's high for 1 cycle.

It implemented `PINB = bitofpin; PINB = bitofpin;` via `lds r24, 0x0100; out 3,r24; lds r24, 0x0100; out 3,r24`, which takes 6 cycles total and produces a pulse that's high for 3 cycles.  (In `setup()`, the value of `bitofpin` was stored in RAM location 0x100, and the value of `portofpin` was stored in 0x101, 0x102.)

Finally, it implemented `*portofpin = bitofpin; *portofpin = bitofpin;` via a six-instruction sequence that takes 14 cycles and produces a pulse that's high for 7 cycles.  Obviously, the compiler could have produced a 4-instruction sequence (by not reloading r30, r31, and r24) that takes 8 cycles and a pulse that's high for 1 cycle, but it didn't.

---
# Compilation on Mega
`loop()`, from compilation of the example program for a Mega or Mega 2560 board:

    void loop() {
      PORTB |= 0x01;                // Set Uno pin 8
     218:   28 9a           sbi     0x05, 0 ; 5
      PORTB &= ~0x01;               // Clear Uno pin 8
     21a:   28 98           cbi     0x05, 0 ; 5
      udelay();
     21c:   fa df           rcall   .-12            ; 0x212 <_Z6udelayv>
     21e:   81 e0           ldi     r24, 0x01       ; 1
      PINB = 1;                     // Toggle Uno pin 8
     220:   83 b9           out     0x03, r24       ; 3
     222:   83 b9           out     0x03, r24       ; 3
      PINB = 1;                     // Toggle Uno pin 8
     224:   f6 df           rcall   .-20            ; 0x212 <_Z6udelayv>
      udelay();
     226:   80 91 00 02     lds     r24, 0x0200
      PINB = bitofpin;              // Toggle Uno pin 8
     22a:   83 b9           out     0x03, r24       ; 3
     22c:   80 91 00 02     lds     r24, 0x0200
      PINB = bitofpin;              // Toggle Uno pin 8
     230:   83 b9           out     0x03, r24       ; 3
     232:   ef df           rcall   .-34            ; 0x212 <_Z6udelayv>
     234:   e0 91 01 02     lds     r30, 0x0201
      udelay();
     238:   f0 91 02 02     lds     r31, 0x0202
      *portofpin = bitofpin;        // Toggle Arduino pin 8
     23c:   80 91 00 02     lds     r24, 0x0200
     240:   80 83           st      Z, r24
     242:   e0 91 01 02     lds     r30, 0x0201
     246:   f0 91 02 02     lds     r31, 0x0202
      *portofpin = bitofpin;        // Toggle Arduino pin 8
     24a:   80 91 00 02     lds     r24, 0x0200
     24e:   80 83           st      Z, r24
     250:   e0 cf           rjmp    .-64            ; 0x212 <_Z6udelayv>

The assembly code for Mega is much the same as that for the Uno, except that `bitofpin` and `portofpin` values were stored in RAM 0x200–0x202 instead of 0x100–0x102, and `rcall` or `rjmp` was used to call `udelay();`, instead of `call` or `jmp`.

---

# Making assembly listings

To make assembly listing files for a program, use a command like

    avr-objdump -CSI$PWD $TMPPATH/togglepin8.cpp.elf > togglepin8.ino.mega.asm

where `$PWD` represents the current working directory that contains a sketch like `togglepin8.ino`, and `$TMPPATH` represents whatever temporary directory the IDE stuck the source in to compile and link it.  The C switch (not used for above listings) tells avr-objdump to demangle symbols.  Switch S says to display source code intermixed with disassembly if possible.  Switch I tells location of source code.

---

# Conditional compilation

Conditional compilation is another way to make the source code portable to several Arduinos.  For example, near the beginning of the sketch one could include the following `#ifdef` and `#define` statements to set up `BITOFPIN` and `PORTOFPIN` values for later use:

    #ifdef ARDUINO_AVR_UNO
    #define BITOFPIN  1
    #define PORTOFPIN PINB
    #endif
    #ifdef ARDUINO_AVR_MEGA2560
    #define BITOFPIN  _BV(PH5)
    #define PORTOFPIN PINH
    #endif

To find out what board-dependent symbols are defined at compile time, turn on verbose output during compilation and look for flags of the form `-Dsym=val`.


body:
I'm developing an computacional module to create risk maps in agriculture, I am using one arduino mega as "GreenSeeker", generating "fake" data to transmit via RS232 connection to one Raspberry PI, where she is process the data and generate the maps with GPS coordinates.

But, I have this cable.

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

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

I need to transmit data throught Arduino mega, and catch this data in the Raspberry PI.

I`ve have doubt about where connect the Serials pins on Arduino, the USB go on connect on the Raspberry PI USB, and the Serial go on Arduino, i need the right pins and where to connect them, and some code example.

title: RS232-TTL Data Transmission

Answers: 1

body:
I think you just want a normal USB A-B cable, exactly like you'd use on a PC.[![enter image description here][1]][1]

You probably could use the cable you picture, but you'd need a female DB-9 connector.  If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.

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


body:
I am struggling to get my head around why this just won't work. In my simple mind this simple sketch should do as it's told. But I am obviously missing something fundamental.

If anyone could shed some light on what I am doing wrong that would be very good!

The sketch is just to control a relay by typing on or off into the serial monitor. However although it uploads, all I get is the `Serial.println` repeating and no action on the physical relay.

I can manage to control things over serial by using the switch, case statements but I wanted to try it using full words rather than single chars and also using IF statements etc.

Thanks in advance!

***EDIT***
I just changed the string inputs to a char input and `serial.readstring` to just `serial.read` and it works with just entering a 1 or a 2 for example. So to re-ask my question - how can I get it to respond the same but using words? Thanks!

    int relay=8;
    String serialInput;

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

    void loop() {
      Serial.println("To toggle relay enter on or off");
      while (Serial.available()==0) {}
      serialInput = Serial.readString();
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      }
      if(serialInput=="off") {
        digitalWrite(relay, LOW);
      }
    }

title: Need help with the basics on serial control

Answers: 1

body:
You are assuming that `Serial.readString()` will magically know how long a string you meant to send, and wait until it's all there.  It doesn't guarantee that.

If your PC uses Linux or Mac, you can use `Serial.readStringUntil('\n')`, which will read until a line end, and send `on<ENTER>` as your command.

If you use Windows, the line endings are `\r\n` so it's a bit more awkward.  Build up your string piece by piece, perhaps

    int relay=8;
    String serialInput;

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

    void loop() {
      if (Serial.available()) {
        char c = Serial.read();   // get one byte from serial buffer
        if ('\r'==c || '\n'==c) {
          // End of line - process the string
          if(serialInput=="on") {
            digitalWrite(relay, HIGH);
          } else if (serialInput=="off") {
            digitalWrite(relay, LOW);
          }
          serialInput = "";
        } else {
          serialInput += c;     // add it to readString
        }
      }
    }

Brief description of how it works:

The string `SerialInput` starts empty.  We do the following repeatedly:

 * If there is a character available on the serial port, read it.
 * If it is not an end-of-line character, add it to the end of our string
 * If it IS an end-of-line character, we know we've got to the end of the line, so...
   * check whether it matches one of our "target" strings, and act on it if so
   * clear it back to an empty string


body: I need to create a library file for Arduino. While surfing the Internet, it shows me to use C, C++. Is a C++/C compiler mandatory to create library files in Arduino? Or we can use the Arduino IDE to create library files?

title: Creating Arduino library file

Answers: 2

body:
The Arduino IDE has a compiler, and will in the end compile the library with whatever `.ino` script you'll write. But you don't need any compiler to write a library. All you need is a text editor, and produce `.cpp` and `.h` files.

However when you test the library, you'll have to use the Arduino IDE to compile it.

body: Libraries are just text files. Use your favourite text editor (such as Sublime Text, Notepad++, etc. NOT a word processor like Word) to create and edit them. It is up to the IDE to compile them for you. You don't need anything else.


body:
I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?

Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module

title: How many modules can an Arduino Nano v3 support (in code)?

Answers: 2

body:
The devices will require some code to make them work and there is a chance, depending on how you write the code, that this may consume all the available RAM on the chip.  However I doubt you will go to more than 60% if you use the standard libraries for those devices, but there is only one way to find out...

Get the libraries for the devices and look at the examples for each device.  You should be able to hack an "example" of your own that calls all 4 examples in the main loop().  This should give you an idea of how much memory you are going to use.

If you use too much it might be possible to snip pieces away from the libraries, the LCD will probably have font tables that you don't need for instance.  Or you could use an alternative Arduino.

body:
The number of modules isn't really relevant; your PC deals with that during compilation and linking. The unbreakable requirement is that the total size of all the modules not exceed the size of available Flash memory.

The Bluetooth module won't need a library module unless you use SoftwareSerial to make another port for it. The two sensors' library footprints won't be too big. The LCD probably has at least one character table and maybe several sizes of each of several fonts. That's likely to be your largest one.

I always find microcontrollers' RAM size to impose much more stringent requirements than their Flash sizes.


body:
I want to use Arduino DUE board as a FTDI programmer.

The task is to program ESP32 module which is connected to the Arduino Serial port.

I can use only DUE Native port. There is no DUE programming port in my design.

title: Arduino DUE as a FTDI programmer

Answers: 1

body:
Yes, it is possible, and not too difficult.
Also, the native port is a lot faster than the programming  port ;)

All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.

This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)

    void setup(void) {
      SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                             //the serial baud here should match the speed that
                             //you try to upload at to the esp32
      Serial1.begin(9600);   //change the Serial port to suit your needs
    }
    void loop(){
       if(SerialUSB.available()> 0){
        Serial1.write(SerialUSB.read());
       }
       if(Serial1.available()> 0){
        SerialUSB.write(Serial1.read());
       }
    }


body:
I have an nRF8001 Bluefruit LE Breakout module and when I check images on how to wire it, the schematic looks like this with the 5V connection:

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

I was wondering whether it was possible to use the 3.3V instead. I looked at the documentation, it says this:

>By connecting 5.0V on the VIN pin, all of the signals will be level shifted between 5V for the Arduino and 3.3V for the nRF8001, meaning you don't need to worry about damaging the IC by providing logic levels that it can't safely handle.

And this, which confirms that it works, right?

>If you are using 3.3V logic, simply connect 3.3V from your development board to the VIN pin on the nRF8001 breakout.

I am pretty new, so I want to make sure, so I do not destroy any modules.

https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up

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

title: Can I use the nRF8001 Bluefruit LE Breakout on 3.3V instead of 5V on my Arduino Uno?

Answers: 1

body: Yes. That nRF8001 board runs on 3.3V. And do make sure that using it with a 5V-Arduino, they put a regulator that steps down 5V to 3.3V. Which is why if you have 3.3V already, you connect it to Vin, and you're good to go.


body:
An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).

I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.

But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.

Was I thinking wrong?

If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?

title: How to flash an ATmega directly without a dedicated flashing device?

Answers: 2

body:
The compiler doesn't do that, a separate program does that.  For most ATMegas and most people, the program that does this is called avrdude.  It interfaces with your ISP and transfers the code when you give it appropriate settings.  See here:

http://www.ladyada.net/learn/avr/avrdude.html

So you get the hex from your compiler, and send that through avrdude to the chip using your ISP.  At no point is the MicroSD necessary.  FWIW, the ATMega must have its code loaded into its flash memory.  It cannot run code from the Micro SD.

body:
Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.

The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using `objdump`.

That HEX file is then loaded by another program, `avrdude`, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.

It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.

It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.


body:
I'm new to Arduino..

I'm currently trying to create a GPRS connection through SIM card. For that, I need to connect a serial UART port.

I don't know how to define the Serial UART. Could you please help me with that?

title: Defining Serial UART

Answers: 2

body:
In the setup function you will need to call the [`Serial.begin()`][1] function.

To receive a serial character you should call the [`Serial.available()`][2] function inside an if statement.

To send a character you can either use the [`Serial.write()`][3] or [`Serial.print()`][4] functions.

Below is a simple example program that will echo the characters back to the PC.

    //-------------------------
    // Simple serial loopback
    //-------------------------

    void setup()
    {
      // initialize the serial communication:
      Serial.begin(9600);
    }

    void loop()
    {
      byte inChar;

      // check if data has been sent from the computer:
      if (Serial.available())
      {
        // read the most recent byte
        inChar = Serial.read();
        // send back the charater
        Serial.write(inChar);
      }
    }

There are plenty of "built-in" examples in the Arduino IDE that use the various serial functions. These can be viewed without any hardware attached. In the IDE go to `File` > `Examples` and from there a lot of the examples for the serial UART are in the `Communications` section. Details of these examples can be found on the [Arduino Tutorial][5] site.

  [1]: https://www.arduino.cc/en/Serial/Begin
  [2]: https://www.arduino.cc/en/Serial/Available
  [3]: https://www.arduino.cc/en/Serial/Write
  [4]: https://www.arduino.cc/en/Serial/Print
  [5]: https://www.arduino.cc/en/Tutorial/BuiltInExamples

body:
The Arduino has only one UART which is used for program upload and for the serial terminal output to your computer. While you can connect it to another serial device that will make debugging cumbersome as 1) you won't be able to send any debug output; and 2) you will need to change it back and forth between your computer and the GPRS as you re-build and upload your code. You pretty much _need_ a second UART to do this any kind of conveniently.

Look up the library module called [SoftwareSerial][1] which can simulate a UART on a second pair of pins, with some limitations: It is limited to communicating at 9600 baud; it can not transmit and receive at the same time; at most, one SoftwareSerial port can be receiving (or even listening) at any one time; and it can interfere with some other internal hardware, notably the interrupt system and at least one of the timers.  (The link points to the Arduino website whose documentation isn't always the very latest, but what's there will give you the idea).

In many cases, and yours is likely one of them, these are not show-stoppers, just something to be aware of as your code becomes more complex. As long as you can operate your device by occasionally sending it a string and receiving another in reply, and your system doesn't include other high-speed devices that must be serviced quickly when they request it, you probably won't notice the limitations.

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


body:
I am working with an Arduino Uno clone that uses the CH340G USB to TTL converter in lieu of the 16U2 found on the Uno. I see that most tutorials suggest downloading the CH340G drivers from what they call ["a chinese website"](http://www.wch.cn/download/CH341SER_EXE.html). I don't quite trust that site, is there any more trustworthy website where one might be able to acquire CH340G drivers for a modern Linux distro (preferably CentOS or Debian).

I ask here because [devices with](https://arduino.stackexchange.com/questions/19059/problem-with-serial-driver-for-ch340g-board/19066#19066) [that chip](https://arduino.stackexchange.com/questions/3700/rename-device-name-ch340-usb-to-serial-mac-os/13344#13344) [seem](https://arduino.stackexchange.com/questions/6553/which-one-arduino-board-to-buy/6606#6606) [to be](https://arduino.stackexchange.com/questions/14264/why-does-the-standard-arduino-ide-not-include-the-ch341g-usb-drivers/14269#14269) [popular](https://arduino.stackexchange.com/questions/17104/trying-to-understand-arduino-products/17108#17108) [in the](https://arduino.stackexchange.com/questions/17104/trying-to-understand-arduino-products/17108#17108) [Arduino](https://arduino.stackexchange.com/questions/22514/arduino-clone-ch340g-atmega328p-midi-over-usb) [community](https://arduino.stackexchange.com/questions/16987/how-to-program-an-offbrand-arduino-uno/16997#16997). If the unix stackexchange site would be a better place to ask then the question can be moved. Thank you.

**EDIT:** Apparently my system is having an issue with recognizing the device. Here are some specs:

    $ lsusb
    Bus 002 Device 002: ID 8087:8000 Intel Corp.
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 8087:8008 Intel Corp.
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
    Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
    Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

    $ lsusb | wc -l
    9

    $ # Now I plug in the Uno clone
    $ # Wait about a minute just to be sure...
    $ lsusb
    Bus 002 Device 002: ID 8087:8000 Intel Corp.
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 8087:8008 Intel Corp.
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 004: ID 04d9:3015 Holtek Semiconductor, Inc.
    Bus 003 Device 003: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11n
    Bus 003 Device 012: ID 045e:0040 Microsoft Corp. Wheel Mouse Optical
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    $ lsusb | wc -l
    9

    $ uname -a
    Linux happiness 4.4.0-47-generic #68-Ubuntu SMP Wed Oct 26 19:39:52 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

    $ cat /etc/issue
    Ubuntu 16.04.1 LTS \n \l

My entire `dmesg` file can be found [on pastebin](http://pastebin.com/4EUssDTx), here is the end of it:

    [37253.943739] usb 3-6: device descriptor read/64, error -71
    [37254.159669] usb 3-6: new full-speed USB device number 15 using xhci_hcd
    [37254.159841] usb 3-6: Device not responding to setup address.
    [37254.363858] usb 3-6: Device not responding to setup address.
    [37254.567744] usb 3-6: device not accepting address 15, error -71
    [37254.679654] usb 3-6: new full-speed USB device number 16 using xhci_hcd
    [37254.679756] usb 3-6: Device not responding to setup address.
    [37254.883917] usb 3-6: Device not responding to setup address.
    [37255.087716] usb 3-6: device not accepting address 16, error -71
    [37255.087749] usb usb3-port6: unable to enumerate USB device

title: Safe place to download CH340G drivers from

Answers: 2

body:
Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users).

The CH340G is fully supported by the default kernel in all distros I have ever used. On my Ubuntu machine the CH340G on my NodeMCU is detected automatically:

    [ 8195.450566] usb 4-1: new full-speed USB device number 2 using uhci_hcd
    [ 8195.630710] usb 4-1: New USB device found, idVendor=1a86, idProduct=7523
    [ 8195.630714] usb 4-1: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [ 8195.630716] usb 4-1: Product: USB2.0-Serial
    [ 8196.675137] usbcore: registered new interface driver usbserial
    [ 8196.675153] usbcore: registered new interface driver usbserial_generic
    [ 8196.675166] usbserial: USB Serial support registered for generic
    [ 8196.677581] usbcore: registered new interface driver ch341
    [ 8196.677600] usbserial: USB Serial support registered for ch341-uart
    [ 8196.677620] ch341 4-1:1.0: ch341-uart converter detected
    [ 8196.690670] usb 4-1: ch341-uart converter now attached to ttyUSB0

Nothing to download, nothing to install, nothing to risk the security of your system with.

body:
"Linux doesn't need drivers (indeed, the whole concept is pretty alien to Linux users)."

I feel alienated, however this information is incorrect. I have at least two Ubuntu machines that did not recognize the CH340g chip. One is Linux Mint 18.2 32bit the other is a Linux Mint 19 64bit. I used the 'driver' that I downloaded from the site in question and guess what? It is the exact same driver that NodeMCU uses. For those that want or need to download the driver, but don't want to visit a 'suspicious site' just go here [nodemcu-dev][1] and you will find three flavors: Linux, MAC and Windows. Strange that they have an MIT license for their own software.

For Linux, just extract the archive CH341SER_LINUX.ZIP, then open a terminal in the directory and use `make && sudo make` then load the module ahem.. driver with (may need to use sudo) `insmod /{path-to-your-extracted-folder}/ch34x.ko` or reboot.

Now, I am not arguing whether or not Linux comes with the module, because I see two (one for each kernel) on just one of my systems located at /lib/modules/{x.x.x-xx}-generic/kernel/drivers/usb/serial/ch341.ko, however the one that is needed comes from the Chinese site in question that happens to be the same place where NodeMCU got theirs (or possibly some other site) for it to be recognized.

Also, I don't get how someone can buy Chinese products (or from anywhere else) and be afraid to visit their site.

  [1]: https://github.com/nodemcu/nodemcu-devkit/tree/master/Drivers


body:
I am completely new at Arduino. I have a joystick:

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

It is however quite different from all the other joystick-tutorials, as their joysticks have 5 pins, not just 4. So I am quite at loss here. How do I connect it?

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

title: How to: Connecting 4-pin Joystick to Arduino board

Answers: 2

body:
If the [link that Mark Smith provided](https://www.aliexpress.com/store/product/Free-Shipping-dual-axis-xy-joystick-module-PSP-2-Axis-Analog-Thumb-Joystick-Module-Thumb-Joystick/1266255_1879823015.html) is correct, that is a “dual-axis mini xy joystick module PSP 2-Axis Analog Thumb Joystick Module Thumb Joystick for Arduino”, with (as other comments suggested) pins labeled on back of board as GND, X, Y, VCC.

To use it, attach GND to Arduino ground; connect each of X and Y to analog inputs, like A0 ... A7; connect VCC to (typically) 5 V.  Then read results on your analog input lines.

Note, it makes sense to test the device using a DVM beforehand.  Measure resistance from GND to VCC to find out overall resistance, so you can decide if 5 V is appropriate or if you should use a lower voltage.  (For example, if overall resistance is several thousand ohms, 5 V is ok; if only a few hundred, add one or two thousand ohms in series and take analog readings using a 1.1 V reference instead of 5 V reference.)  Also measure resistance from GND to X as you move the thumb control, and from GND to Y.

body: For sure there should be 4 pins, 'GND', 'VCC', 'X' and 'Y'. GND (-) is used when the joystick goes into a negative axis (depending x or y) on a Cartesian plane it transfers as negative into the Arduino board. The same thing happens when it goes to positive (VCC (+)) (depending x or y) on a Cartesian plane it transfers as positive onto the Arduino Board.


body:
I have been playing around with this shield for a couple of days now and I have to agree with some statements made in the comments that the "library" lacks many functions.

However I have discovered the following library which was built for the Dynamixel shield: https://github.com/zcshiner/Dynamixel_Serial

I wanted to know since I am using an Arduino Uno, which parameters I would have to change to make it work.

Sorry I am not very fluent in C++. I have tried just changing the direction pin to 10 but it's obviously not sufficient.

Shield to be dealt with: https://dfrobot.com/index.php?route=product/product&product_id=958

The following code should work afterwards:

    #include <dynamixel_serial.h> // Library needed to control Dynamixel servo

    #define SERVO_ID 0x01 // ID which we will set Dynamixel to
    #define SERVO_ControlPin 0x0A // Control pin of buffer chip, NOTE: this does not matter because we are not using a half to full control buffer.
    #define SERVO_SET_Baudrate 57600 // Baud rate speed which the Dynamixel will be set to (57600)
    #define CW_LIMIT_ANGLE 0x001 // lowest clockwise angle is 1, as when set to 0 it sets servo to wheel mode
    #define CCW_LIMIT_ANGLE 0xFFF // Highest anti-clockwise angle is 0XFFF, as when set to 0 it sets servo to wheel mode

    void setup() {
      delay(1000); // Give time for Dynamixel to start on power-up
      Dynamixel.begin(SERVO_SET_Baudrate); // We now need to set Arduino to the new baud rate speed
      Dynamixel.setDirectionPin(SERVO_ControlPin); // Optional. Set direction control pin
      Dynamixel.setMode(SERVO_ID, SERVO, CW_LIMIT_ANGLE, CCW_LIMIT_ANGLE); // set mode to SERVO and set angle limits
      Serial.begin(115200);
      Serial.println("Setup Done!");
      pinMode(13, OUTPUT);
    }

    void loop() {
      digitalWrite(13, HIGH);
      Dynamixel.servo(SERVO_ID,0x001,0x100); // Move servo to angle 1(0.088 degree) at speed 100
      delay(4000);
      Dynamixel.servo(SERVO_ID,0xFFF,0x3FF); // Move servo to max angle at max speed (1023)
      delay(4000);
    }

title: Adapt Dynamixel library to different shields

Answers: 1

body:
You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)

Here are two links for info on Arduino baud rates and Dynamixel serial communications.

[Controlling AX-12 Servos][1]

[How high of a baud rate can I go (without errors)?][2]

  [1]: http://forums.trossenrobotics.com/tutorials/how-to-diy-128/controlling-ax-12-servos-3275/
  [2]: https://arduino.stackexchange.com/questions/296/how-high-of-a-baud-rate-can-i-go-without-errors


body:
Regarding the following code:

    mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    ax = map(ax, -17000, 17000, -1500, 1500);

I know the reason for taking 17000 as value - that's 1g.  But I am not getting how and why 1500 value is taken.

title: What does map() do?

Answers: 1

body:
The `map()` function is well explained [here][1].

In short, it maps one range of numbers to another.  In this case it will map `ax` from the range (-17000:17000) into the range (-1500:1500).

Imagine a ruler with both inches and cm on.  If you have a measurement in inches, you can represent that same measurement (point on the ruler) in cm.  Your "ruler" here has one scale ranging from -17000 to 17000, and another scale ranging from -1500 to 1500.  You're finding the reading on the second side at the point `ax` on the first.

If you mean specifically why are those numbers used -- then I have no idea since you give no context.

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


body:
here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256),
 All i want to create table and wants to  store all  data into  24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so  i can't find any proper library for doing that.!

can anyone tell me how to do that...

any suggestion..Please help me..

thanking you..

title: creating table in 24LC256

Answers: 1

body:
Simplest way to create a table is to view it as a vector of struct's. For performance it is good to make the struct size a multiple of the EEPROM page size.

    struct row_t {
      ... column fields ...
    };

    uint32_t row_addr = TABLE_START_ADDR;
    row_t data;
    data.column = value;
    ...

    eeprom.write(row_addr, &data, sizeof(data));
    row_addr += sizeof(row_t);
    ...

Basically you need to map a two/multiple dimensional table onto a one dimensional address space (of the EEPROM). The programming language can help with some of the calculations (and hide them).

Cheers!


body:
I have an Arduino Uno acting as a master with 3 Arduino Nano's acting as a slaves.

Looking at this example:
http://www.gammon.com.au/forum/?id=10892, it tells me how to send a string from the master to the slave, but I didn't see any examples sending a string from the slave to the master device. I was able to successfully send and receive digits to/from the master and slave, but I couldn't figure out how to send strings from the slave to the master based on the example.

My understanding is that SPI communications can only send information byte by byte, so am I supposed to convert my string into a byte format before putting that into the SPDR variable so that it can be sent back to the master?

In any case, would I be able to get some pointers on how to send strings from the slave to the master?

Thanks in advance.

title: How do I send a string from an Arduino Slave using SPI?

Answers: 4

body: String is only array of char ended by char \0. But you can also access it as array of bytes ended with 0. And send them by one byte until it reaches the 0 (send it too). On master you save it to long enough  array of char (work with it as with bytes) including the final zero and bingo, you have char string transmitted :)

body:
> How do I send a string from the an Arduino Slave using SPI?

Depending on your definition of string it would look something like this (for master):

    String message = "....";
    SPI.transfer(message.c_str(), message.length() + 1);

or

    char message[MESSAGE_MAX];
    strcpy(message, ....);
    SPI.transfer(message, strlen(message) + 1);

For the SPI slave this will need to be transformed to either an SPI ISR or busy-wait for chip-select and then the transfer.

Cheers!

body:
Remember the master controls the transmission (provides the clock), however it *can* be done. For example:

---

## Master

    // master

    #include <SPI.h>

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

      digitalWrite(SS, HIGH);  // ensure SS stays high for now

      // Put SCK, MOSI, SS pins into output mode
      // also put SCK, MOSI into LOW state, and SS into HIGH state.
      // Then put SPI hardware into Master mode and turn SPI on
      SPI.begin ();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

    }  // end of setup

    void loop (void)
    {
      char buf [20];

      // enable Slave Select
      digitalWrite(SS, LOW);
      SPI.transfer (1);   // initiate transmission
      for (int pos = 0; pos < sizeof (buf) - 1; pos++)
        {
        delayMicroseconds (15);
        buf [pos] = SPI.transfer (0);
        if (buf [pos] == 0)
          {
          break;
          }
        }

      buf [sizeof (buf) - 1] = 0;  // ensure terminating null

      // disable Slave Select
      digitalWrite(SS, HIGH);

      Serial.print ("We received: ");
      Serial.println (buf);

      delay (1000);  // 1 second delay
    }  // end of loop

In this example the master initiates a transmission by sending 0x01 to the slave. Then it gets bytes back until a 0x00 byte (signifying the end of the string). The `delayMicroseconds` is there to give the slave time to respond.

---

## Slave

    // Slave

    void setup (void)
    {

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= bit(SPE);

      // turn on interrupts
      SPCR |= bit(SPIE);
    }  // end of setup

    volatile char buf [20] = "Hello, world!";
    volatile int pos;
    volatile bool active;

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
      byte c = SPDR;

      if (c == 1)  // starting new sequence?
        {
        active = true;
        pos = 0;
        SPDR = buf [pos++];   // send first byte
        return;
        }

      if (!active)
        {
        SPDR = 0;
        return;
        }

      SPDR = buf [pos];
      if (buf [pos] == 0 || ++pos >= sizeof (buf))
        active = false;
    }  // end of interrupt service routine (ISR) SPI_STC_vect

    void loop (void)
    {

    }  // end of loop

The slave does everything inside the ISR. The arrival of the 0x01 byte makes it reset its "pointer" to the start of the buffer. After that it responds with another byte from the buffer until it has reached the terminating 0x00 byte.

body:
In part of sender I'm use the convert String to char array method before sending to the receiver.

  **Master**

    #include <SPI.h>
    const int size_arr = 50;  // define array size (must be less than size of slave)
    char buf[size_arr]; // define char array, use for convert from string for send to slave
    String main_dat = "jack,12,47,123,8888"; // real String data

    void setup() {

    pinMode(SS, OUTPUT);
    digitalWrite(SS, HIGH);
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV4);

    }
    void loop() {
    main_dat.toCharArray(buf, size_arr); // convert String data to char array
    Spi_tranmis(buf); // send char array
    delay(500);

    }

    void send_spi(byte pram) {

      digitalWrite(SS, LOW);
      SPI.transfer(pram);
      digitalWrite(SS, HIGH);
      delayMicroseconds(50);

    }

    void Spi_tranmis(char buf[]) {
    for (int i = 0 ; i < size_arr ; i ++) {
      send_spi(buf[i]);
    }

    send_spi('\n');
    }

And in part of receiver i'm use char array receive from master and convert to String leter.

**Slave**

    #include <SPI.h>

    const int size_arr = 51; // define array size (must be more than size of master)
    char buf[size_arr]; // char array , use for recive from master

    volatile byte pos = 0;
    volatile boolean process = false;

    String msg; // real data

    void setup() {
       Serial.begin(9600);
       Serial.println("test");
       pinMode(MISO, OUTPUT);
       digitalWrite(MISO, LOW);
       SPCR |= _BV(SPE);
       SPCR |= _BV(SPIE);

     }

     ISR(SPI_STC_vect) {
      char c = SPDR;

      if (pos < sizeof buf) {
        if (c == '\n') {
          process = true;
        }
         else {
          buf[pos++] = c;
         }
       }
     }

    void loop() {
      recvHandle();

    }

    void recvHandle() {
      if (process) {  // when SPI available
        msg = String(buf);   // convert char array to String
        Serial.println(msg);
        process = false;
        pos = 0;
      }

}

* You must define size of char array in receiver more than sender *


body:
There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.

In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)

I tried accessing the variable stored in the array like this:

    void loop()
    {
    for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

    if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
    {
    Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
    }
    delay(500);
    }

Example unedited sketch from library

 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 #define PPM_INPUT_PIN  2

 void setup()
 {
   Serial.begin(38400)
   TinyPpmReader.attach(PPM_INPUT_PIN);
 }

 void loop()
 {

   Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
   Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
   for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
   {
  Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
   }
   delay(500);
 }

The serial monitor prints this:

    * Period=17928 us *
    ChNb=8
    Ch=1496 us
    Ch=1744 us
    Ch=896 us
    Ch=1560 us
    Ch=1640 us
    Ch=1496 us
    Ch=1536 us
    Ch=1688 us

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.

EDIT: That worked Mark!

New Code Mapping attempt (Compiles,does not work)

    #include <TinyServo.h>
 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

 //int potpin0 = 3;    <---------          // This worked
 int val0;                     // integer to store value

 const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
 const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
             // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

 #define PANSERVO 0
 #define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

 void setup()
 {
   setupServos();
 }

 void loop()
 {
   val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
   val0= map(val0, 1000, 2000, 0, 180);
  // scale it to use it with the servo (value between 0 and 180)
     // scale it to use it with the servo (value between 0 and 180)

 moveServo(PANSERVO, val0);

   delay(5);                           // waits for the servo to get there
 }

title: Accessing Values From Array Within a Library

Answers: 1

body:
This code (from the example) is what prints a single index - index `Idx`:

    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

To print, say, index 3 you'd use

    Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

To simply *get* the value from index 3, without printing it:

    int a = TinyPpmReader.width_us(3);

(assuming it's an `int`)


body:
I have a u-blox gps module and I use TinyGPS (http://arduiniana.org/libraries/tinygpsplus/) to get out the lat + lng.

If i write...

    Serial.println(gps.location.lat(), 6);

...out in the log I get the correct latvalue.
Right now I however work with a BLE (https://www.adafruit.com/product/1697) and when I try to print it like this:

    BTLEserial.print (gps.location.lat()`, 6);

I get a error: `no matching function for call to 'Adafruit_BLE_UART::print(double, int)'`

If I do this instead, the code runs...

    BTLEserial.print ((gps.location.lat(),6));
But I do not get the correct lat, instead I get this value `6.00000000`

I have tried to store the lat like this:

    double myLat;

    myLat = (gps.location.lat(), 6);
    BTLEserial.print (myLat);

But with that myLat also has a value of `6.00000000` which is not correct.

I tried this as well:

    char sValueOne[16], sValueTwo[16];
    char sBuffer[33];

    strcpy(sBuffer,dtostrf(((gps.location.lat(),6)), 15, 8, sValueOne));
    strcat(sBuffer,",");
    strcat(sBuffer,dtostrf(((gps.location.lng(),6)), 15, 8, sValueTwo));

    BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

But with that I still get `6.00000000`. I am starting to run out of ideas now to make this work. I have tried to send it both directly and store it but nothing works successfully.

So how can I adjust the code to be able to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?

Appreciate every help and tips!

title: How to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001?

Answers: 1

body:
The Arduino Stream/Print classes may sometime need some extra attention.

    BTLEserial.println(gps.location.lat()`, 6);

The member function is available in the class Print but gets "hidden". You can help the compiler to find it with a prefix:

    BTLEserial.Print::println(gps.location.lat()`, 6);

Cheers!


body:
I want to use 2 "displays" with 4 digits. The displays are common cathodes with cathode transistors connected to the digits, as the figure:
[![enter image description here][1]][1]
The segments of both displays are connected together on the digital pins.
The problem is that I tried to use some libraries for 7 segment displays and they worked with only one 4 digit display, but when I connected the second display, did not display the numbers correctly. The numbers that will be written are integers and I'm using mega 2560 R3.

Here are my attempts:

    #include "SevSeg.h"
    byte digitPins_1[] = {29, 30, 31, 33};//Digits pins
    byte digitPins_2[] = {25, 26, 27, 28};
    byte segmentPins[] = {38, 39, 40, 41, 42, 43, 44, 46}; //segment pins
    SevSeg disp1;
    SevSeg disp2;

    void setup() {
    disp1.begin(P_TRANSISTORS, 4, digitPins_1, segmentPins);
    disp2.begin(P_TRANSISTORS, 4, digitPins_2, segmentPins);
    disp1.setBrightness(20);
    disp2.setBrightness(20);
    }

    void loop() {
    disp1.setNumber(8888, 0);
    disp1.refreshDisplay();
    disp2.setNumber(1111, 0);
    disp2.refreshDisplay();
    }
or using another lib:

    #include <SevenSeg.h>
    SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
    SevenSeg disp2(38,39,40,41,42,43,44);
    int digitPins1[4]={29,30,31,33};//digitpins
    int digitPins2[4]={25,26,27,28};

    void setup() {
    disp1.setDigitPins(4,digitPins1);
    disp2.setDigitPins(4,digitPins2);
    disp1.setDigitDelay(1600);//time delay
    disp2.setDigitDelay(1600);
    disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
    disp1.setActivePinState(HIGH,HIGH);
    }

    void loop() {
    disp1.write(8888);
    disp1.clearDisp();
    disp2.write(1111);
    disp2.clearDisp();
    }

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

title: How to multiplex multiple displays?

Answers: 3

body:
The code instantiates two instances of the SevSeg class.  This may or may not work.  Really depends on if the class uses any resources are not meant to be shared between multiple instances of that class.  For instance, it is unlikely that one hardware timer can be used for more than one purpose at a time.

But the code continues on to use the same (anode) pin resources for both instances of the class. This is likely not going to work.

Apologies for being vague using qualifier like "unlikely" instead of simply stating that it will not work.  Truth is, one might be able to write a class that can deal with multiple instances of its self.  But it would be very difficult and a far more complex programming task than to simply use one instance for all 8 digits.

In case there is a question as to the maximum number of digits supported for one instance of the SevSeg class, this line is in the one of the SevSeg header files:

    #define MAXNUMDIGITS 8 // Can be increased, but the max number is 2^31

body: Why do you feel you need to multiplex two displays? What is wrong with just having one display of 8 digits? They don't have to be physically together, and it's entirely up to you what you display on each character of the display.

body:
As the answers suggested, it is better to make a single display with 8 digits. But if anyone needs 2, here is my solution:

As suggested, I checked if the library supported, and the solution was to only increase the delay on each digit.

    #include <SevenSeg.h>
    SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
    SevenSeg disp2(38,39,40,41,42,43,44);
    int digitPins1[4]={29,30,31,33};//digitpins
    int digitPins2[4]={25,26,27,28};

    void setup() {
    disp1.setDigitPins(4,digitPins1);
    disp2.setDigitPins(4,digitPins2);
    disp1.setDigitDelay(4000);//time delay
    disp2.setDigitDelay(4000);
    disp1.setDutyCycle(10);//decrease the duty cycle
    disp2.setDutyCycle(10);
    disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
    disp1.setActivePinState(HIGH,HIGH);
    }

    void loop() {
    disp1.write(8888);
    disp1.clearDisp();
    delay(1);// don't need
    disp2.write(1111);
    disp2.clearDisp();
    }


body:
[![Waveform][1]][1]
I want to find the length of upper one signal (purple one). So for that, i used pulseIn() function for that. But i just get 0 as a result in serial monitor.

    int pulsepin = 8;
    int value = 0;

    void setup()
    {
      pinMode(pulsepin, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      value = pulseIn(pulsepin, HIGH);
      Serial.println(value);
      delay(1000);
    }

Here, above is my arduino code which i used. I don't know why I don't get any reading except 0.

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

title: pulseIn() function not working

Answers: 1

body:
`pulseIn()` returns an `unsigned long` (32 bits) not an `int` (16 bits), so you may have some truncation occurring in your program leading to a `0` value.

Hence you should modify your program as follows:

    int pulsepin = 8;
    unsigned long value = 0;

    void setup()
    {
      pinMode(pulsepin, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      value = pulseIn(pulsepin, HIGH);
      Serial.println(value);
      delay(1000);
    }

Also beware that `pulseIn()` has a timeout (it will not wait forever).
This timeout is used for the whole completion of the pulse, i.e. first waiting for the signal to get `HIGH`, then waiting for it to get back `LOW`. If no pulse is detected and complete (**LOW -> HIGH -> LOW**) within this time, then `pulseIn()` will return 0.

Default timeout value is 1 second, but you can set any value (in microseconds) you want that can hold in an `unsigned long`:

e.g. if you need 10 seconds, then:

      value = pulseIn(pulsepin, HIGH, 10000000UL);

I am not sure why you use `delay(1000)` in your `loop()`, I would remove it as a pulse may occur during that time and it would not be seen by your program.

Here is a suggested update (I also used `const` where it made sense but that won't change program behavior):

    const unsigned long PULSEIN_TIMEOUT = 10000000UL;
    const int pulsepin = 8;
    unsigned long value = 0;

    void setup()
    {
      pinMode(pulsepin, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
      Serial.println(value);
    }

You may also want to avoid printing 0 values since they mean no pulse was detected:

    void loop()
    {
      value = pulseIn(pulsepin, HIGH, PULSEIN_TIMEOUT);
      if (value > 0)
        Serial.println(value);
    }


body:
I've got an ESP8266 (NodeMCU) and I am trying to understand the ESP8266WebServer library, as how to use the results across functions.

In my setup function, I have the following:

       server.on("/marquee", []() {
          varOne = server.arg("baseColor");
          varTwo = server.arg("marqueeColor");
          server.send(200, "text/html", webPage);
          Serial.println("Marquee  activated");
          state = true;
          ledMode = "marquee";
        });

In my loop, I detect the ledMode and if it is set to marquee then it runs the following FastLED function, amongst others:

    fill_solid(leds, NUM_LEDS, 0xFF0000);

What I am trying to figure out is how I go from taking a hex color code of say `FF0000` from the URL parameter, and use that in my ```fill_solid``` function.

server.arg stores get the parameter as a string, so I am not sure what needs to be done.  Also, using a variable name in place of the Hex code in the ```fill_solid``` function results in an error due to not expecting the variable

title: Use server.arg results as a function parameter?

Answers: 1

body:
> server.arg stores get the parameter as a string, so I am not sure what needs to be done.

The parameter needs to be converted to an uint32_t (and then to a CRGB or CHSV struct). The simplest way is to use the C library function [strtoul][1]

    uint32_t color = strtoul(arg, NULL, 16);

This can be improved so that it checks that a number was scanned, etc.

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2


body:
i have an output pin connected to a magnetic reed switch. The pin mode is INPUT_PULLUP. When the switch is closed, it connects the pin to GND and drags the pin to a LOW reading. I check the state of the pin in the loop function. Occasionally the pin reads LOW when it shouldn't (the switch is not closed) - e.g. around once per second. What could cause this? The wire from the pin to the switch is about 1m long - could this be long enough to intermittently drag it down to a LOW? Also, it seems to happen much more when the air temperature is hotter.

Circuit summary: Pin (INPUT_PULLUP) -> Magnetic reed switch -> GND

title: Intermittent LOW reading from input pin set to INPUT_PULLUP

Answers: 1

body: My guess would be that you're getting noise interference on the line and it's too much for the Arduino's little internal pullup.  Try adding an external pullup resistor - say 5k-10k (exact value is not critical).


body: How can I set the Arduido IDE to generate the `-S` flag to gcc to see the machine code in Arduino? (the sketches)

title: How do I order the gcc compiler to generate -S flag in Arduino IDE

Answers: 1

body: Compiler flags are defined in the platform.txt of the board you have selected in the **Tools > Board** menu. You can also add compiler flags via a `build.extra_flags` property in the boards.txt entry for the selected board.


body:
I'm a beginner on arduino.

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

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..

    void setup()
    {
      pinMode(LR, OUTPUT);
      pinMode(LV, OUTPUT);
      Serial.begin(9600);
    }

    void readSerial(){
      while(Serial.available() > 0){
        car = Serial.read();

        if(car != '+'){
          buff[i] = car;
          buff[i+1] = '\0';
          i++;
        }
        else{
          sscanf(buff, "%d", &received_code);
        }
      }
    }

    void loop()
    {
      readSerial();
      if (received_code == 200){
        LRstate = HIGH;
        digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
        digitalWrite(LR,LOW);
        delay(100);
        digitalWrite(LV,LOW);
      }
    }

How can I solve my problem?

Thanks a lot.

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

title: Turn on a LED when an other LED turn off

Answers: 2

body:
First, make sure the LEDs are connected correctly: I presume the red LED is connected to whichever pin `LR` is, and the green LED to `LV`.

According to your diagram, your LEDs will be on if the output is `HIGH`, and off if the output is `LOW`.  Your code sets `LR` to high, but then immediately to `LOW` again.

Here's a fixed (I hope) verson of your `loop()`:

    void loop()
    {
      readSerial();
      if (received_code == 200){
        // Turn the red LED on
        digitalWrite(LR,HIGH);

        // Turn the green LED off
        digitalWrite(LV,LOW);
      }
    }

---
Unrelated to the problem you're having, but worth a mention anyway:

There's nothing in your code to stop you overrunning `buf` if you get a longer input than you're expecting.  If this happens you'll get unpredictable results as you trash over whatever happens to be in that part of memory.

body:
In addition to the code changes noted by @MarkSmith, the LEDs are not connected properly. The straight LED pin on the Fritzing diagram is its cathode and must be connected to grounded, and the bent pin is its anode and must be at +V (+5v, in this case), for the LED to light. To turn the LED on, the anode must be at +V and the cathode at ground. To turn the LED off bring both pins to the same voltage, usually by grounding the anode (logic 0 on its connected pin).

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

To identify the cathode on a real LED, look inside its plastic blob (that's a technical term :) and you'll see two bits of metal, each on a wire, like two flags. The larger flag is the cathode. Usually, the cathode also has a shorter external lead and the plastic blob has a flat edge on that side, but the larger flag is definitively the cathode:

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/HLGIC.png
  [3]: https://i.stack.imgur.com/pCtJX.png