Teensy 2.0 usb xinput device So I came across a library that lets you turn your TeensyLC/3.X into an xinput device. I only have a 2.0 on hand. I spend the past few hours messing around with the LC example to see if I could hack it over to work on a 2.0 board. Admittedly, it will take much more time analyzing everything before I can make a more educated attempt. I saw another project that is able to use the 2.0 as xinput devices but the firmware is only available in its hex form.

So I'm wondering what would be the best way to go here... all of the xinput code is in the /core/teensy3 directory. It has many spidering dependencies which will take a lot of time to go through and try and port(would that even work?). Is there a super "lite" version of the core that lets you fill out device descriptors/handshake/etc? If there is, the xinput just becomes a task of emulating the xinput packets.

Anyway, as this is my first usb input project, any suggestions would be greatly appreciated. Again, I already have the 2.0 and I know its possible so just getting a LC/3.X I'd like to avoid. I'm more just looking for direction on the best way to get started.

The Teensy 2.0 is a completely different MCU from the 3.0 with very different libraries.

USB on the 32U4 on the 2.0 typically uses the LUFA library for USB.

So to answer your question: I doubt it will be possible to port code written for the 3.0 SAMD based teensy to the AVR based 2.0 teensy without basically rewriting it from scratch.

The Arduino Leonardo also uses a 32U4 so you might want to look for examples code written for the Leonardo.

The examples from the LUFA library may be useful but they are not designed to be used with the Arduino IDE.

UPDATE From the comments, there is this project:
https://github.com/bootsector/XInputPadMicro that uses LUFA and targets the Leonardo.


How to connect neo 6m 6pin module with nodemcu v3 I got this neo 6m gps module from a broken drone. and i would like to connect it to nodemcu v3 board.
most of the gps module that i have seen are with 4 pins (vcc,gnd,tx,rx) , but this module has 6 pins (gnd,vcc,txd,rxd,scl,sda) .
i am not sure how to wire it up and what library to use.

The 4 pins VCC/GND/TX/RX are the same as any other GPS module.
The other two pins, SCL and SDA, are nothing to do with the GPS. They connect to the HMC5883L compass chip.
Use the normal TinyGPS library for the GPS, and a HMC5883L library (such as this one) for the compass.


Atmega boot loading UART or SPI I have an Atmega 328 chip and want to load the Arduino boot loader to the chip. I have planned to use a SPI protocol to do this, but I have read other posts saying that they have done similar using an UART with using an FTDI chip. I have planned to use the FTDI to support USB.

I did rad some information that said that loading the boot loader through UART is very slow.

Which is best? I would like to save space, if I do not need a SPI header then I would like to remove this. Is what I have read correct?

Thanks

I have read other posts saying that they have done similar using an UART with using an FTDI chip.

You have probably misread something. A brand-new, blank ATmega328 can only be programmed over SPI, or via parallel programming (more pins). There is no "native" UART bootloader.

It's possible to use certain FTDI chips to bit-bang the SPI programming interface. This is probably what the posts you're reading are referring to. As the post suggests, though, this is slower than using a programmer which directly supports the SPI interface, and is only really suitable if you don't have a better programmer available.

If space is a concern, one option to consider may be to provide the ISP port as a set of test points and use pogo pins to access it during manufacturing. You can lay out the test points however you want, possibly at a finer pitch than the 100 mil header you're probably used to.

Depending on your manufacturing process, another approach may be to program the chip before mounting it to the board.


Serial monitor in Arduino IDE for RobotDyn ESP8266-Pro via CP2102 I bought a couple of "ESP8266-Pro" micro-controllers from a Chinese company named RobotDyn.  There's no real documentation with them, but I've bought a lot of other stuff from them in the past that worked out really well, so I took a chance.

After some work, I am finally able to program the board with the Arduino IDE 1.8.1.

The problem is that I am unable to get the serial monitor working to see what's going on with the code.

What do I need to do to get this to work, or is it simply not possible?  In order to program the board, I need to connect EN to VIN, and both IO0 and IO15 to GND.  I assume I have to disconnect that to actually run the board after programming, but I don't know and haven't gotten anything to work yet.

Here's a photo of the board hooked up for programming.  What do I need to do to restart it with the serial monitor working?

You applied connections like it was a plain esp8266. The board has the necessary pull-ups and pull-downs. Connect it at first only to GND, VCC, TX, RX. The button pulls gpio0 LOW to enter flashing mode at power up.


Getting error invalid conversion from 'const char*' to 'const uint8_t* I have written this sketch, and I am trying to populate the array of wifi hotspots to  set the value in html select using javascript dynamically.

#include <Arduino.h>
#include <Hash.h>
#include "ESP8266WiFi.h"
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ap_ssid     = "ESP8266";
const char* ap_password = "0123456789";

// Create AsyncWebServer object on port 8080
AsyncWebServer ap_server(8080);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width, initial-scale=1">

)rawliteral";

void setup() {
  Serial.print("Setting AP (Access Point)…");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ap_ssid, ap_password);

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

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, getWifiHotspots());
  });

  // Start server
  ap_server.begin();
}

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

}

But I am geting this error

    /Arduino/libraries/ESPAsyncWebServer/src/ESPAsyncWebServer.h:243:10: error:   initializing argument 4 of 'void AsyncWebServerRequest::send_P(int, const String&, const uint8_t*, size_t, AwsTemplateProcessor)' [-fpermissive]

     void send_P(int code, const String& contentType, const uint8_t * content, size_t len,
AwsTemplateProcessor callback=nullptr);
          ^

exit status 1
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

In the library ESPAsyncWebServer.h are these two possible function variants defined

  void send_P(int code, const String& contentType, const uint8_t * content, size_t len, AwsTemplateProcessor callback=nullptr);
   void send_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback=nullptr);

So  when using

const char index_html[] PROGMEM = R"rawliteral(<YOUR HTML here>)rawliteral";

give the compiler the explicit instruction

ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
  request->send_P(200, "text/html", (const uint8_t*) index_html, getWifiHotspots());
 });

The code compiles error free on ArduinoIDE 1.8.12/ESP8266 2.71/ NodeMCUv1 (as not having your definition of getWifiHotspots() I defined it as char)


What are the differences between the 1.0.x and 1.6.x IDEs? What is a summary the main differences between the Arduino 1.0.x and 1.6.x IDEs?  Why do some Arduino products, such as the LightBlue Bean, still require use of the 1.0.6 IDE?

I think Arduino's version history is a bit confusing. I'm not an expert but I think this explanation will help. First let's note that version 1.6 was released 2015.02.09. However, back in 2012, version 1.5 BETA was created and it remained in beta for several years. Meanwhile, the 1.0.X version evolved independently here's an excerpt from the changelog

ARDUINO 1.0.6 - 2014.09.16
ARDUINO 1.0.5-r2 - 2014.01.08
ARDUINO 1.0.5 - 2013.05.15
ARDUINO 1.0.4 - 2013.03.11
ARDUINO 1.0.3 - 2012.12.10
ARDUINO 1.0.2 - 2012.11.05

So you can see that 1.0.6 isn't as old as one may think. Many vendors probably chose not to develop their products against the 1.5 version (or branch) because of its beta status. 1.5 being in beta for as long as it did lends to a confusing version history. I did get the impression that LightBlue Bean is working on compatibility with 1.6.x because their getting started page mentions

  Download and extract the Arduino app, version 1.0.5. We currently do not support newer versions of the Arduino IDE.


Is two modules using Serial Interface on one Arduino Uno possible? I was wondering if I have both a Bluetooth HC-05 module and a GPS module (uBlox 7N) is it possible both for both to be using the serial interface?

I'm aware they cant be operating simultaneously with one another but if I using the RX TX pins for the GPS module, can I receive a location, store it in a variable then terminate the GPS serial usage and using software serial with 2 pins of my choice transmit data via the Bluetooth module which also requires the serial pins?

You are right, that you need one Serial interface for each module. The Uno has only 1 hardware serial interface (hardware means, that the Arduinos hardware will do the communication work in the background and you can let it do other things in the meantime). But you can add more serial interfaces, on other pins, that work purely through software. For this the SoftwareSerial library is meant.

SoftwareSerial comes with some limitation, since the load of communication has to be done in software instead of hardware. For example it becomes unstable at high baudrates. Especially for the HC-05 you should not use baudrates of 115200 baud and higher. Also - since it uses pin change interrupts to work - you can only listen at one SoftwareSerial at any given time.

Since you only have 2 modules, it should be easily possible, to utilize SoftwareSerial and access both of them with the Uno. If you at some time want to use more serial modules, you can still change to a bigger board like the Mega.

Note: Be sure to disconnect the module from the hardware serial, before programming the Uno over the Serial interface (USB), or the programming will fail.


Why is there no smooth value from ADXL335? I have written this code to read x-acceleration from ADXL335.

Why is the value toggling between 342, 343, 344 even at rest? Is there anything I need to do to get a smooth curve?
How to increase resolution? (I'm using a Mega 2560)

int Xcurr,Ycurr,Zcurr;
int Xpre=0,Ypre=0,Zpre=0;
int res=0;
// these constants describe the pins. They won't change:
const int groundpin = A1;
// analog input pin 4 -- ground
const int powerpin = A0;
// analog input pin 5 -- voltage
const int xpin = A3;
// x-axis of the accelerometer
const int ypin = A2;
// y-axis
const int zpin = A4;
// z-axis (only on 3-axis models)
const int stpin = A5;

void setup() {
  Serial.begin(9600);
  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
  pinMode(stpin, OUTPUT);
  digitalWrite(stpin, LOW);
}

void loop() {
  Xcurr=analogRead(xpin);
  Serial.print(Xcurr);Serial.print("\n");
  delay(100);
}

It is called moving average, the calculations you can use to prevent such problems can be found at wikipedia

In principle, what you do is take the average over the last x measurements to take away the peaks.


Resetting 16U2 Processor on Uno (R3) This question got me thinking, the OP was wondering about how to "bring back" Leonardo boards connected to a Raspberry Pi via USB. The Leonardos would occasionally drop off line and could not be brought back by resetting the board.

So I got curious and hooked a Uno up to a Pi via USB and started poking around. I had the idea that perhaps resetting the 16U2 would do the trick. It does not. After resetting the 16U2 (by grounding the reset pin in the ICSP connector). This is what I see in the kernel log on the Pi:

[ 6277.570058] usb 1-1.3: USB disconnect, device number 11
[ 6278.576503] usb 1-1.3: new full-speed USB device number 12 using dwc_otg
[ 6278.684793] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 6278.684823] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

As opposed to this:

[ 6325.960510] usb 1-1.3: USB disconnect, device number 12
[ 6329.267003] usb 1-1.3: new full-speed USB device number 13 using dwc_otg
[ 6329.382675] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[ 6329.382703] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 6329.382720] usb 1-1.3: Product: Arduino Uno
[ 6329.382736] usb 1-1.3: Manufacturer: Arduino Srl
[ 6329.382753] usb 1-1.3: SerialNumber: 75431343334351F061E2
[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

Which is what I see if I unplug and replug the USB cable.

I'd like to know what happens differently during a 16U2 reset vs. an unplug/replug cycle.

I'd also like to know if there is a way to simulate unplugging and replugging the USB cable. The 16U2 reset comes close (the Pi notices that something happened), but it would be nice if there were a way that either code on the Uno or on the Pi could "wake up" a down USB link.

What I think is happening here is that the HWBE fuse is set (hardware boot enable).

From the datasheet:

  The Hardware Boot Enable Fuse (HWBE) can be programmed so that upon
  special hardware conditions under reset, the bootloader execution is forced after reset.

What this means is that under normal booting (power-on reset) the bootloader is not entered, and the device immediately identifies as a TTY device (ttyACM0) as you saw:

[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

However if you manually reset it, it enters DFU mode with its bootloader, so you can reprogram the main code. Thus it identifies differently:

[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

Thus, a forced reset via the Reset pin acts differently to a power-on rest. By design.

If you search for uno enter dfu mode you will get quite a few hits. People use that technique to reprogram their ATmega16U2 (eg. to act as a MIDI interface).


Custom Bootloader on Atmega328p - PU - 28 pin DIP I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.

I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.

Should I be worried about it?

Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?

The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.


Can the WiFi on ESP8266 be disabled? I've been reading a lot on the ESP8266, but still my understanding is shaky. I have the Arduino IDE running on a PC, which uses wires to connect to the ESP8266 via a USB device (Device Manager > Ports (COM & LPT) > Silicon Labs CP210x USB to UART Bridge). This is how I uploaded a simple sketch to the ESP8266.

It works and has been installed in the wall. I'm happy and relieved to complete the project... except for one small thing: I noticed that it shows up on WiFi. I can connect to it without a password, with a "Limited" connection. After that I'm lost, but I wonder if someone who knows what they are doing can use this unsecured connection to hack my install. I'd like to disable the WiFi, if possible, since I'm not using it.

The worst part is my learning curve now starts over. I thought that when my sketch gets uploaded, it replaces the original firmware. Now "firmware" is an elusive concept. I keep thinking that it shows up on WiFi because of something running in firmware. My sketch hasn't any code for WiFi. What am I missing/do I have wrong?

To turn of the WiFi add the WiFi library and use WiFi.forceSleepBegin();

Firmware is the program/sketch that controls a MicroController Unit aka MCU (and in this case a Arduino).
Best explanation I know is here: https://en.wikipedia.org/wiki/Firmware


UVB sensing with Arduino As part of the research I am involved with, the detection (not imaging) of UV (ultraviolet) sources, either emitters or reflectors is an important factor.

I am aware of the SparkFun UV Sensor Breakout - ML8511 component, which, according to the product specifications, has a decent broadband response across the UVA and UVB, with little amount of visible light.

Is there an Arduino component that only detects the UVB waveband (280nm to 320nm)?

The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.

Basically any device that has an I2C interface should work with an Arduino as long as you know how to interface with the device in the code.

If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"

The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.


New Language - Interfacing with AVR So I'm taking a class where the project is to create a new embedded language. We are using OCaml for the compiler, so I was looking for a way to interface with AVR or its C library in such a way as I can write programs in my language, then compile and somehow get it on the arduino I have. I was curious if there's a library for OCaml or some sort of white paper for interfacing with the board at a high level or even at a low level where I can get this to work.

I have no experience with OCaml or with writing compilers, but I would
suggest that you first learn how to program the Arduino, then teach
your compiler to do so.

You may start by using the Arduino IDE and a couple basic tutorials.
There is an option in the IDE for displaying all the commands it runs to
get your program compiled and linked. Take note of these commands, then
throw the IDE away. Alternatively, you can download one of the few
Arduino Makefiles that float around the Web.

You will see that the basic toolset you need is the following:

The AVR flavor of GNU GCC and the binutils. This allows you to program
the AVR in assembly, C and C++. Calling these tools from your own
compiler should be as easy as calling them from the command-line.
The avr-libc, which is a port of
the libc for the AVR, together with some AVR-specific stuff, and the C
runtime. It does not provide a hardware abstraction layer.
The Arduino core library, a beginner-oriented C++ library built on top
of avr-libc. It does provide a hardware abstraction layer and is
source-level compatible with non-AVR based Arduinos.

In terms of language and API, your main choices are: AVR assembly, C +
avr-libc, C++ + avr-libc, C++ + Arduino core + avr-libc. There are
others, of course, these are just the better known. Pick your favorite,
learn how to use it, then teach your compiler.


Why does my Arduino keep waking up? This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.

I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial here. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).

In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish sleep until interrupt wakes, perform interrupted action, then go back to sleep. What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?

Thanks for the help!

#include <avr/sleep.h>
#include <avr/power.h>

ISR(TIMER1_OVF_vect)
{
 //do nothing
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_IDLE);

  sleep_enable();

  /* Disable all of the unused peripherals. This will reduce power
   * consumption further and, more importantly, some of these
   * peripherals may generate interrupts that will wake our Arduino from
   * sleep!
   */
  power_adc_disable();
  power_spi_disable();
  power_timer0_disable();
  power_timer2_disable();
  power_twi_disable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the timer timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

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

  /*** Configure the timer.***/

  /* Normal timer operation.*/
  TCCR1A = 0x00;

  /* Clear the timer counter register.
   * You can pre-load this register with a value in order to
   * reduce the timeout period, say if you wanted to wake up
   * ever 4.0 seconds exactly.
   */
  TCNT1=0x0000;

  /* Configure the prescaler for 1:1024, giving us a
   * timeout of 4.09 seconds.
   */
  TCCR1B = 0x05;

  /* Enable the timer overlow interrupt. */
  TIMSK1=0x01;
  while(!Serial);
}

void loop()
{
    enterSleep();
    Serial.println("Waking");
    //delayMicroseconds(10000);
}

Yes.  Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.

You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.

If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent.  If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done.  A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.


Why do we use bitwise operators to assign PORTx, DDRx and Pinx? I have come accross a lot of examples using ways similar to the ones shown below to assign values to the pins.

PORTB |= (1<<PORTB2); //set bit 2

PORTB &= ~(1<<PORTB1); //clear bit 1

DDRD = DDRD | B11111100;  //Sets up the pins for output

My question is why do we need to use bitwise operations to make assignements?

My question is why do we need to use bitwise operations to make assignements?

Because you're not assigning, you're modifying.
If you want to turn on just pin 3 (for example) you need to only control bit 3 of PORTB and leave the others alone.
That means you need to "or" the value of just bit 3 being on with the existing PORTB to turn the bit on, or AND it with the inverse (all pins on except bit 3) to turn it off.
To get the value of bit 3 you can remember that it's 4, or you can just use 1<<3 to say "Bit 3" - or use the macro PORTB3 to make it more readable instead of just the number 3.
The operation is commonly known as "Read Modify Write" and in some low-end microcontrollers you have to take special care when doing it.
For example, if you want to control the output pin 3 and currently you have pins 2, 5 and 6 on and the rest of pins 0-7 off (those are the ones on port B on the Uno) the sequence may be like:
Turn on:

Calculate bit value 1<<3    => 0b00001000
Read PORTB                  => 0b01100100
OR the two values together  => 0b01101100
Write to PORTB              <= 0b01101100

Turn off:

Calculate bit value 1<<3    => 0b00001000
Invert it                   => 0b11110111
Read PORTB                  => 0b01101100
AND the two values together => 0b01100100
Write to PORTB              <= 0b01100100


Using a transistor to get 100mA on a IR led What i saw is that the led use 1.3V on 100mA with a 1:10 Cycle (100ms). Im currently at 30mA using only a 100 resistor, but the range of the led is 20cm at max, i want to get at least 2 meters.

Since i know the max output of the Arduino pin is 40mA i need to use a transistor to get the 100 i want. And that is the problem, i read a lot about how transistors works but i can't yet understand how can i achieve 100mA using a transistor.

I did the math using 5v and got 37R.

Is this correct? So i need to use a 37 ohms resistor to get the 100mA i want?

And this resistor is going between the digital input and the transistor base, correct?

Im using a NPN 2n2222 and reading the datasheet 100mA is easy job for this transistor.

I appreciate any help.

Increasing the power to the LED isn't the best way of increasing the distance. In fact it's the worst way.

The 100mA is only for a small duty cycle. You can power it with 100mA but only for a fraction of the time. The overall average light output won't be any more than at 30mA.

The problem you are actually suffering from is the fact that your receiver can't distinguish the LED's light from the background light. That is simple to overcome though. You just need to modulate your LED with a high frequency (typically 30kHz or higher) and perform a high pass filter and amplification on the receiver.

Exactly the same way that remote controls do it.

That way you can distinguish the LED (flashing at a given frequency) from the background light (static brightness or relatively very slowly changing).


How to upload code without closing puTTY My question is quite simple: can you, somehow, upload Arduino code without closing puTTY's serial console? I hate having to close the program to open it again for reading the incoming information.

There is an open source project that will do what you want.
http://com0com.sourceforge.net/
The com0com will create virtual com ports for the programs to connect to.
The hub4com will allow you to route data between the physical port and multiple virtual com ports.
http://com0com.sourceforge.net/hub4com/ReadMe.txt


ADC timer interrupt when ready I have a microphone and I need as precise values as possible. I have been told by my teacher, that it is somehow possible to make a ADC timer interrupt, which would interrupt always when the value is ready, so that the reading itself would not slow the program down.
    I know, how to use timer interrupts to read the analog value every other ms or something and I even have a code that lets the ADC read automaticly and takes the value, but I need to make it take the value always when it's ready, so that I would have every value the ADC read. I tried to look into the datasheet, but it's too complicated for me.
   How can I achieve such thing? I am using arduino uno.

this is the code I have that sets up the ADC interrupt:

  ADCSRA = 0;
  ADCSRB = 0;
  ADMUX = 0;
  ADMUX |= (1 << REFS0) + (1 << REFS1);
  ADMUX |= (1 << ADLAR);

  ADCSRA |= (1 << ADATE); //enabble auto trigger
  ADCSRA |= (1 << ADIE); //enable interrupts when measurement complete
  ADCSRA |= (1 << ADEN); //enable ADC
  ADCSRA |= (1 << ADSC);
  ADCSRA |= 0b010;

ISR(ADC_vect) {//when new ADC value ready
  af = af + ADCH;
  aaf++;
}

I found this on the internet, but it didn't work as I expected.

it is somehow possible to make a ADC timer interrupt

The ADC and the timers are two different things. If you mean a timer interrupt, I'm not sure why you would want that. If you mean an ADC interrupt, yes you can do do that.

Here is some example code from my page about the ADC which shows using the interrupt (on a Uno):

const byte adcPin = 0;
volatile int adcReading;
volatile boolean adcDone;
boolean adcStarted;

void setup ()
{
  Serial.begin (115200);
  ADCSRA =  bit (ADEN);                      // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX  =  bit (REFS0) | (adcPin & 0x07);    // AVcc and select input port

}  // end of setup

// ADC complete ISR
ISR (ADC_vect)
  {
  adcReading = ADC;
  adcDone = true;
  }  // end of ADC_vect

void loop ()
{
  // if last reading finished, process it
  if (adcDone)
    {
    adcStarted = false;

    // do something with the reading, for example, print it
    Serial.println (adcReading);
    delay (500);

    adcDone = false;
    }

  // if we aren't taking a reading, start a new one
  if (!adcStarted)
    {
    adcStarted = true;
    // start the conversion
    ADCSRA |= bit (ADSC) | bit (ADIE);
    }

  // do other stuff here

}  // end of loop

I should point out that if you do an analogRead it blocks until the read is done, so the very next line to be executed after analogRead will be when the data is ready.


Is there a way to define an alias for a hardware Serial I'm porting some code from Arduino Uno over to a Mega and I want to replace a SoftwareSerial defined in the previous code with one of the built-in UARTs.

Rather than go through and replace all references to the serial port, I'd prefer to create an alias for Serial1. The alias can be a constant.

In my old code, I setup the Software Serial as follows:

//SoftwareSerial HMI(HMIRX, HMITX); // Define software serial for the HMI adapter (RX, TX)

I"m not even sure where to start.


Why after the reset the program vanish? I buy a stm32 board as picture below, I connect the Boot0 to 3.3 and use the serial port  download the program.
I use the library https://github.com/rogerclarkmelbourne/Arduino_STM32
The second and third picture is my program. After I download the program, the led on board shine and the serial is normal, but after I press RESET on board, it is not shine. Seemly, the program vanish.
Why it is so ? And how to let the program in board after press reset ?

By connecting BOOT0 to 3.3V you are telling the chip When I reset for whatever reason you must go into the bootloader.

So you reset, and it goes into the bootloader. You then upload your sketch.

At that point the programming software tells the bootloader "Ok, you are done now. Run the program". And it does.

Until you reset. And because you are telling it to go into the bootloader with BOOT0 it dutifully does so, waiting for you to load a new program.

The old program is still there, but you just aren't letting run, since you are insisting that the chip go into the bootloader when you reset.

In order to get your program to run and not the bootloader you must disconnect BOOT0 so it doesn't enter the bootloader.

You only need to connect the BOOT0 when you want to put a new program on there.


How can I make an AC analog voltage with Arduino? I am trying to create an AC voltage in Arduino. Until now I have only managed to get a square wave. How can this be achieved with Arduino?

If I try:

int up;
int down;
int out = 11;

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

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

is it still pulsed DC?

You have a few options:

Use a low-pass filter to round the square wave's edges some so they look more AC-ish.
Use a low-pass filter and have your code create steps of voltage that look AC-ish by varying the PWM widths.
Use an external SPI DAC chip that you can control with more discrete levels to make smoother looking AC.
Look into Direct Digital Synthesis (DDC) to learn more. Google "analog via ddS", lots of hits.


Less hardware dependent development? I'm working on a little Arduino game project that uses neopixel strips as a display. Uploading every code change to the Arduino and testing it on the LEDs is slow and drains hardware lifetime.

Usually I test as much I can using the Serial Monitor, but I can't get it to clear from code which I learned is only possible e.g. when using a terminal. I did that, but it comes with other issues.

Is there a better way to test code on the dev machine instead of the Arduino?
Is there a best practice to have a Serial Monitor (or anything else) act like a display that I can actually refresh/clear? Serial.println() empty lines to scroll the content is not very practical.

You can unit test your code by creating stubs of the functions you are calling, like replacing a couple of includes with their dumb counterparts.
My friend Jan Beayens did something very valuable on that front and he is also the main author of a good replacement for the Arduino IDE when you start needing some more advanced capabilities: Sloeber is the product name and it also contains an improved version of the serial monitor with clear and scroll lock capabilities.

Go check it out.

Disclaimer : I'm a contributor of the project


I need help purchasing components for my Arduino project I am a newbie on this hardware stuff. I need help on purchasing the components

Brief description of my project

I need a device that would remotely detect weight or pressure when somebody push on it and send the info to the webserver or websockets. The device could be located up to 300 ft.

After doing some research on it I learned that I need, arduino uno as the device main platform, xbee for wireless communication with the web, xbee shield for the xbee and Force sensitive resistor sensor to detect small weight or pressure.

Question

First am I correct above mentioned components would solve what I am trying to do? If not what am I missing? Anything I mis-stated?

I have learned that there are stuff like xbee explorer, Arduino stackable headers, break-away headers, and breadboard. Do I really need these?

In the future I want to be able do other experiments with the board like use ultrasonic sensor with it or infrared sensor to detect objects. Will I need to buy anything specific to make these sensors compatible with the board or they are all standard?

Basically I want to buy everything I need in one shot. Thank you in advance. Any help will be appreciated.

I would rather go with ESP8266. You can program that from the Arduino IDE. You don't need anything else than a programming cable (an USB-UART adapter), and you can connect the force sensor to the analog input with one pullup resistor.

There is a similar idea with one button here:
https://www.hackster.io/noelportugal/esp8266-ifttt-easy-button-888a87

You can build your own force sensor:
http://www.todayifoundout.com/index.php/2010/01/how-to-make-a-ridiculously-cheap-analog-pressure-sensor/

If you don't really need to measure the force, there are much easier solutions to detect weight of a person. These give a simple contact once pressed, and can be used like a button (see the first link in my answer).
http://learning.media.mit.edu/projects/gogo/documents/making%20sensors.html#Paper and Aluminum foil.

It is not really possible to buy everything as one batch :) I would say you need:

connection wires
plyers
some cheap multimeter
you may wish to power your device from a battery, so you may need a battery holder and batteries
battery voltage may not be a perfect match for ESP8266, so you might want to get a board with internal regulator, such as https://www.adafruit.com/products/2471
it is handy to start with a breadboard with jumper wires, something like https://startingelectronics.org/beginners/start-electronics-now/tut1-breadboard-circuits/building-cct-step5.jpg

I suggest you to find an ESP8266 based tutorial, Adafruit has a lot of those, and then you'll have an understanding about the tools and components needed.

If you buy some Arduino, consider buying the ones using 32u4 chip, such as Arduino Leonardo or Arduino Micro. The 32u4 chip has more memory, and more performance than the original Arduino Uno, plus it can work as an USB mouse or an USB keyboard too.

For infra (do you mean a PIR which detects humans, or a reflective sensor?) you have quite a lot of possibilities. In case of using ESP8266 directly, check that the sensors work on 3.3V. Some stuff works on 5V, others on 3.3V. You can interface them easily, but this is just another extra thing to cover, so better go with a dedicated 3.3V sensor.

Ultrasonic sensors are coming also in a lot of varieties. Do you need something ridiculously cheap? A sensor with a short range? A sensor with a longer range? I think you have to set up your goal first.

The Leonardo and Uno and Micro boards work both with 5V and 3.3V sensors. Driving these sensors are quite standard, you need to power them with two wires, and have one wire which goes from 0V to 5V (or vice versa) when something is detected. Ultrasonic sensors vary: there are sensors with one analog output, giving a voltage between 0V and 5V propoprtional to the distance. However most of ultrasonic sensors are simple as the ultrasonic principles: they have one input what you drive, and will give one output of the recived echo signal. In this case you have to measure the time elapsed between the drive signal and the echo, which depends on the distance of the object from the sensor.


Array deletion problem I am a bit confused about how memory works in Arduino.  I have created an integer array like so:

int* arr = new int[3] {1, 2, 3};

When I go to delete it:

delete[] arr;

The first element is deleted, and all the remaining ones are still  present and accessible.

Serial.println(arr[0]); // prints 0
Serial.println(arr[1]); // prints 2
Serial.println(arr[2]); // prints 3

First of all: it is not a good idea to do dynamic memory maagement in embedded systems (in casu arduino)
Secondly freeing memory means: marking the memory as available. It does not mean "setting the memory to 0"
because ar still points to the same locaton in memory it is "normal" that it also still reads the old values. Only -according to the C CP0P0 pàrogramming rules- you should not do so. Reading will not cause problems but writing will very likely.


Arduino, relays and building code I want to install several Arduino controlled relays which are use to turn on/off some lights, a fog machine and some door locks in a building.  What do I need to do to insure that the power relays don't violate building code?

Do components need to be put in a box or can they be mounted to a 2x4?
Are there requirements regarding the points were the bear wire is screwed into the relay?

I am assuming that if anyone as ever wired an Arduino into a garage door opener, these questions may have come up.

Disclaimer:   IANAL nor US regulations expert.

There are a few standard certifications that will essentially guarantee that a part will meet US regulatory requirements. Usually more of the form "your building burned down and you have no insurance because ..." rather than prosecuting you for non compliance.

Relays with UL rating bought via a reputable US supplier will usually quality.
eg if Digikey sell it it is PROBABLY Kosher.
Also if made by reputable manufacturers the same applies, as long as its genuine. eg (1 of many) Omron - they don't make no junk largely and even their junk is certified :-).

HOWEVER if you are building something using such parts the whole unit will need to be certified. For small volume applications it may be easier and cheaper to buy comething COTS (commercial off the shelf) which has the relevant certifications. That said,be sure these are legitimate.

As a guide:

US standards a useful introduction

Extensive international standards summary

Wikipedia on UL

MET Labs strut their stuff comparison with UL.

Intertek test labs bow in

Useful - Understanding electrical certification

Possibly useful templates


ATMega328 functions, but will not output to any pins Problem:
ATMega328 Refuses to digitalWrite() to any pins, I can upload and run sketches using the board UNO from the ide on the 328 and can confirm it is working using the serial monitor (see code).
I am using this FTDI module.
Board Manager -- UNO works, but ATMega328 Doesn't

By using the UNO board under board manager, I am capable of writing sketches and communicating with the 328 just fine.
But when I use the ATMega328 at 5.5V,16Mhz I receive the following error.
         Using Port                    : COM3

         Using Programmer              : arduino

         Overriding Baud Rate          : 57600

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Code & Serial Monitor "Proving" it works
I have tried every usable PWM and other pins to attempt to output using LED's, buzzers and even other Arduino's to read inputs but none of the pins will output high when requested.
I believe that Arduino IDE is attempting to compile my code for the UNO and those pins do not work on the ATMega328 but this could be completely incorrect and someone please correct me if this is a wrong assumption.
Lastly, I have been able to use the SCL and SCA pins to communicate with an I2C LED shield.
Does anyone know why I cannot write sketch to the ATMega328 using the FTDI and my configuration.
Posted Below are images and very rough Fritzing schematics of how I am setup.
void setup() {
  Serial.begin(9600);
  pinMode(5,OUTPUT);
}

void loop() {
  Serial.println("TICK");
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
  }

My Breadboard

Fritzing Schematic

This may not be your only problem, but you need a second delay.
void loop() {
  Serial.println("TICK");
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
  delay(1000);    // LOW for a second as well
  }

Otherwise you will not be able to see the LOW part, because it will be really quick.

I believe that Arduino IDE is attempting to compile my code for the UNO and those pins do not work on the ATMega328

The Uno has an Atmega328 on it, and I usually compile for the Uno when uploading to a custom board, so this is not the issue.


How to switch on an AC bulb using arduino as well as regular switch? I'm trying to build a GSM based AC Power ON/OFF switch using Arduino. I've successfully completed the ON/OFF mechanism using SMS with the help of 240v 100amps relay to control the circuit. Apparently I don't want to disturb the regular on/off switch's operation. I want both of them to be operational. When I'm not at home arduino should be the switch control and the regular one should be preferred while at home. I'm actually a noob in this topic, and want your precious help to solve this issue.

This can be done (to a certain extent) using a SPDT (Single-Pole-Double-Throw) relay and an SPDT switch.

The basic principle is the same as when you have two light switches controlling the same light (such as on a staircase - one switch at the top and one at the bottom).  The two switches alternate between one of two different paths for the current. When both switches are routed to the same path the light is on.

Both the Arduino and the switch can turn the light on and off at will. The only problem, though, is that the Arduino has no clue if the light is on or off. To know if the light is on you will need some kind of feedback mechanism.  That might be a simple LDR that looks to see if it's light or dark, or some kind of current monitoring system (current transformer, hall effect current monitor, etc) which the Arduino can use to see if current is actually flowing through the lamp circuit or not.


Two ints declared simultaneously, one "does not name a type" I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):

  int readButtons(){
  rbuttonState = digitalRead(right);
  lbuttonState = digitalRead(left);
  sbuttonState = digitalRead(sel);
  obuttonState = digitalRead(off);
  nbuttonState = digitalRead(snooze);
  int ret = -1;
  if (rbuttonState != lastrButtonState){
        if (rbuttonState == HIGH) {
            ret = right;
          }
        }
        if (lbuttonState != lastlButtonState){
          if (lbuttonState == HIGH) {
            ret = left;
          }
        }
        if (sbuttonState != lastsButtonState){
          if (sbuttonState == HIGH) {
            ret = sel;
          }
        }
        if (obuttonState != lastoButtonState){
          if (obuttonState == HIGH) {
            ret = off;
          }
        }
        if (nbuttonState != lastnButtonState){
          if (nbuttonState == HIGH) {
            ret = snooze;
          }
        }
  }
  lastrButtonState = rbuttonState;
  lastlButtonState = lbuttonState;
  lastsButtonState = sbuttonState;
  lastoButtonState = obuttonState;
  lastnButtonState = nbuttonState;
  return ret;
}

Yet I have the errors that

Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
   lastrButtonState = rbuttonState;
   ^
Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
   lastlButtonState = lbuttonState;
   ^
Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
   lastsButtonState = sbuttonState;
   ^
Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
   lastoButtonState = obuttonState;
   ^
Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
   lastnButtonState = nbuttonState;
   ^
Nixie_Clock_0:70: error: expected unqualified-id before 'return'
   return ret;
   ^
Nixie_Clock_0:71: error: expected declaration before '}' token
 }
 ^
exit status 1
'lastrButtonState' does not name a type

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

(The last line of code is line 72).
I am at a complete loss. Any help?

the following code

is properly indented
is missing the declarations of the variables for the 'button states' and the 'prior button states'
has additional text about a format error
is properly indented
has the code blocks properly separated by a single blank line

and now the code

int readButtons()
{
    rbuttonState = digitalRead(right);
    lbuttonState = digitalRead(left);
    sbuttonState = digitalRead(sel);
    obuttonState = digitalRead(off);
    nbuttonState = digitalRead(snooze);
    int ret = -1;

    if (rbuttonState != lastrButtonState)
    {
        if (rbuttonState == HIGH)
        {
            ret = right;
        }
    }

    if (lbuttonState != lastlButtonState)
    {
        if (lbuttonState == HIGH)
        {
            ret = left;
        }
    }

    if (sbuttonState != lastsButtonState)
    {
        if (sbuttonState == HIGH)
        {
            ret = sel;
        }
    }

    if (obuttonState != lastoButtonState)
    {
        if (obuttonState == HIGH)
        {
        ret = off;
        }
    }

    if (nbuttonState != lastnButtonState)
    {
        if (nbuttonState == HIGH)
        {
        ret = snooze;
        }
    }
}  << extranious closing brace ends the actual function

    lastrButtonState = rbuttonState;
    lastlButtonState = lbuttonState;
    lastsButtonState = sbuttonState;
    lastoButtonState = obuttonState;
    lastnButtonState = nbuttonState;
    return ret;
}


Connecting a time on/off circuit and my adafruit neopixel light strip I'm new to programming and hardware so be gentle.
I've used this tutorial https://www.instructables.com/id/Arduino-Ultra-Mega-Timers/ to create a time on/off circuit.
I'm attempting to connect some adafruit neopixel led strips to a 5v relay. I've been trying to read up on how exactly relays work and what wires would go from GND, 5v, and Dout to NO and NC but I've hit a brick wall because all of the schematics I've found show light bulbs connecting to the relays. A detailed explanation of exactly how to connect the LED strip to the relay and why it works would be great as I am trying to learn!
Thank you everyone!
-Matthew

You cannot find a tutorial for controlling neopixel strips with a relay, because that just does not make any sense. You don't need a relay to control the strip.
The Neopixels consist not only of the LEDs themselves, but also of one LED driver chip per LED (WS2811 and it's siblings). These driver chips control the LEDs based on the data, that you send through the data pin. Actually one Neopixel LED consists of 3 LEDs inside a single package, one LED each for the colors red, green and blue (so that you can create all the other colors with a combination of them). The driver chip controlls the brightness of all three colors.
Thus you only need to connect your 5V power source to the strip (5V and ground) - Be sure to connect the power lines directly to your power supply, so that the LED current does not flow through the Arduino (because that can fry your Arduino) - and the data In pin of the strip to a fitting digital pin of the Arduino. You can use the Adafruit Neopixel library or the FastLED library for controlling them.
To turn the strip on, you set the needed pixels to the wanted color and then call the show method of the library (which sends out the color data through the data pin). To turn the strip off, you simply clear all the pixels (the libraries have extra functions for that), which basically means setting all pixel to black (red, green and blue components all zero).
So forget about the relay and just use the strip directly. Also Adafruit has a very good guide on how to use the Neopixels.


Quick start on Arduino for experienced embedded programmer? I'd like catch up the Arduino concepts (programming & IDE). There are excellent online tutorials available for Arduino but all of them which I saw are made for those who didn't have embedded/electronics background. Going through them is heavily time consuming as I'm already familiar with the embedded programming other than Arduino or Raspberry Pi.

Does any one know any quick reference materials for Arduino which excludes electronic/embedded basics which is meant for experienced embedded programmer? That could be a big time saver for me.

Thanks in advance!

As far as I know, there is no tutorials about using Arduino's for, e.g. "multi-tasking, real time response". That is not the focus of the Arduino community.

The Arduino UNO development board is built around Atmel's ATmega328. The Summary datasheet gives an overview of its hardware capabilities on the first page. If you are familiar with MCU development, that should give you a feel for its hardware capabilities. The complete ATmega8/168/328 datasheet is over 600 pages, and describes every feature, with all registers in detail.

The Arduino IDE uses gcc under the covers. So you likely already know how to use that. When you download and install the Arduino IDE, gcc and gnu binutils for AVR will be installed too.

The Arduino IDE has all of the Atmel header files, so much of the code in the datasheet should compile, link and upload.

The IDE is really designed for beginners. It is to easy to use, but has very few features beyond basic editing, compiling and loading. It does support a serial-monitor to see text printed by the uploaded application, but it doesn't support a debugger like GDB out-of-the-packet.

However, it doesn't prevent you writing C++ code and header files, and it will build the whole collection of files.

Because the IDE lets you create and edit C++ directly, you can install the IDE on any of the three main platforms, and get started very quickly.

You will probably want to visit AVRFreaks who tend to focus at a lower level than Arduino.

There is also AVR LibC library which points you at the documentation for the AVR upload tool, avrdude, and debugger.

Summary: Install Arduino IDE, do a couple of quick projects to get a feel for the system. Then start writing C++ as normal. Install AVR LibC library for a more traditional library, and visit AVRFreaks forums for more technical help and information.


Can I link another device to the Uno's clock? I'm trying to use an unusual 16x2 LCD display with my Uno. As far as I know, it's an EA-X16027AR. It doesn't seem to be compatible with the HD44780 driver, which is typically used for Arduino LCD's.

According to the datasheet, the display's ENB (Enable) pin requires a clock input, described as follows:

  Basical Clock to perform Instructions in Controller LSI. The Clock at the same timing as MPU are usually input.

The timing graphs elsewhere in the datasheet show it wants a speed of around 2 MHz.

Is it possible to get the internal clock signal from the Uno, scale it down to 2 MHz, and output it to a GPIO pin or similar? Alternatively, is it possible to emulate a clock signal at that speed on-board, without adding additional timing components?

Rather than using microprocessor-specific low-level programming, I was able to get a suitable signal using the core tone() function:

tone(11, 2000000);

It can be used to generate a 50% duty cycle square wave of a custom frequency on any individual GPIO pin (I'm using 11 in this case). Given the name, it's obviously designed for producing simple audio output, and 2 MHz is way above the range of human hearing.

The documentation doesn't list any upper limit on the frequency though, and the code it's based on doesn't appear to introduce any limitations. With that said, it clearly can't run faster than the internal timer it's based on (which I think will typically be 8 or 16 MHz).

It seems reasonable to assume that it will be in-sync with the microprocessor's internal clock, although I haven't been able to confirm that empirically as I don't have suitable equipment at home. Similarly, I haven't been able to confirm that it's actually producing a 2 MHz signal, but the LCD display is working properly so it's likely to be in the right vicinity. I had previously tried running it from regular PWM, but that didn't work, so frequency is obviously important here.

The signal can be stopped by calling:

noTone(11);

There are a couple of caveats to be aware of when using tone(). First of all, it can only work on a single pin at a time, so you can't generate multiple signals with it. And secondly, it will prevent some PWM output from working properly (on pins 3 and 11, according to the documentation). This is because it has to reconfigure one of the internal timers which is normally used for PWM.


Using a Micro SD card for data logging, bad idea? Reliable? I'm planning a project that will read data from an I/O board.
The micro SD card would hold data for input bit identity, labeling ?, then logging after events end.

Nothing would be written to or read from the micro sd, unless an event takes place, usually 2-10 events/hour. System will run 24/7 for years, hopefully.
Is a micro sd card the best way?  Is it reliable enough?

We've been maintaining a network of loggers (60+ currently deployed) using SD card connected directly to the SPI pins (see: http://www.mdpi.com/1424-8220/18/2/530 for details) and our experience is that the SD cards are really reliable provided you don't have a brown-out when they are writing, even when we abuse them with hot surface deployments in the tropical sun. And we buy them used, (since the older, smaller Nokia & Sandisk cards have lower sleep currents) but test them well with H2testw.
 However there is one problem that develops over time: the actual SD adapters are not made that well, and tend to have solder flux residue left on the little pads used to hold the contact springs, and these will corrode over time if moisture gets in. I give everything a sonic bath in 90% isopropyl until the parts are squeaky clean, and then always put 2x10gram desiccant packs into the logger housings (with color indicator beads). If you are careful about the cleaning, the contacts last for years, but if you forget, and moisture gets into the housing, then the SD card contact spring solder points are often the first things to corrode.


It seems as if there is a 220K pull-down resistor on analog pin 0 So I am building a project that uses the analog pins for precise measurements of resistance through a voltage divider and I have been having some seemingly unsolvable problems with nonlinear response to linearly changing resistances when using the A0 pin to measure.

I first realized this was the problem when I had a voltage divider consisting of a 76.8K and 100K 1% resistors with Vout connected to A0, and I was consistently getting wrong values. I measured the output voltage of the voltage divider and got 1.7V, instead of the ~2.7 volts I should be getting with my supply. When I disconnected the wire to A0, the voltage rose to the expected level.

I disconnected power and measured resistance between the analog pins of the Atmega328 I was using and ground and found that A0 had 220K of resistance, while all other pins measured as infinite. When using the other pins, the voltage divider returned the expected values and was able to measure a wide range of resistors with values just as accurate as my multimeter. I know I have changed a lot of low-level things with code (analog reference, the comparator, ADC clock prescalers, using analog pins as outputs, etc.) but I don't think any of this could persist while the chip is not powered on. Does doing any of these things connect a resistor in the way I was describing, and is there anything that could cause this to stay "stuck" this way?

They don't connect a resistor as such, but analog input pins do have an impedance which can affect your readings.

If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results.  This is normal.  The input impedance is somewhere in the region of 1MΩ - 10MΩ.

You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.

If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.

Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.


RS485: is "Y" multidrop allowed? I imagine that the proper way to implement an RS485 multidrop bus is the following:

What happens if, in order to save cables, I connect the same 5 nodes above using this other topology?

Will it works?
If no, why?
If "maybe", under which circumstances will it work?

P.S.: yes! I know that MEGA has three Serials and, as such, I could implement two different BUSses (1: Mega<->Mega<->Mega; 2: Mega<->Nano<->Nano), but this will increase the complexity of the software I'm running, as it needs some hacking in order to play nicely with two distinct RS-485 busses;

P.P.S.: This is the bus discussed in this other question

At low speeds and short distances that won't be a problem.

At high speeds (megabits per second) and long distances (hundreds of meters) you may get reflections unless you get the termination just right.


Arduino IDE on Linux - directory not found I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named arduino-1.8.0-linux64.tar.xz, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the install.sh file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did cd Downloads and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.

How can I run the install.sh file? What am I doing wrong? Any help would be appreciated.

You need to extract the archive file first.

$ cd ~/Downloads
$ tar -Jxvf arduino-1.8.0-linux64.tar.xz


Problem with piezo readings and Arduino Due I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

and the following code to observe the readings in the serial monitor:

int piezo = A0;
int threshold = 200;//anything over 200 means I've hit the piezo

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

//this part checks if the threshold has been reached and then writes the strenght of the signal

void loop(){
    int piezoVal = analogRead(piezo);

    if (piezoVal>threshold){
        Serial.println(piezoVal);

        delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
    }
}

The things that bother me are:

if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.
if I do not use delay, then I'm getting getting multiple values one after another
and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?

The problem is timing.  When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero.  You are expecting the code to capture the peak value.  Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.

So imagine this stream of signal values

time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190      190
 2     190
 3     199
 4     210
 5     220      220 - trips threshold, prints and then waits
 6     230
 7     260
 8     280
 9     320      (this point occurs during delay())
 10    280
 11    260

The same exact signal, but at a slightly different time could be read different by the code:

time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190
 2     190
 3     199      199
 4     210
 5     220
 6     230
 7     260      260
 8     280
 9     320      (closer, but still did not read the peak)
 10    280
 11    260

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value.  There are two ways forward: hardware or software.

You could use electronics that latches the maximum value.  If you search "peak hold circuit" you will find many circuits that would capture and hold the peak.  That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak.  Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.

You could use code to capture the peak. Something along the lines of this psuedo code:

lastreading = analogread()
if(lastreading > threshold) {
  peakreading = lastreading
  keeplooking = true
  while(keeplooking) {
    nextreading = analogRead()
    if(nextreading > lastreading) {
      // the signal is increasing, save this and see if next point is even higher
      peakreading = nextreading
      lastreading = nextreading
    }
    else {
      //signal is decreasing, the peak is over
      keeplooking = false
    }
  }

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.


How to print (or store) gps lat, lng value (TinyGPS++) with Bluetooth BLE nRF8001? I have a u-blox gps module and I use TinyGPS (http://arduiniana.org/libraries/tinygpsplus/) to get out the lat + lng.

If i write...

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

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

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

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

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

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

But I do not get the correct lat, instead I get this value 6.00000000

I have tried to store the lat like this:

double myLat;

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

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

I tried this as well:

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

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

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

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

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

Appreciate every help and tips!

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

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

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

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

Cheers!


RGB and Potentiometer How do I start this program???

int x=0;
int P1=A5;
int P2=A4;
int P3=A3;
int R1=3;
int G1=5;
int B1=6;
int R2=9;
int G2=10;
int B2=11;
int sValue1;
int sValue2;
int sValue3;
int oValue1;
int oValue2;
int oValue3;
int timer(1000);

void setup() {
 pinMode(P1,INPUT);
 pinMode(P2,INPUT);
 pinMode(P3,INPUT);
 pinMode(R1,OUTPUT);
 pinMode(G1,OUTPUT);
 pinMode(B1,OUTPUT);
 pinMode(R2,OUTPUT);
 pinMode(G2,OUTPUT);
 pinMode(B2,OUTPUT);

}

void loop() {

sValue1=analogRead(P1);
sValue2=analogRead(P2);
sValue3=analogRead(P3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
{
  setColor1(0,255,255);
  delay(timer);
  setColor2(255,0,0);
}
}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(R1,red1);
    analogWrite(G1,green1);
    analogWrite(B1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(R2,red2);
    analogWrite(G2,green2);
    analogWrite(B2,blue2);

  }
}

Arduino has created binary numbers: B1, B101, B00111, and so on.

It is documented in the reference page "Integer Constants".
The "B1" is defined in "binary.h".

They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.

It is not your fault, you can blame Arduino. Because of this, you should never create variables with the name: B1, B101, B00111, and so on.


Arduino does not work on battery The day before I got my used full package arduino uno. I tested it on USB plug. Everything worked fine. I wrote a piece of testing code and uploaded. After I have accomplished with the test I have unpluged arduino from PC and connected to battery and I see that it does not work. I have used a multi-tester to find out the voltage. It showed 4.7V. Now I wonder should I buy a new battery or there is another reason for this. Anybody, please suggest me what to do.
Update
The battery came with arduino set. It is written that it is a 9V battery. I am plugging it to the battery input in my arduino uno. Polarity is ok. The same program working on connection via usb, does not when connected to battery.

Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).

  @bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)


I2C communication between Arduino Uno and Nodemcu32-s (ESP32) I want to send data between an ESP-32 (NODEMCU-32S) and an Arduino Uno but I haven't found any source on how to do that, so I tried this code:
ESP-32 code:
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(21, 22);      /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}

void loop() {
  Wire.beginTransmission(8);
  Wire.write(3);  /* sends hello string */
  Wire.endTransmission();  /* stop transmitting */
  Wire.requestFrom(8, 18); /* request & read data of size 13 from slave */
  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

And Arduino code:
#include <Wire.h>

void setup() {
  Wire.begin(8);                /* join i2c bus with address 8 */
  Wire.onReceive(receiveEvent); /* register receive event */
  Wire.onRequest(requestEvent); /* register request event */
  Serial.begin(9600);           /* start serial for debug */
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
void receiveEvent(int howMany) {
  while (0 < Wire.available()) {
    int c = Wire.read();        /* receive byte as a character */
    Serial.print(c);            /* print the character */
  }
}

// function that executes whenever data is requested from master
void requestEvent() {
  Wire.write("hello esp");
}

But I found that no data was sent.
I connected pin 21 to A4 and 22 to A5 directly.
I cannot find where the problem is. Also, I don't know whether the device address is correct or not, since when I tried an I2C scanner it didn't discover any device.
Also, I hope that there is a similar method to have two-way UART communication between the Arduino and ESP as I found none since I need both chips to send data to each other.

I'm working on something similar at the moment. Not a complete answer put some thoughts:

Have you considered that the Uno is a 5v board and the ESP32 is 3.3v? You may need a signal level shifter (there are many to chose from) something like Pololu-2595 which is breadboard friendly.

There's a good ESP32 I2C explanation at Random Nerd Tutorials.


Arduino Debounce Sketch I want to use 4 Push Buttons and 4 leds in my project. What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds? So my sketch is only for one push button and one led. So tell me how I can solve this problem.

Here is the code:

const int buttonPin =2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}

void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}

if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:

// if the button state has changed:
if (reading != buttonState) {
  buttonState = reading;

  // only toggle the LED if the new button state is HIGH
  if (buttonState == HIGH) {
    ledState = !ledState;
  }
  }
  }

  // set the LED:
 digitalWrite(ledPin, ledState);
 lastButtonState = reading;
 }

What do I need to change in my sketch for multiple input push buttons and multiple outputs of leds?

easy:

1) study your code to understand how it debounces one input;

2) isolate those parameters / variables used to debounce that specific input;

3) group those parameters / variables into a struct and pass a pointer to that struct to your code;

4) rewrite your code so that it takes the pointer to that struct and debounces accordingly;

5) use that code on as many inputs as you wish.

that's the general approach you take to coding any task.

hope it helps.


Connect Digital monitor to Arduino? I need a small display with ~ 5 digits.
The display needs to show number of visits to my site in real-time.

(Every time someone visits it needs to increase by one).

I thought to create an app, that fetches server stats every 10 seconds, and checks new number of visitors.

Do you think it is better to do with Arduino or Raspberry Pi?

Do you know of a digits monitor that can be connected to it?

It all depends on how used to you are with using pi or arduino. What you want can be done in both ways.
The displaying of count is common for both. It can be done using a 16X1 LCD display, 5 different 7 segment LED connected via decoders or a graphic display module. Interfacing all these with Arduino will be relatively simpler than Pi.

For the fetching of data and sending it to your device for displaying it. You can use ESP8266 Wi-Fi module with arduino and pull the data. Which is not as simple as it sounds but it is not impossible too.

For pi, (like @max246 said) you can run a python script and use another api to get the data.


Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2 I would like to create a custom Arduino board based on the Arduino Due. Upon looking at the Due's schematics under the documentation tab there are some stuff that i do not need and removed them. the last thing that i want removed is the ATMEGA16U2. This part just takes so many components that i want it removed.

I would like to build my code using the arduino IDE and with the 16u2 gone i do not know a way how to upload my codes.

This seems to be possible since under the documentations there is a native usb port of the due that is directly connected to the SAM3X8E,

from here on out im lost what how do i upload my code to the same sam3x8E

Special tools that i have that might be usefull:

J-link EDU Mini
USB to UART

My Current draft schematics:

Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).

There are two ways of entering the bootloader:

Wipe the flash with the ERASE button (or trigger from 16U2).
Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.

You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.


HC-SR04 ultrasonic sensor: How to check voltage on the ECHO pin I'm using and ESP8266 with HC-SR04 ultrasonic sensor. The sensor requires 5v input and will also output to the GPIO pins at 5V.

ESP8266 has a strong recommendation to use 3.3V into the GPIO pins. I've found some setups online with people using voltage dividers to bring the ECHO pin voltage down.

Example on a PI: https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/

I'm using a basic multimeter that i've found to be pretty accurate. When I put the BLACK cord on the ECHO and RED on the GROUND (of sensor pins), I get variable voltage readings. I'm trying to ensure a 3.3V coming from the ECHO into my ESP.
Questions:

Am I putting the black and red cords on the appropriate areas?
If yes to question 1, then why am i get such a variable of readings?
How can I test to ensure only 3.3V coming out of ECHO?

You have your leads backwards. But that doesn't matter, since there's nothing to measure. You'll only see a voltage (and even then only a brief pulse) when an echo is actually received.

You would need an oscilloscope to be able to read that voltage.


How to connect an industrial sensor to Arduino Uno? I want to use a sensor to read pressure in rooms. But sensor like MPX series isn't capable to read air pressure change under 100 Pa. So I want to use industrial sensor like Dwyer 607 Series, and dont have a clue how to connect it to arduino. Anyone can help?
Thanks :)
Fyi, this is the manual instruction for the sensor http://www.dwyer-inst.com/PDF_files/E_76_low.pdf

That uses the industry standard 4-20mA current loop system. For that you really need a special chip to interface it.

You can buy shields that interface to 4-20mA current loops.


Arduino Variable Data Type? Is there a variable data type available for Arduino? I have a class that should have a member that will differ in data type, in the past I have used the "variable" keyword in c++ but when I tried to use it the compiler yelled at me. I searched online and found a couple of articles that mentioned that if you are using an alternate GUI (I am using eclipse mars) that you can enable the feature but I can not find the correct settings as the examples I had found were for Juno and below.

Here is an example of what I am trying to accomplish

class DisplayItem{

   public:
   variant *displayVar;

   void Display(){
      Serial.println(displayVar);
   }
}

int intDisplay;
String strDisplay;

DisplayItem item();
item.displayVar = &intDisplay;
item.Display();
item.displayVar = &strDisplay;
item.Display();

I realize I could create a overloaded function to display different data types but it would be allot easier if I could simply assign a reference to a variant datatype and reuse the variable.

Edit

So after looking through the answers I think I have this figured out. I needed to keep track of which variable was being set, I put together a quick example in hopes it will help someone else out with the same question.

class DisplayItem{

   private:
   int iVarType;

   union{
      int *i;
      float *f;
   } displayVar;

   public:
   void SetVar(int *var){
      displayVar.i = var;
      iVarType = 0;
   }

   void SetVar(float *var){
      displayVar.f = var;
      iVarType = 1;
   }

   void Display(){
      if (iVarType == 0){
         Serial.println(displayVar.i);
      }else if (iVarType == 1){
         Serial.println(displayVar.f);
      }
   }
}

int intDisplay = 1;
float floatDisplay = 0.123;

DisplayItem item();
item.SetVar(&intDisplay);
item.Display();
item.SetVar(&floatDisplay);
item.Display();

Will Display:

1
0.123

For the situation illustrated in the question – displaying data – polymorphic functions already exist, and might as well be used in this case.  Specifically, use the Streaming.h contributed library.  It adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it via Streaming5.zip from arduiniana.org .

In other cases, a union data structure allows treating an area of memory different ways.  Wikipedia's Union type article explains the general idea.  See eg tutorialspoint.com/cprogramming for union syntax and usage.  For some reason, arduino.cc's Language Reference page hasn't got union on its list of language features.  However, mcgurrin.com has a page called There is Power in a Union that codes a simple Arduino C example two ways (where bearing is an int):

higherByte = compass.read();
lowerByte = compass.read();
bearing = ((higherByte<<8)+lowerByte)/10

-vs-

union Data {
  byte b[2];
  int value;
};
...
union Data data;
data.b[0] = compass.read();
data.b[1] = compass.read();
bearing = data.value/10;


Controlling a stepper with MATLAB I am trying to control a 28BYJ-48 stepper motor + ULN2003 motor driver module  (this is a picture) using MATLAB.

I tried to follow the instructions on this page, but these instructions are specific to Adafruit MotorShield, and I couldn't understand how to modify the code to fit my motor/driver.

Specifically:

How do I wire my motor/driver/Arduino?
How do I modify this command:

shield = addon(a, 'Adafruit\MotorShieldV2')

Do I need to flash my Arduino with any libraries?

Adafruit Motor Shield V2 itself generates signals that are required for motor control.

ULN2003 motor driver module requires signals at the input. This is a significant difference.

Example of use this driver with MATLAB. Not need to flash Arduino any libraries.

a=arduino('com3','uno);

pins={'D8', 'D9', 'D10', 'D11'};
steps={'1100', '0110', '0011','1001'};

steps_size=size(steps,2);                        %steps = 4

for i = 1:50

    step = steps{mod(i,steps_size)+1};      % step=1,2,3,4

    for j=1:4
        writeDigitalPin(a, pins{j}, str2double(step(j)));
    end

    %pause(0.01);

end

Wiring example (Copied from CheapStepper v0.2)


Can I use arduino pro micro rx tx as digital pins I'm using arduino pro micro Atmega32u4 5v 16Mhz
I want to use it to make a HID Keyboard and Mouse but I ran out of pins so I was wondering if I can use the RX and TX pins as digital input pins. Will it work? Will it affect the communication of the arduino  to the computer?

Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.
You can use those pins for digital operation with no problems, you just won't be able to use Serial1 for communication with serial peripherals.


Arduino weird bluetooth module Recently I bought a BT module from eBay which was very cheap. I didn't really noticed the image and I just bought it. When it came I couldn't find any holes to solder the headers. Also the specific module is pretty rare and I couldn't find anything.

Here is an image:

How do I wire up this chip?

From the picture you posted, i was able to google and find something called a BC04-B Bluetooth serial module. It looks almost exactly like yours, and I found a diagram on how to hook it up.

I also believe that these are the serial commands you can use with it...


Arduino only sends HTTP 1.0 requests I'm trying to connect to an http server that uses HTTP 1.1, my problem is that even thought the request is in HTTP 1.1 format and the server does actually use HTTP 1.1(I tried it in a browser) it only responds with HTTP 1.0. I'm using this modified example of the web client, I updated the Ethernet library yesterday and for my server I'm using Node 8.4.0, I'm testing with google first even though I know the server can respond with HTTP 1.1.

Ethernet shield model: Han Run HR911105A 16/02

Arduino: Mega 2560

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
  client.print("GET / HTTP/1.1\r\n");
  client.print("Host: www.google.com\r\n");
  client.print("Content-Type: application/x-www-form-urlencoded\r\n");
  client.print("Cache-Control: no-cache\r\n");
  client.print("\r\n");
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
}

With this I get the following response:

Thank you in advance

The device sending the request has no bearing on if it is HTTP 1.0 or 1.1. Only the content has an effect.

That and what is in the path - and I suspect that may be your problem: your are going through a squid proxy - and an old version at that. It is most likely that the proxy is changing the request to be a 1.0 request instead of a 1.1 request.


NodeMCU wiring for Serial1? I'm trying to get telemetry data to be sent out Serial1 on the NodeMCU board.  I read that TX is (by default) mapped to pin D4.

Ultimately, there will be a Raspberry that will be listening for these messages, but I don't have it yet.  So to quickly test this, I connected an oscilloscope with Serial decoding to D4 and the GND of the probe to GND on the NodeMCU.  The problem is I'm not getting any indication of activity out D4 when I run the following code:

Serial1.begin(9600);
Serial1.printf("some text");

Am I wiring the probe correctly?  Am I missing another serial command in the sketch?

When I move to the rPI, do I GND both boards together, then write TX (D4) to RX on the rPI?

You can do Serial.swap() in setup() to swap Serial away from RX/TX pin. Serial is then on D7 as RX and D8 as TX (and you can wire some serial module there).

Bridge with jumper wire D4 pin with TX pin. the Serial1 output will go over the USB chip to Serial Monitor and you will see the prints to Serial1.

This will not disturb the flashing mode, because bootloader will still listen on standard Serial pins.


Actual baud rate of UNO R3 Firmata protocol Probably a silly question. But the Internet is confusing me.
The Firmata website says the default baud rate is 57600. But AFAIK, the baud rate set for UNO R3 is 9600(In Windows device manager, it say so). I'm making the Firmata client program and have to set the baud rate. I'm confused whether it's similar to the serial protocol or not.
[Using the StandardFirmata sketch]

The baud rate is whatever the program opening the port requests it to be. The stuff in the device manager is only the default used if nothing else is specified when the port is opened.

And the Firmata protocol just squirts bytes over serial. It's based upon the MIDI protocol, which is just serial.


AT Commands HM10 BLE Module - Not working I got the ble module to work fine following online guide. However when i changed the baud rate: AT+BAUD1 which changed to 19200 however ever since i was not able to get at commands to work.

tried: arduino nano, FTDI programmer, software serial, normal tx, rx

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(8,9); //RX|TX

void setup(){
  Serial.begin(9600);
  BTSerial.begin(9600); // default baud rate
  while(!Serial); //if it is an Arduino Micro
  Serial.println("AT commands: ");
}

void loop(){
  //read from the HM-10 and print in the Serial
  if(BTSerial.available())
    Serial.write(BTSerial.read());

  //read from the Serial and print to the HM-10
  if(Serial.available())
    BTSerial.write(Serial.read());
}

You changed the baud rate that the Bluetooth module uses to communicate with your Arduino but you forgot to change the baud rate that the Arduino uses to communicate with the Bluetooth module. These must match. From consulting the SoftwareSerial library's reference page, you can see that is set by this line of your code:

BTSerial.begin(9600)

That sets the software serial communication rate at 9600 baud. You need to change it to this:

BTSerial.begin(19200)


Voltmeter using Arduino mega 2560 giving unexpected result after some time I have been trying to construct a smart energy meter that can observe readings of 220v household. For now i am working on voltmeter. I have been following the circuit I attached. Transformer step down 220V to 6V. Zener diode is of 5V.
The output from the circuit( 5v max) is fed to arduino Mega 2560 A0 pin.
* I am powering arduino using a USB cable *
Arduino takes this voltage as input from pin A0 in form of analog values between 0 to 1023. 0 being 0 volt and 1023 being 5v.So any random analog value corresponds to X=(5/1023)*Y where Y is obtained analog value. X is then multiplied by a value obtained by hit and try method (165 in my case) to reach the exact reading of voltage in line observed via multimeter.
Now the problem is that, everything works fine when i calibrate it, but after some time when i switch circuit on the value is inaccurate by margin, and i have to calibrate it again and again every time I turn circuit on after some time.If i switch circuit on soon after switching it off, it gives almost accurate value. I guess this issue is due to the capacitor, but i don't know anything about it or how to solve it I have constructed the same circuit more than 5 times, soldering it 3 times and 2 times on bread board and i am sure there is no problem with my implementation, verified it many times.
this is my code:

float V; // Voltage samples
float V0;

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

void loop() {
  for(int i=0; i<=20000; i++){
    V = V + analogRead(A0);
  }
  V = V / 20000;
  V = round(V);

  float V0 = V * (5.0 / 1023.0);
  I0 = I0 * 165; // has to be callibrated again and again each time circuit is switched on after a while

  Serial.print("Voltage = ");
  Serial.print(V0);
  Serial.println(" -------------- ");
  delay(1500);
}

this is the link i am following
http://engineerexperiences.com/3-phase-smart-energy-meter-using-arduino.html

Any help would be appreciated, Thanks!

With that circuit you can expect a roughly 10% variance in the output voltage depending on the exact moment at which you sample the voltage.

The basic circuit you have, and the waveforms generated, are like this:

That green waveform is the one you are reading. As you can see, exactly where you sample defines what the result will be.

Since you're trying to average over an undefined period (20,000 samples of how long per sample exactly?) you're not going to get a particularly well defined output.

You should change your sampling strategy to perform multiple samples over a well defined period to find the maximum value. That is the value you should then use in your calculations.

Ideally, you want to repeatedly sample for at least one entire waveform cycle. At 50Hz that's a period of 20ms (17ms for 60Hz).

For example:

uint16_t maxval = 0;
uint32_t ts = millis();
while (millis() - ts < 20) {
    uint16_t val = analogRead(0);
    if (val > maxval) {
       maxval = val;
    }
}

// Use "maxval" in your calculations.

With this strategy, because you're looking for the peak value, you don't care about the impact that the capacitor has on the circuit (except that it will remain artificially high for a period if the voltage drops), so you could actually simplify the circuit and remove that capacitor completely.


Yet another basic and silly question about C++ strings I made a sketch like this:

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

  char str1[64] = "test with spaces";
  char str2[32] = "test with spaces";

  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

//  if (strcoll(str1, str2)) Serial.println("Equals"); // <-- this won't compile for Arduino UNO { why ??? }
//  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  strcpy(str1, "test+with+spaces");
  strcpy(str2, "test with spaces");

  Serial.println();
  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  strcpy(str1, "test+with++++++++++++++++++++++++++++++++++++spaces");
  strcpy(str2, "test with spaces");

  Serial.println();
  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

}

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

}

bool areEqual(char* string1, char* string2) {
  return ((strlen(string1) == strlen(string2)) && (strstr(string1, string2)));
}

Which produces this:

test with spaces
test with spaces
Different
Different
Different
Equals

test+with+spaces
test with spaces
Different
Equals
Equals
Different

test+with++++++++++++++++++++++++++++++++++++spaces
test with spaces
Different
Equals
Equals
Different

The first comparisson is silly (==), I know. It compares the address of the pointer, not of the string itself. I just put it there to show how hard it is for a programmer who comes from another language to understand such a thing.

The second comparison (strcmp), as the reference says "Compares the C string str1 to the C string str2.", NO, it doesn't. They are exactly the same, except for their pre-specified size. But the strings are equal to my eyes.

The third comparison (strcoll) uses locale to compare the two strings, but how come it says different when they are equal?

The fourth comparison (memcmp), given two pointers to the exact same sequence of characters, why does it say "different"?

The mind blowing part is the comparison "works" when you add as many "+" as you wish to only one of the strings. Isn't a "+" sign also a character?

It's obvious I must be missing something really basic about c++ style strings, but I dare to ask: what is it?

Thanks.

The return value of strcmp does not have boolean semantics, as you seem to incorrectly assume.

strcmp is a tri-state comparator, which returns negative, zero or positive value. For equal strings it returns zero, which means that an equality comparison with strcmp should normally look as follows

if (strcmp(str1, str2) == 0) Serial.println("Equals");
else Serial.println("Different");

while your original code actually does the opposite.

There's a moderately widespread ugly habit of writing such comparisons as

if (!strcmp(str1, str2)) Serial.println("Equals");
else Serial.println("Different");

(note the application of ! operator). It works properly, but it has poor readability. Avoid it. For tri-state comparators is a much better idea to spell out the comparison with 0 explicitly.

And you made exactly the same mistake with memcmp. memcmp is also a tri-state comparator, so it should be

if (memcmp(str1, str2, sizeof str2) == 0) Serial.println("Equals");
else Serial.println("Different");

The same applies to strcoll.

P.S. And in fact such zero-terminated strings represented by char[] arrays are called C-style strings, not C++-style strings.


ARDUINO expected ';' before 'delay' I want to shine LED in 64 of 255 duty cycles = level of brightness but it pops up this error (see picture). Can anybody tell me why and help me ? Thank you.
void setup() {
  // put your setup code here, to run once:

}

void loop() {

  analogWrite(11, 64)
  delay{1000};
  analogWrite(11, 0)
  delay(1000);

  // put your main code here, to run repeatedly:

}

You should write ";" end of each lines.
analogWrite(11, 64);
delay(1000);
analogWrite(11, 0);
delay(1000);