text:
Serial Connection - 3.3v to 5V MCU's
After asking How to connect Arduino & ESP8266, I tried to build such circuit.
First I tried the code one 2 Nano's - to verify 2 MCU sending and receiving messages. After that, I started to build the following circuit:
Take1: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=10K, R2=20K. FAIL
Take2: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take3: MCU A: Arduino NANO ,MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take4: MCU A: Arduino NANO 5V, MCU B: WEMOS mini. Tx to Rx (no vdiv ). OK

Edit1: LCD display is connected to MCU B ( as it was tested using 2 Nano ) via I2C. Messages received are sent to LCD. PLEASE IGNORE LCD shown in not I2C
Edit2:

Diagram updated - GND was missing and POWER IN clarification.

LCD display is an I2C one. It shows properly WEMOS is booting up properly ( shows a boot msg ), and spits every incoming Serial message from other MCU. When TAKE4 and TAKE1 were taken, setup and code worked PROPERLY.

What is done wrong?

why do you say there is something wrong? ... what were you expecting to happen?

@jsotola just added "EDIT1" in my question.

@jsotola sorry. added. Library does not include I2C LCD display.

In your wiring diagram you are missing the ground connection to the Wemos. Also you have the 5V pin of the Wemos connected to Vin on the Nano, I guess to provide the Nano with power. Thats incorrect. 5V needs to go to the 5V pin. Vin is connected to the internal voltage regulator, which needs at least 6V to power the Nano.

Your frizzy thing does not help much, a schematic is better. Use a level converter, doing the resistor trick is playing with the margins of the devices and is not reliable. They give voltage ratings and threshold levels for a reason and it is good to stay away from the margins, the closer you get the more susceptible to noise you are.

How is the whole thing being powered?

You can use a mosfet to convert 5v<->3.3v: https://www.hobbytronics.co.uk/mosfet-voltage-level-converter. In this way you're not relying on the resistors and playing with the input margins

@lurker via nano’s usb

If it's all powered by the nano's USB, why is only the vin connected on the nano and not the 3.3v to the power rail?

@lurker what do you mean ? Vin is 5v

You say that nano is supplying the power to your system. Vin is a voltage input.

I'd the nano is supplying power, wouldn't you want the nano's 3.3v output available to the esp8266?

@lurker Vin also outputs 5v. So it is the same

@lurker it is not about powering the MCUs but the differnt vlogic affecting Serial communication.

@Guy.D Can you address the lack of a GND connection on the Wemos? Is that just a frizzy error or have you really missed it out?

@Majenko yes, it is an error. I'll update the diagram

Vin is NOT the same as 5V. You might measure 5V there (don't know, what the voltage regulator has on the input side, when its not used), but it is not for providing power. You are really risking to kill the voltage regulator on the Nano. Again: Do not use Vin as 5V power source. Use either the 5V pin or provide the Wemos directly with 3.3V through the 3.3V pin (though I'm not sure, if the 3.3V voltage regulator is really able to provide the necessary current for an ESP board)

RX/TX on Micro is Serial1

It's a system and the system starts with proper power and grounding. I thought it was a simple question. Your answer doesn't align well with your picture.

@lurker See edit 2 please.

@Majenko please see edit 2.

@Juraj what do you mean ? Serial.begin(115200) worked as expected, and show output on serial monitor as expected.

Yeah that's what you said: you're powering the system through thenano USB port. Bit you still didn't address the question of how you're then getting power from the nano to the esp8266, assuming you answered my original question about how the system is lowered completely. If the esp8266 is getting power from somewhere else, then please indicate. Yes, that can matter.

@lurker thank you for your replies! WEMOS us powered from Nano as you can see ( or I'm missing something here... )

As @chrisl has already said, Vin is not intended to be used for providing power. The documentation says that it's intended for supplying power TO the Arduino from an external supply.

@lurker OK, so to RAW ? still this is not the problem,since MCU is powered up ( WEMOS & LCD )

If you don't have proper power, it can be the source of various problems.

You seem to be mixing Nano and Micro boards in your setup. You do know, don't you, that the Micro has a 32U4, so Serial is the USB but not the TX/RX pins - you need Serial1 for those. Also the TX/RX pins on the nano are connected to the FT232 chip, which will most likely interfere with your voltage divider.

@Majenko I know 32U4 have Serial comm on that chip and it behaves differently in some manner than 328P. But to get serial connection via Tx and Rx pins should I use Serial1 ? is that what you've ment ?.
And what is the reason for Nano's not to work with voltage divider ?

@Juraj Nano. Typo

Guy.D, yes use Serial1 for communication with esp8266 on RX/TX of the Micro

I would not power the WEMOS from the nano. They are two different microcontroller dev boards and should be each powered off of the same power source. For development, I would use a breadboard power supply that provides 3.3v and 5v. You can put 3.3v on one of the breadboard red power rails, and 5v on the other red power rail (which are designated RED by convention, and BLACK is for ground, which I see you have mixed up in your diagram). This is my advice. I realize you believe this has nothing to do with your problem and will likely ignore it. I wish you luck in solving your problem.

@lurker, Wemos D1 mini is ok with powering over 5 V pin

@lurker Although breadboard is shown in my diagram/ circuit, but this setup will be used as standalone device powered one power source (HiLink 220AC to 5V )

@Juraj Thanks. So a single 5v source would be fine. Also, I was more concerned about current than voltage although I didn't check the mini specs for max current draw.


text:
Fail starting Arduino IDE Ubuntu 18.04
for unknown reason, my Arduino IDE 1.8.12 stopped starting up ( worked OK before ).
Can anyone share some steps understanding why ?
edit1
after executing ./arduino
guy@desktop:~/arduino-1.8.12$ ./arduino
Picked up JAVA_TOOL_OPTIONS:
Set log4j store directory /home/guy/.arduino15
Gtk-Message: 17:15:18.630: Failed to load module "canberra-gtk-module"
java.lang.NullPointerException
    at cc.arduino.contributions.packages.ContributionsIndexer.parseIndex(ContributionsIndexer.java:134)
    at processing.app.BaseNoGui.initPackages(BaseNoGui.java:483)
    at processing.app.Base.<init>(Base.java:273)
    at processing.app.Base.main(Base.java:150)
guy@desktop:~/arduino-1.8.12$

it was a temporary problem with platform index file on server. to recover see https://forum.arduino.cc/index.php?topic=690045.0

did not solve the problem

then start ./arduino from command line to see the log

see edit 1 in question

Delete your arduino storage directory: rm -rf ~/.arduino15 being careful not to delete ~ instead.

it is the problem. did you delete the package_index.json file and the cache folder?

@Juraj I did delete the folder as noted on comment 1 ( in arduino15 older ), (in arduino folder ) there was nothing to delete

@Majenko I mv that folder, and now it is almost as fresh install ( what was important to me was all repositories that were installed ). it seems that additional boards should be configed again

and the file? did you delete package_index.json?

@Juraj - perhaps not, because I see it ( or it was re-created ). Lucky I was mv that folder. But again, I'll have to re-define boards. On the other hand, tools as: decoder, and 8266 Data upload, are there...

nothing should change if you only delete that one a file and the cache folder. stack trace decoder and SPIFFS upload tool are in Sketchbook folder in tools

@Juraj For some reason, I can't OTA now for that specific PC for every MCU I try - it is not a code problem. When I'm using my MAC laptop, same code, same MCU - it works as expected. Error ia " o response from device"

Firewall does this

@Juraj Mr.Know-all. Thankyou

source: Stack Exchange

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

sort: votes


text:
7segment display on Multi Function shield - Arduino Uno
I’ve bought this shield .
I’m looking for a way to display decimal point, without using any a designated library.
Most examples as this one shows only 0-9.
EDIT1 update link
Link

this display requires frequent refresh else it looks like it shows only one number

Does this answer your question? delay() problem for 74HC595 and 7-segment

The link to the example is dead. The decimal point is just like any other segment on the display. Set the corresponding output pin of the 75HC595 shift register to high or low (depending on the way, that the display is wired).

So if you click your 2nd link, it includes sample code for various sections of the multi-function shield.
One of them is titled "segment display".
If you look at that code, line 7 defines the bit patterns for each of the digits from 0 to 9:
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

If you map them out in binary, you get:
0xC0,   1100 0000   0
0xF9,   1111 1001   1
0xA4,   1010 0100   2
0xB0,   1011 0000   3
0x99,   1001 1001   4
0x92,   1001 0010   5
0x82,   1000 0010   6
0xF8,   1111 1000   7
0X80,   1000 0000   8
0X90    1001 0000   9

A 0 character has all the segments lit except the middle "cross-bar". An 8 character has ALL of the segments lit. But the bit pattern for 8 is 1000 0000. That suggests that a 0 bit means a segment is lit, and 1 means it is off. Since the highest order bit of all of those characters is 1 (off) it suggests that the high-order bit is the decimal place bit. (It's the only bit that never changes.)
So if you replace
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

with
const byte SEGMENT_MAP[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0X00,0X10};

You should get all the digits drawn with their corresponding decimal place lit.
I'd try that first to verify that I'm correct.
I'd then suggest writing code that reads the segments value for each digit, decides if you want a decimal place at that position, and if so, doing a bitwise AND (& in C/C++) on the value with 0X7F to clear the decimal bit for that character. (Remember it looks like a 0 means a given LED segment should be lit.
You could modify the function WriteNumberToSegment() to take a "lightDot" parameter, and have it change the bit if you pass TRUE (1):
void WriteNumberToSegment(byte Segment, byte Value, bool lightDot)
{
    digitalWrite(LATCH_DIO,LOW);
    bool bits = SEGMENT_MAP[Value]);
    if (lightDot) {
       bits &= 0x7F; //To light the decimal for this digit, clear the 0x80 bit
    }
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, bits);
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, SEGMENT_SELECT[Segment] );
    digitalWrite(LATCH_DIO,HIGH);
}

(I don't remember for sure if bool is a valid type in Arduino C/C++. If not, just replace bool with uint8 in the above.)

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


text:
ESP8266 RF Calibration
As an off-Topic to my main question, regarding Robodyn's Uno+Wifi - it seems that Wifi does not work ( fail to connect and fail find any network ).
Juraj advised to use External Antenna ( did not work ) and try to make an RF calibration as shown on espressif's site. Which I fail to understand how it is done.
a) Can anyone help with RF Calibration ?
b) Might it be another reason for that ?
Guy
EDIT_1
Just to be clear, a sלetch was uploaded and executed successfully to the ESP8266 module (Basic WiFi connect and network scan ).
Edit_2

Every ESP8266 schematic I can find has a 5.6pF capacitor between the LNA pin and the antenna. Robotdyn's doesn't - it has a resistor. Looks like they aren't that great at designing RF circuits...

@Majenko - So by definition it has no WiFi ? Can it be fixed ?

I'm not so sure. I'm going by the schematics here, but they don't seem to match what I am seeing in the product image. What I think is R13 looks to actually be a capacitor... It looks like there's no real relation between the published schematics and what is really on the board.

@Majenko - See Edit1 please ( to be sure )

Yeah, I had been following your original question.

I think the schematics were drawn by a child. They haven't even got any component values on them...! They're useless.

@Majenko - it could have been funnier if I hadn't purchased it :).
Do you know what might be the drivers for ? under "Documents" tab on their site

They'll be for the CH340G.

Have you closely inspected the soldering of the ESP8266 chip on your board?

I'm using linux - that I could find ( that it belong to CH340 ). But under Windows, it actually have an exe file

@Majenko see pic. Don’t see anything suspicious

Ok, looking at that I can tell you that there is a capacitor fitted to connect the LNA to the u.FL connector. What value that capacitor is I can't say. There is no capacitor fitted to use the PCB antenna. So you must use an external antenna (make sure it's a 2.45GHz one) or modify the board.

Looking at the colour of that capacitor for the u.FL it looks way higher than 5.6pF. More like 1nF.

@Majenko - I took it from Wemos D1 mini Pro I guess it is what needed. As said - with or without  the antenna, I get nothing.

I'd be inclined to removed the u.FL capacitor and solder in a known 5.6pF into the PCB antenna capacitor footprint.

I would try to upload AT firmware. forum users reported QOUT setting for flash

@Juraj - how can I do that ?

https://blog.gabrielcsapo.com/arduino-web-server-mega-2560-r3-built-in-esp8266/

@Juraj - Excellent reference!!

it has some problems, the author didn't want to change. he wrote it based on a forum session with me. you can download the AT firmware 1.7.4 here https://www.espressif.com/en/support/download/at?keys=&field_type_tid%5B%5D=14

@Juraj UPDATE: using the blog, each step was done successfuly, incl. downloading the firmware as you pointed, yielded the same result ( using ext. antenna ). :(((((  - while my basic check is network scan ( no networks found ). what can I do more. ??

so return the board or you could try the hardware fix recommended by Majenko

You can't do anything else with the RF calibration then to clean the flash area where it is stored. There are two reason for doing it:
First is reason to delete the RF calibration area is, if it was written by different version of Espressif SDK, including changing between AT firmware and Arduino. Then it is almost always wrong. I think they changed the data structure so some values are swapped.
Second reason is if the SDK did the calibration in wrong conditions like without antenna.
There is not much information about RF calibration. The FAQ has "Please erase the RF parameters to trigger overall calibration."
The AT firmware reference has (addresses for 4MB-C1):

blank.bin 0x3FB000 Initializes RF_CAL parameter area.
esp_init_data_default.bin 0x3FC000 Stores default RF parameter values, has to be downloaded into flash at least once. If the RF_CAL parameter area is initialized, this bin has to be downloaded too

The esp8266 Arduino core writes the data of esp_init_data_default.bin as part of the sketch's binary.
EDIT: the SDK does the 'digital calibration' at boot. it takes some microseconds. it is not done at every boot, but after some count of resets. this can be configured in the init section

Thank you again. From FAQ, I don't have any operative steps what to do.

flash blank.bin to 0x3FB000  or erase the entire flash.

Erasing using esptool.py ? since erasing using Arduino IDE did not solve it

Arduino IDE uses esptool.py. btw. what are your Tools menu settings?

Right... silly me. I'm setting Generic ESP8266 Module... now when I'm thinkg of it - the default is 1MB. Is that what you ment ?

set 4 MB end try to erase the flash again. but I think the esptool.py is not fooled with the setting when it executes the erase

Nope - setting to 4MB, nor to Wifi Arduino under ESP8266 didn't make it :(


text:
Problem importing a library in .h file
I have following code:
MyApp.ino:
#include "DfRobotLcdShield.h"

void setup() {
}

void loop() {
}

DfRobotLcdShield.h:
#include <LiquidCrystal.h>

When I try to compile, I'm getting the error:
In file included from MyApp.ino:1:0:
c:\temp\build5856181074637812172.tmp\DfRobotLcdShield.h:4:27: fatal error: LiquidCrystal.h: No such file or directory
 #include <LiquidCrystal.h>
                           ^
compilation terminated.
Error compiling.

When I add
#include <LiquidCrystal.h>

directly to the .ino file, it works. I'm using the latest Arduino-IDE 1.6.3.

It sounds like you're outgrowing the limitations of the Arduino IDE. I'm not offering this as an answer because changing IDEs is not a quick fix, but consider upgrading to more capable tools in the not-too-distant future.

This seems to be a general problem of the Arduino IDE: It only recognizes libraries that are included in the (primary) .ino file.
If you look at the invocation of the compiler, the path to any given library is only added if this library's header file is included in the .ino file.
I tested this with the EEPROM library. If this library is included in the .ino file, the compiler is called with
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs -I/usr/share/arduino/libraries/EEPROM /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where the important part is the -I/usr/share/arduino/libraries/EEPROM.
If I now remove #include <EEPROM.h> (but still have it in another header file which in turn is included in the .ino as in your case), the compiler call changes to
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/eightanaloginputs /tmp/build2678545434708654378.tmp/test.cpp -o/tmp/build2678545434708654378.tmp/test.cpp.o

where now the include path to the library is missing.
TL;DR
If you need to use a library, just (also) add an include to the .ino file. It doesn't cost you anything and will solve your problem ;)

#include <file> vs. #include "file"
From the gcc documentation:

#include <file> is used for system header files. It searches for a file named file in a standard list of system directories. [...]
#include "file" is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. [...]

Try #include "LiquidCrystal.h"
Or where is the library located?
Be sure the include specifies the location.
You might have to add the library location to your environment variables.

LiquidCrystal.h is a system library and hence, according to my limited C knowledge, has to be included with < >.

Did you add it through "sketch -> include library -> LiquidCrystal.h"?

I've tried that, too, without any difference.

Can you verify that this file is in your libraries folder? You could try to put it in your project folder, so that the linker doesn't have to look that far

Yes, it is there - please read my 2nd last sentence in the question.

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


text:
Leonardo: disable TX- and RX-LED
I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them by software. What is the reliable way to do it?

Examine the schematic and determine if they are wired to supplies, or to I/O pins.  If supplies, desolder the associated resistors.  If I/O pins, modify the bootloader and USB core to leave them off, or try issuing raw ATmega I/O access to turn them off if the are simply left on after the bootloader and not being constantly re-driven by USB traffic.

@ChrisStratton why not just desolder them in the first place? I don't know why it'd be bad to desolder the LED in the first place...

Just put a piece of tape over them...

Software modifications are cheaper and easier to reverse.  Tape doesn't save power.

How they are driven currently? The straight-forward way using digitalWrite(pin, LOW) does not work. pinMode(pin, INPUT) doesn't work either.

Try adding this to your setup routine:
TXLED0;
RXLED0;

These macros (and their cousins TXLED1, RXLED1) are used to control the TX an RX LED's on Leonardo. They are defined in https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/leonardo/pins_arduino.h#L95-L98

If that doesn't work you can try the solutions suggested here: http://forum.arduino.cc/index.php?topic=145262.0

Switching the IDE to upload to "Micro" instead of "Leonardo" really solved the LED problem.

See my new answer for more elaborate explanation and a maybe better solution.

Alternatively: the pin mapping in the Arduino world is D17 for RX and D30 for TX, so instead of TXLED1 you can also use digitalWrite(30, HIGH).

Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.
Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:
olimexino32u4.name=Olimexino-32U4
olimexino32u4.upload.protocol=avr109
olimexino32u4.upload.maximum_size=28672
olimexino32u4.upload.speed=57600
olimexino32u4.upload.disable_flushing=true
olimexino32u4.bootloader.low_fuses=0xff
olimexino32u4.bootloader.high_fuses=0xd8
olimexino32u4.bootloader.extended_fuses=0xcb
olimexino32u4.bootloader.path=caterina
olimexino32u4.bootloader.file=Caterina-Leonardo.hex
olimexino32u4.bootloader.unlock_bits=0x3F
olimexino32u4.bootloader.lock_bits=0x2F
olimexino32u4.build.mcu=atmega32u4
olimexino32u4.build.f_cpu=16000000L
olimexino32u4.build.vid=0x2341
olimexino32u4.build.pid=0x8036
olimexino32u4.build.core=arduino:arduino
olimexino32u4.build.variant=olimexino32u4

Create another folder 'variants' inside the olimexino folder.
Inside that, create the folder 'olimexino32u4'.
Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder
Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.
Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:
#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED1          PORTD |= (1<<5)
#define TXLED0          PORTD &= ~(1<<5)
#define RXLED1          PORTB |= (1<<0)
#define RXLED0          PORTB &= ~(1<<0)

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.

I've tried both values on TXLED and RXLED - one did not work. Only selecting the "Micro" board worked.

This is the best solution. The problem stems from UART activity taking control of the Tx & Rx LEDs. Switching to the 'micro' board just reverses the states of these LEDs. By creating a custom pins_arduino.h board, and defining these macros to nothing will disable their use entirely by the UART, making them simple GPIOs.

The TXled is connected to physical pin 22, or PD5. RXled is connected to pin 8, or PB0. They are connected to the cathode of the led, so they have to be HIGH to turn off the leds.
To turn them HIGH use:
PORTD |= (1<<PORTD5);
PORTB |= (1<<PORTB0);

Not sure what the firmware does, and if it sets the leds back to low every once and a while. So in addition I would suggest also setting those pins to inputs.
DDRD &= ~(1<<DDD5);
DDRB &= ~(1<<DDB0);

The Olimexino-32u4 connect the LEDs to GND, but as written in my comment, this approach does not work.

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


text:
ESP8266 failure to connect to router
I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):
void setup() {
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  delay(2000);
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(115200);
  delay(10000);
  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

When launching, I see following output:
<"random" bytes>
Ai-Thinker Technology Co. Ltd.

invalid

Performing a reset shows more:
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ŒÂÕ�MEM CHECK FAIL!!!
äsl�‚rô
Ai-Thinker Technology Co. Ltd.

invalid

The mode is set to station:
AT+CWMODE?

+CWMODE:1

OK

Listing the access points works fine:
AT+CWLAP

+CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
+CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
+CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

OK

But logging in to my Fritzbox router fails (WPA2):
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in AT+CWLAP).
I've tried nearly everything, e.g. AT+CWMODE=3, AT+RST, AT+RESTORE). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.
Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?
Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

It looks like the ESP8266 could not obtain the IP address over DHCP (it was enabled in the ESP8266, but the Fritzbox was configured for a limited range only .200 - .209). When setting the IP explicitly:
AT+CIPSTA="192.168.92.82","192.168.92.254","255.255.255.0"

OK

and then trying to connect, it worked:
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
WIFI GOT IP

OK

Pinging also works now: :)
AT+PING="arduino.stackexchange.com"

+39

OK

In my case when I try to connect to my router, I get the following output:
AT+CWJAP="myssid","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:
AT+CWDHCP=1,1

If that works, you will get this message:
OK
WIFI GOT IP

Old old old post I know, but pretty sure this is the (more universally) correct answer, rather than the accepted one.

I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post.
I did a AT+RESTORE followed by AT+UART_DEF=9600,8,1,0,0 since, as expected, my module expected communication on 115200 after the restore.
Then... as if by magic, everything works now...
AT+CWJAP="ssis","pwd"
WIFI CONNECTED
WIFI GOT IP

!

I really don't know what was wrong that the RESTORE fixed... I must have screwed up the module by experimenting with various commands somehow.

I had many headaches related with this CWJAP:1 error and few others like Ok in return for change IP number command but actually the IP number still the same as before !!! The solution: The AT+RESTORE command to bring the ESP8266 back to the factory defaults... When not logical things happens for unknow reason probably is due to some internal register has dirty values inside and only a AT+RESTORE can normalize them...


text:
Avoid a Pro Micro waking up a PC?
I have an Arduino Pro Micro mimicking as a HID, connected to a PC.
The PC BIOS is configured to wake from keyboard events - it is switched on by hitting a key on the regular keyboard. This is a wanted feature and should stay.
Unfortunately, it also wakes when the Arduino sends HID events, which is understandable and pretty obvious, but to be avoided.
Is there something in the USB protocoll, or even in the Arduino HID libraries, that lets me tell the chip to either not wake up the host (unlikely, I guess); or so that I can detect when the PC has shut down, so I can tell the Arduino to go sleeping as well until the PC wakes up again?
EDIT: I am using the "HID-project" USB library (HID 2.4.3) from https://github.com/NicoHood/HID.

You should be able to detect if the host is sleeping. Which USB library are you using?

@Gerben, I use the library at https://github.com/NicoHood/HID .

you can simply disable the "wake on keyboard" feature of your pc, if that helps

No, @dandavis, I would like just this one device to "behave".

maybe there is a key or two that doesn't wake up the pc. i always used pause to wake, but one laptop i had ignored that and a few other keys. it might also be possible to interrogate the locks without toggling, which hopefully wouldn't wake the PC.  i think it's possible because i thought i've plugged in a keyboard to a sleeping PC, had the caps lock light come on, but still had to press space to actually wake up the PC... Also, i wonder if those lock interrogations would time out  were the PC sleeping; a way to detect sleep.

There are many doubtful points in here. Your PC is powering USB ports when sleep or completely shut down? And why you send HID events with your Arduino if you don't want to do?

@user30878, it's nothing mysterious. PCs powering USB ports when off is pretty standard (else, "wake on USB" would be hard to implement); and my device must send HID events (it is a HID device). This questions asks about selectively avoiding the "wake on USB/HID" functionality for a single device by either telling the PC so (which is likely impossible as we are talking about BIOS/close to hardware-level functionality), or having the device detect when the PC is sleeping (more hopeful, but nobody came forth with a suggestion, and I didn't find anything about it anywhere else).

Ok but do you need send HID events always (continuously)?

Unfortunately, yes. The device sends HID events when some analog input changes; this can happen if someone bumps against the table or something like that.

We need to know your exact aim. You can send sleep command to your pro mini with PC just before sleeping. You want to don't wake up the PC from hid but your hid device is always active. It's meaningless

@user30878, I'm sorry if my question offends you. I believe it is pretty meaningful and precisely formulated. If you know a way to send a sleep command form the PC to the device, I'm all ears - just keep in mind that there is no dedicated OS driver for it, as it uses the default HID protocol.

Yes you can send commands to your pro mini from PC easily. You can use virtual serial com  ports with c#, c, Java etc... And you look like already know Arduino programming. But you maybe will need a push button or something like that for waking up the pro mini again.

@user30878, writing a program on the PC, and adding a push button is exactly what I wish to avoid with this question. If I went to that direction, then I would just have an on/off switch on the device and be done with it (which is what I've done meanwhile, anyways).

Look answers below

https://superuser.com/q/596758/697394

Assuming you are using windows, on the device manager you can access each device's properties (power management tab), where you can allow or not each device to wake your system up.

Check your BIOS for an option to wake up on a particular key combination, rather than "any key".
Another option is to configure a particular USB port to be powered down when the computer is asleep (or discover which ports are powered down if no such option is available). If that doesn't help, you can try to put a USB hub between the Arduino and the PC: many hubs don't cope with sleep modes very well, so there's a chance they won't re-transmit anything your Arduino is sending unless the PC wakes up. If your computer has USB3, you can try a USB3 hub, which has an even higher chance of exhibiting this behavior since BIOS often lacks USB3 hub support.

Any bios have this particular key option?


text:
is a 5V cellphone power supply stabilised?
can I feed my arduino UNO with a 5V cellphone USB power supply ?
Since the arduino board doesn't regulate the 5V from the USB input, is a cellphone power supply sufficiently regulated ?

Please state the reason for downvoting this question. The blog posted by Look Alterno proves that the question is relevant.

It is a USB (1.0 & 2.0) requirement that a USB Host power lines are 5 volts and can supply up to 500mA.  Here is a USB power standards table from wikipedia.org.
If your Arduino project pulls more, then the 5 volt level may drop.  That is to say, for more than 500mA you will need to consult the power pack specifications.

In general terms yes, the output of a USB power adaptor for a mobile phone will be suitably stabilised.
Most phones have the ability to monitor the voltage and adjust the charging current depending on the voltage they see. If the voltage drops below, say 4.5V, they will reduce the current they draw until it rises back above that threshold (as can be seen if you use a 1A cable on a 2A charger, the phone will throttle the current to within the 1A range since the cable imposes too high a voltage drop).
For this reason it is important that power adaptors put out the correct voltage otherwise mobile phones wouldn't be able to work properly with them.
Cheap imported USB power adaptors often fall far below proper safety standards, though, so you should use a proper branded one (Apple, Samsung, etc) from a reputable dealer, not something for $4 off eBay. Those cheap ones are a serious safety hazard and can cause electric shocks and fires.

So this means that the stabilisation is done by the phone and not by the adaptor. Since the Arduino will not reduce its current draw, using a USB power adaptor for mobile phone is a bad idea.

No. The power supply has to be stabilised for the phone to be able to detect a voltage drop from incorrect cable, etc. If the supply wasn't stabilised the phone would get confused and not be able to charge.


text:
Arduino compiler shows different value of sram memory
I have this code that shows the available sram memory
    int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

The arduino compiler shows a different value.

the arduino compiler shows 1856 bytes and
Serial port shows 1850 bytes

What is the correct value?

probably both ..

Did you take the used space on the stack into account?

Both are correct depending on what value you are interested in. The compiler tells you the size of the global variables. Your code tells you how much memory is free at any one time. Running code requires memory (most often the stack growing to accommodate local variables and the "stack frame" with a copy of the CPU registers in it every time you call a function).
In other words the compiler tells you how much is in your glass when it's handed to you by the barman but your code tells you how much is in there once you have taken a sip.


text:
Arduino Turn on a led with the PCA9865
I am using the PCA9865 to light a led
My circuit
Arduino to PCA9865
A5 > SLC A4 > SDA 5V > 5V GND > GND and
5 volts from a battery

My code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  //~60 Hz updates
}

void loop()
{
  int pin = 0;
  pwm.setPWM(pin, 4096, 0);
}

the led does not light

add a current limiting resistor in series with the LED. could you light the LED with Uno directly? set higher freequency

really? you wired it to 4 and 5 instead of A4 and A5?

As written in the comments check resistor/led AND make sure you get power/GND to the terminal on the PCA board as this is needed for powering servos/leds/motors hanging on the board. I use about 10 on my layout and they are fantastic for powering all kind of appliancies. I patched the lib but in your case this is overkill. Instead of
void setPWM(uint8_t num, uint16_t on, uint16_t off);

you could also try
void setPin(uint8_t num, uint16_t val, bool invert=false);

but that is not the problem here
EDIT
Thanks for the foto now its clear why not. You have to connect A4 (UNO SCA) -  SCA (PCA9865)  AND A5 (UNO SCL) - SCL (PCA9865) see diagram:

I added a photo of my circuit


text:
Change Word Color
I tried to change the color of the words but nothing happens, I do not know what I'm doing wrong. I am using official Arduino editor of code with words.txt
#######################################
# Syntax Coloring Map For testing
#######################################

#######################################
# Datatypes (KEYWORD1)
#######################################

Test    KEYWORD1
Diego   KEYWORD1
Ulises  KEYWORD1
PALMA   KEYWORD1

#######################################
# Methods and Functions (KEYWORD2)
#######################################

doSomething KEYWORD2
Argentina   KEYWORD2
Brasil      KEYWORD2
Alemania    KEYWROD2
Chile       KEYWORD2

#######################################
# Instances (KEYWORD2)
#######################################

#######################################
# Constants (LITERAL1)
#######################################

The of this page www.Arduino.cc

ARDUINO 1.8.3, es aquí https://www.arduino.cc/en/Main/Software

An IDE is a tool that helps us to develop our applications in a friendly way

is the editor of code

I'm sorry my communication in English is not perfect .. Arduino ide or Arduino Aide I was referring to using the text editor

The question's reference to “official Arduino with words.txt” is rather ambiguous.  So far there has not been any clarification whether the question refers to the usual Arduino IDE environment.
However, supposing the question intended to refer to the usual environment, note that the Library Tutorial document at arduino.cc says to do the following to set up a list of highlighted keywords:

Create a file called keywords.txt in the [library] directory

Thus, renaming your words.txt to keywords.txt may solve the problem.

Just to clarify, tabs need to be used as separators in the keywords.txt file, as spaces will not work.


text:
Process Sensor Data from Arduino Yun with Python
I'm currently working on a small project with my Arduino Yún.
I want to process the sensor data in python and send them in a message queue. I need to use Python3.
I cannot find a way to get the sensor data in my Python code.
I already tried to start the python process in my sketch and use the println method of the process object but this doesn't work.
I also tried to use the BridgeClient class from the Arduino Github but it won't work either.
Summarized:
I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.
I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.
The section below contains my Arduino sketch, which does the measurements.
#include <SparkFunHTU21D.h>
#include <Wire.h>

HTU21D myHumidity;

int trigPin = 11;
int echoPin = 12;

void setup() {
  // put your setup code here, to run once:
  pinMode(A1, INPUT);
  Serial.begin(9600);

  myHumidity.begin();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  //Perform 5 SoilMoisture-measurements and get mean
  float soil = meanSoilMoisture(A0, 5);
  float humd = myHumidity.readHumidity();
  float temp = myHumidity.readTemperature();

  float distance = getDistance();

  String dataString;
  dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
  Serial.println(dataString);

  delay(4000);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  long duration = pulseIn(echoPin, HIGH);

  // Convert the time into a distance
  return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
}

float meanSoilMoisture(int analogPin, int nMeasurements) {
  float sum = 0;
  for(int i = 0; i < nMeasurements; i ++) {
    sum = sum + readVH400(analogPin);
    delay(50);
  }

  return sum / nMeasurements;
}

//Perform Measurement
float readVH400(int analogPin) {
  int sensor1DN = analogRead(analogPin);
  float sensorVoltage = sensor1DN*(3.0 / 1023.0);
  float VWC;

  // Calculate VWC
  if(sensorVoltage <= 1.1) {
    VWC = 10*sensorVoltage-1;
  } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
    VWC = 25*sensorVoltage-17.5;
  } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
    VWC = 48.08*sensorVoltage-47.5;
  } else if(sensorVoltage > 1.82) {
    VWC = 26.32*sensorVoltage-7.89;
  }
  return(VWC);

}

I'd like to have a way to send dataString to the linux side of the Arduino Yún and process it with Python3.
As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the println method of the process.
{...}
Process proc;
void setup() {
    {...}
    proc.begin("python3 /mnt/sda1/test.py");
    p.runAsynchronously();
    {...}
}
{...}
    proc.println(dataString);
{...}

I've tried to read this dataString in Python3 in different ways, e.g. I've used the input method, because I read in a forum that I can handle such input like a keyboard input.
It didn't work and I didn't get an error, neither in Python nor in my sketch.
I've read different examples using the Bridge library. So I set up the sketch:
{...}
bridge.put("data", dataString);
{...}

I'd like to try out the BridgeClienton the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.
I would highly appreciate any help from you.

Are you having problems with the python code or Arduino code?

I've written arduino code that does the measurement and python code that processes the measurement and pushes the data into the message queue. I'm having problems with the connection between these two sides. I just need to send the measurment data to the python code somehow - with python3.

Please show us the code you are using. If the problem is with the Arduino sketch, it's "on topic" and we can help you. If the problem is with the python code, it would be better suited for Stack Overflow. Here is a link to a Stack Overflow question that has a simple sketch and python script to test if communication between the two is working: https://stackoverflow.com/questions/24682354/arduino-python3-script/30177116

It's an Arduino Yun, so I'm pretty sure this forum should be better for python and arduino sketch related questions. My code isn't relevant since I'm just reading sensor data, I don't have code for the communication between Yun Arduino and Yun Linux (python3)

It seems to me that you don't understand my question bc. you ignored the fact that I'm searching for a solution for an Arduino Yun. I have a Arduino Uno where everything works fine but I need another device where I listen for the serial data from the arduino. The Arduino Yun has a build in linux system, so I wouldn't need the additional device. I'm struggling to get the data to this linux system.

Please have a look at this question and it's answers: https://arduino.stackexchange.com/questions/18043/share-data-between-the-two-processors-of-the-arduino-yun. Have you tried the "Bridge library"?

Show us the code, or at least the parts relevant to the communication, and any errors etc associated. Edit your question and paste it in. Without that it's more or less impossible to help you.

When you say you tried using the bridge, did you try the tutorial on the Getting Started with Yun page? It is near the end and titled "Communicating with OpenWrt-Yun via Bridge". Once you get that working, maybe tweak it for your particular project? And definitely post the code. Just saying this didn't work, or that didn't do what I want is not helpful because we do not know what you did nor what you are expecting.

I didn't thought that it would be that hard to get sensor data from the arduino side to the linux side of the YUN since I thought this device was build for exactly this reason. I can't find one working example on the net (with python3), I don't want to migrate the BridgeLibrary from Python2 and it seems to me that there are no other options. Thank you to @VE7JRO for your "helpful" link - as quoted there: "Anyway, the real take away here is that the Yun is definitely not worth the hassle for me."

Right now, there are 2 votes to re-open this question, so I'm re-opening it. Comments are for clarifying the question and are not to be used to complain about Arduino products.

You are right, I'm sorry about that.

raphael, as per my comment earlier, we can not read your mind and sometimes you have to start at the basics to rule out possibilities. Did you try the tutorial at getting started with Yun???? If so, did that work? If not, what exactly did not work? When I exactly i mean what errors did you get? At what point did output stop? What happened jut before that and so on. Remember we can not see your environment, we can only rely on what you tell us and the problem might just be that you missed something.

also, i note that you have not actually shown us anything yet...  Please refer to
How to ask a good question
and
create a Minimal, Complete, Verifiable example. Especially the MCVE link (i.e. the second one)

You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.
Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.
From this post to the thread on the Arduino forums, Yun Serial connection between Arduino and Linux

Accepting HTTP connections, as shown in the Bridge tutorial, is
  but one facet of the Bridge library. (And probably the least useful
  and least efficient facet.) It is intended for accepting incoming
  connections from the greater network, not necessarily the local Linux
  processor.
The Bridge library is a collection of different classes that perform a
  variety of operations, all over the serial link between the two
  processors, and all can be used at the same time. The Bridge uses a
  network port paradigm, not HTTP. Using ports gives it a little more
  overhead, but it allows multiple simultaneous "connections" between
  the sketch and Linux sides.
I suggest you take a look at the Process tutorial. It does what
  you want, and 95% of the time it is the only part of the Bridge
  library that I use. The example defines Process objects that are local
  to a function, which run simple commands that do a little bit
  different f processing, return a result, and then exit.
My projects typically define a global Process object which starts a
  Python script, and keeps the connection open. Once open, the sketch
  can write to the Process object at any time, and the Python script
  reads that data from STDIN. Python can write to STDOUT at any time,
  and the sketch can read it from the Process object. The Process class
  derives from the Stream class, just like Serial, so your sketch can
  use any of the read/write methods you would use for a serial port. On
  the Linux side, you are just reading/writing as you would to the
  console. By default, Pythons runs in a buffered mode: I've found that
  you need to add the -u option to the command line that runs your
  Python script, or add it to the hashbang at the beginning of your
  script.
There are those who disable the Bridge library, and use the serial
  port manually on both sides. This can be done, but I've not had to
  resort to that yet. The Process class does everything that a direct
  serial connection can do, and more: you can have multiple simultaneous
  Process connections going, and you can still use all of the other
  Bridge library features. If you disable the Bridge library, you get
  just the one connection stream. It would be a bit more efficient, but
  unless you are dealing with high amounts of data, I'll bet you don't
  need to do that.
My typical project has the sketch running as a rather dumb I/O
  processor, passing barely digested input data down though one or more
  Process objects to a Python script. The Linux side does all of the
  heavy processing and network communications, and then sends output
  data back up the sketch which outputs it to the pins.


text:
LED doesn't turn on as specified on code State Machine
This is the question from the homework I'm doing "Design and implement a state machine with a single button to turn on and off two LEDs The first LED should be turned on and off with a quick press of the button, the second LED should turn on and off with a long press (1 second)."
I have this code
int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int ledPin2 = 8;
int ledPin = 9;
int boton = 10;
int boton2 = 11;
int val_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s1 = 0;
unsigned long t_s2 = 0;
unsigned long tiempo = 50;
unsigned long bounce_delay_s1 = 5;
unsigned long bounce_delay_s2 = 1000;
boolean prendido = false;
boolean prendidoP = false;

void setup()
{
  pinMode(boton, INPUT_PULLUP);
  pinMode(boton2, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  SM_s1();

  if(prendido == true)
  {
    led();
  }

  if(prendidoP == true)
  {
    led2();
  }

   Serial.print("state 1 =");
   Serial.println(state_s1);

   Serial.println("************");

}

void led()
{

  switch(state_s1)
  {
    case 0:         //OFF
    digitalWrite(ledPin, LOW);
    t_0_s1 = millis();
    state_s1 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s1 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin, HIGH);
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s1 = 0;
    }
    break;

  }
}

void led2()
{

  switch(state_s4)
  {
    case 0:         //OFF
    digitalWrite(ledPin2, LOW);
    t_0_s1 = millis();
    state_s4 = 1;
    break;

    case 1:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
      state_s4 = 2;
    }
    break;

    case 2:         // ON
    digitalWrite(ledPin2, HIGH);
    t_0_s1 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= tiempo)
    {
     state_s4 = 0;
    }
    break;

  }
}

 void SM_s1()
 {
  switch(state_s2)
  {
    case 0:         //RESET
    state_s2 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(boton);
    if(val_s1 == LOW)
     {
      state_s2 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s2 = 3;
    break;

    case 3:         //WAIT
   if(val_s1 == HIGH)
     {
      state_s2 = 0;
     }

    t_s1 = millis();

    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s2 = 5;
    }
    break;

    case 5:         //ARMED & WAIT
    t_s2 = millis();
    val_s1 = digitalRead(boton);
    if(val_s1 == HIGH && t_s2-t_s1 < bounce_delay_s2)
     {
      state_s2 = 4;
     }

     if(t_s2-t_s1 >= bounce_delay_s2)
     {
      state_s2= 6;
     }

    break;

    case 4:       //TRIGGERED
    state_s2 = 0;
    prendido = not prendido;
    break;

    case 6:     // ARMED 2
    state_s2 = 0;
    prendidoP = not prendidoP;
    break;

}
}

It will work the first time but then the LEDs won't turn off and sometimes when the button is pressed hard, it will turn both LEDs on, please help me.

please use the {} button to format the code

how do you press a button hard? ... is the button touch sensitive?

case 3 never reads if the button is pressed. It only uses the old value stored in case 1. I think case 3 should start with a val_s1 = digitalRead(boton);

Do you have the state-diagram for us, as the code is hard to understand with all those meaningless variable names.


text:
Arduino nano Serial port not recognized
First sorry for my bad english, not my native lenguage.
Today I started working on my Arduino nano (first time used). When plugged for the first time the "L" led started blinking, after that I tried to write a simple program but I noticed that the "Port" option on the Arduino IDE was Gray. So I couldn't choose the port. After that I searched A LOT but nothing seems to work.
While trying to test if the problem was the Arduino and not the PC, I make a simple circuit with 1 LED, 1 resistor of 1Kohm, and a breadboard. I connected the 5V pin to the LED and GNG to the other point, And when I did this the "L" LED stopped blinking forever. I am 100%  sure that I did not make a short circuit. ¿Maybe the breadboard is in a bad state?
Additional info:
-Windows 10.
-The port doesn't appear at Device manager (tried every port of my notebook).
-The "POW" led is ON when I plug the USB.
- The Arduino is a clone (chip CH340G).
So now I don't know if the problem is the port or if the Arduino Nano is dead because of a possible short circuit between 5V and GND pins.
thanks in advance!

Did you install the CH340G drivers?

I can't because the COM doesn't appear on Device Manager.

Not even in Unknown Devices ?

No. It doesn't appear at all.

Sounds like you most likely killed it. Maybe show how you wired the LED up with a photograph of it on your breadboard.

I can't show a picture, but I'm 100% that the connection was OK because that was my first fear so I watched closely and the 5V pin wasn't in the same line that the GND pin.

Maybe then it's just the curse of the cheap Chinese clone.

I assume you have tried another USB port and another cable, and tried something else in the USB port you had the Arduino in?

Yes, I tried all that.

And the results were that the board didn't wake up no matter which cable and port you tried, and the something else worked fine in the port you had been using?

Yes, I have an Arduino Uno and that works fine. When I plug the Nano The "POW" LED turns ON but nothing more.

Sounds like it may be fried. Possible that the CH340G has died.

Yes I think the same. Thanks for all your help !

I think your Arduino got short or the transmitter-receiver in it is damaged so the device manager cannot recognize the COM port.It once happened with my Arduino Uno. Try changing the USB cable.If it does not help your Arduino is damaged.


text:
New Microcontroller - programmer is not responding -
I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.
I get the following:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.
Did I buyed a bad/wrong MC, or I need to make something else?
Both have the same name :
ATMEGA328P-PU

The new micro controller has already a boot loader installed.

The new micro controller has already a boot loader installed. -- Are you sure? I have bought cheap chinese Nanos that haven't had a bootloader installed. If you don't buy it from a reputable source there is no telling what you may get. If in doubt program the bootloader on it yourself. Also make sure you set the right fuses on it.

@Majenko Also make sure you set the right fuses on it I do not understand this part. I plugged it the same how the original was. I also have two boards, and I followed Youtube tutorials about installing the boot loader and I installed the boot loader again and worked fine. But, after i decided to upload a sketch, got those errors

That's basic knowledge you should have before you start working with any microcontroller. The "fuses" tell the chip how to operate. What clock source to use, what boot vector, etc. All important stuff and has to be correct. You would normally do it before (or as part of) programming the bootloader.

@Majenko I followed this Tutorial and I had no problems.

http://heliosoph.mit-links.info/arduinoisp-reading-writing-fuses-atmega328p/

I managed to fix the problem by downloading the latest version of the Arduino IDE from their website and works fine now.
I use Linux mint 18 and installed Arduino via apt and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.

Likely you were trying to talk to the bootloader at the wrong baud rate, or were talking the wrong serial port.  If you only have the single board mentioned and no dedicated programmer or second arduino board to use as one, you haven't actually (re)loaded a bootloader.


text:
Power ON/OFF a car using Arduino with IR remote control
I'm trying somehow to power OFF the car when the song plays using Arduino using Infrared (IR) Remote.
I decided to play a song (SuperMario) using a Buzzer and when I press the Power ON button works fine and the song plays.
The problem is when I press Power OFF, I have to wait until the song ends to Power off the car.
I was thinking that maybe I need threads or something, but I'm not sure, or maybe there is a better way to fix this.
Here is a Demo program:
#include "IRremote.h"

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define powerLedRed    2
#define powerLedGreen  3
#define receiver       5
#define buzzer         7

void translateIR( void );
void powerON( void );;
void powerOFF( void );
void swap( int *x, int *y );
void playSuperMario( void );
void buzz( int targetPin, long frequency, long length );

int power           = 2;
int switchOFF       = 0;
int switchON        = 1;

int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7,  0, NOTE_C7, NOTE_E7, 0,
  NOTE_G7, 0, 0,  0,  NOTE_G6, 0, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0
};

int tempo[] = {
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
};

int underworld_melody[] = {
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_DS4, NOTE_CS4, NOTE_D4, NOTE_CS4, NOTE_DS4, NOTE_DS4, NOTE_GS3,
  NOTE_G3, NOTE_CS4, NOTE_C4, NOTE_FS4, NOTE_F4, NOTE_E3, NOTE_AS4, NOTE_A4,
  NOTE_GS4, NOTE_DS4, NOTE_B3, NOTE_AS3, NOTE_A3, NOTE_GS3, 0, 0, 0
};

int underworld_tempo[] = {
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,
  6, 18, 18, 18,  6, 6,  6, 6,  6, 6,
  18, 18, 18, 18, 18, 18,  10, 10, 10,
  10, 10, 10, 3, 3, 3
};

IRrecv irrecv(receiver);
decode_results results;

void setup( void )
{
  pinMode(buzzer, OUTPUT);
  pinMode(powerLedGreen, OUTPUT);
  pinMode(powerLedRed,   OUTPUT);
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
}

void loop( void )
{
  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);
  for (int thisNote = 0; thisNote < size; thisNote++) {
    int noteDuration = 1000 / tempo[thisNote];
    buzz(buzzer, melody[thisNote], noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    buzz(buzzer, 0, noteDuration);
  }
}

void buzz( int targetPin, long frequency, long length ) {
  digitalWrite(13, HIGH);
  long delayValue = 1000000 / frequency / 2; // calculate the delay value between transitions
  long numCycles = frequency * length / 1000; // calculate the number of cycles for proper timing

  for (long i = 0; i < numCycles; i++) { // for the calculated length of time...
    digitalWrite(targetPin, HIGH); // write the buzzer pin high to push out the diaphram
    delayMicroseconds(delayValue); // wait for the calculated delay value
    digitalWrite(targetPin, LOW); // write the buzzer pin low to pull back the diaphram
    delayMicroseconds(delayValue); // wait again or the calculated delay value
  }

  digitalWrite(13, LOW);
}

void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
}

void swap( int *x, int *y ) {
  if (*x != *y) {
    *x ^= *y;
    *y ^= *x;
    *x ^= *y;
  }
}

inside the translateIR function I have this:
void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

Here is a VIDEO Demo.
How to fix this?

There are two ways you can accomplish this. FYI, my buzzer is connected to pin 11 which is a PWM pin on the Arduino UNO.

Get a DFPlayer mini which can play the song and all you do is press the stop function to stop the music just like in your code. (Recommended)
Use MelodyWithoutDelay(Okay, but it works just as well and is less expensive)

For this answer, I will explain the MelodyWithoutDelay method.
As you have heard before, the delay function is a terrible way to stall the Arduino.  This is because the Arduino can not be aware, or multitask, while it is staring at its own clock.  I dealt with the same issue when I tried to "multitask" my Arduino to play music while receiving commands via Bluetooth.
For this reason, I created code a bit similar to the ToneMelody example given by Arduino.  I called it MelodyWithoutDelay.  It's a pretty swag name :)
Anyway, all you have to do replace my melody[] and noteDuration[] code with your melody[] and tempo[] code. And you have to change lengthOfSong to the number of notes in your melody from start to finish.
You might have to include the pitches.h file from the toneMelody example code given by Arduino.
But the bare meat you should be looking at is the void melodyWithoutDelay().
Instead of creating the code applicable to you, I will create the most basic form, which is the one I show below.  I need to show the MelodyWithoutDelay example to some viewers out there for their own projects too!.
Just marinate your head in the code and it should give you a good understanding on how to attack your mission.
If you want to test my code, Upload it and all you have to do is type 'g' in the Serial monitor and you should be able to pause and play the song.
If you're wondering where I used the code check out my Instructable.
Good Luck!
Here is the code:
    //Invented by Nathan Ramanathan
#include "pitches.h"  //File with all the music notes in the known universe
#define buzzer 11

unsigned long songMillis = 0;
bool check = false;
int thisNote = -1;
// notes in the melody:
//int melody[] = {
//  NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
//};

int melody[] = {//The FINAL COUNTDOWN song
  NOTE_B4, NOTE_A4, NOTE_B4, NOTE_E4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_E4, NOTE_FS4, 0, NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,   NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,NOTE_FS4,0,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_A4,   NOTE_G4,NOTE_FS4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_E4,NOTE_B4,NOTE_C5,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,    0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4,0, NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,   NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  16, 16, 4, 4, 2, 16, 16, 8, 8, 4, 2, 16, 16, 4, 4, 4, 4, 16, 16, 8, 8, 8, 8,  4,8,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,4,6,16,16,8,8,8,8,  2,16,16,3,16,16,8,8,8,8,4,8,1,4,8,16,16,4,4,2,16,16,8,8,8,  2,16,16,4,4,4,8,16,16,8,8,8,8,4,6,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,  4,6,16,16,8,8,8,8,4
};

const int lengthOfSong = 23+25+25+30+9; //For some reason the millis() doesn't like calculating array size.
//////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200);
  Serial.println("Type 'g' to hear a melody.");
}

void loop() {
  // no need to repeat the melody.
  unsigned long currentMillis = millis();
  if (Serial.available()) {
    int c = Serial.read();
    if (c == 'g') {               //type 'g' to start song
      check = !(check);
    }
    if (c == 'h') {               //type 'h' in the serial monitor to confirm that the arduino listens to you while it plays music!
       Serial.println("Hello");
    }
  }
  else {
    if (check) {
      MelodyWithoutDelay(currentMillis);
    }
  }
}

void MelodyWithoutDelay(long cMillis) {
  int noteDuration = 1700 / noteDurations[thisNote];
  int pauseBetweenNotes = noteDuration * 1.2;

  if ((cMillis - songMillis <= pauseBetweenNotes / 4)) {
  }
  else if ((cMillis - songMillis <= pauseBetweenNotes)) {
    tone(buzzer, melody[thisNote], noteDuration);
  }
  else {
    if (thisNote >= lengthOfSong) {
      thisNote = -2;
      check = false;
    }
    thisNote++;
    noTone(buzzer);
    songMillis = cMillis;
  }
}

Did you figure out your issue and is it working now?

What you have to is in the for loop within function playSuperMario to check for the Off button. If so, stop the loop.
This is assuming the delay for waiting until the note is finished is ok.\
Maybe a better 'design' is not to use playSuperMario as one function, but within the loop function, to keep a boolean that defines if the song is playing or not. If playing, call a function: playNextNoteOfSuperMario. You also need to keep the index of the next to play note.
Something like:
bool CurrentlyPlaying = false;

Maybe you can skip this variable CurrentlyPlaying since it is probably the same as (power == 2) ??. 2 means something, so use an enumeration for that.
void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
  CurrentlyPlaying = false;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
  I would expect power also to be assigned here.
  CurrentlyPlaying = true;
}

int CurrentNote = 0;

Set this variable again to 0 when Power On button pressed
void loop( void )
{
  if (songPlaying)
  {
      playNextNoteOfSuperMario();
  }

  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playNextNoteOfSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);

  int noteDuration = 1000 / tempo[CurrentNote];
  buzz(buzzer, melody[CurrentNote], noteDuration);

  int pauseBetweenNotes = noteDuration * 1.30;
  delay(pauseBetweenNotes);

  buzz(buzzer, 0, noteDuration);
}

I already tried something similar (if (power == 0 ){} ) inside that loop, didn't work, or maybe I not understand you. Could you provide an Example?


text:
SPI communication between two Ethernet Shields (W5100)
I am a newbie to the world of IoT, I want to ask...
Is it possible to connect two Ethernet shields with SPI? And if yes, how can I codes them?
I have reference from http://www.gammon.com.au/spi and I've tried SPI communication between two Arduino Unos send & receive any data type..
Now.. I want to put Ethernet Shields to each Arduino Unos, and I want to make them can communicate via SPI, It's like they can send & receive data type (ping IP address each other). If that scenario can running well, is it possible I can ping Shield one and Shield two?
(without router/switch, for this IoT research I still used local network, each Arduino w/ Shield plug to each laptop via RJ45 & USB port of course)
Topology:
Laptop A <===> Arduino Uno w/ Ethernet Shield <---> Arduino Uno w/ Ethernet Shield <===> Laptop B.

Note:

<===> = RJ45
<---> = Wire jumper (SPI or Pin 13 12 11 10, GND)

Sorry for my bad language, I didn't speak English well..
Can anyone help me?
Thank you,
H.


text:
I'm looking for the StreamSend.h library for use in Arduino/ESP8266 serial communications using struct
I've come across an interesting yet old article within StackExchange which has great examples of sending structured variables over serial communications. The library StreamSend.h and it's source code no longer exist on this site and I'm finding it difficult to track down. The examples shown look good and I'd like to use them in my application. My application is communication of large amounts of data between an ESP8266 and a Arduino UNO (both are combined on the same PCBA) via UART serial.
This is the article I'm referring to:
Sending Large Amounts of Serial Data
Can somebody send me the StreamSend.h library please or alternative methods for sending large amounts of data over serial (by large amounts of data I mean reading/writing say 10 to 20 variables of various data types so struct would suit well). Thank you.
Regards,
Brian

The code is in the article you linked to - right under StreamSend Class. Copy that code, save it as StreamSend.h or StreamSend.hpp.

Thanks romkey. I have created the StreamSend.h file and the ESP8266 and Arduino programs both compile.I send the struct from the ESP to the Arduino using the same code in this blog for send and receiving a struct. I can see on the serial monitor that the ESP appears to be sending data but the Arduino is quiet. I've noted the StreamSend.h file has #include "Arduino.h" but no reference to ESP8266. So could this be an issue?

I'd suggest asking that in a new question.


text:
How can I execute two functions at the same time?
#include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}

When I run this code and send '2', the servo() functions start, but it includes a delay function.
Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts after the servo function. I want to start this at the same time.

then send 3 ...

You have to check for a new instruction in the servo function too, e. g. before and after delay(5000) and splitting it into a while loop running one thousand times delay(5) and checking if there's a new instruction.

The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)
The answer is to rewrite your code to use millis() instead of delay. You record the current millis() value, and compare the new time to millis() to see if enough time has passed.
For the most part you should stop using the delay() function and forget exists. It will get you into trouble.
Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.

Make little task using millis function.
// GLOBAL VARIABLE
uint32_t taskMillis = 0;

....

// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.
https://www.youtube.com/watch?v=v5SpPXMmHJE
I hope this anwser will help you.


text:
CapacitiveSensor Library example works with great with UNO but not with Nano Every?
The CapacitiveSense library is the key to my project. A custom art touch lamp.
Arduino CapacitiveSensor Library
It works great with the Arduino UNO but the Nano Every has vastly different performance and issues with exactly the same code and HW. The Arduino is just too large for my project so I had high hopes that the Nano E would be a compatible fit.
My HW setup is per the example. Using a high value Resistor between pins 7 and 8 for Send and Receive(sensor). Works for the Uno but the Nano E just outputs a -2. Even though I tried resistor values 56K to 2M!. Realize the error -2 can mean a missing resistor. So I then tried the Threshold 3 way switch example code which suggests that just using pin 8 as an antenna is possible. I have a small steel plate (3"x4") connected directly to pin 8. Again Arduino Works great. By that I mean that I can adjust the parameters labeled in the code as a, b and c to get a repeatable trigger output to the serial monitor. The Nano Every with the same code though gets vastly different readings for cs and they don't stabilize. By vast , I mean Arduino returns cs numbers in range 100 to 200;s while the Nano E returns in the 33000's. Now I can make the code recognize those numbers for a trigger but subsequent touches range all over the place (1000's to 50000's) making touching the plate highly random with triggers.
I have made large tables (many hours) trying to dial the parameters in on the Nano with no success while it took me about 10 mins to dial in on the Arduino for reliable operation.
Why would the Nano Every be so different from the Uno?
The Threshold example code (bottom of page) in the library reference is perfect my setup as it is described as a used for a 3 way switch. The example code is below.
#include <CapacitiveSensor.h>
CapacitiveSensor cs_7_8 = CapacitiveSensor(7,8); //10M Resistor between pins 7 and 8, you may also connect an antenna on pin 8
unsigned long csSum;

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

void loop() {
    CSread();
}

void CSread() {
    long cs = cs_7_8.capacitiveSensor(80); //a: Sensor resolution is set to 80
    if (cs > 100) { //b: Arbitrary number
        csSum += cs;
        Serial.println(cs);
        if (csSum >= 3800) //c: This value is the threshold, a High value means it takes longer to trigger
        {
            Serial.print("Trigger: ");
            Serial.println(csSum);
            if (csSum > 0) { csSum = 0; } //Reset
            cs_7_8.reset_CS_AutoCal(); //Stops readings
        }
    } else {
        csSum = 0; //Timeout caused by bad readings
    }
}

Serial Output with Uno board with nice triggers.
parameters cs>700, csSum>=1500, samples are 10,
799
812
Trigger: 1161
I realize this is a lot of detail in this question. But I've searched this and other boards for anything on getting Capacitive Sensor to work reliably on any other board beside Uno and haven't found anything.
I'm also aware of the grounding issues talked about in relation to touch sensing. I had a previous post here about that using the Trinket M0 but abandoned that due to grounding issues with it.
I still have issues whether the Nano is connected via USB or an independent AC-DC power supply with 12vdc going to Nano.  I don't see any grounding issues with both the Arduino Uno and nano every with either USB power or independant AC-DC 12v power
Any insights appreciated.

You may have more luck with the plain Nano (not the Every), as it is built around the same MCU (ATmega328P) as the Uno.


text:
PlatformIO - Creating a library including a 3rd party library
I'm using PlatformIO, and I'm trying to create a library who uses another library in it.
(1) For that I created an empty library called ABCD.h stored in a newrep github repository.
(2) 3rd party library chosen is Panda_segmentBed_I2C.h with no particular reason.
(3) That library was inserted as needed to lib_deps and initiate build update the newly create library that it pulled 3rd party library as needed, as shown in pic1
(4) ABCD.h includes #include <Panda_segmentBed_I2C.h>
(5) Now to simulate a use of ABCD.h library inside a code, I've created a new project called TEST_NEWREP. Only 1 line was added to project:  #include <ABCD.h>
(6) After running build I get an error that 3rd party library, inside ABCD.h is not found.
(7) see TEST_NEWREP tree:

**Edit 1 - update .gitignore **
Somehow, when Project is created, a default .gitignore includes an ignore of .pio library. Perhaps in some cases it should be ignored, but when that Project is a library, it does not upload .pio\libdeps. Now after the exclude is removed, all dependencies are pulled as needed when build the project, BUT STILL ERROR REMAINS THAT Panda_segmentBed_I2C.h is not found.

You main.cpp should be in the same source directory with ABCD.h and ABCD.cpp (as a local library), and you declare it as #include "ABCD.h" in your main.cpp.

@hcheung but main.cpp is not part of library files.

You don't need to mess with the .gitignore, when compiling the code, the platformIO will download the library based on your libdeps configuration in your platformio.ini file.

If ABCD.h is a separate library, then you only need to set up the libdeps in your platformio.ini to use it. From the first picture you shown, the ABCD.h is not an independent library, but a local file to the project newrep.


text:
ESP32, ArduinoOTA.h LittleFS.h and data file upload OTA
I'm having a sketch, that works perfectly fine - connects to WiFi, uploading files using Esp32 LittleFS data Upload using Arduino IDE (when still connected to my PC), and sketch updates  via OTA (using ArduinoOTA.h library).
But when I try to Esp32 LittleFS data Upload when MCU is not connected to my PC, I get an error messages:
espota : /home/guy/snap/arduino/70/.arduino15/packages/esp32/hardware/esp32/1.0.6/tools/espota.py

[LITTLEFS] data   : /home/guy/Documents/Dropbox/Arduino/sketch_jul26a/data
[LITTLEFS] start  : 2686976
[LITTLEFS] size   : 1472
[LITTLEFS] page   : 256
[LITTLEFS] block  : 4096
/sketch_param.json
/sketch_param_32.json
/myIOT2_topics.json
/myIOT_param.json
/sketch_param_8266.json
[LITTLEFS] upload : /tmp/arduino_build_103180/sketch_jul26a.littlefs.bin
[LITTLEFS] IP     : 192.168.2.132

Sending invitation to 192.168.2.132 ..........
20:10:59 [ERROR]: No response from the ESP
LITTLEFS Upload failed!

Just to clarify:
A) sketch OTA works as expected (yes, I changed local USB to the remote one).
B) Tested on 2 different ESP32 MCU's, and failure is the same.
Question:

Is it possible to OTA data files using ESP32, ArduinoOTA.h, LittleFS, ArduinoIDE ? (It works when using ESP8266).

Guy

I can confirm that I've uploaded littlefs data to an ESP32 over OTA using PlatformIO. I haven't tried with ArduinoIDE but it should be possible. Have you tried uploading while monitoring the serial output (i.e. leave it connected to the PC). If you see something in the output, it might be format error coming from the ArduinoIDE upload tool, but I suspect it's just failing to connect.
Is it definitely connecting with the same IP between sketch upload and file upload? When I have these types of problems, it's usually because I've done something in the sketch to disable WiFi or the OTA check. Have you tried uploading the sketch again over OTA?

Uploading sketch, as mentioned, works flawlessly. And entire procedure on ESP8266 works both sketch and data files (sketch fits both MCUs).


text:
Char Array in PreProcessor
I need to define an array, that later on will be the name of a class, and will be pointed to.
For example (in a non pre-processor way):
const char *button_names[4]={"b0","b1","b2","b3"};
and later on (when it will be define in pre-processor), in a function it will be called as :
static Button2 button_names[i]
How can I define it that array to be in pre-processor?
Edit2:
Button2 *Buttons[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; // Here I use an optional up to 8 Buttons.

and later on, after I read parameter file: i get the numSW
/* Below example is only to check if I can use such technique - I know it is not a good coding. Example here is only for up to 4 Buttons*/
void init_buttons()
{
        for (uint8_t i = 0; i < numSW; i++)
        {
                if (i == 0)
                {
                        static Button2 bt1;
                        Buttons[i] = &bt1;
                }
                else if (i == 1)
                {
                        static Button2 bt2;
                        Buttons[i] = &bt2;
                }
                else if (i == 2)
                {
                        static Button2 bt3;
                        Buttons[i] = &bt3;
                }
                else if (i == 3)
                {
                        static Button2 bt4;
                        Buttons[i] = &bt4;
                }

                Buttons[i]->begin(buttonPins[i]);
                if (buttonTypes[i] == 0) /* On-Off Switch */
                {
                        Buttons[i]->setPressedHandler(OnOffSW_ON_handler);
                        Buttons[i]->setReleasedHandler(OnOffSW_OFF_handler);
                }
                else if (buttonTypes[i] == 1) /* Momentary press */
                {
                        Buttons[i]->setPressedHandler(toggle_handle);
                }
                Buttons[i]->setID(i);
        }
}

Could you give some background on what you are trying to achieve?

@EdgarBonet - Well it is complicated... I do not want to hard code the number of Button/ Relays each board have. it can be a dual relay, and possibly up to 16 relays on-board.
The amount of Buttons/Relay are stored in a paramter file which obviously read after all classes have been defined and created. So .... see edit 2 in a sec.

I cannot see the usefulness of these preprocessor macros.Please, explain what you are trying to achieve rather than how (e.g. with the preprocessor) you think you may achieve it. So far this looks like an XY question.

@EdgarBonet I hope Edit 2 is clearing that up

My main goal is to be able to define, not in code but reading from a paramter file, the number of instances of Button2 I need, since I want to use same code, for 2,4,8,16 Relays board.

use dynamic allocation with new

@Juraj I hope I explained my self right :( .... did you understand my main goal ?- Can you exaplin with an example how new solves it? ?

@Juraj Thank you- it was so simple.

void init_buttons()
{

        for (uint8_t i = 0; i < numSW; i++)
        {
                Buttons[i] = new Button2;   // <--- **Thnx to Juraj**!!!
                Buttons[i]->begin(buttonPins[i]);
                if (buttonTypes[i] == 0) /* On-Off Switch */
                {
                        Buttons[i]->setPressedHandler(OnOffSW_ON_handler);
                        Buttons[i]->setReleasedHandler(OnOffSW_OFF_handler);
                }
                else if (buttonTypes[i] == 1) /* Momentary press */
                {
                        Buttons[i]->setPressedHandler(toggle_handle);
                }
                Buttons[i]->setID(i);
        }
}

why not  Button2* buttons = new Button2[numSW];? then you can do buttons[i].begin()

I need Buttons[] to be defined at the beginning of code, meaning "global" (to have access to instances). I define it inside a function, since that was I can use nunSW that was read from parameter file in flash.

sorry, yes, in setup() buttons = new Button2[numSW]; while Button2* buttons; is global


text:
Leonardo (32u4): Timer0 problems with CTC mode
I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:
#define ALARM_PIN 11

void setup() {
  digitalWrite(ALARM_PIN, LOW);
  pinMode(ALARM_PIN, OUTPUT);
  noInterrupts();

  OCR0A = 60;
  // Toggle OC0A on compare match
  TCCR0A = (0 << COM0A1)
         | (1 << COM0A0)
  // CTC mode
         | (1 << WGM01)
         | (0 << WGM00);
  // prescaler = 256
  TCCR0B = (0 << WGM02)
         | (1 << CS02);
}

void loop() {
}

Any idea, what could be wrong?
Update
I've played with it a little bit more:
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 250);
}

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  OCR0A = 60;
  TCCR0A = (1 << WGM01);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 0);
}

What happens when you connect an led to pin 11? What happens if you flip the polarity of the led around? (So pin11--resistor--led--ground and pin11--resistor--led--vcc). If pwm is working then the led should be lid either way.

You should re-enable interrupts after you finish setting up. Use either
interrupts();

or
sei();

If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.
Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.

Thanks for the answer, but I don't need the interrupt, the port pin should be toggled automatically on compare match.

You are correct. I thought at the time that the bits would also control the compare match output, in any case you might not want to leave interrupts off.

Enabling interrupts at the end of setup() using sei(); does not make any difference.

Your value of 60 for OCRA will give you tone of around 16666hz which isn't audible to us humans. Try setting it to 255. That should give you a 4000hz tone, which is audible. (Or get your neighbors dog, and see if he dislikes hearing it)
You can use this online calculator to help you get the correct value for OCRA.
Note that you need 2 cycles to get a full wavelength (1 low and one high), so two toggles.

16MHz + 256 prescaler and the OCRA set to 60 should give me ~500Hz. I've tried different values, even your 255 but without success.

A decent-sized portion of the population can hear 17kHz sounds. 19kHz would be a bit of a stretch though.

My mistake. I don't know where I got that 8-prescaler from.


text:
Leonardo (32u4): ways to brick it programmatically
When the Leonardo was introduced, I think, I've read some articles about being cautious to do some things, that could cause it to not load any new sketches any more, so one has to rewrite the bootloader. Because I plan to use power-saving options, e.g. to disable unused hardware components like USB port, I fear to do something wrong.
One Leonardo-delicacy I've found so far:

if interrupts are disabled, uploading new sketches fails unless one presses the Reset button as soon as the Arduino IDE is showing "Uploading..."

What stuff (except of the usual hardware-related thinks like connecting output-configured pins to fixed potentials) could damage the controller or require to reflash the Leonardo with a fresh bootloader?

Generally, Arduinos are impossible to brick via software unless messing with the fuses on the chip (or designing a robot to destroy the board :D).

The bootloader is always run before your own program. So when you press the reset button the bootloader will start and you can upload you new program, even if the your old program was faulty. Disabling certain components is just temporarily, and they should restore when the device is reset. By changing the fuses you can make certain option permanent, so try to avoid having  to changing those.

Gerben, could you please add your comment as answer?

If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

Power on, boot loader starts, USB device enumerated on PC.
A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.
The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.

It is possible, with some really clever code, to exploit the bootloader to overwrite itself.
Excerpt:

The solution is actually conceptually fairly simple. A bootloader, by
  its very nature is designed to download new firmware to the device.
  Therefore it will contain at least one spm instruction. Because the
  spm configuration register must be written no more than 4 cycles
  before the spm instruction it means there are very few sequences that
  practically occur: just sts, spm or out, spm sequences. So, all you
  need to is find the sequence in the bootloader section; set up the
  right registers and call it.
However, it turned out there was a major problem with that too. The
  V-USB self-programming bootloader's spm instructions aren't a neat
  little routine, but are inlined into the main code; so calling it
  would just cause the AVR to crash as it tried to execute the rest of
  the V-USB bootloader.
Nasty, but again there's a solution. By using a timer clocked at the
  CPU frequency (which is easy on an AVR), you can create a routine in
  assembler which sets up the registers for the Bootloader's out, spm
  sequence; calls it and just at the moment when it's executed the first
  cycle of the spm itself, the timer interrupt goes off and the AVR
  should jump to your interrupt routine (in Application space). The
  interrupt routine pops the bootloader address and then returns to the
  previous code - which is the routine that sets up the out, spm
  sequence. This should work, because when you apply spm instructions to
  the bootloader section the CPU is halted until it's complete.

So basically, you can do some fancy programming, and get the bootloader to hose itself, rendering the MCU useless without a dedicated programmer.

I managed to brickwall an ATMega128RFA1. The bootloader, and the software I uploaded in it, were working fine. But it was impossible to erase/write the ROM.
After checking for what have happened, I discovered in the datasheet that some fuses in the AVR core are intended to protect accidental writing on the ROM. Some kind of security fuses.
I never found the bug which wrote in these bytes (as it was a really big program and we were 3 peoples involved in the coding) but yeah, we just blew a fuse and lost an MCU because of a bug.
As for the leonardo, several things could happen, but none of these can brickwall your board unless you blow one of this protection fuse.

The one I know of is making the Leonard act like a USB mouse that flaps everywhere and types random keys so you can't reprogram it without doing some kind of trick to get around it. But they mention this on the api docs.


text:
Olimexino 32u4: Wire.endTransmission() hangs
I'm trying to get a TAE5767 (FM radio) to work. According to this instructable I'm trying it on a 5V-Olimexino 32u4 (Leonardo-compatible) with following code (Arduino 1.6.3):
#include <Wire.h>

void setFrequency(float frequency) {
  unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  byte frequencyH = frequencyB >> 8;
  byte frequencyL = frequencyB & 0xFF;
  Wire.beginTransmission(0x60);

  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write(0x00);
  Serial.println("sending");
  Wire.endTransmission();
  Serial.println("sent");
}

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

  Wire.begin();
  setFrequency(89);
}

void loop() {
}

Unfortunately, it only prints
sending

First, I thought I'd damaged my chip, but I'm now using the second with the same result. I've also tried the I2C-Scanner from Nick Gammon, but it prints nothing. I've tried adding 2.2k resistors from SCL and SDA to 5V without success. Does someone has a clue what I can try?

I've did not got it working with Wire. Hence I've implemented a I2C protocol myself using bit-banging and then it works.
Update from 2017-September-16
The problem was not Wire.h but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.