How to dynamically set pinMode and dynamically write value to pins in Arduino using arrays? I am trying to create a library called "LED" for LED Sequencer in Arduino IDE,where the user has to configure the LED pins using an array and pass it to  LED constructor in program and then will be able to use BlinkAll(),LeftToRight() and RightToLeft() Functions which lights the LED from Left to Right or Right to Left based on the sequence mentioned in the array. The problem is when I initiate the array and pass it to the constructor Pins 4,5,7 are not working at all , Please help me find what is the possible issue
the code in LED.cpp file is shown below

#include <Arduino.h>
#include "LED.h"

LED::LED(int channel, int* a){
  _channel = channel;
  for(int i = 0 ; i < channel; i ++)
  {
    _pins[i] = a[i] ;
    pinMode(_pins[i],OUTPUT);
  }
}
void LED :: BlinkAll(int delay_ms)
{
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],HIGH);
   }
   delay(delay_ms);
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],LOW);
   }
   delay(delay_ms);
}
void LED :: LeftToRight(int numberofLEDs, int delay_ms)
{
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i =0 ;i<_channel; i++)
  {
//    if (i > 0)
//    {
//     digitalWrite(_pins[i-1], LOW);
//    }
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}
void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
    for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

LCD.h

#ifndef LED_h
#define LED_h

#include <Arduino.h>

class LED
{
public:
  LED(int channel, int* pins);
  void BlinkAll(int delay_ms);
  void LeftToRight(int numberofLEDs, int delay_ms);
  void RightToLeft(int numberofLEDs, int delay_ms);
  void BlinkAlternate(int delay_ms);
private:
  int _channel;
  int _pins[16];
};

#endif

Sample Code

#include "LED.h"

int const LED_pins[8]={5,6,7,8,9,10,11,12};
int const No_of_LED = 8;

LED led(8,LED_pins);

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  led.LeftToRight(1,500);
  led.RightToLeft(1,500);
}

It seems in the LeftToRight method, you didn't comment out enough (or too much), because  you use a for loop inside another for loop which is probably unintended.

In the RightToLeft' method I will try to fix the problem, so you can change theLeftToRight` method similarly.

void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
  for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

The first for loop is to switch off the LEDs, I would make this a separate method, so it can be reused in both the LeftToRight and RightToLeft method, so you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i + 1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

void LED::SwitchAllLedsOff()
{
  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
}

The problem is also, that you always write HIGH to a pin, since it overwrite the possible LOW assignment within the if statement. To correct this you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel ? HIGH : LOW);
    delay(delay_ms);
  }
}

You also can use an if statement, but in this case the ternary (? :)  statement is more clear since the assignment is for a single destination (_pins[i + 1]). So in case i >= channel, it is set to HIGH, otherwise set to FALSE. I also inverted the operator, but you can keep it inverted too.

Third, _channel seems to be the number of elements in the array, if you use it in an index it should start with _channel - 1, so you get:

void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel - 1; i >= 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel - 1 ? HIGH : LOW);
    delay(delay_ms);
  }
}

There might be more problems, but the above are at lest some of them.

Also I changed your way of using spaces, although it's a matter of personal style, yours I never saw before (which doesn't mean it's incorrect of course).

(note I have not tested the program).


Remove Bootloader on Arduinos I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?

Thanks.

You don't "remove" the bootloader, you just ignore it.  When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.


How to keep a specific bit set all the time for bit masking I2C operations? I've been working on I2C and I learned how to initialize, send and receive with I2C communication protocol.

Next, I wanted to run the LCD1602 I2C adapter. But the module has a different bit masking, it turns out that I have to keep a specific bit set so I can control the remaining 7-bits, because otherwise I can't control the upper 4-bits if this bit is 0.

So, I put the 8-bit variable for the bit masking operations in the global section and initialize it with uint8_T bitmasking = 0x08; but it's volatile. I used static keyword, but the bit is not constant.

So what's the solution?

Regards,

'static' just avoids reinitialization and is used for local vars in timed interrupts for example.

volatile is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information

The appropiate keyword would be const, which tells the compiler this var mustn't be changed.

But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use const in the declaration.
I assume you are not using the variable correctly. You are meant to use a bitwise OR | in order to set the required bit along your actual data.

So do it like this:

data_byte |= bitmasking;
write8(data_byte);


How to enable maximum Dead Code Removal? I am running out of code and data memory space on ATMega328P.

Code size is big as I used several libraries, but, I only use a few functions of those library.

Apparently, the default IDE is only doing a partial job in dead code removal (remove unreferenced code and data).

Some experiments shows:

A normal program that uses several Arduino libraries is 22 kilo bytes in code size.
Rename setup to o_setup.
Rename loop to o_loop

Add

void setup(){};

void loop(){};

Code size is 8 kilo bytes while the program is 'empty' effectively.
Start a new program.

Add

void setup(){};

void loop(){};

Code size is 0.5 kilo bytes

Apparently, the IDE (linker called by IDE) is doing a 'partial' dead code removal job, as reducing code from 22kB to 8kB (case 1 and 2), instead of 0.5kB (case 3).

How can I enable maximum dead code removal function (reclaim code space occupied by unused library functions)?

Enable your IDE's verbose of the compile via the preferences. From there you can see exactly what and how it is being compiled.

In short the IDE (and toolchain) will compile everything and anything it can find into an object. Where only the used code is compiled in the linking phase, as garbage collection is enabled with the "--gc-sections" command.

Note that the optimization level is "-Os" or "Optimize for size". In IDE 1.0.+ this appears to be hardcoded. Where as in IDE 1.5.+ the compiler options are configurable, in "\arduino-1.5.6-r2\hardware\arduino\avr\platform.txt" can be customized to meet your needs.

Where you can use the avr-objdump command as described in https://stackoverflow.com/questions/15291750/does-importing-libraries-load-everything-in-arduino/15296808#15296808.

I would recommend 1.5.6r2 and not 1.5.7 as the gcc commands won't run individually without some path manipulation.


compilation terminated. exit status 1 error compiling for board arduino/genuino uno hi i have done this code for my uno R3 and i cant upload it
any suggestions

#include"DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht( DHTPIN,DHTTYPE);
const int ledPin=13
int piesoPin=9
void setup(){
  serial.begin(9600);
  pinMode(ledPin,OUTPUT);
  pinMode(piezoPin,OUTPUT);
  delay(5000);
}
void loop(){
  int t=dht.readTemperature();
  int h=dht.readHumidity();
  Serial.print(t);
  if(t>26){
    digitalWrite(ledPin,HIGH);
    digitalWrite(piezopin,HIGH);
    {TONE(9,3047,400);
    delay(1000);
    noTone(8);
    delay(100);
    }
    delay(1000);
    Serial.print("ON T=");
  }
  else(digitalWrite(piezoPin,LOW);
  digitalWrite(LEDpIN,LOW);
  Serial.print("OFF,T=");
  }}

Two errors I see is a typo and missing semicolons.

const int ledPin=13
int piesoPin=9

Should be

const int ledPin=13;
int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.

Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.

However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


Where are the digital and analog pins for the adafruit atmega 32u4 breakout board? Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.

The information is right there on the product page for you. It took be a total of about 4 seconds to find it.

http://ladyada.net/products/atmega32u4breakout/


toInt error when converting character of string to interger with the following code:

int foo = bar[1].toInt;

or

int foo = bar[1].toInt();

I get this error

request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

the context for this is bar is the response from a HTTP client over web sockets

The Arduino function toInt requires a String object.
You're passing it a single character, not a String.

int foo = String(bar[1]).toInt();


How to Control 2-wire Rotary-Gear Linear Actuator Any ideas how to control a 2-wire DC 5V 10mm Stroke Mini Linear Actuator based Rotary Gear Motor? Most linear actuators (aside from solenoids) are controlled via 3-4 wires. Do I need a separate motor controller for the actuator to control it via an Arduino Uno?

I suspect that's little more than a geared brushed DC motor with a fancy "nut" on it. So yes, you will need any standard motor driver rated for the correct voltage / current (an H-bridge).


How can i connect 01 ESP8266 to a shift register? I am connecting this shift register to my esp8266 01 for more GPIO options.
it appears there is a GPIO 16 but it's tied to a RESET pin. I checked both datasheets :
i checked the esp8266 01 datasheet
http://www.microchip.ua/wireless/esp01.pdf

i checked the datasheet for the shift register for more information on what kinds of pins can be hooked to each of the input pins.
https://www.sparkfun.com/datasheets/IC/SN74HC595.pdf

also thinking whether it's viable to connect one of the other available pins of the esp8266 and use it for this connection with the shift register. (either RX or TX)

My understanding is need to connect 3 pins of the ESP8266 directly to the shift register for its latch, clock , serial pin.

also wondering if can connect the serial pin of the ESP8266 to the serial pin of the shift register?

While I do believe you could use GPIO2, TX, and RX for your connections, I don't think the clock is explicitly exposed on the ESP-01. That means your code would have to "emulate" a clock via GPIO2 (most likely) with that pin going to your shift register's clock pin. That said, it's really hackish and I'd recommend other ESP dev board that has a pin for the onboard clock.


Making HTTP post and get using Arduino I need to know how I can make http posts and http get from Arduino MKR1000 ( act as a client) to a local server.

I made it on Raspberry pi using python like this:

import requests
import json
     url = 'http://192.168.2.139:8040/api/sensor'
     value = {"LDRValue": 200};
     r = requests.post(url, json=value)
     r = requests.get(url)

Maybe this link will be helpful for you.

Arduino-mkr1000-getting-starter-wifi

#include <WiFi101.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiSSLClient.h>
#include <WiFiUdp.h>

/*
* This example is modified from the original file
* https://github.com/arduino-libraries/WiFi101/blob/master/examples/
 SimpleWebServerWiFi/SimpleWebServerWiFi.ino
*/
#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "yourNetworkSSID";      //  your network SSID (name)
char pass[] = "yourNetworkPassword";   // your network password
int keyIndex = 0;                 // your network key Index number (needed    only for WEP)
int ledpin = 6;
bool val = true;

int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
Serial.begin(9600);      // initialize serial communication
Serial.print("Start Serial ");
pinMode(ledpin, OUTPUT);      // set the LED pin mode
// Check for the presence of the shield
Serial.print("WiFi101 shield: ");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("NOT PRESENT");
return; // don't continue
}
Serial.println("DETECTED");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
digitalWrite(ledpin, LOW);
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid);                   // print the network name (SSID);
digitalWrite(ledpin, HIGH);
// Connect to WPA/WPA2 network. Change this line if using open or WEP          network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin();                           // start the web server on port 80
printWifiStatus();                        // you're connected now, so print out        the status
digitalWrite(ledpin, HIGH);
 }
 void loop() {
 WiFiClient client = server.available();   // listen for incoming clients

if (client) {                             // if you get a client,
Serial.println("new client");           // print a message out the serial     port
String currentLine = "";                // make a String to hold incoming data from the client
while (client.connected()) {            // loop while the client's connected
  if (client.available()) {             // if there's bytes to read from the client,
    char c = client.read();             // read a byte, then
    Serial.write(c);                    // print it out the serial monitor
    if (c == '\n') {                    // if the byte is a newline character

      // if the current line is blank, you got two newline characters in a row.
      // that's the end of the client HTTP request, so send a response:
      if (currentLine.length() == 0) {
        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
        // and a content-type so the client knows what's coming, then a blank line:
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html");
        client.println();

        // the content of the HTTP response follows the header:
        client.print("Click here turn the LED on pin 9     on
");
        client.print("Click here turn the LED on pin 9 off
");

        // The HTTP response ends with another blank line:
        client.println();
        // break out of the while loop:
        break;
      }
      else {      // if you got a newline, then clear currentLine:
        currentLine = "";
      }
    }
    else if (c != '\r') {    // if you got anything else but a carriage      return character,
      currentLine += c;      // add it to the end of the currentLine
    }

    // Check to see if the client request was "GET /H" or "GET /L":
    if (currentLine.endsWith("GET /H")) {
      digitalWrite(ledpin, HIGH);               // GET /H turns the LED on
    }
    if (currentLine.endsWith("GET /L")) {
      digitalWrite(ledpin, LOW);                // GET /L turns the LED off
    }
  }
}
// close the connection:
  client.stop();
  Serial.println("client disonnected");
  }
}

void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}


Advanced ADC setup on Due (SAM3X8E) to increase precision I want to make some precise measurements with Arduino Due. Although I'm using very good external voltage reference (LTC6655) measured data is still jumping around, especially significant when I'm trying to measure low voltages (0.1-0.05V). Can I improve ADC accuracy by changing it's settings?

The default Arduino Due ADC settings are:

// Initialize Analog Controller
pmc_enable_periph_clk(ID_ADC);
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
adc_disable_all_channel(ADC);

So, with adc_init we can configure frequency and startup time. And with adc_configure_timing we configure tracking time, settling time and transfer time. But how to select those values? Does increasing of that times improves precision?

Useful links:

Datasheet - ADC description starts on page 1317.

Atmel Software Framework - see adc.h and adc.c.

Generally speaking the input BandWidth of the analog signal is a major cause of noise in a ADC circuit as well as improper ground and reference generation and layout techniques.  Be very careful that ALL of the analog paths do not have any digital current return paths. Remember that at 12 bit for a 1.25V reference an LSB is ~300uV. I have not ever measured the SNR of the SAM ADC but I doubt that it is the specified ~60db (i.e. 10bit) unless absolute care is taken during the layout/routing.
Recommend:
1) Limit input BW to the correct channel ground. (well below Nyquist BW if possible to avoid alliasing)
2) Oversample if possible.
3) Insure low digital I/O of peripherals during sample period.


Why isn't the stack pointer changing in this simple sketch? I'm playing around with context switching, and my first idea is to play with SP and see how it changes.  However, Sp doesn't do what I expect.  The sketch is below. I'm using an Uno R3.  What I expect to see is that SP should first print out some value, then it should be 4 integers further along (4x2 bytes?) when printed the second time.  But that doesn't happen, and both times I see the exact same value for SP.  What could the problem be?

    void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.print("X = ");
  Serial.println(SP,HEX);
}
void loop() {
  // put your main code here, to run repeatedly:
Serial.print("BEFORE: ");
Serial.println(SP,HEX);
int y = 15;
int z = y;
int g = z + y;
int dsf = z-y;
  Serial.println(dsf+g); //this should make these variables DO something...
  Serial.print(" After = ");
  Serial.println(SP,HEX);
  delay(1000);
}

Another way the compiler can optimize is to compile small or single-use functions inline. What you expected would get wrapped inside a call and return sequence, may not.

Inserting __attribute__ ((noinline)) ahead of the function definition can suppress that optimization:

__attribute__ ((noinline)) void foo(int bar)
{
   // do something
}

suppresses the inlining for function foo(). Inlining has frustrated my investigations more than once, so I created this easier to remember macro. (The keyword is just __NOINLINE; the #else-clause is there so that, umm, "someone", doesn't unwittingly try to use the "__attribute..." declarator with another compiler that doesn't recognize it).

// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif


Use TFT LCD with Uno and Wi-Fi shield I need to work with Arduino Uno, LCD and Wi-Fi shield.

I was wondering whether I can use the LCD in the link, 2.2" TFT Display - Test the Display with the Uno and Wi-Fi shield - and how to search for them?

Start by checking which pins are used by the shields and if there is any conflicts. Check the shield schematics and example libraries.

If there are any conflicts, check if the shields has any jumpers that may be used to change the pin configuration.

Cheers!


Need to set an output pin without it going LOW during initalization For a control system I am using a relay module that controls a larger relay for high-current electrical stuff, as part of a battery protection circuit for my solar plant.  This module switches 120 VAC for the larger one.  The larger one is set up to latch the power off until a button is pressed manually.

I have several Adafruit relays, (single, dual, quad) and they all seem to be active-LOW.  I am using one of them for this project.

My problem is that I can't seem to prevent my Arduino Nano code from briefly setting the output pin LOW in setup, setting in motion the cascade involving latching the power off.

If at all possible with this hardware, I would like to prevent the need to manually reset the latch when uploading code changes.

Here is how I am initializing that pin in my setup code:

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

All in one line.  The LOW pulse is just long enough to trigger the other relay.

I know I can probably find parts like an inverter chip or maybe a different relay, but really want this working yesterday.

So my question is:  Is there any way to prevent it from pulling it LOW during initialization?  Or, is there a different approach I should take in relation to this relay output?

Thanks in advance

Arduino sketches are actually (somewhat constrained) C programs.  As such, what is true for C is usually true for sketches.  In C, a segment of code usually ends with a ";".  It matters not if there are two (or more) of these on a single line.  The computer will execute the segment before the first ";" first and the segment after the first ";" second.

In this case you are setting a register inside the Atmel processor on the Nano to the "out" direction.  So it will force the associated pin to what ever the data in already set up in that pin's data register.  Then you are setting that pin's data register to high or 1.

Instead, try setting the data register to 1 before setting the direction register to "out".  Do this by switching the order of the code segments.

In case this does not work.  Or in case you find the relays acting randomly on power up, consider the relay driver inputs to be high impedance and susceptible to any noise prior to the Nano taking control of the relay driver control pins.  In such a case, consider adding pull up resistors small enough to ensure the inputs of the relay drivers are held at a known voltage but high enough such that the Atmel processor in the Nano can easily over power the pull up resistor when necessary.


Looking for information and/or how to connect the RF433Mhz module (WL101-341/WL102-341) I'm trying to find information about this 433MHz RF module: QIACHIP

Apparently it can be connected to an Arduino with the RadioHead library, but I don't have diagrams of how to connect them togheter in order to send/recieve data, becasue the module have 4 pins (Vcc, Gnd, Dat and En). I guess Dat pin should be connected to any Arduino pin, but as I only have one module I dont wanna risk it. I have no previous experience with RF modules :-(
I have found some Youtbe video, but the language of the video is in russian, and I don't know that langauge (I even ask the owner of the chanel for subtitles).
Please, if anyone have worker whit this module before, share:

How to connect the module with an arduino?
A simple example of how to send a simple word (let's say: "Hello") from the transmitter to the reciever

You're right not to just go ahead and wire things up. There's a couple of nuances that you need to take into account.
Transmitter

Ignore the EN pin - that does nothing on that module
The transmitter is 1 3.3V device. You need to power it from the 3.3V pin and use logic level (5V -> 3.3V) translation on the Data pin

simulate this circuit – Schematic created using CircuitLab
Receiver
The receiver is much simpler as it is a 5V device:

simulate this circuit
On the Arduino it shouldn't matter what IO pin you use, the Radiohead library should work fine with any of them.  These modules are pretty dumb - you raise DAT high on the TX and DO on the RX goes HIGH. Very simple.


Receiving partial messages when using VirtualWire and ServoTimer2 I'm writing a project where an Arduino board that is connected to a servo engine receives commands from another Arduino. The possible commands are:

Move 10 degrees
Reset position
Sweep until you're told to stop

My problem is with the sweep-mode, when I get the sweep command, I get into a while loop, that first checks for a sweep-terminator and then sweeps.

} else if (message == sweep) {
  Serial.println("sweep");
  while (msg1 != sweep_term) {
    // set the direction for the servo to move
    if (val == 750){
      val = 2250;
    } else {
      val = 750;
    }

    // move the servo
    myservo.write(val);
    // wait for the servo to move
    delay(15);

    // wait for a message
    if (vw_get_message(buf1, &buflen1)) {
      buf1[buflen1] = '\0';
      msg1 = (char*)buf1;
      memset(buf1,'0',VW_MAX_MESSAGE_LEN);
      Serial.print(buflen1);
      Serial.print(" [sweep] Got: ");
      Serial.println(msg1);
    }
  }
}

For some reason, when I'm in this loop I don't get the sweep terminator message, or I get a part of it. I suspect that the servo is responsible for this, since when I run the same program without myservo.write()s I do receive those terminators.

If msg1 is of type char* (as is implied by the cast in msg1 = (char*)buf1;), then it seems to me that that statement will copy the address of buf1 to msg1.  Then, when you fill buf1 with ascii zeroes (ie, characters '0') msg1 ends up being a string of ascii zeroes.

On the other hand, if msg1 is of type String (to go along with your comment about buf1 being of type String) the cast should be unnecessary.

Note, if you don't give the source for the vw_get_message() routine and the declarations for all of the constants and variables used in the code extract, it's unlikely anyone can definitively answer your question.

Note, the while test, msg1 != sweep_term, may not be well-defined on entry to the while loop.  Or, if msg1 is left over from a previous use, you won't enter the loop at all.  Consider writing the loop in the form do { ... } while (msg1 != sweep_term); instead.

Note, if (as said in a comment) buf1 is of type String, then the statement memset(buf1,'0',VW_MAX_MESSAGE_LEN); is a line of code I'd recommend against, because it treats buf1 as a simple array rather than as an object.  (In this case it should make no difference, but it requires some research to be sure of that. [1,2,3,4,5])


Bluetooth hc-06 and Standalone Atmega168(possible?) I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.

I want to be able to transfer information serially between the two devices over bluetooth.

I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.

I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)

The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.

I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.


Combining code for multiple sensors in one program (Arduino) I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.

Here are the sketches:

Gas sensor MQ2 code :

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);

This is the DHT11 code :

#include <SimpleDHT.h>

int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
    // start working...
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Data");
}

void loop() {

  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared.  Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays

#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
  Serial.println("Starting");
}

void loop() {
  int analogSensor = analogRead(smokeA0);
  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop().  This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)

#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      Serial.begin(9600);
      Serial.println("Starting");
    }

void loop1(){
   int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

void loop2(){
  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

void loop() {
  loop1();
  loop2();
}


Firmata: strings sent from the computer become damaged after Arduino I have a Python program that acts as a Firmata client. This program connects to the Arduino at a user-specified COM-port (with Firmata onboard, the sketch can be seen below), sends the user-requested string message to the Arduino, and awaits Arduino's reply. If the reply is present, the program prints it out as a list of ASCII symbol codes.
I expect the program and the sketch to work this way (block scheme is below), but the strings coming from the Arduino are damaged. They don't contain all symbols which were sent, but they contain only the first symbols in some random order, with a \0 symbol present after each character in the string. For example,

String sent to the Arduino
Received as ASCII symbol codes
Received as a string

A
(65, 0)
A\0

AB
(65, 0) where is the B?
A\0

ABC
(65, 0, 67, 0) the B lacks presence
A\0C\0

ABCD
(65, 0, 67, 0) the received data length remains the same, but B and D aren't present
A\0C\0

ABCD(10)
(65, 0, 67, 0, 40, 1, 48, 1) WHAT IS THIS?
A\0C\0(\10\1

DHTt(4)
(68, 0, 84, 0, 40, 0, 41, 1)
D\0T\0(\0)\1

Program's screenshot:

Awaited work algorithm block scheme:

Python program code:
import pyfirmata, time

class CustomArduino(pyfirmata.Arduino):
    def __init__(self, port: str):
        pyfirmata.Arduino.__init__(self, port)
        self.iterator = pyfirmata.util.Iterator(self)
        self.iterator.start()

        self.add_cmd_handler(0x71, self.receiveString)

    def receiveString(self, *args, **kwargs):
        print(f'Received: {args}')

    def sendString(self, data):
        self.send_sysex(0x71, bytearray(data, 'utf-8'))

    def send_sysex(self, sysex_cmd, data=[]):
        """
        Sends a SysEx msg.
        :arg sysex_cmd: A sysex command byte
        : arg data: a bytearray of 7-bit bytes of arbitrary data
        """
        msg = bytearray([pyfirmata.pyfirmata.START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(pyfirmata.pyfirmata.END_SYSEX)
        self.sp.write(msg)

print('STRING TESTER\nPlease input your COM port: ', end = '')
myCom = str(input())
device = CustomArduino(myCom)

while True:
    device.sendString(input('Send: '))
    time.sleep(1)

Arduino sketch:
#include <Firmata.h>

void stringCallback(char *myString)
{
  //The function accepts one charset.
  Firmata.sendString(myString); //send the *same* charset  back
}

void sysexCallback(byte command, byte argc, byte *argv)
{
  Firmata.sendSysex(command, argc, argv);
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback); //when there is a STRING incoming to the Arduino, call 'stringCallback'
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
  pinMode(13, OUTPUT);
}

void loop()
{
  while (Firmata.available()) {
    Firmata.processInput();
  }
}

How I can deal with this?

You have to understand the Firmata protocol to write your own client library. The spec is here: https://github.com/firmata/protocol.
In this particular case, you need to know that data that is sent (the string in this case) can never use bit 7 of the data, since these values have special meanings. Therefore, Firmata sends every byte as two bytes, first bits 0-6 and second bit 7 as bit 0 of the next byte. Therefore, the conversion to UTF-8 is not sufficient. You need to do a two-byte-per-8-bits encoding. The same applies for the reply.


Electric meter pulse counting using LLC I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.

http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/
https://jonarcher.info/2014/03/arduino-based-electricity-monitor/

And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.

But I wanted to have a different setup, and what I am thinking is:

inside the electric meter, tap into the blinking LED
From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
From the LLC, connect it to the Arduino
Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?

If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)

A good way to get electrical isolation is with an opto-coupler, also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.

You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

simulate this circuit – Schematic created using CircuitLab


Door control with Arduino and limit switches I want to make a door with two limit switches and three buttons: one for stop and the other two for open and close. I run into a problem with the code with the start buttons and the limit switches. I can't make the code because I'm a beginner. Please can somebody help me with some code or something like that?

I'll appreciate it if you help me, because it's for my school project:)

You will need to write code to

Control a motor. Likely a DC motor with two way control. This can be done with four MOSFETs and several diodes or much better, one H bridge IC. Your code will need to determine which one of two lines going to the dc motor is getting connected to the positive rail, and which one to the negative/ground, or both disconnected, using the three buttons you described.
You will need to write code that monitors the limit switches. I would suggest you use interrupts for these. One pin goes to ground, the other goes to the Arduino interrupt pin. You can use attachInterrupt() function to write functions that execute right away. Make sure you read up on which pins on your Arduino will support interrupts.
You will need to stop the motor movement either directly or by throwing a switch using the interrupt (or whatever detection method you use for the limit switch).

*one special consideration is that any variables that you use inside of interrupt functions should be marked as volatile, so int myVar; becomes volatile int myVar;
*also don't use Serial.print or millis() inside of your interrupt functions if can avoid it.

From here Google 'Arduino switch' and work on an implementation of limit switches separately. If you want to, Google 'Arduino Interrupts' and improve your implementation to use interrupts. Next, Google 'DC motor bidirectional control Arduino'. Work on it standalone. Once both work separately, combine into a single project.

Let me know as you go through these if you have specific questions, and I would be happy to help you learn how to build it using the components you have.


Can UNO log more PCB 353b33 accelerometer data points compared to TDS3014B oscilloscope? I'm currently recording data points from an analog accelerometer(PCB 353b33) using a TDS3014B oscilloscope which has Record Length of 10,000 points at a Sample Rate 1.25 Ga/s. I'm want to record more data points, would it be possible to use UNO as a data acquisition device and record much higher data points than the oscilloscope(>> 10,000)

No way. The UNO has only 2.5kb of RAM, so you can't cache the data points and you would need a very quick link to get the data out. And sampling at 1.25 GigaSamples/s is orders of magnitude beyond an UNO, as its maximum clock frequency is only 16 MHz. An Uno is about $20, while your TDS3014B is around $1500. Sometimes, there's a reason for a different price tag.


How do I properly use the WiFi capabilities of ESP8266? I am creating a project with an ESP8266 (Arduino IDE) which requires it to serve a webpage to a client. The module will be connected to a WiFi network by default, but when that WiFi network is not available, I need it to turn on its Soft Access Point, so that the user can still access that webpage by connecting to the AP. When the WiFi network becomes available, I want the module to reconnect to the WiFi network and disable the SoftAP.

Here is the chunk of code in my sketch that deals with all the WiFi stuff:

void wifi() {
  if(WiFi.status() != WL_CONNECTED){
    WiFi.mode(WIFI_AP_STA);

    if((unsigned long)(millis() - waitUntil) >= interval){            //this section I used as an alternative to the delay() function, the delay is 3 sec
      WiFi.begin(ssid, password);
      waitUntil = waitUntil + interval;

      if(WiFi.status() == WL_CONNECTED){
        Serial.println("Connection successful! ");
        Serial.print("IP: ");
        Serial.print(WiFi.localIP());
        WiFi.softAPdisconnect(true);
      }
    }
  }

  if(WiFi.status() != WL_CONNECTED && softAPEnabled == false){
    Serial.println("WiFi not connected, enabling SoftAP...");

    WiFi.softAP(softAP_ssid, softAP_password);

    softAPEnabled = true;

    Serial.println("SoftAP ON");
  }
  else if(WiFi.status() == WL_CONNECTED && softAPEnabled == true){
    WiFi.softAPdisconnect(true);
    softAPEnabled = false;
    Serial.println("SoftAP OFF");
  }
}

Here are the problems:

The webpage works fine when the module is connected to WiFi and I go to the IP address from a browser, but when SoftAP mode is enabled, and I connect to the AP and go to 192.168.1.1, it does not work. The next problem may be related to this.
I don't think I'm using WiFi.mode() correctly. I currently have it set to WIFI_AP_STA, but after problem 1 occurred, I tried to change it to WIFI_AP and WIFI_STA individually as I needed each mode, but this still did not work.

The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings


How to send HTTP request to specific port using Ciao? I currently have a working REST client on my arduino, but the requests always go to port 80, how do I make it send the request to a specific port?

This is my current code:
/*
File: RestClient.ino
This example makes an HTTP request after 10 seconds and shows the result both in
serial monitor and in the wifi console of the Arduino Uno WiFi.

Note: works only with Arduino Uno WiFi Developer Edition.

http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient

#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {

    const char* connector = "rest";
    const char* server = "download.arduino.org";
    const char* method = "GET";
    const char* resource = "/latest.txt";

    Serial.begin(9600);
    Ciao.begin();

    pinMode(2, INPUT);

    delay(10000);
    doRequest(connector, server, resource, method);
}

void loop() {

}

void doRequest(const char* conn, const char* server, const char* command, const char* method){
    CiaoData data = Ciao.write(conn, server, command, method);
    if (!data.isEmpty()){
        Ciao.println( "State: " + String (data.get(1)) );
        Ciao.println( "Response: " + String (data.get(2)) );
        Serial.println( "State: " + String (data.get(1)) );
        Serial.println( "Response: " + String (data.get(2)) );
    }
    else{
        Ciao.println ("Write Error");
        Serial.println ("Write Error");
    }
}

If I add for example :8080 to the end of the server variable, it does not work.

So how do I make that request go to a specific port?

You can find a portdefinition on your arduino in this path:

/usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf

{
 "name" : "restserver",
 "description" : "REST server connector for the Ciao Core",
 "authors": ["Arduino Team <swdev@arduino.org>;"],
 "repository" : "https://github.com/arduino-org/Ciao",
 "version" : "0.0.2",
 "params" : {
            "port" : 80
             },
 "log" : {
         "level" : "info"
         }
}

The confusing part is that your Arduino has a server client connection on it self from the cpu/linino server to the mcu/arduino client.

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


Receiving two values over serial port using servos So I have a java program that picks up the mouses x and y coords on the display and I would like to send those to my arduino and then move my two servos to those locations (I have two servos ontop of each other, one for x and one for y).

The java (processing) code i have is below

void draw(){  //same as loop in arduino
  background(52, 152, 219); // background color of window (r, g, b) or (0 to 255)
  //lets give title to our window
  fill(0, 255, 0);               //text color (r, g, b)
  textFont(font);
  text("Ripple Effect Maker", 80, 30);  // ("text", x coordinate, y coordinat)
  ellipse(mouseX, mouseY, 33, 33);
  int x = mouseX;
  int y = mouseY;
  port.write(x+":"+y);
  println(x+":"+y);
  //println("y="+y);
  delay(100);
}

I don't have much arduino code because I can't seem to find a way to split the data into two seperate variables and then move the servos to their corresponding variables.

Thanks for the help!

Your problem is that you aren't providing anything to split the data on. You just send the X and y coordinates with a : between X and y. There's nothing between the y and the next X.

By changing the line

port.write(x+":"+y);

To

port.write(x+":"+y+"\n");

You then get the linefeed character to split your data on.


High precision timing on Arduino for serial communication I am using an Arduino Uno to send time and voltage information over the serial port to Python to plot. However the interval timings between successive time stamps appears to be increasing over time, affecting my plotting. This is especially true when the baud rate is set to 9600, where my initial time differences maybe 1320 and increases to 16400 after a relatively short period of time. When this rate is put to maximum of 115200 bps the change is slower and less noticeable, from around 1340 to 1500 even after a relatively long run of sending. All times are given in microseconds.

I would like to know if I can reduce or eliminate this effect, and if not understand why it exists. I have read things about interrupts and delays causing this, but I do not fully appreciate the complexity of the electronics at hand and would like to know:

Can I get greater precision in the timing?
What causes this change in timing?

Here is what I currently have:

#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

Use a timer and ISR (interrupt service routine) to make timing more accurate.

Take a look at my 1ms timed interrupt Proof of Concept. The idea is to have a reasonably accurate 1ms 'heartbeat' in the system that can be used to trigger other events. In the PoC it is used to blink an LED at ½Hz, but having access to the new variables millisecondCounter and secondCounter enables you to trigger events in the main loop at arbitrary (but accurately timed) moments.


Powering ESP8266 from Leonardo's 3.3v pin I'm new to Arduino, and I'm trying to connect my Leonardo via WiFi using a ESP8266 module. What I want to know is if I can power it directly from the onboard 3.3V pin like in the image:

Or do I need an external voltage regulator? I don't want to damage it.
Thanks!

The Leonardo is specified to provide only 50mA on the 3V3 pin. A ESP8266 can use up to almost 300mA when transmitting. Consider using a LDO regulator connected to the 5V pin instead.


Why is the atmega chip reset three times during programming? I'm trying to understand the auto reset process and why a capacitor hooked up between DTR and Reset works so I ran it through my logic analyzer and I'm seeing the chip reset three times during the programming process. Does anyone know why it's done three times and not just once?

You can see in the picture the top pin is the DTR and the bottom two are attached to reset (digital/analog). When DTR drops low the reset pin does too for between 200-500us but it does it three times in around 1 second.

It does it to "force" a reset.

Historically, when you open the serial port on an FTDI interface, the DTR will automatically go LOW.  However, recently FTDI decided it'd be a good idea to change their driver so that when you open the port the DTR line doesn't go low - you have to manually tell it to go low.  But this is only on the FTDI official drivers.

If you have a driver that is newer than a certain date (no idea what date) then just running avrdude by itself on an FTDI interface may not work properly since DTR isn't being lowered.

To get around that Arduino have included a forced toggling of the DTR line as part of the programming sequence to make the target board reset.

But of course, if the driver is old enough, or not the "official" FTDI driver (i.e., you're in Linux for instance) then the lowering of the DTR by avrdude works fine.

So what you are seeing there is first a brief toggle of DTR by the IDE to force a reset, then avrdude opening the port and DTR going low, then finally the IDE toggling DTR again one last time to force a final reset.

And to me that says you're either not in Windows, or you have an FTDI driver while does toggle the DTR line automatically.

I also have a feeling that avrdude may also have started including manual control of the DTR line within it - so if avrdude is new enough, even with a new FTDI driver that doesn't automatically, you will still see the repeated action of DTR.

It's what we call belt and braces.  Use every method possible to get the board to reset, so no matter what you hardware and software arrangement the board has a very good chance of being reset into the bootloader.


Release power to stepper motor I'm driving a large stepper motor via a GeckoBoard G213V and arduino UNO and I have that mostly working fine. However, I'd like to 'release' the stepper so it can swing freely.

There's two reasons I want to do this:

1) (Most important) I want the rotated object to naturally swing back to the 0 position thanks to gravity.
2) The motor gets hot - I'd rather not juice it when it should just be sat at 0.

Anybody know how I can do this? I'm using the AccelStepper library so a solution compatible with that would be ideal.

From the documentation:

  TERMINAL 7 Disable
  This terminal will force the winding currents to zero when tied to the step and direction controller +5V.

  The DISABLE input on the G213V is optically isolated and requires logic “1” to DISABLE and logic “0” to ENABLE the drive. Once it is disabled, the motor windings are unergenized[sic] and the motor freewheels. (emphasis mine)

So, feed the disable input a high.


Client.connect galileo gen2 not working I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage.
I get this in the Serial monitor:

My code:

/*
  Web client

 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[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
// 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(216, 58, 217, 206); // 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);
IPAddress dns(192, 168, 1, 122);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// 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 Leonardo only
  }
  delay(5000);
  // start the Ethernet connection:

  Ethernet.begin(mac, ip, dns, gateway, subnet);
  Serial.println("connected to ethernet");
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  int ch = client.connect(server, 80);
  if (ch) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.print("connection failed, error code ");
    Serial.println(ch);
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (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();

    // do nothing forevermore:
    while (true);
  }
}

Any help is greatly appreciated.

6 months after figuring out the answer, I found this question again. I solved this question by adding system("ifup eth0") which completely solved the problem.


Why use a motor driver board? I'm just getting into electronics in general and I'm confused a bit as to why I'd want/need to use a motor driver board instead of just setting up my own transistor/diode/etc when attempting to power and control a DC motor.

Any chance someone could clarify the point to using a motor driver board instead (assuming there is another option as I think there to be)?

A motor driver board is just a convenient way of creating what is known as a "H Bridge". This is an arrangement of 4 (or more, but 4 primary) transistors.

You can make it yourself with discrete transistors, but it is simpler to just use a pre-made chip.

A H Bridge gives you greater control over a motor than a single transistor alone. It allows you to control the direction, which you can't do with a single transistor, and it also gives you access to braking modes where the motor becomes harder to turn thus assisting in slowing down the load.

With a single transistor you can turn the motor on and off (or vary the speed if you use PWM) but that is all.

simulate this circuit – Schematic created using CircuitLab


Hooking up the Arduino to a car's 12v I am planning an uno based tachometer for my truck, which doesn't have a tachometer. With nothing in place for me to get a reliable signal, I started looking at other sources to read the rpm from the engine.

It seems to me that an engine should affect the power every time a cylinder fires --the power should spike in some way. So in theory I should be able to hook up to the 12v cigar lighter, count the spikes, and calculate the rpm. It would only need to be accurate within 500 rpm or so.

This is a two part question.

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?
How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter.  Armed with that you can then tell:

If there is any power fluctuation from the engine, and
What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a high pass filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.

Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.

For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.

Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

  How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.

The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.


Turn on led by phone and phone contacts I would like ask for help. Can you give me an advice how to create (contacts) nubers who can turn on led.

#include <GSM.h>
#define PINNUMBER ""
GSM gsmAccess;
GSMVoiceCall vcs;
char numtel[20];

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

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

Serial.println("Receive Voice Call");

boolean notConnected = true;

while (notConnected)
{
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  notConnected = false;
else
{
  Serial.println("Not connected");
  delay(1000);
}
}

vcs.hangCall();

Serial.println("Waiting for a call");
}

void loop()
{

switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL:

  break;

case RECEIVINGCALL:

  Serial.println("RECEIVING CALL");

  vcs.retrieveCallingNumber(numtel, 20);

  digitalWrite(13, HIGH);

  vcs.answerCall();
  vcs.hangCall();
  digitalWrite(13, LOW);

  break;

  }
  delay(1000);
  }

So, retrieveCallingNumber is documented in here. It "retrieves the calling number, and stores it" in a character array passed as second argument.

The simplest solution to check if this number is among the allowed ones is to construct a string from this and compare it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)

Something like this:

vcs.retrieveCallingNumber(numtel, 20);
String s = String(numtel);
if (s == "allowed number goes here") {
    // toggle LED etc.
}


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

Something to note about flashing - it would take anywhere from 10-50 tries before it would flash successfully, the other times it just failed to upload and spit out the espcomm failure to connect message, or it got halfway through the upload and quit. This is the only clue to me that maybe my board is just bad, and it won't be able to run any sketch - I ordered another ESP8266, but I'm still wondering if I could be doing something wrong, it seems fairly straight forward, and I have done a lot of research about this up until this point. This is my first arduino project, other than the starter projects.

Also not represented in the diagram are the female to male jumper cables I am using to connect to the ESP8266. Those connect to the breadboard, and then I plug another wire into the breadboard on the same row to attach it to what it needs to be attached to. I figure none of this stuff matters - as long as it is powered (red LED) it should be working.

Any ideas why the onboard LED isn't blinking? Or is the sketch not running at all? Does the upload problem matter...could it be producing a false positive result? The only other idea I have where something could be different is an output capacitor for the voltage regulator, I have been told that a 10mF capacitor is what I would use (but I have also been told it doesn't matter...and neither does the filter capacitor, I just put it in anyway).

CODE (straight from Arduino IDE / ESP8266 examples):

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

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

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

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

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

Mike pointed out my regulator matters (because of dropout voltage) - I am using this one:

http://www.nteinc.com/specs/1900to1999/pdf/nte1904.pdf

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


6 + 1 motors connected to an arduino uno? Is it possible to connect 6 dc motors and 2 dc servo motors to an Arduino Uno? I intend to control the Uno with a Raspberry pi connected through USB.

Assuming every motor to be bidirectional, how many L293 or L298 motor driver boards do I need? Is there any other better option than using multiple driver boards?

Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.

In addition, each servo will need one output pin (typically 9 and 10 for both servos).

Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!

If you can wire all 6 enable pins together, then you will need "only" 15 pins.

Also, note that if you want to control the speed of the DC motors, you will need PWM pins, but then you won't get enough with a UNO.

Regarding drivers ICs (L293 or L298), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so you will need 3 of them overall.


Accelerometer readings on a moving object I hope this stack is the right place for this question.
I have an accelerometer mounted securely on a swaying object -lets say a stick or pole-
this object is swinging back and forth in small angles (+- 20) with a frequency of about 2-3 times a second.
Im using the accelerometer output to calculate the tilt of the object, however since the frequency of the swings is relatively high the accelerometer readings are very high as well, and not reliable for calculating the tilt.

from my research i have seen that accelerometers work best in a stable environment.
Is there any way to improve the reliability of my accelerometer output in this setup?

A few things to consider.

First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.

Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation.  Getting to the max tilt is easier mathematically.

Just for starters.


Format error with ESP8266 compile I get this error when I try to compile and upload the code for the ESP826612E

fork/exec /home/c/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++: exec format error

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

Anyone has solutions?

I suspect you are running a 32-bit compiler on a 64-bit operating system. You will need to install the 32-bit support libraries.

$ sudo apt-get install libc6-i386


ATtiny85 and INPUT_PULLUP I have read some conflicting sources about what pins have internal pullup resistors available for the Attiny85 microcontroller. Can all I/O pins work with INPUT_PULLUP, or just some of them? And if so, which ones?

Thanks!

Check the datasheet, probably just search for "internal" or "pullup"  I believe there are little more pins/ports as portB, so they should all have internal pull ups.


exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)' The code below

// include the library code:
#include "LiquidCrystal.h"
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2,4,5,6,7);

void setup()
{
// set up the LCD’s number of columns and rows:
lcd.begin(16,2);
// Print a message to the LCD.
lcd.print("hello");
}
void loop()
{
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

Gives me the following error:

exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

It seems as if you are missing a parameter in the lcd() call. It seem to take six arguments, not five.

From the Blink example in the LiquidCrystal library:

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Also, looking at the library definition, from LiquidCrystal.cpp:

class LiquidCrystal : public Print {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
...
}

The number of arguments accepted by the various overloaded constructors are (respectively):

10
11
7
6

So, your statement:

LiquidCrystal lcd(2,4,5,6,7);

is missing a parameter (or more) as it only has five.

This explains why the error that you are seeing has five ints listed in the parameter list:

'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'


Pulse Sensor Working Bottom-Side-Up Better? i recently bought me an pulse-heartbeat sensor.
Connected him to my brand new M1 mini as well.

I wrote a piece of Code which just outputs the Raw ADC Value from A0 (where the pulse sensor is connected).

Now I'm confused.. When i open Serial Plotter, i get this:

Which is confusing because i don't get useable Values when putting the sensor up side down, which is the promoted way to do this (i guess!!)

When i press the other side against my wrist, i get this:

Which i can work with..

But it still doesnt look like some of those perfect diagrams on the internet.

Any can help me understand why i get this type of behaviour?

thanks, nice friday , luca

From what I see, this is a pulse sensor that work with light. It emits a bright light beam, that is reflected by the pulsing blood. To work, it must send the light directed to your veins. It should work well on your finger, because the probability to target a vein directly is much greater with a small finger then e.g. a wide wrist. Also the veins in your finger are closer to your skin and the oxygen situation is more different while pulsing, so the blood has more impact on the reflection.

The second curve might be a light source in your room, or an electrical wave. (?) I doubt it is your heart, because, if the numbers below the graph are milliseconds, then your heartbeat would be between 10-15 beats / second, i.e. 600 - 900 per minute. That would be too much even for a hummingbird ;-).


Remove blocking delay() toneMelody function? I would like to change the delay() into a nonblocking function in the code below. I've implemented it (a part of a tutorial from arduino.cc) in my code, but the delay() is blocking the rest of my code. Can anyone help me to change this?

void speelMelodie(int melodie){

if(melodie == 1){

      for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      tone(speaker, melody1[thisNote], noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes); // <-- this one has to be changed

      noTone(speaker);
      }
  }

else if (melodie == 2) {
      // the same part as previous part (for loop)
  }

else if (melodie == 3) {
      // the same part as previous part (for loop)
  }
}

Define  global vars befor setup()

unsigned long timeStamp = 0;
bool pauseOn = false;

and use it

void speelMelodie(int melodie) {

  if (melodie == 1) {

    for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000 / noteDurations1[thisNote];
      if (millis() - timeStamp < noteDuration && pauseOn == false) {
         tone(speaker, melody1[thisNote], noteDuration);
      } else { // reset value and change pauseOn to true
        pauseOn = true;
        timeStamp = millis();
      }
      int pauseBetweenNotes = noteDuration * 1.30;

      //delay(pauseBetweenNotes); // <-- this one has to be changed
      if (millis() - timeStamp < pauseBetweenNotes && pauseOn == true) {
          noTone(speaker);
      } else {
         pauseOn = false;
         timeStamp = millis();
      }
    }
  }
}

We need the state variable pauseOn to differentiate between the two states play note or silence. The code compiles, but you have to finetune in your program.A final tip Tutorials using delay() other than

for debuging or
in setup for initializing hardware

are of very low quality
-> Its like a blind person talking about color composition.


How to program and arduino UNO via NodeMCU ESP8266? I don't have my USB type A cable to program my UNO, I would like to program it via a NodeMCU ESP8266.
Maybe with the TX and Rx pins, I've seen people program certain versions of ESP with a UNO board.
How do I do this and is it possible?

The UNO's USB connection is little more than a USB to UART converter.  The NodeMCU's USB connection is also little more than a USB to UART converter.
With a little jiggery pokery (yes, that's a technical term) you can replace one with the other.
By keeping the NodeMCU in RESET mode (tie the EN pin low, or hold the RESET button) you can use the TX and RX pins as the output to the onboard USB to UART converter to connect to the TX and RX pins of the Arduino.
The tricky part is getting the Arduino to reset at the right time: you have to press the Arduino's RESET button at just the right time. Normally this is done by a small capacitor between the DTR signal of the USB to UART converter and the RESET pin, but you don't have access to the DTR signal, so you will have to do it manually. Timing here is everything. Press upload, and just as AVRDude starts to execute you press RESET. Having verbose compilation turned on in the IDE can help.
It may take a few attempts to get it right.


Controlling servo with IR led and photodiode I have found myself a really nice scheme of a buzzer that is controled by the IR led and photodiode by I want to upgrade it so it can be used for controlling a servo. What I have in mind is that when there is no object the servo whould stand still and when object comes by it will go to 90 degrees, wait for 5 sec and go back to 0 position. I just want to know is that possible for an Arduino starter and where should I look for help. Thanks.

Yes that is possible.

Start by googling for the two halves of your project separately. Find a project, example or tutorial which controls a servo. Get it working. Understand it.  Then find one which deals with a sensor similar to the one you want to use, get it working, understand it.

Then you'll have everything you need to get your project up and running.


Help using thermistor with esp8266 So I am trying to use this thermistor to measure temperature and with this code below it always puts the same value (2147483647).  I used this tutorial to do the wiring and coding.  I don't think the wiring is the problem but think the problem is somewhere in my code or perhaps I am using a wrong type of thermistor?  Am I missing something?  Any help is greatly appreciated.

I am only using a 1k resistor in series with the thermistor but don't think that would be a problem, right?

Edit: I should have mentioned I'm using the adafruit huzzah esp8266 so there are a few pins.

#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22
#define THERMISTORPIN 4

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "xxxx";
const char* password = "yyyyyy";
const char* host = "data.sparkfun.com";
const String publickey = "uuuuuu";
const String privatekey = "ttttttt";
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

//thermistor variables
const int thermresistor = 987; //value of resistor in series with thermistor
int thermtemp = 0;
uint8_t i;
uint8_t numsamples = 5;
uint8_t To = 25;
const int B = 3950;

void setup(){
    Serial.begin(115200);
    delay(10);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
  delay(500);
}

    fieldData[0] = 1; //humidity
    fieldData[1] = 2; //garden temp
    fieldData[2] = 3; //light
    fieldData[3] = 4; //outside temp
    fieldData[4] = 8; //water temp

//turnpumpon();
posttophant();
//turnpumpoff();
ESP.deepSleep(1200000000, WAKE_RF_DEFAULT);

}

void posttophant()
{
    fieldData[0] = dht.readHumidity();
    fieldData[1] = dht.readTemperature(true);

    //read outside temp (otemp) data and convert to a temp
    for (i=0; i<numsamples; i++){
      thermtemp = analogRead(THERMISTORPIN);
      thermtemp += thermtemp;
      delay(10);
    }

    //take the sum of all the readings and divide by # of samples to get avg.
    thermtemp = thermtemp / numsamples;

    #voltage divider equation
    thermtemp = thermresistor / (1023 / thermtemp - 1);

    //Steinhart eqn.
    thermtemp = 1 / (log(thermtemp / thermresistor) / B + (1 / (To + 273))) - 273;
    fieldData[3] = String(thermtemp);

    WiFiClient client;

    const int httpPort = 80;
if (!client.connect (host, httpPort)){
  return;
}

    client.print("POST /input/");
    client.print(publickey);
    client.print("?private_key=");
    client.print(privatekey);
    for (int i=0; i<NUM_FIELDS; i++)
    {
      client.print("&");
      client.print(fieldNames[i]);
      client.print("=");
      client.print(fieldData[i]);
    }
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(host);
    client.println("Connection: close");
    client.println();
}

Considerations about the ESP8266 analog pin

The ESP8266 has only one pin that allows analog read. This pin is call A0 on the NodeMCU module or A on the ESP8266 Huzzah (some other ESP module don't expose that pad - for example ESP8266-01) or might label it differently - check the documentation of your ESP module.
Following your edit: make sure that you connect your thermistor to the A pin of the Huzzah ESP8266 module.

You should keep in mind that this analog pin is a 10bit ADC with in principle limited input voltage range.

To read an external voltage applied to the ADC pin, use analogRead(A0). Unless you are using a board specially design to increase its range, the input voltage range is 0 — 1.0V. As @dandavis pointed out some boards (Node MCU e.g.) include a voltage divider on board to give you a full 0 - 3.3V input range.

Thermistor equations

The datasheet of your thermistor states that the TCR coefficient is 3000ppm/%C and has a 10K value [note that the manufacturer doesn't provide you with the temperature at which R = 10K]. The equation of the resistance variation ∆R with temperature variation ∆T is given by:

∆R = ∆T*10k*3000ppm = 30*∆T

So if T_0 is the temperature where R = 10k, the equation of the resistance value is given by:

R = 10k + (T-T_0)*30

I am assuming that you are using the 3.3V supply of your ESP and creating a voltage divider using the 1K resistor and the thermistor.
There are two ways to do this divider:

1. Voltage divider option 1

simulate this circuit – Schematic created using CircuitLab

[Note that the thermistor needs to be connected to the A pin of your ESP8266.]

2. Voltage divider option 2

simulate this circuit

Equation of voltage at node A

For both case here is the voltage V_A seen at node A:

1. Voltage divider option 1

V_A = R_series *3.3 / (R_th + R_series)

2. Voltage divider option 2

V_A = R_th *3.3 / (R_th + R_series)

Analysis of the variations of V_A with temperature

Lets look at the difference between the 2 formulas above:

1. Voltage divider option 1

The numerator is a constant with temperature while the denominator changes with T. You will get a strong variation.

2. Voltage divider option 2

Both the numerator and denominator increase with temperature. You won't get a lot of variation on V_A with temperature. You should avoid this configuration.

Analysis of the maximum allowed value of R_series

The important consideration is that for your ESP module V_A cannot be higher than 1V.

1. Voltage divider option 1

Increasing R_series will increase V_A so we compute a maximum value:
1V = 3.3V*R_series_max/(R_series_max+10K)

That gives you: R_series_max = 4300Ohms

2. Voltage divider option 2

Increasing R_series will decrease V_A so we compute a minimum value:
1V = 3.3V*10k/(R_series_min+10K)

That gives you: R_series_min = 23kOhms

This is the reason why it was suggested to you using a 30k resistor in that case.

Considerations about temperature measurement precision

The voltage variation ∆V on the node A of the ESP between temperature T1 and T2 can be computed as follow:
∆V = 3.3 *1K/(1k + 10k + 30*T1) - 3.3 *1K/(1k +10k+ 30*T2)

If we assume that the thermistor is 10K for ambient temperatures the baseline voltage measured on the A pin is:
3.3V*1K/11k = 0.3V

For a 0 to 1V 10bit DAC of the ESP8266 that is around: 2^10*0.3 = 307

A change of 10C would lead to a variation of voltage of:
∆V = 0.3 - 3.3 *1K/(11k + 300) = 8mV ~8ADC code

The equation of ∆T vs ∆V is not linear but for small variation of temperature with your current setup you get ~1ADC code per degree.

Depending of your application this might not be enough for you. As suggested in several comment you could:

Add more thermistors in parallel
Increase the 1K series resistor (but not too much or you will saturate the ADC).
Change the architecture of the measuring circuit (RC oscillator using the thermistor and interrupt counter in the ESP, 555 timer circuit loaded with the thermistor and interrupt counter, ...)
Or since you want to do humidity and temperature measurement why don't you get the BME280 module. It can be read over I2C and libraries are readily available to read it with the ESP8266.


TLE9879 BLDC shield won't communicate I just got the TLE9879 BLDC shield, which I connected to an Arduino Leonardo. Compiling the example sketch (bldc_shield_blinky_test) went fine, however, upon flashing it to the board the LED on the shield doesn't change the color (it stays white) and the following line is repeatedly printed to the Serial console:

  WARNING: Board[1]; Command[901]; Answer[0]

I have initially tried the shield in its out of the box state. I have since then flashed it with the HALL version of the shield software, using the project included in the SW distribution that comes with the shield. In both cases, the shield behaved as described above when connected to the Arduino.

Does anybody know what this warning message is about?

I never use TLE9879, but I could guess of why it doesn't work as expected.

For ATMega328p-based Arduino boards (i.e. Uno, Nano and Pro Mini), it has pin 11, 12 and 13 as SPI’s MOSI, MISO and SCLK signals, but at the same time these signals are also available on those board’s In-Circuit Serial Programming (ICSP) header pin 4, 1 and 3, except for Pro Mini which does not have a dedicated ICSP header.

This however is not the case for Arduino Leonardo and Arduino Micro which are based on ATMega32U4, for those boards, the SPI is only available on ICSP header. This is one of the reasons that some of the Arduino shields designed for Arduino Uno does not work with Arduino Leonardo when SPI communication is involved.

Based on the information of TLE9879, the SPI port is connected to pin 11-13 so it is designed to work with Arduino Uno but will not work for Arduino Leonardo.


Where are the traces connected to RESET-EN leading? Once again, I am following this schematic, and I am confused as to where RESET-EN connects:

This is how I have it mocked up it Fritzing, but I feel like this is incorrect:

This is the DTR output of the ATmega16u2 which is connected to RESET pin of the ATmega2560 for reset by avrdude over DTR signal before upload of the sketch. There is a trace by default. Cutting the trace disables the auto-reset. Soldering a bridge on  RESET-EN pads re-enables the auto-reset.

the schematics part you quoted in question misses the long unconnected line for the RESET label. It leads here:


What makes this library work exclusively with Atmega328P boards? I've been looking into libraries that read CPPM signals that I can use on my Arduino Pro Micro, and this one looked promising (github.com/jmparatte/CPPM) until I read that it only works on Atmega328P chips. Sure enough, I tried it, and it doesn't function on the Pro Micro as it does on my Arduino Uno. Why is this the case, i.e. what does it have that the Atmega32u4 doesn't?

  Implementation

  This library works only on ATmega328 implementation of Arduino UNO,
  Duemillanove and similar, also Leonardo. It uses the 16bit Timer1. So
  PWM analogWrite() on pin 9 and 10 are unavailable. The library Servo
  is not compatible because it also uses Timer1.

I tried to do some research on my own, to no avail:

Timer1 isn't specific to 328P, 32u4 has it
For all I can tell, there isn't any difference in the interrupt capabilities of the 32u4...
ICR1 and TCNT are, again, features that the 32u4 has
My signal is connected to the OC1A pin that is used as the CPPM source (pin 9, PB5)

I'm new to this kind of thing and really stumped as to what could be the issue here.

That library relies mostly on Timer 1 and, as you already noticed,
the Timer 1 of the ATmega32U4 is very similar, if not identical, to
the one of the 328P. At least similar enough to expect the library to
work identically.

I took a look at both datasheets and the only difference I can see that
can possibly affect the library is the pinout. The pins relevant to the
library are:

       328P  32U4
ICP1 =  PB0   PD4
OC1A =  PB1   PB5

The pinout of the 328P is hardcoded into the library. CPPM.h contains
these lines:

#define CPPM_ICP1 8 // Input Capture Pin of Arduino UNO is pin 8 - ICP1 (Atmega328 PB0)
#define CPPM_OC1A 9 // Output Compare Pin of Arduino UNO is pin 9 - OC1A (Atmega328 PB1)

CPPM.cpp has two instances (here and here)
of this:

if ((PINB & _BV(PINB1))) // rising edge ?

If you change the code in these three places to match the pinout of the
32U4, I would expect the library to work for you.

You could also change that conditionally as

#ifdef __AVR_ATmega32U4__
    ...
#else // assume ATmega328P
    ...
#endif

in order to make the library compatible with both MCUs, and then submit
a pull request to the original author.


How to upgrade ESP8266 NodeMCU SDK from V2.5.2 to V3? ESP.getFullVersion() output:

SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020Connecting to DO_231455

I upload sketches from the Arduino IDE. How do I update the SDK?

I have the flasher tool but I can't seem to find documentation on what to do from this point:

I've downloaded the assets from Github

The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Presumably you've already followed the instructions to put the URL for the ESP8266 Arduino Core in the preferences for the Arduino IDE.

Once that's there, to update the ESP8266 Arduino SDK, go to the Tools menu, select Board, then select the Boards manager (the first item in the menu).

That will bring up a dialog listing all the board families your Arduino IDE knows how to build for. You can limit the list to those with updates available by selecting "Updatable" in the "Type" field. Or just scroll down or search till you find the ESP8266 entry. Click it and if there's an update available you'll see an "Update" button appear on it. You can also reinstall older versions by choosing a version and clicking the "Install" button.

However, there is no version 3 as yet. At the time that I'm writing this, 2.5.2 is the most recent release of the SDK.


Is Teensy compatible with the Arduino keyboard library? I am thinking about buying some Teensy micro-controllers, but I want to know if the teensy are compatible with the arduino keyboard library.

It looks like the Teensy designer uses the standard Arduino mouse and keyboard library:

https://www.pjrc.com/teensy/td_keyboard.html

On another note, I'm sure Teensy is a fine product, but I prefer other open hardware solutions like Pro Micro which can be had on AliExpress.com for  under $4 ea.


Problem connecting 10W led + Led driver Directly Arduino Uno can anyone give me an advice on connecting an 10W led + 12 volt drive to an Arduino Uno? it works without the board but when i tried to connect to Uno it doesn't work anymore. Thankyou

To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board.
More easy and reliable option would be using Relay Board.

You can visit this link and can get more idea....

http://www.electroschematics.com/8975/arduino-control-relay/


Why does my Wemos D1 Mini stops working while charging via solar? I'm using an battery shield to recharge my battery. I want to use a solar panel, so I bought one (5V 240mA). I'm pretty sure, it won't recharge my battery fully, but that's not the point.
I've assembled my board with my shield, soldered the solar panel together with an schottky-diode and put it on USB (since the shield allows charging via USB). All fine, I get some electric power in the sun - yeah!
But my Wemos D1 Mini only runs for say 2-3 minutes and than ... dead? Restarting works, but only lasts again 2-3 minutes. This only happens while the battery shield is charging via solar. I already tested using any USB charging (my computer) - this simply works.
Basically I rebuild the circuit like described on TheAustrian/Wemos-D1-Mini-BME280-Weather-Station but only one solar panel attached and using the Wemos D1 Mini Battery Shield instead of the TP4056.
Any hints what's going on? Why can't I run the board while charging via solar? Did I miss something?

The TP4056 Module will output a max of 4.2V which is less than the 5V the Wemos D1 Mini is expecting on its 5V connection (Assuming you have connected the circuit as shown in the Github guide). When the solar panel is charging it's likely that the TP4056 is causing a driving issue on the supply of the Wemos causing it to potentially Brownout .
I would not connect the solar panel to the Wemos like this, I would have it connected to the battery then the battery connected to a 5V Step Up Power Converter like shown below (This reduces efficiency but give the MCU a stable supply),

My recommendation for the wiring,


Cannot upload sketch to Arduino Nano I've been using Arduino UNO for quite sometime and brought a new Arduino Nano. When I connected it to my computer, the power usb lit up and the blink sketch started running ( as expected of course).

Now I opened up the IDE and switched boards. But when I try to upload code to my Nano I get an error-

  avrdude: ser_open(): can't open device "\.\COM3": The system cannot find the file specified.

Clearly the IDE can't see my board. Uploading to my UNO goes fine. The serial port option is greyed out so I can't change it.

I have searched extensively online for a solution and have found none. This must be either a very unique issue or a very simple one.

When using a cheap knockoff Nano, it seems that in the newer versions of the Arduino IDE (at least in 1.8.8), you may need to select "ATmega328P (Old bootloader)" from the Processor options under the Tools menu in order to upload sketches.


DHT11 Humidity/Temp Sensor showing incorrect values So I am trying to use a humidity sensor with an LCD, but have run into this problem I have yet to fix. My problem is that when it is turned on, it returns the values Humidity: 255% and Temp: 255C. I know for sure that I am getting a signal from the sensor and that is working 100% (I have tested it without an LCD display). I have asked about this in the Adafruit Discord server and someone brought up the possibility of the data being clipped somewhere in the data collection/signal processing/printing chain. Still very confused about how I can fix this, I ask for help.

Here is some code:

#include <dht11.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

dht11 DHT;

#define DHT11_PIN 7

void setup(){
  lcd.begin(16, 2);
}

void loop()
{
  int chk = DHT.read(DHT11_PIN);
  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(DHT.temperature);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(DHT.humidity);
  lcd.print("%");
  delay(1000);
}

Obviously the DHT sensor has not acquired data to make sure do as follows:

void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t) ) {
   lcd.setCursor(0,0);
    lcd.println("DHT not ready!");
    return;
  }
 lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.print("%");
  delay(1000);
}

Make sure you connected the DHT the right way and initialized

DTH11

    Pin1 --> 5v and 10k ohm resistor

    Pin2 --> Arduino Pin7 and 10k ohm resistor

    Pin3 --> no connection

    Pin4 --> Gnd

Initialize correctly

    DHT dht(DHT11_PIN, DHT11);

and in setup() you have to start like

 dht.begin();

Now test and report back