text:
Standalone 328p Programming with CH340G programmer
I have made a standalone arduino board with a Atmega328p w/ Uno bootloader taking inspiration from this video https://youtu.be/sNIMCdVOHOM
However, when I try to program mine all I get is "Problem uploading to board".
I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter to program the board instead.
Other things that I have tried:
Swapping Tx/Rx from adapter to board
Adding 100nF capacitor on DTR to RST
Trying without DTR
(The board also has a 10k pullup resistor on the RST line)
Burning a new bootloader after programming with Arduino as ISP
Any suggestions are greatly appreciated.
Thanks,

Verbose Upload Output
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM7 -b115200 -D -Uflash:w:C:\Users\Admin\AppData\Local\Temp\arduino_build_446007/Blink.ino.hex:i
     Using Port                    : COM7
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe8
avrdude done.  Thank you.
Problem uploading to board.

Please edit your question to include the verbose upload output (File > Preferences > Show verbose output during: > compilation (uncheck) > upload (check) > OK).

What crystal did you use?

The crystal is a 16Mhz

Well, one thing you should do is ISP load a sketch that actually uses the serial in both directions, and verify that you have that communication actually working.

I have previously tried using serial communication on the board via  ISP with the UNO however, I was unable to receive understandable data  - everything that came out was random symbols that wasn't what I was looking for.
This is why I had swapped to using this adapter as I thought it would be much simpler to function :P

Huh?  ISP is for programming, not asynchronous serial communication at runtime.  It sounds like you have a problem, bu you're going to have to be absolutely specific about exactly what you tried.

The problem I have currently is using the USB adapter to program the circuit, which I didn't think had anything to do with when I programmed the circuit through my UNO.
When I did that I tried hooking the RX/TX pins up from the UNO to my standalone board for serial communication (something I saw online which said that was how it was done). When this didn't work I switched to my USB adapter to try program the standalone board through that

Have you set the right fuse bits on your chip for the 16MHz crystal, or are you still running on the internal oscillator? If you are your bootloader and sketch serial baud rate will be completely wrong.

I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter.

Because the ATmega family does not support a partial flash erase via ISP, loading a sketch via ISP removes the bootloader.
Therefore you must (re)load a suitable bootloader using the ISP connection, before you can perform a serial upload of a sketch using that bootloader.

Oh, I didn't know that.
Would I be able to flash the bootloader from my Uno to use on this board, using the same ISP connection that I did previously?

I just tried burning the booloader from my UNO onto my other board, then reconnecting the USB adapter and it still does not upload and I receive the same error.

There are two stages to programming a chip.  First is to get the firmware (the bootloader, for example) on there, which you have done.
Second is to configure the chip to operate in the way you have wired it up. Specifically to configure the oscillator and clock source.
The bootloader and your sketch all expect the chip to be running at 16MHz. It uses that constant value to calculate things like the baud rate for serial communications.  If the chip isn't running at 16MHz then all those calculations will be meaningless.
You have connected a 16MHz crystal, which is good, but unless you tell the chip to use it you will still be using the internal oscillator for your clock source as set in the factory.  This is an 8MHz oscillator with clock division down to 1MHz.
You need to configure the fuse bits on the chip using avrdude and your Arduino as an ISP.
This article details exactly how to do it and teaches you what the fuses are and what they mean.

Fuses should automatically be set appropriately when the IDE is used to burn the bootloader, unless the boards file is broken.

@ChrisStratton Maybe it is. Or maybe he had the wrong board selected. Going by the comments the baud rate is wrong, which points to a mismatch between the oscillator (or fuses) and F_CPU.

I just assumed that when I programmed it with Blink the first time on breadboard (with my UNO) it was all set up correctly as the timing looked correct. I will check that article and see.


text:
Mounting an Arduino inside a PC
I want to mount an Arduino Pro Micro inside my PC, hooked up to the PC's USB.
I don't want to have external cables for this, but have it neatly cabled inside.
My motherboard has USB connectors with 9 pins (5+5 grid, 10th pin key), like these:

These connectors would take a cable that looks like this:

But how would I connect this to the Arduino that has Micro USB?
I've been looking everywhere, but 9-pin USB to USB Micro does not seem to exist?
The closest I could find is a cable that goes from USB micro to a 5-pin header:

What is the preferred way to hook up an Arduino Micro with internal cabling?
Why does the 9-pin to USB-micro not exist?

why 9 pin USB to USB? .... top picture shows two USB cables

@jsotola I don't understand what you mean. Top picture is of a motherboard with 2 USB connectors. Middle pic is of a connector that would fit it. Bottom pic is of a cable that I found to be available. What is missing is a cabled that is 9-pin one end, and micro usb at the other end.

sorry, 2nd picture shows two separate usb cables

@Bram, @jsotola is highlighting in the comments that the example photo you show with a 9 pin keyed  two row connector has two usb cables connecting to it. USB connections often have four wires each. The standard wire color coding is:

(Source Wikipedia - USB)
Board manufacturers are often looking for a simple way to connect multiple panel mount USB ports to the PCB and this could have been a cheap and convenient way to connect two USB ports per pcb connector.
Some suggestions:

Research the specific motherboard online to see if a schematic or connector layout is available. It’s quite likely to be laid out like this:

Experiment by making your own connector, and use a multimeter to figure out which are the power and which are the data wires.
If the old USB ports which used to connect to the PCB are still available, investigate further until you’re more confident about how they were wired.
An adapter may help you experiment further to understand the PCB connections further.

A micro-USB breakout board may help you experiment with connections on the Arduino side.

no need to experiment.  5th pin in micro is for otg ID: https://electronics.stackexchange.com/questions/35462/why-does-micro-usb-2-0-have-5-pins-when-the-a-type-only-has-4

Thank you! My local electronics shop had the breakout board in stock! I don't know yet what to do with pin ID, though. I think it is needed to specify which side is device, and which side is host.

I think the PC as host would be a could configuration to try first.

@Bram, checkout @Abel’s link in the comment above for more information about the ID pin.

source: Stack Exchange

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

sort: votes


text:
HID with bidirectional communication
I want to build a gamepad HID using the Arduino Micro, and intend to use Nico’s HID library for that.
But I would like to send some config info from the PC to the Arduino HID as well.
Can you have a gamepad that not only sends state to the PC, but also receives a configuration from the PC?
I intend to use this with a Linux PC as host.

Yes, but the configuration side of things will not be part of the gamepad HID.  You will need to set up a second communication channel - be that serial or raw HID - to do the configuration.

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


text:
USB OTG and ESP32-S2
I have an ESP32-S2-DevKitM-1 which is supposed to able to act as USB HID device.
But whatever I try using either ESP-IDF or Arduino-IDE, I can't get any data from it.
I ran this esp-idf example.
I also ran the arduino example.
I connected GPIO20/19 to D+/D- of a USB cable.
When I plug in that cable, my host computer logs:
usb 1-6: new full-speed USB device number 93 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb 1-6: new full-speed USB device number 94 using xhci_hcd
usb 1-6: device descriptor read/64, error -71
usb 1-6: device descriptor read/64, error -71
usb usb1-port6: attempt power cycle
usb 1-6: new full-speed USB device number 95 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 95, error -71
usb 1-6: new full-speed USB device number 96 using xhci_hcd
usb 1-6: Device not responding to setup address.
usb 1-6: Device not responding to setup address.
usb 1-6: device not accepting address 96, error -71
usb usb1-port6: unable to enumerate USB device

The esp-idf example fails to send, because tud_mounted() is false, and the arduino-ide example fails on SendReport(): not ready.
How can I get the ESP32-S2 to talk USB with my host computer?

This problem went away when I replaced my DIY USB cable connection with an Adafruit USB-C breakout board.
I checked all the connections of my cable, but somehow it would not work, until I replaced it.


text:
Arduino nano ATmega328p with CH341 won't upload
When I try to upload a sketch to an Arduino Nano, it stays stuck on uploading, and after a time it shows the following error code:

stk500_getsync() attempt 1 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 2 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 3 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 4 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 5 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 6 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 7 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 8 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 9 of 10: not in sync: resp=0xc2
stk500_getsync() attempt 10 of 10: not in sync: resp=0xc2

Sometimes the resp=0xc2 variable changes to another hex code.
The weird thing here is that before this happened everything worked fine. I could upload and the serial communication was fine. But after trying to upload the same sketch with a different variable, this started to happen.
Windows recognizes the COM port, in Arduino the COM port is selected. Sometimes, without doing anything, the Arduino works fine again, I can see the serial communication fine, but after some time the serial communication stops sending and again I can't upload the sketch.
I have 2 Arduino Nanos. Both of them start presenting the same problem. But the other one has the Power, RX, and TX led always on and this one never worked again, like the other one that sometimes can upload the sketch and see the serial communication that the last sketch was sending. I have an Arduino Mega, this one has the ATmega16U2 to communicate to USB and this one works fine. And I also have a NodeMCU Lua, with CH341. But this one works just fine.

Do you have an oscilloscope? If so, check on the RX and TX pins if, when writing something in a serial terminal, a signal passes through the USB/UART bridge. If it does, the problem is the microcontroller (maybe flash the bootloader again). If it doesn't, the CH341 is broken. Also check the +5V voltage...

I don't have an oscilloscope :(. I manage to upload the Blink program and at first time it was blinking at the rate of 1 second, but after some time the blink start going wild and start blinking really fast. About the serial communication, I put RST to ground, and connect RX to TX and I opened the serial monitor and I start sending words and both RX and TX light up every time i hit enter. But nothing show in terminal. I already flash the bootloader again in both and still the same. In the one that the TX and RX are always on, it didnt let me flash the bootloader.

The suggestion by John Allen is exactly what it took to get my 1.8.5 IDE to upload successfully to my Nano boards. Happy Day!!
Just a note - the 'ATMega328P (Old bootloader)' option does not seem to be available in IDE 1.8.5 on my old WinXP machine.

If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --> Processor:"ATmega329P" --> ATmega328P(Old Bootloader)

Open your device manager in computer if ot would show your arduino nano as USB 2.0 then you need to install CH340G DRIVERS from Google install it and then again connect it to the computer your problem would be solved but remember to remove TX and RX pins before uploading code...

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


text:
Recording of sensor results but only retain the last 3 sets of data
I'm doing a radiation-seeking robot, which will find the source of the radiation autonomously. But in this case, my robot will spin 180 degrees to detect the nearest source of radiation and 1 set of data recorded is considered for every 180 degree turn. However I think it is not possible to store all of the data in the Arduino due to a storage problem.
Therefore is there any function in Arduino that can only record the last 3 sets of data from the sensor? For example, after it has recorded 3 sets of data, the fourth set data could be recorded by overwriting the first set of data. I would be really grateful if anyone could help me with this.
PS if possible I don't want to install an SD card in my Arduino.

It depends how big the data is... if one data set is 100 bytes, you can spend 300 bytes of internal SRAM memory.
What you also can do if the memory usage is too big, is to add external SRAM, like the 32K256 which has 32 kb (kilobyte) SRAM or the 23LC1024 which has 128 kb SRAM.
To loop through the data sets you can easily use a so called 'ring buffer'.
You allocate 3 sets of data (like 3 arrays of a byte array), and an index. the index you increase after every use like:
index = (index + 1) % 3

External SRAM normally uses SPI to communicate with, and you can read/write it by a single byte, multiple bytes or page (typically 128 to 512 bytes). You cannot directly store variables in it, but you have to manually keep track where you store what ... for 3 data sets this will be relatively easy. You can even calculate (beforehand) the number of data sets that can be stored and cycle through them as needed.

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


text:
Can I use an Arduino Uno to support an RFID reader, Zigbee module and a touch screen at the same time?
I'm almost a beginner to microcontrollers and have done a few simple projects, but this time I have to use an Arduino Uno (powered by a battery) to support an RFID reader (RC522), a Zigbee module and a touch screen altogether. Apparently there are too few pins to support all the modules. What is the easiest way to implement such a system?

use an i2c or spi screen. try to match that protocol with your other modules. with all i2c modules, you can connect all three with only 2 pins. With all SPI, you still only need 5 or 6 pins.

Also I don't know what the RFID, zigbee and touch screen uses (generic GPIO pins, I2C, SPI, something else)?
You always can combine multiple inputs/outputs using a multiplexer (i.e. 74HC165, 74HC595), although it will mean extra software and less performance.
About the touch screen, that might be problematic regarding performance and memory usage, since the Uno has only a few KB and even the more expensive Arduino's do not have that much memory you might need.


text:
Arduino motor driver 3.7v
I am planning to build my own micro quadcopter, so I bought an Arduino 101 and 3.7v micro DC motor.
So the next step is finding a motor driver that can control these four motors, using PWM pins on the Arduino board. I spent a lot of time searching for it, but all I found was a 5v motor driver and other types of Arduino shields that can't work in my project. Has anyone my requirement (name of motor drive, micro-controller, circuit)?
Thanks in advance.

Build your own H bridge with suitable MOSFETs?

Majenko do you have any pdf about the circuit and the element that i need , because i'm still a student so i know a little bit about electronic components .Thanks !

https://www.google.co.uk/search?q=h-bridge+mosfet&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi7sdaU55fTAhXIvBoKHRnQDcEQ_AUICCgB&biw=1120&bih=619

@Majenko He doesn't need a H bridge unless he wants to fly the quad upside down (would be cool to make your quad flip and stay flipped :D ). All he needs are some big logic-level N-channel mosfets. For the components you can easily find information on google about how to connect them, just search for "arduino mosfet motor control", but make sure your mosfets are logic level (it's a must, these motors can draw some amps and you don't want your fets to catch on fire because of them not being fully switched).

@AndreiDragan That is very true. Imagine the acrobatics you could do though :)


text:
Arduino is running as a server, but want to occasionally act as a client to update time
My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.
It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:
https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/
... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.
Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?

you don't need to worry. and use the built in SNTP function, not an Arduino library. https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/Time/SimpleTime/SimpleTime.ino

it's not in access-point mode is it? if so, that's a problem. otherwise you can run arbitrary client requests from a server no problem.

I think not (access-point).   My sketch is built on top of the SimpleWiFiServer example.

There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).
But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's SimpleTime example.

I have used the code in the SimpleTime example and it works like a charm.   Thanks.  I'm simply going to call getLocalTime once a day and reset my RTC.   I don't care if I'm off by a few seconds, just don't want those to accumulate over many days.

I was mildly concerned I could get into an infinite loop - RTC is running fast, when time of day for adjusting via SNTP comes, it gets reset to slightly earlier time, and then hits the adjustment time again.   But that's just silly - it doesn't get retarded much at all the second time.

what for the RTC? ESP32 has built in RTC and updates it over SNTP

I am using cheap ($4.95) PCF8523 w/ battery.

I did not know about one on ESP32 (Adafruit's doc for HUZZAH32 does not mention it).  It appears to require an external crystal for any kind of reasonable accuracy, and doesn't maintain if ESP32 is off.  Of course, if I usually am wifi-connected and with SNTP, maybe that doesn't matter.


text:
Combining 2 IF statements, getting nowhere and pulling hair out! ;)
I`m new here so just wanted to say hi!
I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.
Trying all sorts with LCD, temperature etc.
But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.
Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I`m running into issues.
If anyone can look over the code and advise me where to put "if(h < humLowTrigger){"
I have tried before the times, included it in each line of the times and after the times and still not working.
So all help and knowledge greatly appreciated.
Cheers for now Alan
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

#define humLowTrigger 70
#define DHTPIN 7
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

RTC_DS1307 rtc;

void setup () {

Serial.begin(9600);
dht.begin();
Wire.begin();
rtc.begin();

pinMode( A2, OUTPUT);
digitalWrite(A2, LOW);
}

void loop () {

float h = dht.readHumidity();
float t = dht.readTemperature();

DateTime now = rtc.now();

if (now.hour() == 15 && now.minute() == 5) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 8) {
digitalWrite(A2, LOW);
}
if (now.hour() == 15 && now.minute() == 10) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 12) {
digitalWrite(A2, LOW);
}

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %");
Serial.println();
Serial.println();
delay(2000);

}

In addition to LookAlterno's answer (which I upvoted), the last part can be reduced to:
if ((h < humLowTrigger) && (now.hour() == 15)) {
  if (now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

See my comment under Look Alterno's answer. You need to turn the mister off at the designated time, even if the humidity has risen.

Note this was changed on the code of LookAlterno before he updated it.


text:
Logic Gates Identifier
I want to build a program which identifies logic gates connected to Arduino, by testing the output with changing the input voltage...
Here is the code:
int output1 = 0;   //Change output pins HERE
int output2 = 1;   //and HERE
int input = 2;     //Change the input pin HERE, where we will read the data (0 or 1)

void setup() {
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(input, INPUT);
  Serial.begin(9600);  // Start serial communication at 9600 bps
}

void loop() {
  int result[12];
  for(int i = 0; i < 2; i++) // For failure test, it runs 3 times
  {
    digitalWrite(output1, LOW);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4] = digitalRead(input);
    digitalWrite(output1, LOW);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 1] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 2] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 3] = digitalRead(input);
  }
  if(result[0] != result[4] && result[0] != result[8] && result[1] != result[5] && result[1] != result[9] && result[2] != result[6] && result[2] != result[10] && result[3] != result[7] && result[3] != result[11]) // See if the results don't matches...
  {
    Serial.println("Input read error, please try again!");
  }
  if(result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1) // AND gate
  {
    Serial.println("This is an AND gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 1) // OR gate
  {
    Serial.println("This is an OR gate");
  }
  else if(result[0] == 1 && result[1] == 1 && result[2] == 1 && result[3] == 0) // NAND gate
  {
    Serial.println("This is a NAND gate");
  }
   else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0) // NOR gate
  {
    Serial.println("This is an NOR gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 0) // EXOR gate
  {
    Serial.println("This is an EXOR gate");
  }
  else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 1) // EXNOR gate
  {
    Serial.println("This is an EXNOR gate");
  }
  else // If there is no match...
  {
    Serial.println("This is not even a gate");
  }
}

It always gives back 1s... I have tested with leds, it works perfectly by changing the input, but as soon as serial.begin is declared in setup, it fails to work, the just stays on and I said, the program just gives back 1s.
What I'm missing?
Thanks!


text:
Problems adding ESP8266 wifi board
I just received an ESP8266 wifi module and I am trying to add the board. However I am having an issue. All websites/tutorials say to use http://arduino.esp8266.com/stable/package_esp8266com_index.json, however nothing is there. Can it be found somewhere else?

Can you please add more information to your question.

I am mirroring (eventually when the uploads finish) most of the files here: http://majenko.co.uk/esp8266

It looks like the server is down.  Isitdownrightnow reports that it's been down for almost 4 days: http://www.isitdownrightnow.com/arduino.esp8266.com.html
There is a discussion about it over on the ESP8266 forums: http://www.esp8266.com/viewtopic.php?f=26&t=3134&start=8
Let's hope it will be back again soon.


text:
Arduino Uno with ESP8266
#include <stdlib.h>
#include <SoftwareSerial.h>

#define SSID "name-of-my-network" //replace XXXXX by your router SSID
#define PASS "password-of-network" //replace YYYYY by your router password
#define IP "184.106.153.149" //thingspeak.com IP

const int tempPin = A0; //configure Arduino pins
String GET = "GET /update?key=thingspeak-api-key&field1=";
SoftwareSerial mySerial(10,11); //Serial communication to ESP8266 module(RX, TX)
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long delay_time = 60000;

void setup() {
  Serial.begin(57600);
  while(!Serial) {
    ;
  }
  mySerial.begin(115200);
  Serial.println("Initializing...");
  //communication with wifi module
  mySerial.flush();
  mySerial.println("AT");
  delay(2000);
  if(mySerial.find("OK")) {
     Serial.println("Communication with ESP8266 module: OK");
   } else {
     Serial.println("ESP8266 module ERROR");
   }
   connectWiFi();
   //initialize timer
   starttime = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
  if ((millis() - starttime) >= sampletime_ms) {
    char buffer[10];
    int analogReading = analogRead(tempPin);
    String temperatureStr = dtostrf(analogReading, 4, 1, buffer);
    temperatureStr.replace(" ","");
    updateSensors(temperatureStr);
    //wait next sampling cycle
    Serial.print("Wait ");
    Serial.print(delay_time/1000);
    Serial.println("s for next sampling");
    Serial.println();
    delay(delay_time);
    //initialize new cycle
    Serial.println();
    Serial.print("Sampling (");
    Serial.print(sampletime_ms/1000);
    Serial.println("s)...");
    starttime = millis();
  }
}

void updateSensors(String tempStr){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  mySerial.println(cmd);
  delay(2000);
  cmd = GET;
  cmd += tempStr;
  cmd += "\r\n";
  delay(1000);
  int strsize = cmd.length();
  mySerial.println("AT+CIPSEND=" + String(strsize));
  delay(2000);
  mySerial.print(cmd);
  if(mySerial.find("OK")) {
    Serial.println("Transmission completed with success");
  } else {
    Serial.println("Transmission failed!");
  }
}

boolean connectWiFi(){
  Serial.println("Connecting wi-fi...");
  String cmd ="AT+CWMODE=1";
  mySerial.println(cmd);
  delay(2000);
  mySerial.flush(); //clear buffer
  cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  mySerial.println(cmd);
  delay(5000);
  if(mySerial.find("OK")) {
    Serial.println("Connection succeeded!");
    return true;
  } else {
    Serial.println("Connection failed!");
    return false;
  }
  Serial.println();
}

I am using the above code and have connected the ESP8266 to the Arduino as follows:

TX of ESP8266 to pin number 11 of Arduino
  Rx of ESP8266 to pin number 10 of Arduino
  Vcc of ESP8266 to 3.3V power supply taken from Arduino
  GND of ESP8266 to GND taken from Arduino
  CH_PD of ESP8266 to GND

It seems that I can't get the ESP8266 working. Could anyone could help me? I would really appreciate any help since I cannot continue my project.

Does your ESP module have the AT firmwware?

If you interconnect two serial devices, the RX of device 1 is connected to TX of device 2. You appear to have connected RX to RX and TX to TX.

CH_PD of ESP8266 to GND should be at 3.3v instead of 0v...

Often the issue with this module is that the 3.3v of Arduino is unable to maintain enough current for the ESP8266 to work properly. I assume you have the proper firmware flashed to the wifi module

Yes, you are right. After many different attempts p, I figured that out. When I use the module with h a 3.3V FTDI, it works perfectly. When I use it with Arduino, data that is being sent to or received from the module, is corrupted. Arduino can't supply enough current to the ESP8266 module.

This code is used to upload temperature data on pin A0 to things speak
Create thingspeak account and create channel you get api key it seems that this code uses field1 to upload data upload this code to arduino the change ssid and password

authors: Віктор Єрьомкін


text:
Additional boards manager option is missing from Arduino IDE
I am new to Arduino. For the project I am trying to do, I want to install the ESP8266 extension. But the additional boards manager URL option is missing from the Arduino IDE. What should I do to add the extension?

Update to a version that has the option.

I just installed the ide 2 days ago . I have the latest one.

What version do you have that you think is the latest one?

Version of installed ide is 2:1.0.5+dfsg2-4

1.0.5 is ancient.

You need to download and install a recent version of the Arduino IDE from:
http://www.arduino.cc/en/Main/Software
When you install the Arduino IDE using apt-get you get a very outdated and non-standard version, which does not have the Boards Manager feature. The reason for this is that the license documentation of the Arduino IDE does not currently meet the required standards for the package manager:
https://github.com/arduino/Arduino/pull/2703

the URL is the following and the 1.8.2 IDE accepted it:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
Good luck,
endre
P.s.: I found the answer/URL here:
No Response to AT commands

this worked....actually this is the correct url

You stated in the comments that you are using version 1.0.5. This is a very old version. Go through you computer and make sure you uninstalled any old versions, then try to reinstall the ide.
Make sure you download from arduino.cc, the official location to download the software.


text:
Arduino 101 accelerometer drift or calculation error?
I want to calculate the displacement of the Arduino 101 board compared to the starting point (only in the x direction so far).
In below data I'm swinging the board multiple times in circles around my laptop and then putting it back at the origin a few seconds later.
Regardless if 1ms-100ms between the loops, the numbers show no sign of the board returning to the origin. I've calibrated the accelerometer x-axis as closely as possible.

Am I doing something wrong in deriving the acceleration/velocity/distance, or is this the level of compounding error to expect?
If so, can combining gyro data correct acceleration (thought it mainly worked the other way around)?
I have a GPS meant for correcting position but was hoping any drift wouldn't be this quick.
EDIT: I was incorrect re. use of gyro data; the attitude of the board, which was not consistent in my swings, will effect the acceleration output. Gyro data can be used to calculate and "cancel out" this gravitational impact, and get a more accurate (linear) acceleration (http://www.cl.cam.ac.uk/research/dtg/www/files/publications/public/abr28/ojw28_thesis.pdf). Will report back in a few days.
Code:
#include "CurieIMU.h"

float gravity = 9.80665; // to convert G forces (1 m/s2 = 0.101972 g; 1 g = 9.80665 m/s2)
long t1; // create object for first time reference, set time just before the loop later on

// Variables that are dependent on value from last loop
float vx, vy, vz;
float imu_x, imu_y, imu_z;

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial to open

  Serial.println("Initializing IMU device...");
  CurieIMU.begin(); // start accelerometer / gyro
  CurieIMU.setAccelerometerRange(2);  // accelerometer range to 2G - might need to be greater later on (18 m/s2 highest possible now)

  /*

  // Auto-calibration to ensure accelerometer doesn't drift
  CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS, 0); // 89.69999 creates both positive and negative spikes
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS, 0);
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS, 1);
  delay(1000);

  */

  // Hardcoded accelerometer offsets after testing
  CurieIMU.setAccelerometerOffset(X_AXIS,89);

  // Fetch the offsets from the IMU
  float x_offset = CurieIMU.getAccelerometerOffset(X_AXIS);
  float y_offset = CurieIMU.getAccelerometerOffset(Y_AXIS);
  float z_offset = CurieIMU.getAccelerometerOffset(Z_AXIS);

  Serial.println("Current x_offset, y offset, z offset");
  Serial.print(x_offset, 6);
  Serial.print("\t");
  Serial.print(y_offset, 6);
  Serial.print("\t");
  Serial.println(z_offset, 6);
  delay(5000);

  t1 = millis(); // set the first time reference

  Serial.println("ax_g (g), ax (m/s2), t1 (ms), t2 (ms), td (ms), tds (s), vx (m/s), imu_posx (m)");

}

void loop() {

  // Fetch G forces
  float ax_g, ay_g, az_g;   //scaled accelerometer values
  CurieIMU.readAccelerometerScaled(ax_g, ay_g, az_g); // read accelerometer measurements from device, scaled to the configured range

  // Convert G force to m/s2
  float ax = ax_g / gravity;
  float ay = ay_g / gravity;
  float az = az_g / gravity;

  // Calculate time since last loop
  long t2 = millis();
  float td = t2 - t1; // time delta in ms
  float tds = td / 1000; // delta in seconds for easier logic

  // Calculate current velocity: velocity (m/s) = velocity (m/s) + acceleration (m/s2) * deltaTime (s)
  vx = vx + ax * tds;
  vy = vy + ay * tds;
  vz = vz + az * tds;

  // Calculate position: position (m) = position (m) + velocity (m/s) * deltaTime (s)
  imu_x = imu_x + vx * tds;
  imu_y = imu_y + vy * tds;
  imu_z = imu_z + vz * tds;

  // Print the values
  Serial.print(ax_g, 6);
  Serial.print("\t");
  Serial.print(ax, 6);
  Serial.print("\t");
  Serial.print(t1);
  Serial.print("\t");
  Serial.print(t2);
  Serial.print("\t");
  Serial.print(td, 6);
  Serial.print("\t");
  Serial.print(tds, 6);
  Serial.print("\t");
  Serial.print(vx, 6);
  Serial.print("\t");
  Serial.println(imu_x, 6);

  // Reset start values for next loop
  t1 = millis();

  delay(1);

}

I don't think millis is going to be accurate enough, try micros instead and grab it only once per loop.

This is dead reckoning and is very difficult.  When (few) cars do this (after loosing their GPS signal) they usually count the number of wheel rotations and turning direction.  Just consider if you stopped moving your Arduino.  Then your acceleration would go to zero but your integral calculation of velocity may not due to noise or round off error.  If this happens, the integral of  your velocity (position) would continue to change.

@ratchetfreak thanks, will try in combination with the edited conclusion above

Do you have to use 9600 baud?  That's quite slow, and is probably introducing 70ms of that 100ms delay.  Why not use 115200?  Also, did you try using doubles instead of floats - although I guess this would only help with minor drifts.

The Arduino 101 contains the Intel® Curie™ Module, this module contains an Inertial Measurements Unit or IMU for short among other sensors and peripherals
The IMU of this module is Bosch BMI160 which is a low cost MEMS IMU, this IMUs typically suffer from systematic errors and random/stochastic errors, the following diagram summarize them:

If we take the bias error as an example of those errors, an uncompensated accelerometer bias introduces an error proportional to time (t) in the velocity and proportional to t^2 in the position. For example, consider a case where accelerometer bias is 10 m/s^2. If this bias offset is not removed from the measurements, it can generate a 500 m error in position after 10 seconds and 12.5 km error after 50 seconds. Let us back to our IMU, if we read the data sheet the Zero-g error "or bias" is 40mg for the 8g sensing accelerometer and Ta = 25 Celsius with normal VDD and the IC has been assembled on board. If we just consider this 40mg bias error "dropping other error sources" it is 0.392266 m/s^2 so after 10 seconds the position offset will be 1.96133 meter even if you don't move the Arduino.
I suggest you read "MEMS-Based Integrated Navigation" book here it will give you a good vision about MEMS based inertial sensors and basic navigation concepts.


text:
Fade sketch stuck in mathematical loop
I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!
It worked generally but sometimes while turning the potentiometer, the LED would be stuck at a fixed level of brightness. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.
I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?
*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

-----------------------------Fade sketch edited by me----------------------
/*
 Fade, edited with maximum intensity controlled by potentiometer reading
 */

int led = 11;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
int potPin = A0;    // set the pin that reads the potentiometer voltage
int potValue = 0;   // declare and initialize potValue
int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  //read the voltage at the pot
  potValue = analogRead(potPin);

  //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
  potValueConverted = round(potValue/4);

  // set the brightness of pin 11:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

Serial.println(brightness);

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= potValueConverted) {
    fadeAmount = -fadeAmount;
  }

  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

Dividing an integer by an integer yields an integer. There is no need to round.

Interesting! Thanks for pointing that out.

It seems like the problem occurs when brightness is a lot higher than potValueConverted.
For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.

brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.
a quick hack fixes this problem (as far as I can tell)
 if (brightness <= 0 ) {
    fadeAmount = 5;
  }
 if (brightness >= potValueConverted +5 ) {
    fadeAmount = -5;
  }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.

if (brightness >= potValueConverted +5 )

the LED would be stuck at a fixed level of brightness.

that's by design: think about what happens when potValueConverted is very small.
edit:
to change the brighness, I would do this:
  brightness += fading; //change brightness;
  if ((brightness < BRIGHTNESS_MIN) || (brightness > BRIGHTNESS_MAX)) {fading = -fading; brightness += fading;} //bound brightness to _MIN and _MAX

if potValueConverted is very small then the LED will cycle very quickly with output like 0,5,0,5,0,5... causing a very dimly lit LED.
However, when the LED gets stuck, the brightness can be 80, 100, or 250, it doesnt always stay dimly lit, it simply gets stuck.


text:
ESP8266 sketch worked a few times but now doesn't seem to run
When I flash my code:
/* Create a WiFi access point and provide a web server on it.

 Author: Lucio A. Rocha
 Last Update: 21 Aug 2016

*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* Set these to your desired credentials. */
const char *ssid = "MaisonBlanche";
const char *password = "7932gLBw";

ESP8266WebServer server(80);

const int led = 2;  //GPIO2

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
 * connected to this access point to see it.
 */
void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"\
  \
    <title>MicroCloud</title>\
    \
  \
  \

You are connected on MicroCloud #2!
\

Uptime: %02d:%02d:%02d
\

Status: Light ON

\

Turn ON

\

\

Turn OFF

\
  \
",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );

}

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");

  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  pinMode(led, OUTPUT);
  digitalWrite ( led, HIGH );

  //URLs available to query
  server.on("/", handleRoot);
  server.on ( "/on", turnON );
  server.on ( "/off", turnOFF );
  server.begin();
  Serial.println("HTTP server started");

}

void turnON(){

  digitalWrite ( led, HIGH );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"\
  \
    <title>MicroCloud</title>\
    \
  \
  \

Request: Light ON
\

Uptime: %02d:%02d:%02d
\

\

Status: Light ON

\

Turn ON

\

\

Turn OFF

\
  \
",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void turnOFF(){

  digitalWrite ( led, LOW );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"\
  \
    <title>MicroCloud</title>\
    \
  \
  \

Request: Light OFF
\

Uptime: %02d:%02d:%02d
\

Status: Light OFF
\

Turn ON

\

\

Turn OFF

\
  \
",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void loop() {
  server.handleClient();
}

onto the ESP8266 with this setup:

For my serial output I get:
en 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

I got it to work semi successfully before now. I was basically following along with https://create.arduino.cc/projecthub/luciorocha/esp8266-control-led-with-smartphone-8a59f3. I got to the point where the code was being run successfully - but then something unexpected happened, when I thought the LED would go on, when I selected the turn on button, nothing happened. When I selected turn off, the blue LED on the board turned on and stayed steady. Then, when I selected turn on again, the LED on board went off. I thought the sketch was supposed to manipulate pin 2, but it seemed to be manipulating the onboard LED instead, and in the reverse way that it should.
Now, I can upload it, but the only thing it does after that is spit out the above serial output. I have tried running it with:
GND -> GND
VCC -> 3.3v
CH_PD -> 3.3v

Other sketches seem to work, so maybe something I did triggered an ESP8266 setting which now conflicts with something in the code?
UPDATE
I double checked that other sketches are running - also running is a sketch that connects the ESP8266 to my network - it connects and gets assigned an IP. I made this simplified sketch of the one above, involving the connection process:
/* Create a WiFi access point and provide a web server on it.

 Author: Lucio A. Rocha
 Last Update: 21 Aug 2016

*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println();
  Serial.print("Configuring access point...");

  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP("MaisonBlanche", "7932gLBw");

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
}

void loop() {

}

The only thing it outputs (no connection) to serial is:
0, len 1384, room 16
tail 8
chksum 0x2d
csumcL⸮
~ld

So it seems as if the problem is with my code, or it is able to connect to a network as a client but not as a softAP?
UPDATE
I ran this code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

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

  Serial.print("Setting soft-AP ... ");
  boolean result = WiFi.softAP("MaisonBlanche", "7932gLBw");
  if(result == true)
  {
    Serial.println("Ready");
  }
  else
  {
    Serial.println("Failed!");
  }
}

void loop()
{
  Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
  delay(3000);
}

The same garbled serial output appears, and then it started outputting:
Stations connected = 0
Then the output changed to:
Stations connected = 1
Does this just mean it is successfully connecting using softAP?
UPDATE
I think I have narrowed it down what is not working to the ESP8266WebServer. I used this code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

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

  Serial.print("Setting soft-AP ... ");
  boolean result = WiFi.softAP("MaisonBlanche", "7932gLBw");
  if(result == true)
  {
    Serial.println("Ready");
  }
  else
  {
    Serial.println("Failed!");
  }

  server.on("/", handleRoot);
  server.begin();
}

void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

    "\
      \
        <title>BEASTMODE</title>\
        \
      \
      \

You are connected on BEASTMODE!
\
      \
    ",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );
}

void loop()
{
  Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
  //delay(3000);
  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());
  server.handleClient();
}

When the loop starts it begins to output:
Soft-AP IP address = 192.168.4.1
Stations connected = 0

It seems to go between 0 stations connected and 1 station connected. I go to 192.168.1.4 in my browser, and it never loads the page, it just times out. So if it has a softAP IP address - but it is not accessible, then maybe the server isn't working for some reason. Also I read how you can put the chip into different modes (STA/AP/etc

This works fine, doesn't use ESP8266WebServer which seems to be the culprit. It is the web server from ESP8266WiFi. At the bottom there is a link to a blinking LED example which works for me. You just type in <ip>/gpio/0 in browser for off, and change it to /gpio/1 for on.


text:
Code runs, then doesn't run after I add some routine code
I am programming an ESP8266-01.
I have this code which I am using to operate an on-off switch, which is being used as an override switch for when the relay is turned on and off over the internet:
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed = true;
      pressed2 = false;
    }
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
      pressed2 = true;
    }
  }
}

The above code never starts to run (nothing gets output on the serial) and the relay turns on. The thing is, this code works:
void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

Basically the way the code is set up, it is handling things so that the pin doesn't get read after the instance first instance that it is read (this is what the bool pressed is helping to do).
Why doesn't the first version work?
UPDATE
Whole working sketch:
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

bool pressed = true;

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(0, INPUT);
  pinMode(2, OUTPUT);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  // put your main code here, to run repeatedly:
  int read3 = digitalRead(0);

  Serial.print(read3);
  Serial.println(" input (1 is off)");

  if(read3 == 0) {
    Serial.println("in on");
    digitalWrite(2, 1);
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
  }
}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("request from interwebs: ");
  Serial.println(topic);
  rest.handle_callback(client, topic, payload, length);

}

i updated my quesiton with the full sketch

im pretty sure pin 3 and pin 1 are for serial on esp8266

pin 0 is just gpio...all i do to make it not work is add a bool variable at the top, ad an if statment, and the places where the bool gets set

yup, i dont understand how what i am adding could break it, is it having two bool variable declared up top? or maybe i need to add delay somewhere?

I used this - it does the same thing basically, just moved where the bool variables were.
if(read3 == 0) {
    if(pressed2) {
      Serial.println("in on");
      digitalWrite(2, 1);
      pressed2 = false;
    }
    pressed = true;
  }
  else {
    Serial.println("in off");
    if(pressed) {
      Serial.println("in off once");
      digitalWrite(2, 0);
      pressed = false;
    }
    pressed2 = true;
  }


text:
Obstacle avoidance algorithm
TARGET
The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).
This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot  manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.
I will appreciate it if I could get some helpful suggestions and insights.

Pathfinding usually relies on the obstacles/path being known to the algorithm. The most basic form of obstacle avoidance is simply trying to get around it. This can be done by checking if there is an object infront of the robot, and if so, go to the right (and ocassionaly check if the obstacle is still there). Just try to program this out and then find scenario's where it makes sense to go back, to check if you can go around the left side. It can often help to think of how YOU would solve this problem if you were the robot.

In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

There is a very simple weighted index algorithm called the 'Bubble Rebound Algorithm' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.
Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.
But first I suggest you take a look at my blog post about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.
I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.
On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.

The problem
Given an unknown graph (or just world), a robot/person should be able to find a way between two points.
Pathfinding is often done on a known world, this website allows you to check out the different algorithms, which very much look like what you want to achieve.
Since you mentioned moving obstacles, you may also look at collision avoidance algorithms. But it depends on if the moving obstacles themselves also avoid collisions. To be able to avoid moving obstacles, you'll have to be able to know their location, direction and speed, to be able to calculate where you would collide (and how to avoid it). But usually, just braking whenever they get too close may just work (maybe even drive backwards if they get even closer).
The approach
So, we've got a startpoint and an endpoint. Our initial plan would be to travel straight from start to end, since this is obviously the shortest path.
But it would be ideal if there wasn't an obstacle, and for us to verify our approach, we'll just think of an obstacle. Let's say there is a wall right in front of you, what are you going to do? You can't see where it ends (I believe your robot doesn't), so you're just going to walk around it, you could choose a random way, (left or right, maybe even backwards)
What algorithm
Basically you want to get to the endpoint, so you're going to have an algorithm that has some kind of "fitness" based on how close you are to the endpoint.
You could:

Brute force: Try every single route, until you've found the way.
Right hand rule: I've heard that, in mazes, if you always hold your right hand against the (right) wall, eventually you'll get to the end.
Greedy algorithm: Just move towards the point, if you can't go any furhter, choose whatever seems to get you closer. If nothing is getting you any closer, choose the route that moves away the least.
Heuristic algorithm: Move one way, until choosing another round will be more likely to be a solution, then choose to go down another lane. Until this one seems to be leading you away.
Search algorithm, like breadth first or depth first search, check this video

Just try some of the algorithms, to see which one works best. Or try to determine/explain why one algorithm is/should be better than the other.


text:
State Machine with If/Else?
I am trying to make a state machine with if/else. But some of the code does not seem to be executing. I have information being displayed on an LCD screen so I know where it is, and it stays on Todo=1 and does not go to the next state. I have tried using switch/case and it works. But I think it might be better for my project if I use if/else. Can I do this using if/else?
Void loop{
  if (state == PLAY) {
    Todo = 1;
    Mastermachine(Todo);
  } else if (state == TRYAGIN) {

  }
}

void Mastermachine(int Todo) {
  if (Todo == 1) {
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
    SongSeq[largestindex];
    for (int index = 0; index < largestindex; index++) {
      SongSeq[index]();
    }
    Todo = 2;
  } else if (Todo == 2) {
    for (learnindex = 0; learnindex < largestindex;) {
      MIDI.read();
      if (learnindex >= largestindex) {
        Todo = 3;
      }
      lcd.setCursor(16, 2);
      lcd.print(String(Todo));
    }
  } else  if (Todo == 3) {
    if (array_cmp(learn, note, largestindex, largestindex) == true) {
      largestindex++;
      delay(2000);
      Todo = 1;
    } else {
      delay(2000);
      Todo = 1;
    }
    lcd.setCursor(16, 2);
    lcd.print(String(Todo));
  }
}

Consider a switch statement instead of the if/else statements.

Make the state a global variable. Todo is lost after each call of MasterMachine() (if you do no introduce a loop).

Inside Mastermachine(), Todo is a copy whatever is passed as its paramter. Even if you make a global named Todo, it will be 'hidden' by the parameter of the same name. That parameter goes out of scope - disappears - when Mastermachine() exits, including any changes made to it within the function.
There are a few choices to accomplish what you want to do, but the easiest is probably to make a global Todo and get rid of the parameter Todo in Mastermachine(); i.e., make it void Mastermachine(void). Then the name Todo inside the function will refer to the global by that name.

Your loop executes continually, always setting the state to 1.....
The called state machine supposedly changes the state, but it get set back to 1 every time the loop executes.
The loop program needs to do the state changes, not the masternachine function.

would moving Todo=1 somewhere else fix that issue ?

If you want to have Todo=1 set only once, place it in setup.


text:
How to pass input from a Midi controller to a function?
I am trying to pass the input[], data1(pitch) from a Midi controller to the waitForButton function. When a key is pressed it sends data1(pitch) into the array input[], and when the key is up the array value goes to zero. But the input isn't being passed to the function as I am pressing the keys on the Midi controller. What am I missing?
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=1;
    noteOn(0,data1,100);
    input[0]=data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=0;
    noteOff(0,data1,100);
    input[0]=0;
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if(key ==-1 || key != note[index]) {
      mademistake = true;
      state = 2;
    }
  }
}

int waitForButton(int laps) {
  int keyPressed= -1;
  int check;
  boolean keyBackUp = false;
  currentMillis = millis();
  // The number of ms since the program started running
  previousMillis = currentMillis;
  // Records the point when we start spinning the loop.
  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < laps & keyBackUp == false) {
    lcd.setCursor(16, 2);
    lcd.print(String(keyPressed));
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++) {
      if (input[i] != 0) {
        keyPressed = input[i];
        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);
        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < laps & keyBackUp == false) {
          check = input[i];
          if (check == 0) {
            keyBackUp = true;
          }
          currentMillis = millis();
        }
        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);
        // See if they took to long.
        if (currentMillis - previousMillis > laps) {
          keyPressed = -1;
          // They took to long to let the button up so they lose.
        }
      }
    }
    currentMillis = millis();
  }
  return keyPressed;
}

the change of the array is shown in the  MyHandleNoteOff and  MyHandleNoteOn functions.

You don't need to call getData1() because the MyHandle function already get this in their parameters. You are probably not using volatile.

so i should use pitch instead of data1 ?

@CL. making that change had no effect.i think the while loop is blocking.dose it look like the while is the issue?


text:
USB control panel with endless turn knobs
I understand that some arduinos are capable of presenting themselves as a USB HID device to a PC.
I would like to use one to build a custom input controller that lets me read maybe 8 or so turn knobs that can infinitely turn left and right.
I am new to Arduino, but have cross-compiled avr binaries before.
Which arduino would be a good choice for this? And any additional parts that would help?
The end product would look like a MIDI mix panel, but it shouldn’t talk MIDI, just USB HID (to a linux PC.)
Note: there is an expensive, and out of stock, device that is similar to what I have in mind called MIDI Fighter Twister, pictured below, to get an idea.

Any with a native USB interface. Look for ATMega32U4 based ones. All the rest is about interfacing and that depends how many encoders you have and how they interface.

Options for the Arduino you have:

Get an Arduino supporting HID drivers (e.g. 32u4 based boards, Due /Zero/ Arduino Leonardo/ Micro or Pro Micro/ M0)
You use this library it supports UNO/MEGA/Leonardo/(Pro)Micro/ any 8u2/16u2/at90usb8/162/32u2/32u4 compatible boards and some more

Then you have to "just" code the communication between your programm and the HID driver -> pretty standard serial/usb stuff.
The parts (knobs) you seek could be rotary encoders, which have no fixed zero point, endless rotation and need 2 input pins per encoder (except GND or optional push function). The signals a rotary encoder produces (and what can be handled by libraries) are based on a 2-bit gray code available on 2 digital data signal lines.
So when choosing whatever Arduino make sure you have enough (usable) I/O ports for the number of encoders and possible additional parts (status led/s or similar, I2C LCD display)


text:
Arduino as USB HID is slowed down when PC doesn't read events
I have an Arduino Micro that is acting as a HID device for a Linux PC.
I use this call to send the HID values:
HID().SendReport(1, _values, sizeof(_values));
This works in principle, but I noticed this issue:
If my Linux PC is not actively reading the events from the Arduino, then the Arduino is slowed down. My rotary encoders are missing signals, is one symptom.
But as soon as I read the events with my Linux PC, the Arduino loop() runs at full speed again.
I suspect that this is due to recv/send time out delays in the USB core code? Because I noticed this in USBCore.cpp:
u8 timeout = 250;               // 250ms timeout on send? TODO
Anyway, I tried to solve this issue in the following manners:
Check for configuration and suspension with:
     if (USBDevice.configured())
      if (!USBDevice.isSuspended())
         ...

Which did not work.
I also tried monitoring the increments of the frame number:
  // See if USB shows activity.
  static uint8_t prev_fr_num = UDFNUML;
  static uint8_t num_times_idle = 0;
  uint8_t fr_num = UDFNUML;
  if (fr_num == prev_fr_num )
  {
    if (num_times_idle < 255)
      num_times_idle++;
  }
  else
  {
    num_times_idle = 0;
    prev_fr_num = fr_num;
  }

And then only send if num_times_idle is smaller than a threshold. Again, this did not help.
The only way to make it fast, is by reading the events with linux, like so:
$ jstest /dev/input/js0
or alternatively:
$ evtest /dev/input/event5
How can I have the USB HID stuff not slow down my loop code when the PC is not paying attention?
Thanks!
Bram

please reduce the code to smallest code that still exhibits the issue and add the code listing to your question

USB is actively polled by the host and a client can not initiate communications. Maybe it's a buffer filling up?

For those that hit the same issue, here is how I solved it:
Expose the USB_SendSpace() information in the HID interface by editing
/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.cpp
u8 HID_::SendSpace(void)
{
        return USB_SendSpace(pluggedEndpoint);
}

And adding the interface to class HID_ in:
/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.h
That way, before calling HID().SendReport() you can check for send buffer space available by calling the HID().SendSpace() method.
If there is no space, just skip the SendReport() calls, and the Arduino loop() will no longer be slowed down by time outs.


text:
Arduino IDE missing libread.s0.6
I just recently installed the ESP8266 libraries on the arduino IDE using the boards manager, the code compiles fine with the ESP, but when the board is changed to UNO, i get this error,
opt/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libreadline.so.6: cannot open shared object file: No such file or directory

Any solution to this?

So install it?
$ sudo apt-get install libreadline6

Or, if you need the i386 version on an x64 platform:
$ sudo apt-get install libreadline6:i386


text:
Format error with ESP8266 compile
I get this error when I try to compile and upload the code for the ESP826612E
fork/exec /home/c/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++: exec format error

I don't understand what the problem is, It was working fine for days until today.
Anyone has solutions?

I suspect you are running a 32-bit compiler on a 64-bit operating system. You will need to install the 32-bit support libraries.
$ sudo apt-get install libc6-i386


text:
Function for converting milliseconds to minutes?
I'm playing around with a Neopixel strip and want to be able to enter the amount of minutes I want an LED to do something rather than in milli seconds. So for example,
void loop() {

colorWipe(strip.Color(0, 0, 255), 50);
delay(sConversion(5));

colorWipe(strip.Color(0, 0, 0), 50);
delay(sConversion(5));

In my mind this should then delay the code by 5 minutes instead of doing
void loop() {
colorWipe(strip.Color(0, 0, 255), 50);

delay(300000);

The function I wrote is
sConversion(int minutes) {
    int milli = minutes * 60000;

    return milli
};

When I write this same function in JS it returns the correct value, 300000. But when I run it in the Arduino IDE the blue light never changes.
I have this function outside my void loop() and void setup(). Is that the correct place to put it? I have no errors returned.
Full code sample
void setup() {

strip.begin();
strip.show();

}

int sConversion(int minutes) {
    int milli = minutes * 60000;

return milli;
}

void loop() {

colorWipe(strip.Color(0, 0, 255), 50); // Blue
delay(sConversion(1));

colorWipe(strip.Color(102, 204, 0), 50); // Green
delay(300000);
}

void colorWipe(uint32_t c, uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
    };
};

Is this the reason?

No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt.

https://www.arduino.cc/en/Reference/Delay

Function for converting milliseconds to minutes?

1 min has 60 seconds and 1s has 1000 me.
So take the ms and divide it by 60k you will get its equivalent min.

int sConversion(int minutes) {
    int milli = minutes * 60000;

return milli;
}

If minutes is greater than 1, you will overflow the int and not get the right answer.  Use unsigned long here instead.
unsigned long sConversion(int minutes) {
    unsigned long milli = minutes * 60000ul;

return milli;
}


text:
ESP8266 blink sketch not blinking LED
After flashing the blink sketch to the ESP8266, I removed all the unnecessary wires from flashing - and my setup to try and run the sketch looks like this:

Something to note about flashing - it would take anywhere from 10-50 tries before it would flash successfully, the other times it just failed to upload and spit out the espcomm failure to connect message, or it got halfway through the upload and quit. This is the only clue to me that maybe my board is just bad, and it won't be able to run any sketch - I ordered another ESP8266, but I'm still wondering if I could be doing something wrong, it seems fairly straight forward, and I have done a lot of research about this up until this point. This is my first arduino project, other than the starter projects.
Also not represented in the diagram are the female to male jumper cables I am using to connect to the ESP8266. Those connect to the breadboard, and then I plug another wire into the breadboard on the same row to attach it to what it needs to be attached to. I figure none of this stuff matters - as long as it is powered (red LED) it should be working.
Any ideas why the onboard LED isn't blinking? Or is the sketch not running at all? Does the upload problem matter...could it be producing a false positive result? The only other idea I have where something could be different is an output capacitor for the voltage regulator, I have been told that a 10mF capacitor is what I would use (but I have also been told it doesn't matter...and neither does the filter capacitor, I just put it in anyway).
CODE (straight from Arduino IDE / ESP8266 examples):
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Mike pointed out my regulator matters (because of dropout voltage) - I am using this one:
http://www.nteinc.com/specs/1900to1999/pdf/nte1904.pdf

not all esp-01's ive used correctly map led_builtin, or you have a pin mode that conflicts with it. the board may also be flaky or have thermal issues.

Here's how you test your voltage regulator setup:

Disconnect the ESP8266.
Connect a 10 ohm 1 W (or higher) resistor across the output of the v-reg.  One end goes to the output, the other goes to ground.
Measure the voltage across the resistor.  If it stays regulated close to the expected 3.3V, then you're fine.  If not, then this setup can't supply enough current for the ESP8266.

so do you think that there isnt enough power after the power goes through the regulator?

Ive tested the voltage coming out of the regulator (+ side on voltage regulator output, - side on ground coming out of esp8266) and it reads 3.3v  or 3.27 maybe...is that close enough?

@ewizard Yes, that's close enough.  But is that with a load on it?  That's why I suggested the test above.

so the resistor simulates the load? how close does it have to be to 3.3v? im going to go get a 10 ohm 1 watt resistor

@ewizard It has to be at least the minimum voltage required for the ESP8266 to run.  You'll have to find that spec.

Does trying two AA batteries rule out having to do this test?

@wizard Two AA batteries don't have enough voltage to correctly power the ESP8266 and probably even the voltage regulator.

sorry i meant 3 batteries ... anyway, i did the test and it is fine...stays right at 3.3v across the resistor

@ewizard Then your problem is not the power supply.  I would have a capacitor on the v-reg output, though.  I have a 330uF on mine to handle surges in current draw.  I would also triple-check all connections.

ok ... a someone suggested i use a 10uF for the regulator i have...does that make sense?

i tried a 10uF output capacitor and nothing changed...also triple checked wires,I'll be able to see if it is the module tomorrow...seems like there is something wrong with the flash (ram) on this one

The ESP8266 is power hungry, the Arduino may not have enough output current to power it.  Also, which voltage regulator you're using matters, as some have higher dropout than others.

Thanks for your answer, the red LED is on...so its getting power? I am using the NTE1904 http://www.nteinc.com/specs/1900to1999/pdf/nte1904.pdf - what is dropout?

Could lack of power be causing my upload problem? (infrequent success)

dropout voltage is very low (0.45V) so shouldnt be an issue? how can i test if the arduino is giving enough current?

@ewizard Okay, yeah, the dropout on that v-reg is low.  Are you able to run the ESP from a real power supply?  Normal current draw is around 100mA, which might be too much for the Arduino.  And peak current draw can be three times that.  How are you powering the Arduino?...That matters.

Power hungry, I have measured 270mA in the peeks and the Arduino can't supply near that. I have had the same issue!

so you guys are saying I need to power from something else? would a 9v battery work (I'm aware its not economic, just want to solve the problem)? I don't have a legit power supply really, I'm running the arduino from USB (my computer). If 9v doesnt work...would AA or AAA be enough?

for some reason the 9v on my arduino board isn't working, I plug it in and the board doesn't turn on so that isn't an option, I do have a 9v battery snap, or I could get a cheap power supply?

@ewizard A standard 9V battery cannot supply much current at all.  Use several AA (or C or D) batteries in series if you have have nothing else.

I just tried with 3 AA batteries and no blinking led...it was being powered though...i'm thinking maybe my chip is defective

@ewizard 3 AA batteries and the voltage regulator?  If you used the batteries directly without the regulator you probably destroyed the chip.  Otherwise, try reprogramming it.

yah with the regulator...ill try reprogramming it while battery powered - i read that the arduino uno puts out 500mA on the 5V, shouldnt that be enough?

I just tried reprogramming and it is still just as hard to upload

Some ESP8266 - V01 boards won't blink integrated led (only works with GPIO2), so connect it to a resistor (~150 ohms), in series with an external led to ground. I don't know why... is just the way that it is...


text:
ESP8266 Blink sketch - does not blink / or stays constant
I uploaded the Blink sketch (from the ESP8266 examples, in the Arduino IDE) successfully.
Depending on which wire configuration I am using two different things happen:
wiring 1:
CH_PD -> 3.3V
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

wiring 2:
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

There are TX/RX lines in the picture from when I was flashing - they aren't being used for running the sketch.
With wiring 1 the LED stays on (doesn't blink) - I was wondering if this was because I still had the VCC -> 3.3V connected. So I disconnected that, which gives way to wiring 2.
With wiring 2 the LED doesn't come on at all, it is the same as wiring 1 except without VCC -> 3.3V.
Why is it constant when 3.3V is going to VCC, and constantly off when I disconnect it? Why doesn't it blink using wiring 2?
UPDATE
A diagram as requested, sorry it was my first time doing this:

Code:
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

The picture shows an Arduino Uno, and no ESP8266 -- where is your ESP8266?

its out of the picture - the wires that blur off the screen lead to it...i was trying to show wiring on board - all that is going on with it is the power light is on as it should be.

with a ESP-01S, all you'd need is GND+VCC+GPIO2...

yah it the extra wires are from flashing...would what im doing now not work for some reason? I disconnected the GPIO0 from ground and disconnected 3.3v from CH_PD...didnt bother with serial lines

You should connect Vcc to 3.3V, because that's how the ESP8266 is powered.
RST is active-low reset and should be pulled to 3.3V

I am sending to LV...its the green wire, it gets blocked out. So running standalone vcc should be 3.3v? what about ch_pd? Oh wait I messed up my pins...wiring 2 vcc is still connected

Just saw you have RST to GND, RST is active-low reset, so it needs to be pulled high to 3.3V otherwise the device is always in reset.

oh wow that could be it ill try...im new to this...to pull high where would i put the resistor? the leg on the switch across from the blue wire? (vertical)

You just put a resistor between RST and 3.3V directly. Instead of RST to GND, you RST to one side of resistor, then plug the other side of the resistor to 3.3V.

would i move my reset button to in between RST and resistor->3.3v. to switch it on and off that power?

Your reset button would go between ground and the RST line. The resistor that remains between 3.3V and RST will limit the current so you don't short out your power supply during reset.

ok thanks was wondering about where the ground came in

i re-flashed the code and still no blinking. just to be sure...for the reset button I have RST -> 3.3v and for the switch its RST -> switch -> ground

is it possible that the LED_BUILTIN variable in the code is referencing the wrong pin? its used like this void setup() {   pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output }

I can't comment as my karma is too low so if I am wrong please just someone let me know and I'll simply delete.
I thought that the RST pin being pulled to ground resets the chip, if this is the case surely in your setup you are constantly reseting your chip, so it won't do anything. My understanding is that you should have the reset pin pulled up to 3.3V with a 10K resistor.

thanks...where does the resistor go? this is my first time "pulling"...im guessing the leg on the bottom left to 3.3v?

I'm not sure if it's the leg on the bottom left... You havnt provided a picture of your esp8266 board. But it should connect your esp8266 RST pin to the 3.3V source!

instead of ground? so my switch could be in between RST and 3.3v?

Yes, exactly. Like what Jose says

I reflashed the code and no luck...see comment on below answer

I think it's best if you edit your original post with a picture of the esp8266 and how you've wired it. Also post your code in full. Thank you

I think it's best if you edit your original post with a picture of the esp8266 and how you've wired it. Also post your code in full. Thank you

Also you say you use LED_BUILTIN. Why, why not use pin 2 if that is what your Led is connected to? At the moment it should make the led on the esp8266 board flash. Not the external one, unless LED_BUILTIN is pin 2?

oh interesting...i uploaded how I have it wired above...i was thinking about trying this two ....just using 2 for gpio2...i guess I'll try it...i was just using LED_BUILTIN is what they use in the arduino esp8266 examples for blink sketch, I thought it represented one of the gpio2...so the blue led is what would flash with that variable?

And also the code?

i updated it its above

Why is the transitor there?

the voltage regulator?

Ahahahah. I'm tired jesus my bad!

haha no problem

Assuming you flashed it correctly, I see no reason it shouldn't not work now, other than wrong pin assignment, try pin 2? Also when it runs I'm assuming the voltage regulator isn't necessary as the arduino can provide 3v?

yah the flash was successful...went to 100% then unloaded bootloader, im about to try pin 2 now...ur right this sketch is to make the blue led blink...but it doesnt do that either

I read in one place that whatever is responsible for the flash upload is "flakey" and doesn't work everytime...have u heard this? defective models...because I can upload but it takes tons of tries before one works

Let us continue this discussion in chat.


text:
What current is safe for Wemos d1?
I've got 12V / 400mA power supply for my Wemos D1 R1, and I'm using VIN output(I need 12V for led strip). I need to change this power supply because of color, and I can't find similiar with the same parameters. The question is - Is power supply with 12V / 1A - 2A safe to use?

Yes. The quoted current of a power supply is the upper limit of what it is capable of providing.

With very few exceptions, electronic devices only draw as much current as they need, limited by their resistance.
The current rating on a power supply is the MAX current it can provide before the voltage drops. Having a higher current power supply may waste energy, but won't hurt anything.
According to Ohms law, V = IR
Where V = Voltage
I = current, in amps
R = resistance, in ohms
(voltage = current times resistance.)
Or, solving for current:
I = V/R

current = voltage divided by resistance.
So if you have a 12 volt power supply, and a 100 ohm resistor, you'll get 12/100, or 0.12 amps, flowing through the resistor.

I am a bit confused you state:  VIN output, that is the voltage input to the onboard regulator. For the power supply use one of the same voltage but capable of more current. Current is the maximum a power supply will give reliably. Current is the current needed by a load so if the load is less then the source and the voltages are the same it is a go. The answer is yes either is ok but be sure you have enough current from the power supply + some to cover all of the LEDS.


text:
Interrupt every second on ATTiny84 (and sleep the rest)
I'm building a digital watch just like in this post, except I'm using an ATTiny84. However, the ATTiny84 doesn't have an asynchronous Timer2 like the ATMega328 and does not have a power save mode, so it cannot wake up from the Timer2 interrupt as is suggested in that post.
I need to increment my 'seconds' counter every second, and I need to do it precisely so I don't lose/gain time (so I can't use the watchdog timer which, as I understand, does not use the crystal oscillator but rather its own imprecise clock). I was planning on just keeping the CPU on and using an external crystal, but it seems that that takes a lot of power (~3mA). Even with the SLEEP_MODE_IDLE, I could only get the current draw down to around (~1.2mA).
Like Nick Gammon suggested in that post, I feel like the real solution is to sleep when not changing the counter. Is there any way to wake up after a precise amount of time in the POWER_DOWN or STAND_BY modes?

Is there any way to wake up after a precise amount of time in the
  POWER_DOWN or STAND_BY modes?

I'm afraid not. You will have to use a timer. Since the ATtiny84 does
not have an asynchronous timer, you will have to keep your timer
clocked. This means the clkIO clock domain has to stay
active. Now, take a look at the table “Active Clock Domains and Wake-up
Sources in Different Sleep Modes”, on page 33 of the ATtiny84
datasheet. It shown that “Idle” is the only sleep mode
that keeps this clock domain active.

Even with the SLEEP_MODE_IDLE, I could only get the current draw
  down to around (~1.2mA).

There are ways to bring this down. First, there is a collection of
functions named power_*_disable() in the avr-libc. You can use
these to power down every single peripheral except the one timer that
you will be using.
Most importantly, you can save power by reducing the clock speed. Since
these devices have extremely little leakage current, the current draw is
roughly proportional to the clock frequency. You can then achieve huge
power savings by drastically reducing that frequency. Obviously, your
processing power will also suffer, but this may not be an issue for a
simple binary clock.
I think the best option for you is to clock your ATtiny84 off a
32.768 kHz watch crystal. See the section
6.2.4 – Low-Frequency Crystal Oscillator in the datasheet.
These crystals can be very accurate, as they are specifically designed
for time keeping. And the frequency is so low that the current draw from
the MCU will likely be negligible compared to whatever other components
are in your clock.
Edit: answering the question in the comment.

Wouldn't waking from idle still use the watchdog timer though? Or is
  there a way to wake up based on the 32.768 kHz crystal?

As the watchdog timer is way too inaccurate, it is of no use to you.
Instead, you would use either Timer 0 or Timer 1, and configure it to
deliver an interrupt every 32,768 CPU cycles. This interrupt will
be your 1 Hz wakeup source.
You can do this with either timer, in either CTC or fast PWM mode. You
have to configure the prescaler and the TOP value such that
prescaler_factor × (TOP + 1) = 32,768
Then, enable the relevant interrupt, and define the corresponding ISR
that will advance your clock by one second.

Thanks, it looks like the power used by a 32.768 kHz crystal is low enough for me if running in idle. Wouldn't waking from idle still use the watchdog timer though? Or is there a way to wake up based on the 32.768 kHz crystal?

@AnubhavSrivastava: see expanded answer.


text:
STM32F103 (Blue Pill) with stm32duino + BME280 + SSD1306 strange behavior
I'm going crazy trying to understand some strange reads from BME280 sensor.
With this code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

#define SAMPLES_NUM             100
#define SAMPLES_OFF             256

#define GRAPH_X                 (SCREEN_WIDTH - (SAMPLES_NUM + 1))
#define GRAPH_Y                 16
#define GRAPH_W                 (SAMPLES_NUM + 1)
#define GRAPH_H                 47
#define DATA_X                  10
#define DATA_Y                  0

#define SEALEVELPRESSURE_HPA    1000
#define PRESSURE_HPA_MIN        980
#define PRESSURE_HPA_MAX        1045

TwoWire Wire1(PB9, PB8);
TwoWire Wire2(PB11, PB10);
Adafruit_SSD1306 *display;
Adafruit_BME280 *bme;

void setup() {
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, LOW);

  delay(500);

  Wire1.begin();
  Wire1.setClock(400000);

  Wire2.begin();
  Wire2.setClock(400000);

  delay(100);

  display = new Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2);
  bme = new Adafruit_BME280();

  while (!display->begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    delay(500);
  }

  delay(500);

  display->clearDisplay();
  display->dim(0);
  display->setTextSize(1);
  display->setTextColor(WHITE);
  display->setCursor(0, 0);
  display->println("Display initialized");
  display->display();

  int b = 0;
  display->println("init bme...");
  while (b == 0) {
    b = bme->begin(BME280_ADDRESS_ALTERNATE, &Wire1);
    display->print("b=");
    display->print(b);
    display->print("; ");
    display->display();
  }
  display->println();
  display->display();

  if (b == 1) {
    bme->setSampling(Adafruit_BME280::MODE_FORCED,
                    Adafruit_BME280::SAMPLING_X1, // temperature
                    Adafruit_BME280::SAMPLING_X1, // pressure
                    Adafruit_BME280::SAMPLING_X1, // humidity
                    Adafruit_BME280::FILTER_OFF);
  }
  delay(5000);
}

void loop() {
//  bme->takeForcedMeasurement();
  float _t1 = bme->readTemperature();
  float _h1 = bme->readHumidity();
  float _p1 = (bme->readPressure() / ((float)100.0F));

  display->clearDisplay();
  display->setCursor(0, 0);

  display->print("T  : ");
  display->print(_t1, 1);
  display->print((char)247);
  display->println("C");

  display->print("RH : ");
  display->print(_h1, 1);
  display->println("%");

  display->print("P  : ");
  display->print(_p1, 1);
  display->println("hPa");

  display->display();

  delay(5000);
}

And if I uncomment //  bme->takeForcedMeasurement(); it wait forever.
I get an obviously erroneous read:
T  : 66.1°C
RH : 100.0%
P  : -1599.7hPa

With this code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

TwoWire Wire1(PB9, PB8);
TwoWire Wire2(PB11, PB10);
Adafruit_SSD1306 *display;
Adafruit_BME280 *bme;

void setup() {
  pinMode(PC13, OUTPUT);
  digitalWrite(PC13, LOW);

  delay(500);

  Wire1.begin();
  Wire1.setClock(400000);

  Wire2.begin();
  Wire2.setClock(400000);

  delay(100);

  display = new Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire2);
  bme = new Adafruit_BME280();

  while (!display->begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    delay(500);
  }

  delay(500);

  display->clearDisplay();
  display->dim(0);
  display->setTextSize(1);
  display->setTextColor(WHITE);
  display->setCursor(0, 0);
  display->println("Display initialized");
  display->display();

  int b = 0;
  display->println("init bme...");
  while (b == 0) {
    b = bme->begin(BME280_ADDRESS_ALTERNATE, &Wire1);
    display->print("b=");
    display->print(b);
    display->print("; ");
    display->display();
  }
  display->println();
  display->display();

  if (b == 1) {
    bme->setSampling(Adafruit_BME280::MODE_FORCED,
                    Adafruit_BME280::SAMPLING_X1, // temperature
                    Adafruit_BME280::SAMPLING_X1, // pressure
                    Adafruit_BME280::SAMPLING_X1, // humidity
                    Adafruit_BME280::FILTER_OFF);
  }
  delay(5000);
}

void loop() {
  bme->takeForcedMeasurement();
  float _t1 = bme->readTemperature();
  float _h1 = bme->readHumidity();
  float _p1 = (bme->readPressure() / ((float)100.0F));

  display->clearDisplay();
  display->setCursor(0, 0);
  display->println(_t1, 1);
  display->println(_h1, 1);
  display->println(_p1, 1);

  display->display();

  delay(5000);
}

I get perfect read:
24.5
45.7
1009.8

I can't understand the problem.
Wiring it's ok and I can detect on both I2C bus devices address with i2cscanner.

Your question isn't clear: when you uncomment that line, does it wait forever or do you get an erroneous read? What else is different between the 2 sketches?

Sorry sorry if i wasn't clear enough. However if I uncomment it wait forever, otherwise it take erroneous reads. However, I tried, if I change some print, for example a display->print("Temperature:"); before display->println(_t1, 1); , reads changes systematically. It seems like a stack overflow or a memory bad allocation, or something like that...

So basically, if you uncomment that function call, the code waits forever (where does it "wait" exactly? Within the takeForcedMeasurement()? Find out exactly where.). But if you leave the line commented out, you get wrong values. And aside from this, you get unstable behaviour just from changing the Serial.print() statements. Like you said, this is possibly some issue with memory. Is there a reason you're allocating display and bme on the heap? Take them out of setup() and declare them statically in file scope, then see if anything changes.

Yes I tried to declare statically and is not that the problem. I think it wait forever on takeForcedMeasurement() because the same problem, and it not get the reply and wait forever for it.

That's a different issue from the strange behaviour you observed. Does changing the Serial.print() strings still affect the execution?


text:
Edit JSON File on SD Card
I am currently Working on a project, where I save values in a JSON File on an SD Card.
The JSON looks something like this:
{ "ID1":{[[starttime, endtime],
          [starttime, endtime],
          [...]],
  "ID2":{[[starttime, endtime],
          [starttime, endtime],
          [starttime, endtime],
          ...],
...
}

I have to add start and endtimes to IDs, so I have to edit the file.
Is there a nicer/easier/better way than the following?:

Create Buffer (e.g. 512 Bytes)
Read 512 Bytes from file to buffer
Edit/Add Values in Buffer
Save Buffer to another File
Repeat 2. to 4. until end of file
Remove old File and rename new File

I am currently using the ESP32 Core SD.h Libary

you could seek() in the file and overwrite bytes in the file. but not add or remove bytes.

To add data, no, there is no better way. The way you describe is called "stream editing" and is the normal way on low-memory machines. TBH I'd work in lines, not blocks of 512 bytes.

Also TBH I wouldn't use JSON. It's not great (as you see) at editing. Instead a simple CSV format would be better where you can just append data to the end of the file, then collate it later on the computer in excel.

Going by line is a good Idea! I will give it a try. I need a JSON File, because I want to use the data in a React App. The reason why I use the SD Card is in case of a failure I want to be able to retrieve the data. Thanks a lot!

you can use notepad++ text editor to sort a csv file and to add JSON formatting to the columns

react can read csv, you just have to parse it into an array of arrays or an array of objects. you also have enough RAM on the 32 that you can just template the whole file and print it in one go.