Arduino Sending faster/more data to a web server I'm working on a project that reads vibration on a building using an accelerometer and displaying it's data on a web server. The plan is to read 10 samples/second from the accelerometer and send that data every 5 seconds to a web server using arduino yun.

So there would be 10(samples/sec) x 5(seconds) x 3(3 axis - x,y,z) = 150 data points that will be sent to the webserver, I tried this with the client.get() command but it cannot send that much data to a web server, I also tried POST request but i've had trouble with the sending it multiple times since it needs to have a delay.

What are the other options that I can do in order to achieve this? Any suggestion would help and please if you think my question is bad or not stated properly don't report me, I'm still new here in stack exchange. Any help/suggestion is much appreciated

Arduino Code for POST request

#include <Bridge.h>
#include <HttpClient.h>
#include <YunClient.h>

//IPAddress server(192,168,1,200);
byte php_server[] = {192,168,1,9};

YunClient client;
String data = "", datax="", datay="", dataz="";
unsigned long ts_0 = 0, tr_0 = 0, t_read = 100;
int counter=0;

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

}

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

  if((millis()-tr_0>=t_read)) {

    if(counter<49) {
      counter++;
    }
    else if(counter == 49) {
      //Serial.print("sent");
      String dat = "0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12,0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12, 0.24,1.24,4.56,8.97,3.15,7.23,9.34,0.12,6.21,8.12";

      send_to_ws(dat);
      Serial.println(dat);

      counter = 0;
    }
    tr_0=millis();
  }
}

void send_to_ws(String data) {
  if(client.connect(php_server, 80)) {
    Serial.println("Connected");
    client.println("POST /arduino/add.php HTTP/1.1");
    client.print("Content-Length:");
    client.println(data.length());
    Serial.println(data.length());
    Serial.println(data);
    client.println("Connection: Close");
    client.println("Host:192.168.1.9");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(data);
  } else {
    Serial.println("Connection error");
  }
}

Serial monitor output when running this sketch, It prints it in the serial monitor but only blank data is being pushed in the database of the server

Option 1.
Send a single message from the client to the server.  This message should contain all 150 points of data.

Option 2.
Send the data in a format other than as a string.  Base64 encoding of the raw numeric values would be ideal, but its going to add extra load to the CPU.  Depending on the range of the data (0-359) and the resolution (use 2 DP) you might be able to use just 4 bytes for each data point.  Because you are using a fixed length value to represent each point you no longer need separators in you data so a single reading goes from 21 bytes to 12 bytes.

Option 3.
Hand off the data to a second processor that is dedicated to sending the data.  The Yun would write the data into a shard circular buffer and the other processor (possible another Yun or an ESP8266) would read the data from the buffer, convert it and write it to the server.

I can't say which is best, because I don't know enough about you system, but if you could expand on your details we should be able to narrow it down.

After reading you answer above.  If you ranges are 0-10 with two DPs then I would look at option 2 first.  If each reading can range from -9.99 to +9.99 you take the absolute value and multiply by 100 and write that as a 2 digit hex number to your message body.

uint8 number = ((reading < 0) ? 0x80 : 0x00);  // Set the high bit for negative.
number += (abs (reading) * 100);
messageBodyString += String (number, HEX);

That will give you 2 bytes per point, and a 300 byte (+overhead) message should be transferable within 5 seconds.

Here is some quick code to explain the encoding and decoding

unsigned int Encode(const float& value)
{
    unsigned int result = (value < 0) ? 0x80000000 : 0x00000000;// Work out and set the sign bit
    result |= (unsigned int)abs(value * 100.0);             // Get the absolute value (ignore sign) and multiply
    return result;
}

float Decode(const unsigned int& value)
{
    const bool isNegative = ((value & 0x80000000)  != 0);       // Get the sign bit
    float result = (float)(value & 0x7FFFFFFF);                 // To remove the sign bit
    result /= 100.0;                                            // Divide to return to the original number of dps.
    if (isNegative)
        result = 0 - result;
    return result;
}


Connecting to network with wifi shield I just bought a WiFi shield and I cannot connect to my wireless network (WPA2).

I used the sketch from the Arduino site for connecting to WPA network and put my SSID and password on but it doesn't connect (I know the credentials are correct as I used my phone to connect with these WiFi credentials).
When I read the serial monitor it just keeps trying to connect. The WiFi-shield board error light is red
I checked my network settings and my block level is at is lowest (NAT only).

Why can't I connect?

In the loop:

// attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

Can you add Serial.print(status); before the delay so you can see if any of these arise:

WL_IDLE_STATUS = 0
WL_NO_SSID_AVAIL
WL_CONNECT_FAILED
WL_CONNECTION_LOST
WL_DISCONNECTED

They are defined in wl_definitions.h


What does this lines mean in RFID UID Card Reader Code? I'm currently doing a project using RFID. I'm wondering how this lines of the code work. I know that this has something to do with getting the UID of a scanned/tapped card, but can someone please explain or elaborate to me each line, how it executes? Thank you very much.

  String ID = "";
  for (byte i = 0; i < 4; i ++) {
    ID += (rfid.uid.uidByte[i] < 0x10 ? "0" : "")
          + String(rfid.uid.uidByte[i], HEX)
          + (i != 3 ? ":" : "" );
  }

The code formats UUID as a string of 4 hex bytes (each bytes a pair of hex digits) separated by colons.

String ID = ""

Blank the string

for (byte i = 0; i < 4; i ++){

Iterate over the four bytes of the UUID

  ID +=

Add the following to the string "ID"

(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +

If the hex number to be displayed is less than 0x10, add a leading '0' to the string 'ID'. This ensures the UUIDs are all aligned and all bytes within the UUID are displayed as two hex digits (even if only one is needed). It uses the ternary condition operator, which is a compact if/then/else that can only return one of two values (rather than executing chunks of code). See https://en.wikipedia.org/wiki/%3F: for more on the ternary condition operator.

 String(rfid.uid.uidByte[i], HEX) +

Add the UUID to the string 'ID' as HEX.

   (i != 3 ? ":" : "" );

Another instance of the ternary condition operator. This one adds a colon to the string 'ID' after the hex byte unless the index is 3 (ie the last one).

 }

End of for loop.
This means that the result is nn:nn:nn:nn instead of nn:nn:n:nn: (leave off trailing colon and differing numbers of hex digits).


Can't retrieve data from X-NUCLEO-IKS01A1 using I2C protocol So I bought this nucleo expansion board, the X-NUCLEO-IKS01A1, and on the package it says it is compatible with Arduino Uno.

My goal here is to read data from any sensor on this board. (When I can read one, I can probably read the others too using the same structure)

Here's my code.

#include <Wire.h>

#define ADDRESS 0x1E
#define REGISTER 0x16

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

void loop() {
  // put your main code here, to run repeatedly
  Serial.println(I2CreadByte(ADDRESS, REGISTER));
  delay(5000);
}

uint8_t I2CreadByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data; // `data` will store the register data

  Wire.beginTransmission(address);
  Wire.write(subAddress);
  Wire.endTransmission(true);
  Wire.requestFrom(address, (uint8_t) 1);

  data = Wire.read();
  return data;
}

This should return the temperature in 2's complement. But all it returns is a 1 (I can guarantee you it's not that cold in my room).

I have the board plugged on my Arduino.

Can anyone tell me what I'm doing wrong?

Here's the datasheet for the sensor I'm trying to communicate with.

Datasheet

The sub addresses are on page 33 and the I2C explantation on 27. It's called the LSM6DS0.

Thanks sooo much in advance.

You're using a wrong slave address. From the datasheet:

  The Slave ADdress (SAD) associated to the LSM6DS0 is 110101xb. The SDO/SA0 pin can be used to modify the less significant bit of the device address. If the SDO/SA0 pin is connected to a voltage supply, LSb is ‘1’ (address 1101011b), else if the SDO/SA0 pin is connected to ground, the LSb value is ‘0’ (address 1101010b). This solution permits to connect and address two different inertial modules to the same I2C bus.

This means your sketch should contain:

#define ADDRESS 0x6A  // if SDO pin is pulled down

or:

#define ADDRESS 0x6B  // if SDO pin is pulled up

It's also a good idea to check if there's actually anything in the Wire buffer (with Wire.available()) before you attempt reading.

Finally, I suggest you read both OUT_TEMP_H and OUT_TEMP_L registers, in order to calculate the temperature correctly. The datasheet says the temperature output is zero at 25 degrees Celsius and that the sensitivity is 16 LSB/C. This means you have to read both registers, combine their results to get a 16-bit signed integer (OUT_TEMP_H is the MSB), divide it by 16 to get the temperature offset, and add the result to 25 degrees Celsius to get absolute temperature.


Arduino Mega Hall sensor interrupt for a speedometer I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.

I have a little code put together from the Internet:

const byte LED_pin =13;
const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
unsigned long Speed = 0;
unsigned long PrevSpeed = 0;
volatile byte hall_rising = 0; // interrupt flag
volatile unsigned long irqMicros;
unsigned long startMicros;
unsigned long elapsedMicros;
unsigned long ledFlashStartMillis;
const unsigned long ledFlashWaitMillis = 10;
unsigned long displayStartMillis;
const unsigned long displayWaitMillis = 100;

void wheel_IRQ()
{
  irqMicros = micros();
  hall_rising = 1;
}

void setup()
{
  pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
  pinMode( LED_pin, OUTPUT );
  Serial.begin( 9600 ); // can this be faster? faster would be better
  delay( 1000 );

  attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
}

void loop()
{
  if ( hall_rising == 1 )
  {
    elapsedMicros = irqMicros - startMicros;
    startMicros = irqMicros;
    hall_rising = 2;
  }
  else if  ( hall_rising == 2 )
  {
    if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
    {
      hall_rising = 0;
    }
  }

  // print speed 1000/Wait (10) times per second
  if ( millis() - displayStartMillis >= displayWaitMillis )
  {
    Speed = wheel_circumference * 0.0009 / elapsedMicros;

    displayStartMillis += displayWaitMillis;
    if ( Speed != PrevSpeed )
    {
      Serial.print(Speed); // this shows mm/sec with no remainder
      Serial.println(" kmh");
    }
    PrevSpeed = Speed;
  }
}

But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

You either need to change your code to count the number of revolutions in the interrupt.  Then divide that value in your main loop by the elapsed time to get the angular velocity.  This may or may not work, as the number of revolutions may be small or even zero when you do the calculations.  Thus contributing to errors.

Or, change your code to record the elapsed time between rising edges in the interrupt.  Then find the inverse of this value.  This may be better as you could even miss an event in your main loop and still calculate the speed.  Careful not to take the inverse of zero.

To calculate speed you need to find the rotational speed of the wheel, and, consequently, how fast you are bicycling.  Use this equation:

...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above.  Do not forget that the interrupt routine is probably using milliseconds and not seconds.

Also, do not forget to clear out the last value reported by the interrupt.  No matter which of the above 2 approaches you take.

Also consider special cases.  For instance, when you stop bicycling the interrupt will never fire.  In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.


Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection I'd like to create a process to programmatically turn-on/activate a separate USB device connected to my computer...Thinking another way to state the problem, I want the Arduino to complete the USB power circuit and then "turn off" on a schedule.

In an essence, I'd like to have my Arduino facilitate the manual process of un-plugging a USB into my computer (lets say for 5 seconds) and then re-plugging it in (let's say for 5 mins)-- rinse and repeat on a schedule....I'd like to have this coded/programmed though (I'm ok in the Arduino IDE -- sample code would really help me out a ton though) -- I'm not going to setup an actual servo to do this.

I thought getting a Arduino Shield would be the right place to start but I'm really lost.  I also thought getting a USB cable with a flip power switch might be another way to tackle the problem too-- but I haven't started to mess with it yet.

Any ideas or resources to point me in the right direction are greatly appreciated.  Thanks so much.

I'm not aware of any off the shelf "shields" which would accomplish this goal.  Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.

Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.

Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones.  Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried.  If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.

At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.

It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper.  This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated.  An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first.   Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.

Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.

Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.


Atmega328P 8MHz External Clock Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?

I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

The easiest way is to use the settings:

Tools > Board > Arduino Pro or Pro Mini

Tools > Processor > ATmega328 (3.3V, 8MHz)

The problem with that is the Pro Mini bootloader is 2kB and has a bug that causes an endless reset loop if you do a watchdog reset.

The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.

After selecting the correct configuration for your hardware from the Tools menu, do Tools > Burn Bootloader, which will set the fuses on your ATmega328P and upload the correct bootloader.


Does a pulldown resistor use less battery power than a pullup resistor? I am designing a circuit connected to a simple open-close sensor, like a switch. For ease of construction, the circuit with the sensor switch closes to ground, and uses a 1 MΩ pullup resistor to Vcc to signal HIGH when the switch is open.

I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery. Would it be more efficient to use a pulldown resistor to ground, and have the switch open to Vcc?

Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Thank you!

The input current does not depend on the pin level. Have a look at this discussion from avrfreaks. The input impedance of a digital pin is extremely high. The leakage current of the Atmega328P (here as example chip) is mentioned to be 1uA for both pin states. So this current is both unavoidable and neglectable from a normal view.

But the input impedance of a digital input pin is not only dependent on this leakage current. There is also a capacitance, which will lower the impedance for higher frequencies. So, if you drive the input with higher frequencies, the input will draw more current. But you only have a switch connected to it, which is very very low frequency.

So it doesn't matter, if you pullup or pulldown. The main current consumption will result from the moments, where the switch is activated, since then a current flows through the pullup/pulldown resistor to ground.

  Tangentially, should there be a resistor on the connection to Vcc as well?

No need for a resistor there. The input impedance of the pin is already high enough and you don't want to create a voltage divider with your pulldown resistor (which would change the voltage levels at the pin).


Washing machine controlled by Arduino for homebrewing So, this question might sound a bit silly at first glance (no, I know, it sounds flat out insane), but not all that silly at second.

I have heard once about a guy who transformed some (presumably old-ish) washing machine into his own personal home-brewing apparatus. It is quite some idea if you think about it. Washing machine can easily solve most issues people have with homebrewing. It can carefully control and adjust temperature throughout the long and complicated process of brewing, it can stir, it can pump in fresh water.

Main question is, how to control washing machine to do what I want it to do.  Most automatic washing machines already have some controllers, but I don't see much chance in trying to simply reprogram them (Am I wrong?). Arduino seems like best choice for its simplicity and expandability. However I am still fairly new to Arduino and have trouble imagining how would connecting everything from washing machine (motor, pump, maybe water and temperature sensors) to Arduino actually look like.

So is it even possible? Are there any projects to "bounce of"? (I couldn't find any, but maybe I looked for wrong projects) Should I expect any major problems?

There is an article by Atmel, talking exactly about this (not for homebrewing, though). They provide a link to a PDF file that describe in detail a project involving Arduino and a re-created washing machine.

Note that it seems to be some kind of Bachelor graduation project, and that the students seem to build an entire washing machine. They control the rotor using an Arduino, and even provide the code (and a brief history about washing machines..).

Apart from building the entire machine, there are two main directions here as I see it:

Manipulate the existing washing machine's control board using Arduino. The bad news are the it would require some reverse engineering of the existing controller, because, per my understanding (and I'm not an expert on the subject) there is no one standard and any manufacturer seems to use it's own propriety control board (similar to Microwaves or Dishwashers). The good news are that an expert could probably do it, either by dumping the controller memory and examining the hex code or by using JTag.
Another way to go here is interfacing the electrical hardware itself; see this instructable where the guy connected the Arduino in parallel to the start button, by thus allowing an alternative way to start.

As for a beginner, it would make more sense to go for the latter; in-parallel connection with an existing hardware button should be a fairly comprehensible task. Consider the hazards of working with a high voltage/power device such as washing machines. I must say that on first glance such a project doesn't seem fit a novice, but I would be the last one to hold an enthusiast's back. And if you know any, I would suggest asking supervision from someone with a strong EE background.


Arduino 3.3V Conversion I am fairly new to Arduino. As far I know all official Arduinos run on 5 volts. Or there is Arduino versions that run from 3.3V? I need use Arduino with devices which chipsets all use 3.3V logic level. Do I need modify Arduino to make it  3.3V powered, like described in this Tips, or there is another way? I plan get Arduino UNO R3 ATmega328P board (comes with bootloader for Arduino UNO ZT).

Arduino Pro Mini comes in 3.3v and 5v versions.


ESP8266WebServer how to parse Json payload in post request that is bigger than the ram I need to post a big json to the nodemcu server which would be bigger than the ram's size

I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.

But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.

Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp

The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.

You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.

If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.


Weird text when pressing a certain touch button I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

But the other keys work fine.
Here's the code:

#define SCL_PIN 11
#define SDO_PIN 12

struct keymap {
    int     kCode;
    String  kValue;
  };

keymap keys[] = {
  {1, "1"},
  {2, "2"},
  {3, "3"},
  {5, "4"},
  {6, "5"},
  {7, "6"},
  {9, "7"},
  {10,"8"},
  {11,"9"},
  {14,"0"},
  {13,"CLEAR"},
  {15,"ENTER"}
  };

void setup()
{
  Serial.begin(9600);
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
}

void loop() {
  int Key = Read_Keypad();

  if (Key != 0) {
    for (int x = 0; x < 16; x++) {
      if (Key == keys[x].kCode) {
        Serial.println(keys[x].kValue);
      }
    }

    delay(300);
  }
}

byte Read_Keypad(void)
{
  byte Count;
  byte Key_State = 0;

  for (Count = 1; Count <= 16; Count++)
  {
    digitalWrite(SCL_PIN, LOW);
    if (!digitalRead(SDO_PIN))
      Key_State = Count;
    digitalWrite(SCL_PIN, HIGH);
  }
  return Key_State;
}

It seems by changing 16 to 12 on

for (int x = 0; x < 12; x++) {
      if (Key == keys[x].kCode) {
        lcd.print(keys[x].kValue);
      }
}

fixed it.


Arduino Servo won't move when using classes I'm trying to make a class work with Arduino, however it doesn't seem to trigger properly. The code is compiling perfectly, and it's supposed to control the leg of an hexapod. Also, the example sweep works on this servo, so no problem here. However, the servo is not actually moving. I'm thinking it has something to do with the order of declaring the variables:

#include <Servo.h>

// Abstract each leg, so only those functions can be accessed
class Leg {
  // Actions that can be triggered from outside
  public:
    Leg(int hipPin, int kneePin);
    void up();

  // These should be only available for the leg
  private:
    Servo hip;
    Servo knee;
  };

Leg::Leg(int hipPin, int kneePin) {
  hip.attach(hipPin);
  knee.attach(kneePin);
  }

// Testing the leg: move it up
void Leg::up() {
  for(int pos = 0; pos < 180; pos += 1) {
    hip.write(pos);
    delay(15);
    }
  }

// Initialize the leg
Leg topLeft(9, 10);

void setup() {
  }

// Test the function up()
void loop() {
  topLeft.up();
  }

I'm testing only the pin 9 (leaving the 10 empty). It seems in pain, meaning, you can see the servo trembling but not moving really at 0 degrees.

It looks this problem may be due to bad order of initializers calls for global variables.

In C++, the order of global variable initialization is unpredictable across different compilation units (i.e. C++ source files, not header files). Initialization order is only respected inside one compilation unit.

In your program, there are several global variables that, if initialized in the wrong order, will fail your program:

Leg topLeft; this is your class instance
servo_t servos[MAX_SERVOS];, int8_t Channel[_Nbr_16timers ]; and uint8_t ServoCount = 0; all defined in Servo.cpp

Calling Servo.attach() requires that the 3 variables above have already been initialized, which you cannot be sure of.

How can you fix that?

By not performing the attach() in Leg constructor but delegating it to some kind of init() method that you can call from setup():

class Leg {
    // Actions that can be triggered from outside
    public:
    void init(int hipPin, int kneePin);
    void up();

    // These should be only available for the leg
    private:
    Servo hip;
    Servo knee;
};

Leg::init(int hipPin, int kneePin) {
    hip.attach(hipPin);
    knee.attach(kneePin);
}

// Testing the leg: move it up
void Leg::up() {
    for(int pos = 0; pos < 180; pos += 1) {
        hip.write(pos);
        delay(15);
    }
}

// Declare the leg
Leg topLeft;

void setup() {
    // Initialize the leg
    topLeft.init(9, 10);
}

// Test the function up()
void loop() {
    topLeft.up();
}


Blinking cursor on Arduino is inconsistent and misses inputs I am trying to write a part of a program that prints time and allows the user to move a cursor across it. I have the following code, but there are a few issues with it.

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16,2);
  setTime(12,30,15,0,0,0);
}
int col = 0;

void loop() {
  uint8_t buttons = lcd.readButtons(); //create readable buttons
  char time_out[16];
  lcd.setCursor(0,0);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());
  lcd.print(time_out);
  lcd.setCursor(col,0);
  lcd.blink();
  delay(100);
  if (buttons) {
    lcd.clear();
    if (buttons & BUTTON_RIGHT) {
      col += 1;
    }
    if (buttons & BUTTON_LEFT) {
      col -= 1;
    }
  } //buttons
}

If you upload this to your board, you can tell that the blinking is highly irregular, not at all aesthetically pleasing.

You'll also notice that sometimes, when pressing left/right, the input isn't registered.

I suspect this has to do something with the delay() function used, which pauses the entire program.

I looked into the following method, but this does not work when needing to print something in a loop (as the time library requires).

Any idea how I could make this work better (regular blinking times and no miss of user input)?

Thanks a lot!

I don't have the hardware to test but, it should be more or less like this;
(I have also normalized the code into several functions for better readability.)

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

unsigned long timerBlink; //Required for periodic blinking
int intervalBlink = 100;

void setup() {
    lcd.begin(16, 2);
    setTime(12, 30, 15, 0, 0, 0);
    timerBlink = 0;
}
int col = 0;

void loop() {
    readButtons();
    printDate();
    if (millis() - timerBlink > intervalBlink) {
        blink();
    }
}

void readButtons() {
    uint8_t buttons = lcd.readButtons(); //create readable buttons
    if (buttons) {
        lcd.clear();
        if (buttons & BUTTON_RIGHT) {
            col += 1;
        }
        if (buttons & BUTTON_LEFT) {
            col -= 1;
        }
    } //buttons
}

void blink() {
    lcd.setCursor(col, 0);
    lcd.blink();
    timerBlink = millis();//Start timer for intervalBlink
}

void printDate() {
    char time_out[16];
    lcd.setCursor(0, 0);
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second());
    lcd.print(time_out);
}

Instead of blocking delay function, using timeout with timestamp is a better practice.


ESP8266 Blink sketch - does not blink / or stays constant I uploaded the Blink sketch (from the ESP8266 examples, in the Arduino IDE) successfully.

Depending on which wire configuration I am using two different things happen:

wiring 1:

CH_PD -> 3.3V
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

wiring 2:

VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

There are TX/RX lines in the picture from when I was flashing - they aren't being used for running the sketch.

With wiring 1 the LED stays on (doesn't blink) - I was wondering if this was because I still had the VCC -> 3.3V connected. So I disconnected that, which gives way to wiring 2.

With wiring 2 the LED doesn't come on at all, it is the same as wiring 1 except without VCC -> 3.3V.

Why is it constant when 3.3V is going to VCC, and constantly off when I disconnect it? Why doesn't it blink using wiring 2?

UPDATE

A diagram as requested, sorry it was my first time doing this:

Code:

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

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

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

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

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

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


Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem) Situation: I was trying to make a simple Arduino program that mimics my TV-Remote ON-OFF button.

Diagnosis: It just won't work. So just to check I grabbed another Arduino (2) and added my IR-Sensor to that one and let it look for the signals sent by Arduino (1).

Conclusion: Even though I ran exactly the same program in a loop sending IR signals, Arduino (2) noticed each time another IR signal. The received signals didn't even look like the IR signal I sent.

The program I use to mimic my remote: Link to the Github. It is an example of a Lib

It could be the LED. Just a LED I picked up without being specific. Link to the Documentation of the LED

Sorry not enough rep to comment. Had to answer instead.

So if your schematic is correct then you just fried your LED. You need a series resistor between vcc and the LED.

If it's not accurate and you have the resistor in place, I'd check the LED anyway, it could be a dud. Apply voltage with a resistor and look at it with your cell/mobile phone digital camera, you should see it through the camera glow dimly.

If all is good then it might be the wavelength of the LED, which is 850nm. Most IR LED's I've used are 950nm, actually they all were.

Now I don't know what the specs of your receiver are but it might be out of its sensing (is that a word?) range, also it only has a 20° viewing angle, so check the alignment of transmitter and receiver.

I'm also confused by your statement that your getting signals that don't look like IR. This makes me wonder if your sensor is hooked up properly. It could be background IR or from another source. Look around the room or test elsewhere.


Why do NRF24L01 modules only communicate in 1 direction I have 2 NRF24L01 +pa +lna modules connected to 2 arduino mini pros. One of the modules is on a joystick and the other one is on a airplane. Everything worked perfectly until last week when they stopped communicating. So I wrote a simple receiver and transceiver code to see if they worked. The result is that if the module on the plane is the transceiver and the joystick is the receiver everything works fine. If they have the opposite roles then I only get empty messages onto the serial monitor way more often than the transceiver sends a message.
Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

const byte address[6] = "00001";

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

  radio.begin();
  radio.openReadingPipe(0, address);
  radio.startListening();

}

void loop() {
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }

}

Transceiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7,8);

const byte address[6] = "00001";

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {

  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay (1000);
  // put your main code here, to run repeatedly:

}

In receiving code....try only defining variable.
char text[32];
You change the datarate , palevel and channel in nrf24l01.
See datasheet for more info.
Or visit https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/
You may have power issue because pro mini might not deliver sufficient....to neglect use a 10uf Cap in nrf.


HTTP Requests using Arduino I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.

void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post).
The fourth and the fifth posts also works fine but the sixth is same as the third.
Knowing that my API works 100% with Raspberry Pi and it has no errors.

The same thing for PUT and GET.

After Edition:
After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:

Attempting to connect to WPA SSID: WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.149
signal strength (RSSI):-66 dBm

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...

Starting connection to post server...

Starting connection to post server...

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.

I THINK the problem might be the client.println() statement.  I believe REST messages should be terminated with a \r\n and I think println just does \n.  So if you change it to client.println("\r") it should start working on every message.

Also you might want to consider moving creating the message into a function to reduce the amount of code you have.


How to flash an ATMEGA2560 using a WIZnet 5500? I am wondering if anyone has ever flashed a ATMEGA2560 utilizing a WIZnet 5500? I have looked at this bootloader package but it only supports the 5100. I may have to do it myself but am a little worried as there doesn't seem to be any support/documentation online and I am not the best programmer. Any help would be greatly appreciated.

The latest Ariadne bootloader from 'codebender' is in his 'personal' GitHub repository. It has W5500 support. Per created his fork with better documentation and a hardware package earlier. The loathingKernel's repo still lacks good documentation.

I installed Per's Ariadne package over Board Manager and then I replaced the files in Per's package with files from loathingKernel's repo. The I flashed the bootloader to Mega without problems and the Ariadne bootloader worked for me over W5500.

I configured the upload from IDE too.


Cannot upload sketch to Atmega328p TQFP soldered on PCB After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.

This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:

I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))

Now to switch to the external 16MHz clock which I want to use I found out here that I have to change the fuse values from the default

  lfuse: 0x62   hfuse: 0xD9   efuse: 0x3F

to

  lfuse: 0xFF   hfuse: 0xDE   efuse: 0x05

I tried it two times and both the times it screwed up the ATMega328P chip

C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
se:w:0x05:m

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xDE"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDE:
avrdude: load data hfuse data from input file 0xDE:
avrdude: input file 0xDE contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified

avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Users\p>avrdude -p m328p -c usbasp

avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.

This is my first time using the SMD ATMega328P chips and any help would be appreciated.

It looks like the capacitors on your crystal are considerably bigger than they should be.

You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate.  Without that oscillation the chip can't run, and so it can't respond to the programming.

The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.

  CX1 = CX2 = 2(CL - CSTRAY)


Determining power consumption with Arduino and JeeLib I built a basic LED blinker to serve as a car theft deterrent. Originally I was using a 9V battery and delay() but I've refined my approach to consume less power. Here's my code, utilizing the JeeLib library:

#include <JeeLib.h>

int led = 13;
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

void loop() {
  blink_quick();
  blink_quick();
  Sleepy::loseSomeTime(8000);
}
void blink_quick() {
  digitalWrite(led, HIGH);
  Sleepy::loseSomeTime(250);
  digitalWrite(led, LOW);
  Sleepy::loseSomeTime(250);
}

It just blinks twice every 8 seconds. I also used 4 AA batteries as they have a higher amperage rating. How long should this system work before I need to replace the batteries?

My thinking is that AA batteries offer 2000mAh and an Arduino typically consumes about 45mA on average. If I were running the above code with delay() instead of the JeeLib functions, it would last for 44 hours. Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib. I am just interested in figuring out how long I can let this run without changing the batteries, and admittedly I am not experienced enough to tell definitively.

Thanks!

What board are you using? For example, the Uno has a lot of other components that will consume power, even if you sleep the main processor. Instead use something like a Pro Mini.

You can bypass the voltage regulator, and just supply 4.5v by using 3 AA batteries. You can even use just 2 AAs if you have the 3.3v version. The lower the voltage the less current the ATMega uses.

Most importantly, measuring the power consumption using a multimeter. Measure the current the led uses. Disconnect the led, and measure how much the arduino uses. Use this handy Battery Life Calculator, and just fill in those numbers.

Run the led with the lowest current, where the led is still visible enough. Running a power-led at just 1mA will still give a decent amount of light.

In your situation, if coded correctly, power usage of the ATMega is negligible. The only real power user is the led. If you run the led at 1mA, and use a set of AA batteries, you get around 3.5 years of running time, no problem.


Arduino Zero: Enable RTTI I need dynamic casts for my project, I'm getting:

error: 'dynamic_cast' not permitted with -fno-rtti

It appears that RTTI (run-time type information) is disabled with the fno-rtti compiler flag.

How do I change this?

It apparently is true that “RTTI (run-time type information) is disabled with the fno-rtti compiler flag”; however, looking at compiler.c.flags and compiler.cpp.flags in platform.txt, no fno-rtti compiler flag is set, suggesting that gcc sets it by default.

One way to turn off fno-rtti is adding a -frtti flag into the appropriate flags string in platform.txt.  As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.

Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.

Edit 1: On Linux, typical file paths to platform.txt are like /opt/arduino-1.6.3/hardware/arduino/avr/platform.txt or /opt/arduino-1.8.0/hardware/arduino/avr/platform.txt.  I don't know the location on OSX.  However, a command like locate *avr/platform.txt should reveal its location.  (If locate is a new install on your system, first run updatedb, which may take a while.)


Arduino Leonardo as keyboard for an iPad I'm trying to make a Arduino Leonardo as a Keyboard for an iPad. I was successful with an Arduino UNO. However I'm hoping to use an ATmega 32U4 because of the better HID functionalities and smaller boards like the Beetle.

The problem I'm having is that when I connect the Leonardo to my iPad, the iPad shows an alert saying that the Leonardo is using too much power.

Tried running the board with an external power source. Then I get a different alert: Device not Supported.

At this point I believe that the problem is not necessarily power, but the fact that the Leonardo is announcing itself to the iPad and the iPad does not like it. In the UNO project, through re-flashing, the board acts only as a HID.

Is there a way to make the Leonardo (or other ATmega 32U4 based board) to not advertise itself on the USB port while allowing the HID functionality to operate?

If indeed the descriptor is the problem then yes you can change it.

In the core file USBCore.h is the line:

#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

Just change the 500 to something smaller (it has to be an even number).

However it may be that the Leonardo isn't programmed to support the Boot Protocol for HID. In which case that would require bigger changes to the USB and HID stacks in the core.


Can I control two coreless DC motors using L293DD SMD IC? I wish to control two 3.7V 6x12mm Coreless DC motors (both direction and speed individually). The only constraint is that the motor driver (circuit) has to be as small as possible.

I've seen couple of driver circuits used in quadcopters where a single FET (such as IRLML2502) is used to control the speed of coreless motors. However, the direction control is not possible with such a circuit.

It requires at least 6 MOSFETs and maybe Schottky diodes to prevent back EMF (similar to half H-bridge like here). Even after this, opposite direction control for two motors at once cannot be achieved. Then I figured all of this will increase the area required and decided to replace it with L293DD IC. Now my question is:

Can the L293DD SMD IC be used to control these motors?
Is there an alternate solution/circuit/IC which can minimize the size and area?
Are ESCs required for these small coreless motors? Can they be controlled directly via the L293DD (like normal motors)?

PS: The controller will be ESP8266 and the entire system will powered by a 3.7V 300mAh LiPo battery.

Can the L293DD SMD IC be used to control these motors?

Yes

  Is there an alternate solution/circuit/IC which can minimize the size and area?

Any of the more modern MOSFET based H-Bridge drivers that exhibit far less loss than the antiquated l293d

  Are ESCs required for these small coreless motors?

No

  Can they be controlled directly via the L293DD (like normal motors)?

Yes

The L293 is old and, well, basically crap. For efficient battery based operation you realy need to be looking for something a little more modern and efficient. There's length to choose from - take a look on your favourite electronics supplier (which means not Amazon...)


Question about a code This code is used to toggle an arduino on and off , the problem is that i can't comprehend it at all. can someone explain to me how does it work ?

New = digitalRead(button);
  if ( New!=old)
  {
    if ( New == HIGH ){
      if (LEDstatus == LOW)
    {  digitalWrite(LED,HIGH);
    LEDstatus = HIGH;
    }
    else
    {
      digitalWrite(LED,LOW);
      LEDstatus=LOW;
    }
    }
    old=New;
  }

First, fix the indentation:

New = digitalRead(button);
if ( New!=old) {                        // If the button state has changed
    if ( New == HIGH ) {                // If the button is now in the pressed state
        if (LEDstatus == LOW) {         // If the LED was off
            digitalWrite(LED,HIGH);     // Turn the LED on
            LEDstatus = HIGH;           // Remember the LED state for next time
        } else {                        // The LED was on, so turn it off
            digitalWrite(LED,LOW);
            LEDstatus=LOW;              // Remember the LED state for next time
        }
    }
    old=New;
}

That makes the code a whole lot easier to understand.

It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.

Each button press changes the state of the LED.

if it was off, it turns it on. If it was on, it turns it off.


getting error 'Serial' was not declared in this scope I am adding Dust Sensor to my particle photon project at home,

I got this GitHub project that I want to test before implementing a final code.

I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.

but I keep getting error:

'Serial' was not declared in this scope

'Serial1' was not declared in this scope

'DEBUG' was not declared in this scope

'DEC' was not declared in this scope dustSensor.cpp:13:57:

I do have Serial.begin(57600) called in setup() function but still get the above error

I learned that I needed to include Arduino.h header file

apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.

The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.


Arduino TCP Server establishes connection with client but does not receive data I am trying to send and receive data with the TCP server but I am not receiving data.

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

// Parametros de conexion a red WIFI.
const char* ssid = "bits";
const char* password = "12345";

// Start a TCP Server on port 5000
WiFiServer server(5000);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,password);
  Serial.println("");
  //Wait for connection
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 Serial.println(WiFi.localIP()); // IP

  // Start the TCP server
  server.begin();
}

void loop() {
  TCPServer();
}

void TCPServer () {
   WiFiClient client = server.available();
    if (client) {
      Serial.println("We have a new client");
      Serial.println("Hello, client!");
        if (client.available() > 0) {
            char thisChar = client.read();
            Serial.println("We got data");
            Serial.println(thisChar);
            delay(200);
        }
    }
}

Test Capture: In the capture it is seen that the code is executed until the following instruction.

Serial.println("We have a new client");
Serial.println("Hello, client!");

You have created a TCP server. You need to connect other clients to it to start data send and receive process between them. If you just simply run this and wait, then you probably won't get anything because nobody is attempting to connect to it.


Making a current GPS code run once, and only once, after the code is 'activated' I have a GPS code that I need to run only once, but every different try gives me errors, including placing the whole code in void setup(). Is there any way that this code can be run just once? As of now, the code repeats itself, putting out data over and over again - I need just one set, right when the code is activated.

Here is the code:

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2);
Adafruit_GPS GPS(&mySerial);
#define GPSECHO  true
boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup() {
  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");
  GPS.begin(9600);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
  GPS.sendCommand(PGCMD_ANTENNA);
  useInterrupt(true);
  delay(1000);
  mySerial.println(PMTK_Q_RELEASE);
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v) {
  if (v) {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();
void loop() {                  // run over and over again
  if (! usingInterrupt) {
    char c = GPS.read();
    if (GPSECHO)
      if (c) Serial.print(c);
  }
  if (GPS.newNMEAreceived()) {
    if (!GPS.parse(GPS.lastNMEA()))
      return;

  if (timer > millis())
    timer = millis();

  if (millis() - timer > 2000) {
    timer = millis(); // reset the timer
    Serial.print("\nTime: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Location (in degrees, works with Google Maps): ");
      Serial.print(GPS.latitudeDegrees, 4);
      Serial.print(", ");
      Serial.println(GPS.longitudeDegrees, 4);
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
    }
  }
  }
}

I've been trying to get this for a while, and I'm new to programming!

Put everything from your void loop() into your void setup. Put them AFTER the original setup and you should be good to go.

DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!

Here, try this:

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2);

Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true

boolean usingInterrupt = false;
void useInterrupt(boolean);

void setup()
{

  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  GPS.begin(9600);

  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);

  delay(1000);

  mySerial.println(PMTK_Q_RELEASE);

  if (! usingInterrupt) {

    char c = GPS.read();

    if (GPSECHO)
      if (c) Serial.print(c);
  }

  if (GPS.newNMEAreceived()) {

    if (!GPS.parse(GPS.lastNMEA()))
      return;

    if (timer > millis())  timer = millis();

    if (millis() - timer > 2000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
        Serial.print("Location: ");
        Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
        Serial.print(", ");
        Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
        Serial.print("Location (in degrees, works with Google Maps): ");
        Serial.print(GPS.latitudeDegrees, 4);
        Serial.print(", ");
        Serial.println(GPS.longitudeDegrees, 4);

        Serial.print("Speed (knots): "); Serial.println(GPS.speed);
        Serial.print("Angle: "); Serial.println(GPS.angle);
        Serial.print("Altitude: "); Serial.println(GPS.altitude);
        Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
      }
    }
  }
}

SIGNAL(TIMER0_COMPA_vect) {
  char c = GPS.read();

#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;

#endif
}

void useInterrupt(boolean v) {
  if (v) {

    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  } else {

    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
}


AVCC and AREF when using a reference voltage lower than 5V? I'm designing a circuit that will use a 2.5v reference for the AREF. Should AVCC be powered from 5V or 2.5V?

AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6...4 use digital supply voltage, VCC.

So it should be connected to 5V.


Atmega328p screen + midi, possible? I'm trying to build this Midi2CV (control voltage for analog synths) using a Arduino Nano:

https://photos.app.goo.gl/3IhhFL3PrLELLODB3

I was hoping to use this Nokia screen too for settings and debugging purposes, but I just realized there's only one hardware serial port on 328p and software serial seemed to be doomed for MIDI:

SoftwareSerial too slow for MIDI?

So I have three peripherals:

DAC (MCP4822)
Nokia 5110 screen
MIDI

I've gotten both the DAC and screen to work fine on normal pins so I'm thinking I'm good with just using the hardware serial for MIDI and the DAC and screen can use software. Or am I in for a world of pain without getting a more powerful chip with more hardware serial ports? And if so, what's the recommendation? (shoestring budget)

Of your three functions (DAC, screen and MIDI) only one (MIDI) actually uses UART.

The other two devices are SPI devices which, while it is a serial protocol isn't UART (serial is a concept not a protocol).

Connect the DAC and screen to the SPI port (you can share SCK, MOSI and MISO, but select different CS pins) and you have the UART pins (0/1) available for MIDI use - as long as you don't want to use the USB connection which is linked directly to those pins.


Not able to split string into 2 char I am trying to split an incoming string into 2 integer values since I have to control 2 dc motors with it. The processor is node MCU and I get following error:-

Com Port Reading:-

WiFi connected
Received: "84+62"
"84+62"

Soft WDT reset

>>>stack>>>

ctx: cont
sp: 3ffffd90 end: 3fffffc0 offset: 01b0
3fffff40:  2b343822 00223236 3ffee70c 40204148
3fffff50:  3ffe85ee 3ffee6d8 3ffee70c 402043c5
3fffff60:  3ffe85dc 3ffee70c 3ffee6d8 402043c5
3fffff70:  3ffe85f0 3ffee69c 00000000 00000001
3fffff80:  00000000 40200038 3ffefca4 0000000f
3fffff90:  00000007 00000000 00000001 402048f9
3fffffa0:  3fffdad0 00000000 3ffee744 40204984
3fffffb0:  feefeffe feefeffe 3ffe851c 401009a5
<<<stack<<<

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

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

Code:-

if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        char charBuf[50];
        msg.toCharArray(charBuf, 50);
        Serial.println(charBuf);

        char left[3] = {};
        char right[3] = {};
        int n = 0;

        while (charBuf != 0) {
          for (int i = 0; i < strlen(charBuf); i ++) {
            if (charBuf[i] != '+') {
              left[n] += charBuf[i];
              n++;
            }
            else {
              n = 0;
              break;
            }
            right[n] += charBuf[i];
            n++;
          }
        }
        Serial.println("Left Motor: "); Serial.print(left);
        Serial.println("Right Motor: "); Serial.print(right);

    }

My desired result is following:-

Left Motor: 84
Right Motor: 62

So what changes I need to make?

You get this memory leak because you overflow the variable right. This does not happen in the for loop itself even though this could be implemented more straight forward. But it's the while loop that doesn't come to an end (charBuf doesn't change and will not become 0) and in the second iteration n will be 1 initially (due to n++ at the end of the for loop). That causes the overflow at right[n] += charBuf[i];.

So: remove the while loop (and use strtok()).


DHT11 and Liquidcrystal setting cursor issue lcd_key = read_LCD_buttons();
float temp = dht.readTemperature();
delay(1000);
// lcd.setCursor(0,0);

if(temp < 0) {
    lcd.print(temp);
}

if(temp >= 0.00 || temp <= 5.00) {
    lcd.setCursor(0,6);
    lcd.print(temp);
    delay(100);
}

Here I got simple code about reading temperature from DHT sensor and lcd but when I raise or lower the DHT's temperature the lcd's cursor always printing my data from 0,0.

I want that when the temperature between 0-5 celcius it shall write data on 0,6 in lcd screen but this code not working.

Thank you for answers.

I guess it because you use

if(temp >= 0.00 || temp <= 5.00){ // writes over 0 OR under 5 which will always be true for all values measured

and not

if(temp >= 0.00 && temp <= 5.00){   // writes over 0 AND under 5 which you want


Cast from uint8_t* to char - loses precision I am trying to decode a received (via websocket) message (JSON) on my ESP8266.

The websocket library provides the data as uint8_t. The JSON library only understands char arrays. As far as I know uint8_t is basically char.

I am getting this error:
cast from 'uint8_t* {aka unsigned char*}' to 'char' loses precision [-fpermissive]

The websocket-function provides the payload as uint8_t:

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)

The JSON Decoder wants a char arr, as provides in the sample:

char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

How to "convert" the uint8_t to char[]?

Here is my full code:

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket = WebSocketsServer(81);
StaticJsonBuffer<200> jsonBuffer;

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
        {
            Serial.printf("[%u] get Text: %s\n", num, payload);
            JsonObject& root = jsonBuffer.parseObject((char)payload);
            // send message to client
            // webSocket.sendTXT(num, "message here");

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
        }
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary length: %u\n", num, length);
            hexdump(payload, length);

            // send message to client
            // webSocket.sendBIN(num, payload, length);
            break;
    }

}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  IPAddress ip(192, 168, 178, 51);
  IPAddress gateway(192, 168, 178, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin("MyWifi!", "passpasspass");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
   webSocket.loop();
  }

Well, you are trying to cast pointer to uint8_t to one character, so it warns you about that. If you cast it to pointer to char, it should work:

JsonObject& root = jsonBuffer.parseObject((char *)payload);


No response in Serial Monitor from es8266 with Arduino nano I have exactly this model of esp8266:

I removed Atmega328p IC from Arduino, and powered Arduino with USB cable. After all, I made this connection combinations:
1)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

2)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd
ESP GPIO0 > GND

3)
ESP Tx > Arudino Tx
ESP Rx > Arduino Rx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

4)
ESP Tx > Arudino Rx
ESP Rx > Arduino Tx
ESP 3.3v > Arduino 3v3
ESP Dh_cp > Arduino 3v3
ESP Gnd > Arduino Gnd

I checked both 9600, and 115200 baud, but on any of them I did not get a reply to the AT command. Have I done something wrong? I get weird characters when disconnecting ESP's GND wire, so some communication exists.

If it is not a genuine Arduino (Chinese clone probably) and it has the CH340 USB to Serial converter chip, then it will not work as the digital Signal on TX does not get pulled to ground when transmitting a digital LOW, (if that's the right way to say it). There seem to be resistors on the board that cause this effect, or something. I do not guarantee that this is your problem but it's highly likely.
Use an FTDI USB to Serial board or similar and you might have better results.


Cannot write to HID USB device (Arduino, V-USB, HidSharp) I am currently prototyping an HID USB device using Arduino Nano and V-USB library. The problem is that although I can read from the device I cannot write to it.
Here is the schema:

As for the firmware I'm using the hid-serial library.
Here is the Arduino code:

#include <HIDSerial.h>

HIDSerial serial;

unsigned char buffer[32];

void setup() {
  serial.begin();
}

void loop() {
  if(serial.available()) {
    int size = serial.read(buffer);
    if (size!=0) {
      serial.write((const uint8_t*)buffer, size);
      serial.write('\n');
    }
  }
  serial.poll();
}

Here is the HID report descriptor:

    0x06, 0x00, 0xff,              // USAGE_PAGE (Generic Desktop)
    0x09, 0x01,                    // USAGE (Vendor Usage 1)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x26, 0xff, 0x00,              //   LOGICAL_MAXIMUM (255)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x95, 0x08,                    //   REPORT_COUNT (8)
    0x09, 0x00,                    //   USAGE (Undefined)
    0x82, 0x02, 0x01,              //   INPUT (Data,Var,Abs,Buf)
    0x95, HIDSERIAL_INBUFFER_SIZE, //   REPORT_COUNT (32)
    0x09, 0x00,                    //   USAGE (Undefined)
    0xb2, 0x02, 0x01,              //   FEATURE (Data,Var,Abs,Buf)
    0xc0                           // END_COLLECTION

And lastly, here is the code running on host (.NET/C# using HidSharp library):

var devices = DeviceList.Local;
var hidDeviceCollection = devices.GetHidDevices(this.vendorId, this.productId).ToList();
var device = hidDeviceCollection.First();
var stream = device.Open();
var buffer = new byte[9];
buffer[0] = 0;
buffer[1] = 42;
stream.Write(buffer);
buffer = stream.Read();

When I run the code above despite stream.CanRead being true I receive an exception "Can't write to this device.". However if I change the code to the "Hello World" example provided by the library I can read from the device without issue.

Found the error.
While the HidSharp was sending output reports, the device driver expected feature reports.
Changing the line

0xb2, 0x02, 0x01,              //   FEATURE (Data,Var,Abs,Buf)

to

0x92, 0x02, 0x01,              //   OUTPUT (Data,Var,Abs,Buf)

resolved the issue.


Comparing two char array I modified a code which replies BAR when I send FOO. The problem is the if else statement always lands on else which prints Wrong command. I tried comparing it to string FOO(??) and also comparing it to char FOO with the same buffer size but no joy. This is the code:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "##########";
const char* password = "##########";

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}

You are comparing a char* to a char*. Array's are contiguous memory locations and the variable name for an array in this case command_1 and incomingPacket point to the first element in the array. Since they are two different array's, the location of the first element in command_1 is different than the location of the first element in incomingPacket so command_1 will never equal incomingPacket.

In order to check if the incoming packet equals "Foo" try

if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the strcmp() compares two null terminated character arrays and returns 0 if they are equal.

Just ensure that the incomingPacket is null terminated I have never worked with this library before.


How can arduino read a frequency higher than 16Mhz? I will like to understand how does Arduino measure a frequency. Also how does my voltmeter can measure a frequency as well. Since I am a beginner on using microcontroler I would read a frequency like this:

void loop()
{
    while(digitalRead(myPin)==HIGH)
    {
       // pin is high
    }
    // measure time using millis (this is the time the pin was high)

    while(digitalRead(myPin)==LOW)
    {
       // pin is low
    }
    // measure time using millis (this is the time the pin was low)

}

With this code it makes sense to me how to measure a frequency and a duty cycle. The problem with this code is that it will probably be very slow and I it will probably read frequencies up to 100Hz and less.

So my questions are:

How can arduino read frequencies higher than 100Hz? How does it achieve that?
I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz? Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

How can arduino read frequencies higher than 100Hz? How does it achieve that?

Interrupts (if you want to do it in software) or a magical piece of hardware called the Input Compare peripheral that is built into most MCUs.

  I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz?

No, that is the speed the CPU operates at. The maximum frequency signal it can read is usually below that (for SPI it's half that, 8MHz, for example).

  Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

It doesn't. The shield does. The Arduino just tells the shield what to do, and the chip on the shield does it.


Venus GPS + Arduino. Kill 3.3V TX during sketch upload I am playing around with the Sparkfun Venus GPS.  I followed this tutorial to get started.  In here the author states that you should

  Upload the following sketch to your Arduino BEFORE making any
  connections. 5V from an IO pin left high on the Arduino may well kill
  the 3.3V output from the Tx pin on the GPS module.

However, I am using the Sparkfun bi-directional logic level converter in between the Arduino and the Venus GPS (because I'm using the 5V Arduino GSM shield stacked on top of the Arduino).  In that case, would the above statement still apply?

If you have a logic-converter between the Arduino and the GPS then you won't have any problems.

The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.

However you could just as easily upload a "do nothing" sketch like this:

int main () { }

That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.


What is the use of reserved pins and SDD2, SDD3 pins of the NodeMCU? How to use the reserved pins on the NODEMCU? What is their use? Also what is the use of SDD pins?

Thanks.

The ESP8266 uses an external flash memory chip to store your program. It communicates with this flash chip over a 4 bit SDIO interface, on GPIO6-11. These pins are labeled SDDn, SDCLK and SDCMD.
Usually, the interface uses all 4 data lines (QIO), but you can also configure it to use only 2 of the 4 lines (DIO), giving you access to two more GPIO pins (9 & 10).
The reserved pins are not mentioned in the schematic. They cannot be IO pins, because there simply are no other pins on the ESP8266/ESP-12. It could be pins connected to the USB chip, connected to power lines, or not connected at all. The designers probably wanted to allow for extra pins on next iterations of the board, without changing the form factor. A quick search online didn't yield any results, so your best bet is to trace the connection on the PCB, or measure it with a multimeter. You probably shouldn't be using them anyway, because they are "reserved".


Can tx and rx pins on the uno be used like regular digital pins? The uno has digital pins marked 0-13.

0 is marked as rx and 1 is marked as tx.
Can these two pins be used as regular digital pins if i am short of digital pins?

Yes you can perfectly use these 2 pins as long as your program does not use Serial.

EDIT: Serial data over USB goes through copper traces connected to the rx and tx pins, connecting them to the USB to serial converter chip.


Update button state in Blynk app through the code I'm using Blynk along with a WeMos D1 R2 and i can change modes through an ON/OFF button.

I can succesfully change mode and make my application go from mode 1 (irrigation) to mode 2 (Fertilization), but through the code i manage to switch from mode 2 to mode 1(after my code does what it is meant to do).

However, i cannot make the button show up as being in mode 1 again, if the application is working properly in mode 1. Any ideas on how to update button condition?

My code follows(below the code you can see the app and the button Using the V1 virtual pin):

void setup()
{
  Serial.begin(9600);             // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT);        // Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT);        // Setup Relay pin as output pin
//pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
  digitalWrite(Relay1,HIGH);
  digitalWrite(Relay2,HIGH);

}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8,level);    // virtualpin 8 distance
}

BLYNK_WRITE(V1)
{
  pinValue = param.asInt();
}

BLYNK_READ(V5)
{
  Blynk.virtualWrite(5,RH);       // virtualpin 8 distance
}

BLYNK_READ(V6)
{
  Blynk.virtualWrite(6,temp);     // virtualpin 8 distance
}

void loop()
{
  Blynk.run();
  timer.run();
  if (pinValue==0)
  {
    // some code here
  }
  else //(digitalRead(sensor_pin) == 1)
  {
    // some other code
  }}

else {
  // a lot of code here
  pinValue=0;                     // here i set pinValue to 0 again in order to return to mode1
}
}
BLYNK_READ(V1)
{
  Blynk.virtualWrite(1,pinValue); // virtualpin 1 state
}

//End of program

BLYNK_READ() is documented as:

  BLYNK_READ(vPIN)

  BLYNK_READ defines a function that is called when device is requested to send it’s current value of Virtual Pin to the server.

That means it is called when the app or the Blynk server requests a state from the hardware/sketch, such as when the app first connects or reconnects to the Blynk server, or when the hardware reconnects to the Blynk server due to some network problem.

But if you just want to update the virtual pin V1 at an arbitrary time in your sketch, just call:

Blynk.virtualWrite(V1, pinValue);

at the point in your code where you want to "change" the button's current state. Not in the BLYNK_READ() function, but in your main code, such as:

[...]
else {
  // a lot of code here
  pinValue=0; //here i set pinValue to 0 again in order to return to mode1
  Blynk.virtualWrite(V1, pinMode);
}
[...]


Same output on displays with different I2C-addresses (AdaFruit library, ESP32) I've got two displays hooked up to a ESP32 via I2C and I'm using the AdaFruit library. All handling display output is packed in a own library. As I was testing I only had one display set up and everything looked fine. Now, in my actual setup with two displays, I only get the output of the first display on both screens. The displays are running on the same I2C-bus, different addresses are set. I also ran a address/portscanner that confirmed the different addresses (0x3C and 0x3D).

I have used separate displays with the AdaFruit library in such a setup before, but only on an Arduino uno and without having code moved to own libraries. So I can't tell if the ESP32 or having multiple files is messing things up or I'm missing something.

Here are parts of code in the cpp-file I used to initialize the displays and some functions I call:

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <gfxfont.h>
#include <SPI.h>
#include "DisplayOut.h"
#include "Game.h"

    /* -------------esp32 Pin setup --------------------- */
    const byte displayData = 21;    // I2C SDA
    const byte displayClock = 23;   // I2C SCL
    /* --------------------------------------------------- */

// Define OLED
#define OLED_RESET displayData
Adafruit_SSD1306 display1(OLED_RESET);
Adafruit_SSD1306 display2(OLED_RESET);

/* some variables */

void DisplayOutClass::init()
{
    // Initialize each display with i2c-address

    display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
    display1.setTextWrap(false);
    display2.setTextWrap(false);
}

void DisplayOutClass::scorePlayer1(int score1)
{
    display1.clearDisplay();

    if (gameMode == 2)
    {
        display1.clearDisplay();
        display1.setCursor(0, 0);
        display1.setTextSize(2);
        display1.setTextColor(WHITE);
        display1.print(playerName[player1]);
    }

    display1.setTextSize(4);
    display1.setTextColor(WHITE);
    display1.setCursor(getCenteredPosX(3, String(score1)), 24);
    display1.print(score1);
}

void DisplayOutClass::scorePlayer2(int score2)
{
    display2.clearDisplay();

    if (gameMode == 2)
    {
        display2.clearDisplay();
        display2.setCursor(0, 0);
        display2.setTextSize(2);
        display2.setTextColor(WHITE);
        display2.print(playerName[player2]);
    }

    display2.setTextSize(4);
    display2.setTextColor(WHITE);
    display2.setCursor(getCenteredPosX(3, String(score2)), 24);
    display2.print(score2);
}

/* some more Functions */

DisplayOutClass DisplayOut;

I didn't post the complete code or the header file, because it exceeds a few hundred lines. But this should show how the I2C-addresses are used. If necessary, I of course can post the rest of the code.

My next approach would be either trying the U8g2 library or trying start a second I2C bus. Since I already have a finished circuit board, so this would be my least preferred option.

Try the new constructors (old ones are deprecated):

Wire.begin(21, 23); // SDA, SCL

Adafruit_SSD1306 display1(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);
Adafruit_SSD1306 display2(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);

display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);


Reading FAN tachometer/RPM on 4 wire fan using arduino I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;

The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;

Need some help or expert advise; I am not sure if the approach works fine or not;

There are no interrupts on pin 9 (unless you are using Pin Change interrupts...?). You have to use pin 2 (interrupt 0), or pin 3 (interrupt 1) (also, on the Mega: 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2)).


Stabilizing output values of conductive sheet(Velostat) connected to analog pin A0 of Arduino I am trying to do some experiments with conductive sheet (velostat). When I apply a force on the sheet it should change the value of resistance(output). I taking the output of the sheet by connecting to analog input Ao of Arduino. But I am not getting constant readings from arduino, even if no pressure is applied. Do I need to build any extra circuitry to stabilize the output value? Can anyone please tell how to stabilize the output value of Arduino?

You need to use a matching resistance to create a voltage divider.


Ask for available ip on ethernet shield Is there any way so an ethernet shield to ask the router for an available ip address? For example to ask for an ip an the router to return 192.168.1.2 if it is available. I am asking it because if we set the ip programmatically and it is attached to another device we gonna have problem.

Using the DHCP (Dynamic Host Configuration Protocol) you can obtain an IP address dynamically from a DHCP server (which a router usually also is), without having to hardcode it into the firmware of the Arduino, thus enabling it to work on different networks.

There is also a library for that: http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter. It's an extension of the official Arduino Ethernet library, written for the Arduino Ethernet Shield, but you'll likely find implementations of DHCP in many Ethernet libraries (I am using the EtherCard library) because it's an important feature to be able to connect to a network without a statically assigned IP and "only" requires UDP (on top of IP).

For e.g. the Ethernet library you call the begin function either with only the MAC address of your device or with MAC and IP address:

Ethernet.begin(mac);
Ethernet.begin(mac, ip);

In the first case it will use DHCP to obtain an IP address dynamically, in the second case it will use the static IP address you provide. Be warned that the second case, due to the needed implementation of DHCP, will increase the size of the compiled binary significantly.


C++ vs. The Arduino Language? What are the advantages of each language when using the Arduino?

I'm thinking this is a good general question, but I'll add a bit about why I'm asking if anyone wants to give me a tip.

I'm experienced in preprocessed languages like JavaScript, PHP, and have fiddled with languages like Java and Visual Basic. In other words I know programming techniques and both classical and prototypal object orientation, but nothing about communicating directly with hardware.

I'm making an octocopter, and am thinking that an object oriented approach will be the easiest. (The software will have very many features...) However I have never written in C++.

Since this is a Q&A site that's supposed to help others, only the general question presented at the beginning is of much importance, but I'd appreciate any comments on my situation.

My personal experience as professor (programming, mechatronics) is that if you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE as eclipse:

http://playground.arduino.cc/Code/Eclipse

Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language.

In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project.


Problem using HC-12 graphical configuration utility, invalid responses I'm trying to use this utility [first time] to config a pair of HC-12s to a different channel, as I already have the default address in use.  It's a very handy utility, though I can find almost no reference to it via Google.

I found reference to the command here:
http://www.thebackshed.com/forum/forum_posts.asp?TID=8246&PN=1

When I use to change the channel, i get 5 error messages of the form:
invalid response(1),
invalid response(3.2),
invalid response(3.3),
invalid response(3.4),
invalid response(3.5)

I am running on Windows 10 x6, using a standard USB cable to an Uno.
The wiring config is as follows:
VCC to 5v,
GND to GND,
RXD to pin 4,
TXD to pin 5,
Set to pin 6

I've also tried connecting the Set pin to GND, as I don't know whether this is necessary or not.

The board also has an 1N4007 diode in series with the power line, and a 1000uf capacitor twixt 5v and GND.  Nothing else.

There is a sample program at:
http://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/

that should accomplish the same function via use of line commands and I shall try that next.  However, the configuration utility is so handy that I would like to have it in my kit of useful tools.

Seeking:
Assistance with the graphical configuration utility by someone who knows more than I, or perhaps a better alternative.

the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.

if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.

feel free to join the backshed forums and ask further questions about the HC-12.

cheers,
robert rozee
(author of the HC-12 config utility)


Why is my passive buzzer clicking instead of buzzing when set to HIGH? everyone. I am working on learning Arduino from scratch and I am on the buzzer lesson. The tutorial I am following consists on writing a code to get an input from the user in the form of an integer number, and, if it is greater than 10 (or whatever threshold you set it to) it will buzz.
I wrote the code exactly as the tutorial said but the buzzer would not buzz, it would do a weird clicking sound instead. I searched for a reason everywhere and could not find an explanation. Most questions in forums were solved by changing the positive wire from the 5V to a regular pin on the board, and those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.
Anyway, I managed to get a buzz by switching from digital to analogWrite and typing a value less than 255. It seemed weird that 255 and HIGH would produce the click, but values less than 255 would buzz, so I tried several analogWrite values:

At 255 the buzzer does the weird clicking.
At 254 the buzzer does a very faint buzz.

The buzzing got louder as I wrote lower numbers until it got stable at around 250, and then got less loud as I decreased the number.
Does anyone know why that is? Is the voltage too much for the buzzer at 255/HIGH? I tried a resistor but still got nothing but clicking with the program set to 255/HIGH.
This is mostly out of curiosity, but I'd still appreciate it if you could answer it.
Here is the code ("Numero" means "number" and "Dame un número" means "Give me a number":
int Numero;

int buzz=10;

int DLY=2000;

String msg="Dame un numero.";

void setup() {

Serial.begin(9600);
pinMode(buzz,OUTPUT);

}

void loop() {

Serial.println(msg);
while (Serial.available()==0){

}

Numero=Serial.parseInt();

if (Numero>25){

  Serial.println(Numero);

  analogWrite(buzz,10);

  delay(DLY);

  digitalWrite(buzz,LOW);

}

}

those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.

You seem to know, that you have a passive buzzer, but you don't know, what that means for you.
A buzzer consists mostly of a piezo element, which vibrates and thus makes a sound, if you provide it with an alternating voltage. Here we have 2 types of buzzers:

The ones, that generate the alternating voltage themselves, thus only demanding a simple constant voltage from you to operate (these are the active buzzers)
and the ones, that only have the piezo and thus demand to be provided with an alternating voltage by you (these are the passive buzzers).

You have the second type, a passive buzzer. The following is happening:
digitalWrite(pin, HIGH) will only set the pin to HIGH. On the transition from LOW to HIGH, you get a click, because the piezo in the buzzer is reacting to that change. analogWrite() on the other hand generates a PWM signal, which is an alternating voltage (alternating between LOW and HIGH).
When changing the number for analogWrite(), you are not changing the frequency, but only the duty cycle (the ratio of HIGH and LOW times in one period of the signal).

analogWrite(pin, 255) means 100% duty cycle and thus a constant HIGH signal. Actually it is equivalent to digitalWrite(pin, HIGH), because analogWrite() is doing exactly that, if you provide 255 (similarily it uses digitalWrite(pin, LOW), if you provide 0). Thus you again hear the same click.
As the piezo in the buzzer needs to oscillate to make a sound, you need to give him time for getting back to the LOW state. With the analog value 254 the LOW time of the signal is rather small, so that the piezo cannot reach its complete LOW state again. The oscillation amplitude is rather small that way. Thus you only hear a very faint buzz.
With analogWrite(pin, 250) you reached the maximum, because now the piezo has enough time to get to its LOW state again. The amplitude is at its maximum here, thus it is the loudest value.
When going lower than 250 towards zero, you are also reducing the amount of energy, that you give to the buzzer, thus the volume will reduce (though this is certainly not a linear process and depends also on the characteristics of the buzzer).

Just as Juraj already wrote in the comments, a passive buzzer can be interfaced with the tone() function. It will generate the alternating voltage for you and you can even set the frequency to your liking, so that you get tones with different pitches. There are tons of tutorials about the tone() function on the web.


Entering integers as bytes in serial monitor I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as 1, and my program stores it as byte incomingByte, the value stored in incomingByte is 49 and not 1. How do I enter the ASCII equivalent of an integer?

Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.


Onboard led HIGH and LOW seems reversed On an ESP32 board I am trying this simple code to control the onboard led.
But if I set it to HIGH, led is OFF, if I set it to LOW, led is ON (fully bright).
What could cause this ?
The board has one red and one blue leds, the blue one is the one that can be controlled.
#define onboard_led 2

void setup() {
  pinMode(onboard_led, OUTPUT);
}

void loop() {
    digitalWrite(onboard_led, HIGH);
    // digitalWrite(onboard_led, LOW);
}

Edit: it was a board like this ("Geekcreit" I think):

As this image from Okdo Page on LED Driving shows, there are two ways to drive an LED from a GPIO output pin:

In the Active HIGH case, a HIGH output on the GPIO will turn the LED on since that will source current out of the pin and through the LED into ground.
In the Active LOW case, a LOW output on the GPIO will sink current from the +V supply into the pin.
In your case the LED is hooked up in the Active LOW configuration and so to turn it ON you must set the pin to LOW.
I'll add that these ESP32 boards are made by many different manufacturers and they are not all identical.