What does it mean when there are two addresses listed in the data sheet for a particular register? I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.

For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.

Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.


Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL? I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from https://github.com/jwhiddon/EDB.

My question is, is the char str[] type the equivalent of VARCHAR?

Here is my arbitrary record definition for my table:

struct LogEvent {
  int logId;
  int unumber;
  char username[10];
  char fname[15];
  char lname[15];
  char role[6];
  char boxid[10];
  char userStatus[2];
} logEvent;

If you mean, are these equivalent:

foo VARCHAR(100);

and:

char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.

You could conceivably put 100 characters into foo but then you would have to store the size of foo in another variable.


MHz Sampling Rate for Arduino How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?

If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.

The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.


Problems with ACS758 Hall Effect Current Sensors - Calibration and no Signal I purchased 3 ACS758 Hall Effect Current Sensors datasheet on ebay. A 50,100 and 200A, all three are bi-directional. They look like this.

With no current the 50A outputs 477 on the analogue input (2.33v), the 100A outputs 509 (2.48v) and the 200A outputs 512 (2.50v). At no current they should all be at exactly mid range i.e. 512 (2.50v). The datasheet says they're factory calibrated as such. I've tested them one after the other, both with 5v from the Audrino and with a separate 5v supply. As I've tested one after the other it's not likely to be stray magnetism or VCC.

I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change.

Is there any other tests I can do to see if I'm doing something dumb or are they all damaged?

I contacted Allegro they were really helpful which was pleasantly surprising.

The 200A has almost certainly failed. The 2.48v is within tolerance and the 2.33v is probably out.

I've been able to better understand the datasheet sections on 0A calibration. "VIOUT(Q) may drift over the lifetime of the device by as much as ±25 mV." and there is an electrical offset voltage noted. @25C it's +/-5mv. It's +/-20mv between 0c and 50c. So still only 45mv. Even allowing for noise it's only 55mv.

About 2.445V at zero amps would be the limit.


create dynamic mqtt topic I have a problem using the PubSubClient. I want to create dynamic mqtt-topics based on a predefined prefix and a suffix and my ESP-macaddress.

My problem is that the PubSubClient requires a cost char* and I cant seem to figure out how to do it dynamically.

Below is my current solution and that is not as convenient as I want. The code below is only pseudocode but that are the crucial parts.

// How I get the mac_address
WiFi.macAddress(mac_array);
for (int i = 0; i < sizeof(mac_array); ++i){
     sprintf(mac_address,"%s%02x",mac_address,mac_array[i]);
}

// Current way, where I hard code the topic_in & topic_out
const char* topic_in = "node/18fe34d77ead/from_node_red";
const char* topic_out = "node/18fe34d77ead/to_node_red";

Below is an example of how I would love to do it but I cant figure out how to do it.

// I would love to be able to do like this
const char* topic_in = "node/"+mac_address+"/from_node_red";

Can any one please help me or point me in the right direction.

It doesn't require const char *, it says "passed string won't be changed inside of call". Externally it can be char * or char [] or Arduino String class with using c_str() method to get const char *.

And as the MAC address won't change a lot, it should be done once in the setup().


MCore(Arduino) - Python bluetooth communication Pc and Mcore with bluetooth module are paired. The port is COM9 outgoing in PC. However, when I send message Arduino does not get anything. I just disconnect arduino from pc and write simple code in Mcore that turn on LED when input message is 1. However still nothing. These are the codes in python and arduino side:

import time
import serial

port="COM9"          #This will be different for various devices,COM port.
bluetooth=serial.Serial(port, 9600)         #Start communications with the bluetooth unit
bluetooth.flushInput()      #This gives the bluetooth a little kick
bluetooth.write(b'1')       #These need to be bytes not unicode
bluetooth.close()          #Otherwise the connection will remain open until a timeout

Arduino code:

char a;

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

void loop()
{
if(Serial.available()){a = Serial.read();}

if (a == '1'){
  digitalWrite(13, HIGH);
  }

  else{
  digitalWrite(13, LOW);}

  delay(100);
}

I have tried to install Pybluez for WIN10, however, there was error. Do you think that this is the reason?

Thanks in advance

Probably because you never called bluetooth.open().

What would be much easier to do is use pySerialTransfer and SerialTransfer.h to guarantee reliable and robust serial communication between Python and your Arduino.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs and come with examples.


Measuring the speed of an object moving fast through air I am new to arduino and am confused about how I would go about doing this: I want to attach a device to a small ball, that will move through the air at speed. The purpose of this device would be to determine the speed of this object as it moves through the air. My ball will always move in the same path because it will be shot out of a tennis ball shooter. My initial intuition would be to use an accelerometer to determine the acceleration at quarter second intervals and then multiply those values by a quarter of a second to obtain the change in speed and then add it to the sum of all the previous change in speed values (starting at 0).

Would this work? Is my reasoning correct? Are there any better solutions?

Thank You!

You are proposing calculating velocity based on sampled acceleration.  Essentially taking the integral of the acceleration.  This is the first step in a process call dead reckoning. This is discussed in this arduino.stackexchange.com answer.  In that answer there is a link to a web page which implements dead reckoning using an Arduino. You will find this equation on that web page:

velocity(i) = velocity(i-1) + acceleration (i)


Arduino beginner question I just got a new pro-micro Atmega32U4 board, and installed the current Arduino IDE (1.8) and cannot get it working.

There is no entry for a pro-micro, so I chose Leonardo as it uses the same chip.

When I choose upload, the two red LEDs blink fast, but I get an error from avrdude, saying that it cannot upload the code.

The board is probably from a Chinese web shop ($6 clone). There are no buttons on the board.

My questions are:

Is there already a bootloader on the chip, or do I have to program one? How do I check this?
How does it know that it must receive an upload, instead of running the flash program?
Which board should I choose in the IDE?

This is the error:

  Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

It looks exactly like this one.

Update: I did everything the manual said. I can choose the pro-micro now. Still the same error message. How do I check what state the bootloader is in?

There is an extensive guide written by SparkFun explaining how to work with Arduino Pro Micro: Pro Micro & Fio V3 Hookup Guide.

There are specific drivers for the board, so make sure you have them installed. There are also board files for the IDE, which allow you to select the Pro Micro in Arduino software.


ESP32 feedback from NTP The basic example for ESP32 NTP is very rough:
void setup()
{
  Serial.begin(115200);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

But it tells nothing about the success of the operation.
I need to know if it was able to update the time from the NTP server... is there a method to know that?
I can't rely on the time struct because I must init it manually at startup, say at 1st Jan 2020 00:00.

Did you follow that manual?
https://lastminuteengineers.com/esp32-ntp-server-date-time-tutorial/
The printLocalTime(); function does all you ask for.
void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

getLocalTimereturns false on failure. Let the printLocalTime do the same.
boolean printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return false;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  return true;
}

Now the print function tells you if it failed (returns false) or not (returns true).


Arduino Joystick Library not Recognized by Games (Steam) I have an Arduino Pro Micro running code that uses the Arduino joystick library to act as a gamepad.  I'm just doing testing right now so there's a single button wired up and configured in the code.
Windows recognizes the gamepad just fine and I can read button presses in the properties dialog for that controller.  However the gamepad doesn't work in games that work with a usb gamepad normally (I testing using Rocket League).
I would like to get my Arduino to act just like a normal gamepad (i.e. an xbox controller).
There is lots of discussion on the internet about making custom USB devices (which is what I'm trying to do) but they never seem to get answered very well or at all.  I want to achieve this on the hardware/firmware/driver side rather than having some windows application running on the computer.  If I have to write firmware on the Arduino, buy a USB PID, and/or write a USB driver for the computer, I'll do whatever it takes.

There is an Arduino Xbox 360 (XInput) library. But I do not use Steam so I have
no idea if this works.
https://github.com/dmadison/ArduinoXInput


PWM output while using I2C with the ATTiny library I've noticed that when using the USI interface on the ATTiny to send I2C via the methods from "Wire.h" with the ATTiny Arduino implementation included from the library manager (ATTinyCore), while analogWrite PWM on PB4 (Arduino pin 4, physical pin 3) works OK, it seems attempting to use it on PB1 (Arduino pin 1, physical pin 6) behaves erratically or hangs the processor.

Is this expected behavior, and is there a workaround? With the SDA line on PWM pin 0, physical pin 5 if that's the case it means when using the hardware USI to do I2C communications, I'm down to a single hardware PWM output, which is kind of a bummer.

This is normal.

Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.

So you can only use Timer1 for your own (PWM) purposes while using the USI.


How to push two values to the same key from Arduino to Firebase I would like to push two values at the same time (to the same node) from arduino to firebase. I tried to create an array and push the array to firebase, however, that is not working.
Here are the two values that I'm pushing, but I would like to push them to the same unique key:
temp1 = sensors.getTempCByIndex(0);
 StaticJsonBuffer<50> jsonBuffer;
JsonObject& timeStampObject = jsonBuffer.createObject();
timeStampObject[".sv"] = "timestamp";

Firebase.push("Sensors/20/temperatures/001", temp1);
Firebase.push("Sensors/20/temperatures/001", timeStampObject);

How it should look like in Firebase
Thanks in advance!

@hcheung thanks for your help! It solved the problem. This is my code now:
StaticJsonBuffer<256> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add(timeStampObject);
array.add(temp1);
Firebase.push("Sensors", array);


How to calibrate a load cell? I'm working with a load cell and HX711. There was no weight on the sensor but I kept getting strange values, I thought it was broken or something so I used my second load cell but the same thing happened again.
I'm wondering what is wrong with it ?
If anyone have worked with it or have an idea how to work with it, please don't hesitate to give your opinions.

 #include "HX711.h"
#include <Wire.h>

#define DOUT  A0
#define CLK   A1

#define DEC_POINT  2
#define STABLE  1

float offset=0;
float calibration_factor = 1;
//float real_weight = 1.560;//kg
float real_weight = 0.5;//kg

HX711 scale(DOUT, CLK);

unsigned char state=0;
long  FindZeroFactor();
float get_units_kg();
void  ReadWeight();
void  FindCalibrationFactor();

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("Auto Calibrate Program");
  Serial.println("Send 'a' to Find Zero Factor (Please Remove all weight from scale)");
  Serial.println("Send 'b' to Find Calibration Factor (Please insert know the weight on the scales)");
  Serial.println("Send 'c' Show weight on the scales");
}
void loop()
{
  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp=='a')
      state=1;
    if(temp=='b')
      state=2;
    if(temp=='c')
      state=3;
  }

  switch(state)
  {
    case 0:
    break;
    case 1:
      FindZeroFactor();
   //   ReadWeight();
      state=0;
    break;
    case 2:
     FindCalibrationFactor();
     state=0;
    break;
    case 3:
      ReadWeight();
      delay(200);
    break;
    case 4:

    break;

  }
}

long FindZeroFactor()
{
     Serial.println("Find Zero Factor");
     Serial.println("Please wait .....");
     scale.set_scale();
     scale.tare();
     long zero_factor = scale.read_average(20);
     Serial.print("Zero factor: ");
     Serial.println(zero_factor);
     return(zero_factor);
}

void FindCalibrationFactor()
{
  unsigned char flag_stable=0;
  unsigned int decpoint=1;
  for(unsigned char i=0;i<DEC_POINT+1;i++ )
    decpoint = decpoint*10;
  while(1)
  {
      scale.set_scale(calibration_factor); //Adjust to this calibration factor
      Serial.print("Reading: ");
      float read_weight = get_units_kg();
      String data = String(read_weight, DEC_POINT);
      Serial.print(data);
      Serial.print(" kg");
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      long r_weight      = (real_weight*decpoint);
      long int_read_weight = read_weight*decpoint;
      Serial.print(r_weight);
      Serial.print(" , ");
      Serial.println(int_read_weight);
      long x;
      if(r_weight == int_read_weight)
      {
        flag_stable++;
        if(flag_stable>=STABLE)
        {
          Serial.print("Calibration Factor is = ");
          Serial.println(calibration_factor);
          break;
         }
        }
       if(r_weight > int_read_weight)
          {
            x = r_weight - int_read_weight;
            if(x > 100)
              calibration_factor -= 1000;
            else if(x > 100)
              calibration_factor -= 10;
            else
              calibration_factor -= 1;
            flag_stable=0;
          }
          if(r_weight < int_read_weight)
          {
            x =  int_read_weight-r_weight;
            if(x > 100)
              calibration_factor += 1000;
            else if(x > 10)
              calibration_factor += 10;
            else
              calibration_factor += 1;
            flag_stable=0;
           }
  }
}

float get_units_kg()
{
  return(scale.get_units()*0.453592);
}
void ReadWeight()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  String data = String(get_units_kg()+offset, DEC_POINT);
  Serial.print(data);
  Serial.println(" kg");
}

The first thing that about Load Cells that always comes to my mind is the circuit which amplifies the load cell's signal, Usually the load cell signal changes in a low mv range, so you have to put a high gain circuit in the way of the signal, which amplifies signal and NOISE. You have to use an instrumentation amplifier for this purpose, otherwise, your signal would become so noisy.

And try to implement a low pass digital filter too, it should compensate the fluctuations and would give you smoother signal.


Serial Moniror, '\r' and Realterm I'm wanting the results from each of the 6 ultrasound modules to print on their respected line after new results have been generated instead of spitting out a continuous flow (see attached image). I've downloaded Realterm and got the results to show on there as I've read that the serial monitor can't do that but I don't know where to put the '\r' syntax within my script as I have multiple serial.prints to display the data I need.

Here is a section for 1 of the ultrasound modules, they are just repeated for the differing modules.

Thanks in advance for any help!

  //Object Ahead Distance.
  long duration1, distance1;
  digitalWrite(trigPin1, HIGH);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   delay(500);
   if (distance1 >= 40){
    Serial.print("Nothing Ahead, Okay");
    Serial.print(distance1);
    Serial.println("cm");}
   else if (distance1 <= 39 || distance1 >= 29){
    Serial.print("Vehicle Ahead, Slow ");
    Serial.print(distance1);
    Serial.println("cm");}```

\r returns the cursor to the start of the current line. You can't use it to go back up to previous lines.

Instead you need to learn ANSI escape sequences to move the cursor around.

For example Serial.print("\e[2J"); will clear the entire screen. Serial.print("\e[1;1H"); will move the cursor to the top left corner of the screen (the coordinates are \e[{Y};{X}H by the way).

You can also add colour and all sorts of other nice things, none of which the Arduino IDE's "Serial Monitor" can do.

You can find a good reference of ANSI escape codes here.


Why does my servo twitch and turn on its own? I've been trying to write a very simple program using Arduino to tell a servo to go to a specific angle when a button is pressed, and to another specific angle when it is released. I find that, even though my sketch is but the simplest possible if then else statement without anything added to it, the servo goes to the right angle when the button is pressed, but when it is released, the servo oscillates between the two specified angles at a regular rate (about once every second). What's even stranger is that when i add delay time to the end of the loop in my sketch, the oscillation becomes more like twitching, and the more delay i add the weirder and less predictable the twitching becomes.

added info

#include <Servo.h>
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup()
{
    Servo1.attach(11);
}

void loop()
{
    switchState = digitalRead(switchPin);
    if (switchState == HIGH) {
        Servo1.write(40);
    } else {
        Servo1.write(70);
        delay(39);
    }
}

the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.

If it does what you expect when the button is pressed, but behaves unpredictably when released, you almost certainly have a floating input.

See Switches tutorial.

In particular, this is a no-no:

Random fluctuations in voltages will make the switch read HIGH and then LOW, and your servo will chase around trying to change positions.

The simplest fix (without changing anything else) is to add a pull-down resistor between the pin and ground, so now the pin reliably reads LOW when not pressed.

Other methods are discussed on that page, including debouncing.


Simple Multiple RX/TX SoftwareSerial? In this project I will be using multiple ESP8266 WiFi modules (4) connected by software serial to an Arduino Leonardo Micro (1 UART). I plan to rotate between all 4 (starting with 2): Open port, write, read response, close port, move on....

This is a very barebones version of my code to address this one issue. Works flawlessly with a single (always open) connection, but it does not work when I close Ser1 (even if I don't start Ser2!!!)
Is the xxxx.end(); command broken or something?
Or am I doing something wrong? :/

Note: This code sends "AT" to the module, it responds with "OK"

When adding Ser2, LED flashes on Arduino periodically indicating it is writing to serial monitor, but nothing appears...

Code:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {

  pinMode(10, INPUT);
  pinMode(16, INPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  //Set up Serial Monitor on host computer

}

void loop()
{

  delay(1000);

  Ser1.begin(9600); // open Ser1

  Ser1.write( 'A' );
  Ser1.write( 'T' );
  Ser1.write( '\r' );
  Ser1.write( '\n' );   // sends the line: "AT" with appropriate format

  Ser1.listen(); // make sure it's listening

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Ser1.end(); //close Ser1 port
  //This breaks the code for some reason....

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.begin(9600); // open Ser2

  Ser2.write( 'A' );
  Ser2.write( 'T' );
  Ser2.write( '\r' );
  Ser2.write( '\n' );

  Ser2.listen();

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }

  Ser2.end();

}

As Ignacio mentions, you should not be stopping and starting the serial ports. Instead just switch between them with .listen():

  Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).

  SoftwareSerial::listen() Manual Page

So your code would be written as:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {
  Serial.begin(9600);
  Ser1.begin(9600); // open Ser1
  Ser2.begin(9600); // open Ser2
}

void loop()
{

  delay(1000);

  Ser1.listen(); // Select Ser1 for receiving
  Ser1.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.listen(); // Select Ser2 for receiving
  Ser2.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }
}


Connect Arduino to PLC (Data Exchange) The Arduino should read data from a PLC. Has anyone experience with this? What would be possible interfaces?

I would prefer OPC-UA, but all the research I did, only OPC-DA was mentioned.

Thanks in advance for your suggestion(s).

@Paul, thanks for your suggestion.

I want to go forward with TCP/IP.
I have now setup a ESP8266 Modul.
The ESP Modul is setup as a Server.
The Server on the ESP Modul is up and running.
I'm also able to connect to the ESP-server with "Hercules", a Terminal Tool.

All the example I found were establishing communicating with Browser and HTML.
I have also checked this, but this is not what i want.

This is the current code communicationg with the web page to toggle a LED.

    void loop() {
    if (esp8266.available()) // check if the esp is sending a message
    {
    debug("available and waiting for command");
    if (esp8266.find("+IPD,"))
    {
      debug("Incomming Request");
      int connectionId = esp8266.parseInt();

      if (esp8266.findUntil("LED","\n")) digitalWrite(LED, !digitalRead(LED));

      String webpage = "
Hello World!
Open [IP]/LED to Toggle LED on D9";

      if (sendCom("AT+CIPSEND=" + String(connectionId) + "," +          String(webpage.length()), ">"))
      {
        sendCom(webpage,"SEND OK");
        sendCom("AT+CIPCLOSE=" + String(connectionId),"OK");
        debug("Send and Close");
      }
    }
  }
}

But the PLC has no web server. So now I would like to do the same thing as client through a terminal.

How can i check what really had beed sent and what the ESP really received?
At this point sending the /LED command has no effect.

Terminal & ESP

Thank you in advance for your advise


MOSFET dimmer IR controlled I am trying to make a group of LED dim with PWM to a MOSFET. The code seems to work for this, but the trouble is that the IR receiver will only receive the signal to turn on the lights and then IR receivers onboard LED goes to a permanent dim state (which is suppose to be off completely).  It then refuses to take input until a Arduino reset is preformed.  I purchased another IR receiver and placed it in the same configuration and it work exactly as intended I could brighten the LEDS and I saw the PWM stretch on my oscilloscope with every click of my remote.  The trouble is that the receiver quickly quit working at this point I think there is a problem with my circuit.  I am attaching the circuit diagram in hopes that someone can help.

Thanks,
Billa

#include <IRremote.h>

int led = 9;
int led2 = 10;
int brightness = 0;    // how bright the LED is
const int RECV_PIN = 7; //IR Receiver Pin
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();

}

void loop() {

  analogWrite(led, brightness);
  analogWrite(led2, brightness);

  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == 0xFF906F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered U");
        brightness = brightness + 5;
    }

    if(results.value == 0xFFE01F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered D");
        brightness = brightness + 5;
    }

    irrecv.resume(); //receive the next value
}

  delay(100);
}

The first error I see with the sketch is right under this line of code Serial.println("Triggered D");. You are incrementing the variable brightness when you probably meant to decrement it.

The second error is with your call to analogWrite(). This function accepts an integer between 0 and 255. You do not constrain the value to that range, and can see what I mean by adding this line of code Serial.println(brightness); right above this one irrecv.resume(); in your sketch. Going from 0 to -5 turns the LED from off to maximum brightness. Is this what you want it to do?

The errors with your MOSFET circuit is a "General Electronics" question, and should be asked on electronics.stackexchange.com. As I mentioned in one of my comments to your question, there is a recommended format for drawing schematics.

My other comment was regarding this Q+A at EE. You won't find a consensus on exactly how to use a MOSFET there either, but the image in this answer may be helpful to you.


Arduino Uno Bluetooth connection I'm trying to connect two Arduino Unos with Bluetooth modules (HC-06 and HC-05). Does anyone know the steps required to do that?

I still haven't figured out:

How to pair the two Bluetooth devices, and;
How to pair each Bluetooth with each Arduino.

If you have any useful tutorials, please let me know.

There is a nice example for Arduino here.

Connecting 2 Arduinos by Bluetooth using a HC-05 and a HC-06: Pair, Bind, and Link

The Uno works the same way as the board in the example.

Arduino 1

Arduino 2


Powering 24 volt solenoid valve with Arduino uno Today I received normally closed solenoid valve which I am going to use in automated pot watering system ,
I realised the valve takes 24 dc volt as input and Arduino has maximum of 5volt , using some power booster I can convert it to some extent but I think 24 volt is too much .

So how should power 24volt solenoid valve from Arduino uno?

Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.


How to remove SD card safely I’m constructing an arduino based sytem that uses a SD card and I’m looking for a way to safely remove the card from the system during operation. One way would probably be to turn of the arduino before removal of the SD card, but that is not acceptable in this context.

The library I’m using:
https://www.arduino.cc/en/Reference/SD

Is it possible to safely remove the SD card during operation? If no, how can I minimize the risk of damage to the SD card while inserting and removing it?

The physical construction of the card and socket are designed such that power to the card is cycled properly when the card is inserted and removed. The only thing the firmware has to do is to stop writing to the card before it is removed.

Unexpected removal can cause a problem in "larger" systems (e.g. cellphones or PCs) because they may have structures open on the card that are not yet complete, but small embedded systems typically do not have the capability to do so and so once all writes are completed the card can be removed.

Detection of non-presence of a card is another issue though, and the firmware will have to be designed to not fail in such a situation.


How can I connect the Tamiya double gearbox to Arduino Uno? I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the Tamiya double gearbox here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work.

I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox with these motors. If I do that, am I right in thinking I could run them from the Arduino motor shield?

If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice!

Here's what I've found about both the motor shield and the motors:

Motors are 3-6V and will use a lot of amperage. This may be a problem with a mobile robot. You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
Motor sheild can provide 2x 2A channels at 5-12 V (Source) using the two + and - terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

This chip was recommended by Pololu on the product page.

Time to whip out your soldering iron! Really, soldering is a great investment and you'll get to a point soon where you'll need one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.

Diagrams from Pololu's site:

  *(Click to enlarge ^^^)**

*I added a little text to this image.


LowPower.idle isn't waiting I am trying to have my Arduino wait in a low power idle state given by the LowPower library made by rocketscream on an Uno. However, when I try to have it wait for 8 seconds, it seems to not pause at all. Does anyone know how to make it so it waits the full 8 seconds before running the next line of code?
Here is the code:
#include "LowPower.h"

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

void loop() {
   delay(100);
   Serial.println("above");
   delay(100);

   LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_ON, SPI_OFF, USART0_OFF, TWI_OFF);

   delay(100);
   Serial.println("below");
}

I would expect this to print "above", then wait 8 seconds, then print "below",  then do it again. But what happens is it runs right through the LowPower.idle without doing anything and the output looks like:

1:12:14.547 -> above
21:12:14.746 -> below
21:12:14.845 -> above
21:12:15.044 -> below
21:12:15.144 -> above
21:12:15.376 -> below

...and so on.
If anyone has any ideas on how to make idle wait, that would be great.
Thanks!

FYI, this issue was brought up nearly 3 years ago, with no response from the author:  https://github.com/rocketscream/Low-Power/issues/36


Splitting DOUBLE in byte for save on EEPROM I'm trying to save in memory (FRAM in this case) DOUBLE value, i try the same method with use of UNION for save FLOAT value, but don't go over the 2nd number after dot, why? Where I'm wrong? thank's for help .

 //---------------------------------------------------------

  union Scomp_double  // si utilizza union x double
  {
    double temp;
    char byte_s[8];
  } S_double;

  //---------------------------------------------------------

double mioDouble = 1234567.12345678;

//-------------------------DOUBLE--------------------------------

  Serial.println("DOUBLE");
  byte d0 = 0;  // contengono i byte del float
  byte d1 = 0;
  byte d2 = 0;
  byte d3 = 0;
  byte d4 = 0;
  byte d5 = 0;
  byte d6 = 0;
  byte d7 = 0;

  S_double.temp = mioDouble;
  d0 = S_double.byte_s[0];
  d1 = S_double.byte_s[1];
  d2 = S_double.byte_s[2];
  d3 = S_double.byte_s[3];
  d4 = S_double.byte_s[4];
  d5 = S_double.byte_s[5];
  d6 = S_double.byte_s[6];
  d7 = S_double.byte_s[7];

  Serial.println(d0);
  Serial.println(d1);
  Serial.println(d2);
  Serial.println(d3);
  Serial.println(d4);
  Serial.println(d5);
  Serial.println(d6);
  Serial.println(d7);

  fram.writeEnable(true);
  fram.write8(11, d0);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(12, d1);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(13, d2);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(14, d3);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(15, d4);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(16, d5);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(17, d6);
  fram.writeEnable(false);
  fram.writeEnable(true);
  fram.write8(18, d7);
  fram.writeEnable(false);

  S_double.byte_s[0] = fram.read8(11); // si ricompone il double
  S_double.byte_s[1] = fram.read8(12);
  S_double.byte_s[2] = fram.read8(13);
  S_double.byte_s[3] = fram.read8(14);
  S_double.byte_s[4] = fram.read8(15);
  S_double.byte_s[5] = fram.read8(16);
  S_double.byte_s[6] = fram.read8(17);
  S_double.byte_s[7] = fram.read8(18);

  double masterDouble = S_double.temp;
  Serial.println(masterDouble);
  //-------------------------DOUBLE-------------------------------

expected result 1234567.12345678 , result taken 1234567,12

how suggest in the comments, and on Arduino reference DOUBLE website

only on arduino 2 float it's 8 byte.


How to send HTTP requests using wifi of Arduino Primo board? I have bought an Arduino Primo board. I have configured it to connect to my wifi router and changed it to STA mode. Now, how do I program it to send HTTP requests to a server? Which library file I should use? Any tutorial?

With Arduino Primo use the WiFi Link library. Look at WiFi Link Examples in IDE menu.

Arduino org web archive pages


Why is my circuit working only when I touch it? I have connected digital pin 2 of arduino to the circuit as shown:

The problem is that the LED is not turning on normally its only turning on when I touch anything on collector side of circuit. What seems to be the reason? Seems like grounding problem as its turning off when I don't touch my legs to ground.

Thank you in advance.

Sounds like you have guessed it: although it's very hard to say from those photos, it doesn't look like you have the circuit grounded.

Connect a ground from the Arduino to the black wire from the battery.


What is the difference betwen “ESP8266Wifi.h” and “WiFiEsp.h” libraries? I'll start a project using NodeMCU V3 WiFi Module, which uses esp8266 chip. However, I am undecided as to which library to use. I don't want use a serial bridge with an arduino, I think it is better to use NodeMcu in Standalone mode.

So, here's my question: which library should I use? And, regarding the type of use, what is their difference? (both libraries reference looks like the same for me)

p.s.: I also heard about the "WiFi.h" library. Does it work only on WiFi shields for arduino or does it also work on esp8266?

It's quite simple:

ESP8266WiFi.h - Runs on the ESP8266 to control the WiFi.
WiFiEsp.h - Runs on an Arduino to communicate with an ESP8266 module with AT commands
WiFi.h - Runs on an Arduino to work with the Arduino WiFi shield.

So the one you want, which is part of the ESP8266 core, is ESP8266WiFi.h.


What's the problem? My motor works properly only when we press the left key and not others int mf11=13;//motor1 1st terminal
int mf12=12;//motor1 2nd terminal
int mf21=9;//motor2 1st terminal
int mf22=8;//motor2 2nd  terminal
int fr=2;//front key
int bk=3;//back key
int rt=4;//right key
int lt=5;//left key

void setup() {
    pinMode(mf11,OUTPUT);
    pinMode(mf12,OUTPUT);
    pinMode(mf21,OUTPUT);
    pinMode(mf22,OUTPUT);
    pinMode(fr,INPUT);
    pinMode(bk,INPUT);
    pinMode(rt,INPUT);
    pinMode(lt,INPUT);
}

void loop() {
    int s = digitalRead (fr);
    int h = digitalRead (bk);
    int i = digitalRead (rt);
    int v = digitalRead (lt);
    if(s==HIGH) {
         digitalWrite(mf11,HIGH);
         digitalWrite(mf12,LOW);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
    if (h==HIGH) {
        digitalWrite(mf11,LOW);
        digitalWrite(mf12,HIGH);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
    }
    if (i==HIGH) {
         digitalWrite(mf11,LOW);
         digitalWrite(mf12,HIGH);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
   if (v==HIGH) {
        digitalWrite(mf11,HIGH);
        digitalWrite(mf12,LOW);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
   } else {
       digitalWrite(mf11,LOW);
       digitalWrite(mf12,LOW);
       digitalWrite(mf21,LOW);
       digitalWrite(mf22,LOW);
  }
}

The reason your code only works for left, is because when v is LOW your else block gets executed and sets all pins to low! You need to use else if.

if(condition1)
{
  ...
}
else if (condition2)
{
  ...
}
else
{
  ...
}


Cannot get Serial working I've bought a module which should communicate via serial RX/TX. The module and code are described here: https://www.dfrobot.com/wiki/index.php/Weather_Station_with_Anemometer/Wind_vane/Rain_bucket_SKU:SEN0186.

I've hooked up everything as described (using an Arduino Nano instead of an Uno, but the rest is the same) and now trying to get things to work. I could not get any decent output. So I decided to switch to a bare-minimum program to read stuff from the serial port in order to see whats going on. I found the following sample: https://gist.github.com/Protoneer/96db95bfb87c3befe46e and implemented this code (only this).

Now what I see is the following:
- With RX/TX connected the wrong way, when I reset the nano, the serial monitor shows me one instance of the string I'm looking for (as described in the module documentation). When connected the right way, the text is not there but that's to be expected as the nano should receive it (and not the serial monitor). This does however prove that the module is actually sending data.
- Serial.available seems to evaluate to 0 all the time, indicating there is no data to be read from the serial line.

So why would Serial.available return 0 even though there seems to be data being sent to serial, as the monitor does show the string I'm looking for with the pins crossed. I have also tried disconnecting the RX line on the module to prevent statements being sent over serial to interfere with the module. The documentation does not state the need to send anything to the module in order to trigger the response. In fact, if you look at the sample code the first interaction with serial (after Serial.begin(9600)) is Serial.available().

Is there anything else I can do from a debug perspective? As you might notice I'm no expert in this stuff.

It seems you have the module connected to the Nano pins 0 and 1, and are also trying to communicate with the PC via the Serial object and serial monitor?

There is a USB/serial converter chip on the Nano that is likely conflicting with your module. You can try SoftwareSerial to get a bit-banged serial port for communicating with the module on some other pins.


How can I call the constructor of a Class after it called once? I have a problem with Classes.
I have a bunch of code, that code is uses Adafruit MQTT FONA library. I call the Class for make new Instance and Connect to specified server with this code;

Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

When I want to connect to another server, I call this Instance's constructor after it called once. But it don't let me to construct it again. How can I construct the same instance again after it constructed once?

void connectMqtt()
{
    Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
}

connectMqtt();

Thanks for helps! Have a good day!

You can't. Once constructed, an object remains constructed until you delete it.

You could either use dynamic allocation and new and delete to create and destroy objects at will, or you could create multiple objects with different settings and use different objects at different times.

Another option would be to modify the library to create a new function that accepts and assigns new server settings. All the constructor does is store the settings in variables - there's no reason why you couldn't just change those variables.


Arduino Yun not getting response from Azure API I posted this on StackOverflow but figured I'd post it here too. Sorry in advance if thats not allowed.
I'm trying to get my Arduino Yun to talk to an API that I'm hosting on Azure. I would like to do more complex things in the future, but at the moment I'm just trying to make a GET request over wifi with a single integer as a parameter.
I'm basically just using the example found here with the url changed. The example works fine, so as far as I'm aware the issue isn't with my board, its with the interaction with Azure.
HttpClient.get() returns an int as a response (not the regular HTTP response codes, its unique for the library). I got 60 initially, and changing my API to accept http calls (instead of just https) fixed this and made me get a response of 0 instead. 0 is the same response that I get from the working Arduino example, but for some reason I'm not actually getting anything in the body of my response, as the client.available() loop is never entered.
The API works as intended when I go to the url in chrome, so the issue arises somewhere due to how the arduino and azure talk to each other, but I don't know enough about either to figure it out and nowhere that I look seems to point me in the right direction.
Any help would be greatly appreciated, thanks.

Found the problem, even though I set azure to accept http requests, it was still redirecting to https which the arduino couldn't handle. I've written a python script to offload the requests to the linux processor, and now it works.


Arduino Mega 2650 + Matlab/Simulink - Serial decimation I am performing a control analysis on an Arduino board.
As such, I want to minimize the board cycle duration.
(Faster board = faster controller).

Introduction:

I use Mathworks Matlab/Simulink to program the board.
I created a model in Simulink,
and embedded this model into my Arduino Mega 2650.

The model includes an Arduino Serial Transmit block.
I am therefore able to use Matlab software on my PC to request
serial transmission from the Arduino board to Matlab.

The Arduino Mega 2650 has the following serial constraints:

Maximum output buffer: 64 [byte]
Maximum baud frequency: ~115,000 [bit/s]

Problem:

To perform my control analysis,
I want to minimize the board cycle duration, and
I want to read several signals simultaneously.

The time it takes to read all signals sent
(as dictated by the baud rate)
is the primary obstacle in reducing my board cycle duration.

Requested Information:

Is it possible to reduce the board cycle duration
without reducing the duration in which
the serial transmission must be completed.

For example,
what if I run my board at 0.001 [s],
but I can only send all of my signals in 0.010 [s],
what will happen during my reads?

If I read every 0.001 [s], obviously I will not receive all of the data,
as this is not feasible in the time that I am allotting.
My concern is regarding what will happen if I read every 0.010 [s]:

Will the passing of several board cycles before the read completes affect the read?
Is there a method to lock the serial output buffer while reading
(such that the data does not change midread)?
How long does it typically take to refill the serial output buffer with the next set of data?

Conclusion:

Ultimately, I would like to run the board as fast as possible,
since I believe that this could significantly improve my controller's performance,
despite not being able to read these additional cycles.

I don't think there will be a problem in this.

I do not understand exactly why you can only send signals every 0.010 s.

The board runs at 16 MHz, that's 16 million cycles per second, however, every 'instruction' normally takes many cycles (let along parsed C/Arduino language).

What you can do is to copy the read information into an array and use it later.

Keep in mind that the serial buffer is 64 bytes. If more is read, data will be overwritten. However, if you copy the buffer into your own (larger) buffer it might help. Also you can change the 64 bytes (it's somewhere in the Serial library).

The buffer works (afaik) with a sort of circular buffer, meaning it can store 64 bytes maximum 'unprocessed' bytes. So you don't have to wait until the buffer is full before processing (actually, this is not even the best method). You can process it as long as there are bytes available.

The pseudo code can be as follows:

lastSignalSent = millis(); // last time signals sent

void loop()
{
    while serial bytes available
    {
        process bytes
    }

    if (millis() - lastSignalSent > 10) // More than 10 ms ago
    {
        Send signals
         lastSignalSent = millis();
    }
}

This assumes the serial byte processing can be done faster than they arrive, but if not, you run into problems anyway, since the serial buffer (of only 64 bytes) will be full too fast.


config file for Arduino Uno installed on Raspberry PI The Arduino code shown runs successfully. My problem is configuring the Arduino IDE so it fits within the Raspberry Pi window. The second image, the built-in serial port /dev/ttyAMA0, is produced. It is blank.

The Arduino Menu bar cannot be accessed. Therefore, the Tools button and other buttons for running the code are not available. The user can adjust the width of the Arduino IDE window but cannot move it around the screen or up or down.

The /boot/config file is setup up for a Adafruit 5" Backback monitor. No other app, Thonny Pi, or the terminal has these problems.

It appears to me that the config file needs some work. That is only a guess.

Any suggestions will be greatly appreciated.

In Linux you can move things around in different ways. For example:

Hold ALT and click and drag anywhere in the window. The whole window will move and you can get to the edge to resize it.
Press ALT-Space then M and you can use the cursor keys to move the window around
Press ALT-Space then X and it will maximise the window to the screen size


Reed Sensor matrix for chess board query NOTE:
This is not a question that has been answered previously in similar questions.
I am using an arduino Mega

I have gone through Bergers Blog(schematic is in this link), but have been breaking my head on the logic of your sensor matrix, I have been breaking my head for the past few days on this one thing.

Initially he set all rows to HIGH then reset the 1st row to LOW to scan the reed sensors, let's assume that all the sensors in the 1st and 2nd row are closed.

My question is that since the 1st row is set to LOW won't it get shorted because the second row is initially set to HIGH?

Also, I used the same matrix as berger but instead I enabled the internal Pull up pins of all the 8 input pins, but yet again I faced the same problem of getting a short , since if a row 1 is set to LOW and row 2 is initially set to HIGH then One sensor in row 1 is closed and a reed sensor in row 2 below the sensor mentioned in row 1 is also closed. Then won't we get a short and random values show on the arduino.

Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches.  For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing.  A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.

Adding a forward biased diode to every switch in a matrix prevents harmful shorts.  For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches.  However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased.  The diode connected to the row driven low would be reversed biased preventing the harmful short.

Using diodes on every switch is costly.  Most computer keyboard do not use this approach.  Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance.  In reality, almost all computer keyboard have an n-key-roll-over limit.  A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.

For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:


Does Arduino Tian/LininoOS support Python 3? I'm using an Arduino Yun running OpenWRT and it only runs Python 2.7.

I need to find a microcontroller+processor+WiFi board that supports Python 3. Does the Arduino Tian work for this, or are there any others?

Yes, run the following

opkg update
opkg install python3-base_3.4.3-2_ar71xx.ipk


ESP8266-12E and MCP23017 , unable to identify the application After googling much I have found that MCP23017 can be used with esp8266-12e for more number of output pins.
I have tried all the programs from different tutorials on internet but could not make it work.

Basically my question is , i want to control all the 16 leds connected to GPA0-7 AND GPB0-7 individually , hence i need a program snippet for make it work.
I am using AP mode for esp8266-12e and sending get methods with params to identify which led to turn on/off.

Even i have written the basic program , can anyone help me completing the entire program. thanks for the help in advanced.

Pins i have connected are

ESP8266-12E    |   MCP23017
−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−
GPIO-14 (scl)  |  PIN-12 (SCL)
GPIO-2 (sda)   |  PIN 13 (SDA)
GND            |  A0,A1,A2

My code:

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

ESP8266WebServer server(80);

void handleRoot() {
    server.send(200, "text/html", "
You are connected
");
}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);
    server.on("/", handleRoot);

    server.on("/led1", [](){});
    server.on("/led2", [](){});
    server.on("/led3", [](){});
    server.on("/led4", [](){});
    // up to 16 leds i have written same method.

    server.begin();
}

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

You have an MCP23017 which connects to the device using the I2C protocol, which means you need the  library.  You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line.
You will then need to send commands to the device to initialise it and set the pins to OUTPUT.  (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).

When running you will need to update the state of this pins by sending messages such as  0x09 0xFF to turn them all on.

It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard.  You will be able to use an Arduino library on an ESP8266.

These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)


Arduino code to control 4 led's from 4 buttons This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.

The code I've written:

const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin

void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}

void loop() {

buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:

// check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.

if (buttonState1 == HIGH) {    //check buttonState
digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, LOW);   // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) {   //check buttonState
digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, LOW);   // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) {   //check buttonState
digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) {   //check buttonState
digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.

I've attempted to edit some of the code in the example sketches to get this to work.

Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.

It is likely you have connected the switches incorrectly.  Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.

Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.

Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at this arduino.cc web page. There this sample code shows how to activate the processor's pull up on pin number 2:

pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.


Best way to interact arduino and python So, i've worked with the pySerial module for python, where I communicated with my arduino via serial. However, this module only works for 32bits and I would like to make my project work on both architectures (I know the person could just install the 32-bits version on the 64-bits architecture). Also, the connection fails a lot of times and I wasn't able to correct it.
I think I can use the true USB power of the arduino Leonardo to connect to the python in a different way, but I don't know where to start. But I think this approach will be more professional.
Im really intersted in learning, so if you guys could at least indicate documents so I can understand how to make this connection between Leonardo and Python, I'll be happy. I've read the arduino page about the CDC but couldn't find useful information.

Thank you so much.

Update:

When i used serial, I had problems with messages getting acumulated at the buffer, and then after some seconds i was reading 10s delayed messages. Also, when I sent a string like: "12345678", it was really easy to get one number less, like: "1345678". This happened frequently to me. So I think I need to implement a protocol to deal with these problems.

I did some work in Java using USB some years ago and I can share some experiences:

Things are not neary as straightforward as using serial.
Your code will probably be platform specific, windows being a bit more weird about handling usb. (unless using something to abstract that away, like PyUSB which wraps libUSB or openUSB, this however does not guarantee platform independency because these libraries also have their weirdnesses).
If you drop down to USB level programming, things can get very messy (again, this can be abstracted away). USB is (at least in my opinion) a complicated protocol, especially for beginners.

So unless you really need something that only USB can provide, a nice and dandy serial communication will give you much less headaches. Thats why serial did not die until now.

As for debugging why your communication is not reliable I would try several things:

See if your application might send something that is interpreted as a control character
Drop your baud rate to something lower and see if it still loses data. If so, you might overflow the buffer of your receiver (and you would need flow control in this case)
Check your hardware! I've had bad wires or solders on numerous occasions


Replacement crystal on Uno for cold temperatures I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?

P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost

There is a solution for just this problem, it's a "crystal oven". It is used to keep a crystal at a constant temperature so that the oscillating ferquency remains very stable.

Crystal ovens are usually expensive as they are quite precise and have good insultaion, but here's a kit that you might adapt for your uses: http://www.minikits.com.au/Oscillator-Heater, or google around to see if you find something that might suit you better.

You could also consider making a heater with a simple temperature regulator of your own to keep the crystal warm  (many temperature sensors for Arduino are available on the web).


fatal error: ESP8266WiFi.h: No such file or directory I used platformio IDE
I did "platformio lib install 1101"
(http://platformio.org/lib/show/1101/ESP8266wifi),
I installed this: http://platformio.org/lib/show/549/WebSockets (follow instructions)
I did similar things to other libraries.
When I click the platformio:build button, it still complains:

fatal error: ESP8266WiFi.h: No such file or directory fatal error:
ESP8266WiFiMulti.h: No such file or directory fatal error:
ESP8266Webserver.h: No such file or directory

Have you overridden lib_dir in platformio.ini? If yes, please remove it.


'Serial1' was not declared in this scope Trying to do serial communication between 2 Arduino Unos.

Code:

#include <SoftwareSerial.h>

int ledPin = 13;
int board;   // 1 = Uno. 2 = Mega.
int on_off;  // 1 = On. 0 = Off.
int buzzerPin = 9;
int Ack_tx = 2; //Acknowledgement tx.
int rec;

void setup()
{
  Serial.begin(9600);      // start serial communication at 9600bps
  Serial1.begin(9600);     // start serial1 communication at 9600bps

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  Serial.flush();
  Serial1.flush();

} // End Setup

void loop()
{

  Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
  //  if(!Serial){ board = Serial.read();}
  while(Serial.available()==0) { // Wait for User to Input Data
  }
  board = Serial.parseInt();  //Read the data the user has input

  Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
  while (Serial.available()==0) { // Wait for User to Input Data
  }
  on_off = Serial.parseInt();

  Serial.println();

  switch (board) {

  case 0:  //Mega board
    if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
    else digitalWrite(ledPin, LOW);              //Select Uno LED Off
    break;  //End Case

  case 1:  //Uno board
    //Serial.println("Off to Uno...");
    //Send on_off info to Uno
    Serial1.write(on_off/256); //Send the Quotient or "how many times" value
    Serial1.write(on_off%256); //Send the Modulo or Remainder.
    delay(50); //Wait for the serial port.

    while(Serial1.available()<2) //Wait for 2 bytes to arrive
     {
      //do nothing
     } //End While

  byte b1=Serial1.read();  //Read Upper byte
  byte b2=Serial1.read();  //Read Lower byte
  rec=(b1*256)+b2;

    if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
    break;
  } //End Switch Case

}

Error:

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

sketch_mar06a:13: error: 'Serial1' was not declared in this scope

   Serial1.begin(9600);     // start serial1 communication at 9600bps

   ^

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

sketch_mar06a:51: error: 'Serial1' was not declared in this scope

     Serial1.write(on_off/256); //Send the Quotient or "how many times" value

     ^

Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
 Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
exit status 1
'Serial1' was not declared in this scope

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

This is a very basic problem I know, but nothing on the internet is helping.

The Uno has no Serial1. It only has one serial port, called Serial. To use Serial1 you will need a bigger board such as a Mega2560, or define it as a SoftwareSerial port and use two other IO pins of your choice for it, though at lower baud rates than Serial can run at.


System voltages: Can I use a 5V touchscreen shield on a 3.3V arduino? The system voltage on my arduino 101 is published at 3.3V, even though it also has a 5V output pin.

My Seeedstudio touchscreen is supposedly a 5V device. http://wiki.seeed.cc/2.8inch_TFT_Touch_Shield_v2.0/

I believe I've successfully ported the library for this touchscreen to the 101 because it now runs and compiles on both the 101 and the Mega, although it gives erroneous values on the 101. Could it be because of this voltage difference? is there any way to fix it?

Edit- I should add that the 101 is labeled as "5V tolerant".

Edit II: I've found a pretty informative review that explains a little bit about how the 101 is supposed to work with 5V peripherals. I'm not sure though how it could work in cases where a shield does not recognize 3.3V as logic high. Usually 3.3V is right around the cutoff voltage for many circuits. http://www.tweaktown.com/reviews/7706/intel-curie-based-arduino-101-programmable-microcontroller-review/index2.html

You'll probably need a fairly common device known as a logic level converter.  One such example, in breakout board form, can be found here: https://www.sparkfun.com/products/12009

There are tons of other options depending on what exactly you need.


Arduino onboard LED pin number as a constant To use the onboard LED on an Arduino one usually has to know the pin number (13 in most cases), but is there a constant in the Arduino IDE one can use as well?

So is it possible to use something like int LED = ONBOARDLED; instead of using int LED = 13;?

Try LED_BUILTIN:

pins_arduino.h:static const uint8_t LED_BUILTIN = 13;


RobotLinking 18B20 pinout and circuit board weirdness I have a Dallas Semiconductors 18B20 temperature sensor on a RobotLinking board. It's part of the RobotLinking 37 Sensors Kit. The board has a LED to indicate activity. It resembles this:

Here's what's weird. All the guides I can find for the 18B20 say that the pin order is GND, DQ, VDD. That should mean pin 1 goes to GND, pin 2 goes to a GPIO, and pin 3 goes to 3.3V or 5V (this one can take either). Yes, I am looking at the sensor's pins from its bottom.

If I do this, the board's LED is lit solidly. I get 0 degree readings, the same as if no device was connected. (Infinite resistance?)

To make this work, and get valid temperature readings, I have to hook it up this way: sensor GND to the GPIO, sensor DQ to GND, and sensor VDD to 5V or 3.3V. The LED only flashes when the temperature is actually read.

Here's a twist: if you look at the circuit traces on the RobotLinking board, it looks like the paths between the male breadboard connectors and the sensor's pins 2 and 3 are reversed. This means if you think you are connecting to pin 3 via the male connectors, you are in fact connecting to pin 2, and vice versa. The path from pin 1 on the sensor to the male pin 1 where it plugs into the breadboard is straight, so pin 1 probably means pin 1.

When I described the above connections I made, I accounted for this apparent circuit pathing weirdness.

Another twist is in the manual, the sensor is soldered to the middle leads. My sensor is instead on the furthest leads from the pins, like in the attached image.

The manual with this kit didn't explain any of this. I'm at a loss to understand my observations. For a generic sensor kit for n00bs, why would one want the pins on the bottom of the circuit board not correspond to the pinout of the sensor?

From the look of the board, it is designed to support multiple devices. I'd suspect that the three sets of holes give different mappings of the device pins to the board pins. Could it be that the sensor is soldered into the wrong set of holes?

If you have a meter or can see the traces you could look to see if the middle set of holes is wired the way you would expect. If that is a photo of your board, it looks like you have enough length in the leads on the sensor to move it to the middle holes.


Different behavior than in simulator: 5V pin works instead of GND. Why is that? I use this simulator to check if what I want to do works. This is how it looks like:

I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.

When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.

Why do you think there are some differences? Can I use 5V pin instead of GND if it works?

My Arduino: Arduino Leonardo.

The RGB LED's are available with common cathode and common anode.  That determines whether you connect the common pin to ground or to +5.

In your schematic you likely mismatched the selected part to what you actually have.  If you have the opposite type of LED as planned, just reverse the connection as you did.  You are not alone in this type of mistake.  see similar whot? here

A digital multimeter with a diode test mode would be very useful here.  The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground.

But did it really work correctly?  Don't you also see that you have to write LOW to the digital output to make the LED light up?


How to pass variables to custom callback functions I want to use the Ticker library of the ESP8266 Arduino core to (asynchronously) delay the switch of a pin to a desired state like below. I am not sure about the "here is" function definitions and I am having a hard time to find some documentation. Please have a look at what I tried so far:

#include <Ticker.h>

Ticker change_pin;

...

    uint8_t desired_state = 1;
    ...
    change_pin.attach_ms(100, [](uint8_t state_to_change_to){
        if( digitalRead(PIN) != state_to_change_to ) {
            digitalWrite(PIN, state_to_change_to);
        }
        else {
            change_pin.detach();
        }
    }, desired_state);

But the compiler's yelling:

espIKEA:145: error: no matching function for call to 'Ticker::attach_ms(int, toogle_light(uint8_t)::__lambda0, uint8_t&)'

   }, des_state);

               ^

...

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:45:7: note:   candidate expects 2 arguments, 3 provided

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note: template<class TArg> void Ticker::attach_ms(uint32_t, void (*)(TArg), TArg)

  void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)

       ^

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note:   template argument deduction/substitution failed:

C:\Users\USER\Documents\Arduino\Scratch\pintest\pintest.ino:145:15: note:   mismatched types 'void (*)(TArg)' and 'toogle_light(u8)::__lambda0'

   }, des_state);

               ^

So, I am having too few knowledge to understand what to do about it. I really would like to avoid having a separate function for the callback body.

PS: Important source file can be found here: Ticker.h

The function you are trying to call is a template function:

template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
    ....
}

So, you need to tell it what type of parameter you are passing:

change_pin.attach_ms<uint8_t>(100, [](uint8_t state_to_change_to) {
//                     ^- tell the compiler about the parameter
    ....
}, desired_state);

To pass more than one parameter: Since the library only allows one parameter, I would create a struct and pass a pointer to it.

struct callback_parameter {
    int i;
    char *p;
};

Then create one of these structs and pass the address of it. You just have to make sure the struct is valid the entire time the timer is running. So either use new, static, or make it global.

callback_parameter param; // global variable

...

change_pin.attach_ms<callback_parameter *>(100, [](callback_parameter * state_to_change_to) {
    ....
}, &param);


Put Arduino in DFU mode (no RST pin) The instructions to put the Arduino into DFU say I should shortcut briefly the 2 leftmost ICSP headers next to the USB port.

But my board does not have them. Does anybody know what are the right headers or if it is at all possible to set my board into DFU mode?

This board doesn't use as USB adapter an ATMega16u2 with Arduino firmware. It uses a simple USB chip CH340. So you can't put it in DFU mode to upload a firmware.


Error while updating ThingSpeak using SIM808 im trying to update ThingSpeak from a SIM808 but I'm getting a network error. Please check below and let me know if there is anything wrong in my methodology.

I'm using terminal.exe to send commands via RS232.

AT
OK
AT+CREG?
+CREG: 0,5 //connected in roaming
AT+SAPBR=3,1,"Contype","GPRS"
OK
AT+SAPBR=3,1,"APN","www" //VODAFONE INDIA "www" is APN (as per the operator)
OK
AT+SAPBR=3,1,"USER","" //blank (as per the operator)
OK
AT+SAPBR=3,1,"PWD","" //blank  (as per the operator)
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
AT+HTTPPARA="CID","1"
OK
AT+HTTPARA="URL","https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE"
OK
AT+HTTPACTION=0
+HTTPACTION: 0,603,0

Note: while I'm typing in the browser url box, https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE, I can update my field. I can make calls, send SMS. I have an internet pack.

Please help.

It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE" (from https:// to http://)


Using NodeJS, socket.io and Adafruit HUZZAH CC3000 breakout board to control Arduino wirelessly? I'm looking to build my a wirelessly controlled lamp and have a few questions. Would I be able to use the Adafruit HUZZAH CC3000 breakout board to receive commands from a website and control a connected lamp?

I just set up a NodeJS server with webpage on my PC and using socket.io and Firmata I was able to communicate with the Arduino using the webpage over a serial connection. Could I set up similar implementation except instead of communicating over serial I'd communicate using Wifi? Would I need to host a web server on the Wifi board itself to communicate with the Arduino or is there some way to just use the wifi board as a communication between external site and Firmata?

I happen to have received the CC3000 shield yesterday and have been playing with it today...

What do you mean by "receive commands from a website"?

If you mean "can it serve a simple website and act upon HTTP requests" (e.g. requests to http://arduino.local/on would turn a lamp off and http://arduino.local/off would turn if off), then yes it can. You make the HTTP requests using javascript's XMLHTTPRequest if you want to be able to communicate from within a web page without having to re-render a page.

There is an example sketch of an HTTP server included in the CC3000 library that would get you started. Note that the example HTTP server sketch can only handle one HTTP request/response at a time.

You will obviously also need some way of controlling a relay of you want to control a lamp.

Update: Since you updated your question to include how you are currently communicating:

I'm not familiar with socket.io or Firmata, but I'm guessing socket.io is a way of getting your web client (browser) to talk directly Firmata which talks to your Arduino over the USB-Serial connection? If so, then I'm not sure if it's possible to use the Firmata protocol over wireless, but it is possible for the CC3000 to act as a generic TCP server and act on data that it receives wirelessly, so it might be possible to communicate between socket.io and the TCP server. The EchoServer sketch shows how to set up a TCP server to receive raw data.

If you're only turning a lamp on/off you basically only need to control 1 pin. Isn't Firmata a bit overkill for that? Be careful about sketch size. I'm not sure how big Firmata compiles to, but the wireless library with some kind or server is over 22,000 byes (of a possible 32,000) on an Uno, so you might struggle to fit both on.


Are there any signal smoothing libraries for Arduino? I am working on a mobile robot controlled via a wireless 2.4 GHz link.The receiver is connected to the Arduino Uno which serves onboard as the main controller. The most critical (and main) input channel coming from the receiver produces a very noisy signal, which leads to lots of minor changes in the output of the actuators, even though these are not needed.

                    Plot of the input of the Arduino in a 30 second interval.

I am looking for libraries that can perform efficient smoothing. Are there any signal smoothing libraries available for the Arduino (Uno)?

Microsmooth is a lighweight signal smoothing library currently being developed by me.

It is still being worked on and the aim is to make it lightweight in terms of memory and fast. The library provides multiple filters for smoothing:

Simple Moving Average
Exponential Moving Average
Cumulative Moving Average
Savitzky Golay Filter
Ramer Douglas Pecker Algorithm
Kalmogorov Zurbenko Filter

To use the library, download and add it to the source directory. Also, add the following line to your source file:

#include "microsmooth.h"


What is better: one sprintf() or multiple strcat() and itoa()? I was creating Arduino function which sends two int and additional chars between them and at the beginning and end of char array - then print that array to the serial port in almost real time. (For example "X50Y100T".)

I don't want to use String object in Arduino and I found two possible solutions:

Using sprintf():

char sendBuffer[16];
void dataSend(int first, int second) {
  sprintf(sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
};

Or something like this:

char sendBuffer[16];
void dataSend(int first, int second){
  char convert[6];
  sendBuffer[0] = 'X';

  itoa(first, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'Y';

  itoa(second, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'T';

  Serial.println(sendBuffer);
  memset(sendBuffer,0,sizeof(sendBuffer));
};

My question is - which one is better from technical point of view?

The sprintf() looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of sprintf()? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of char array?

Why do you feel you need to use either method? Neither are needed. Just print the individual parts:

Serial.print('X');
Serial.print(first);
Serial.print('Y');
Serial.print(second);
Serial.println('T');

No intermediate buffers, just sending the data direct out to the UART.


Arduino Mega's 4 Serial Ports? I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


Serial communication with two devices I have two devices connected to my Arduino using the SoftwareSerial library. However, it seems that they cannot communicate at the same time. I can only communiate with both by switching between which one I am listening to every 1000ms (they poll for 1500ms), but this slows down overall communication significantly. Is there anyway to communiate with both at the same time? Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

See SoftwareSerial Write to return Read in Serial Monitor? - SoftwareSerial cannot both read and write at the same time.

However HardwareSerial can.

  Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?

Yes.

  So, likewise, there is no way to read from both devices using only SoftwareSerial?

That is correct. Not at the same time. SoftwareSerial uses an interrupt to detect the start bit of incoming data. So far so good. But once it gets it, it leaves interrupts disabled while it goes into a timed loop to read all the bits.

Thus, it is impossible for it to react to another incoming byte on another pin at the same time.

Still, you could receive on SoftwareSerial on one pin, and HardwareSerial on another. With HardwareSerial the hardware will run in the background, receiving the byte.


How to close humidity sensor at specific humidity I am using dht humidity and temperature sensor on arduino and i would like to add relay and buzzer on the system. What I would like to do is to close it via buzzer and on 65% humidity run buzzer. The code i use is:
/* DHT-22 sensor with 12c 16x2 LCD with Arduino uno
   Temperature and humidity sensor displayed in LCD
   based on: http://www.ardumotive.com/how-to-use-dht-22-sensor-en.html and
   https://www.ardumotive.com/i2clcden.html for the i2c LCD library by Michalis Vasilakis
   Recompile by adhitadhitadhit
   Notes: use LCD i2c Library from link above, i'm not sure why but new Liquidcristal library from Francisco Malpartida  isn't working for me
   other thing, check your */

//Libraries
#include <dht.h> // sensor library using lib from https://www.ardumotive.com/how-to-use-dht-22-sensor-en.html
#include <LiquidCrystal_I2C.h> // LCD library using from  https://www.ardumotive.com/i2clcden.html for the i2c LCD library
#include <Wire.h>
dht DHT;

//Constants
#define DHT22_PIN 2     // DHT 22  (AM2302) - pin used for DHT22
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 after finding it from serial monitor (see comment above) for a 16 chars and 2 line display

//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{
    Serial.begin(9600);
    lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setBacklight(HIGH);
}

void loop()
{
    int chk = DHT.read22(DHT22_PIN);
    //Read data and store it to variables hum and temp
    hum = DHT.humidity;
    temp= DHT.temperature;
    //Print temp and humidity values to LCD
    lcd.setCursor(0,0);
    lcd.print("Humidity: ");
    lcd.print(hum);
    lcd.print("%");
    if (humidity <= 50)
{
   digitalWrite(ledPin, HIGH);
   digitalWrite(buzzer, HIGH);

 }

 else

 {

 digitalWrite(ledPin, LOW); digitalWrite(buzzer, LOW);

    lcd.setCursor(0,1);
    lcd.print("Temp: ");
    lcd.print(temp);
    lcd.println("Celcius");
    delay(2000); //Delay 2 sec between temperature/humidity check.
}

How to add relay and buzzer to close it with buzzer run on 65% humidity value?

In this code:
void loop()
{
   sample temp and humidity;
   display temp;
   display humidity;

   if humidity <= 50
      LED on;
      buzzer on;
   else
      display temp
      wait 2 sec
   end

There is a missing '}' to to close the if/else.
Why do you display temp twice within the loop?
Where is the logic for the relay and the buzzer at 65%?
Pin numbers for the LED and the buzzer are undefined.
The LED and buzzer pins need to be set to OUTPUT mode in your setup() function.

If I understand your description, you probably need somethng like the following, in your loop function:
   if humidity <= 50
      LED on;
      buzzer on;
   else if hum >= 65%m
      close relay;
      buzzer on;
   end

When I have a problem with program logic that isn't obvious to me, I write it out in pseudo-code as I did above. Once I figure out the logic, then I'll type in C++ with proper syntax.
If I haven't understood your intentions in the above pseudo-code, I'd suggest you do the same thing, until you believe what you've written. Only then try to make it into working code.


Need lot GPIO pins on arduino mega - what are restrictions? I would like to use as much as possible GPIO pins on Arduino Mega especially with (mis)using pinMode(x,INPUT); and pinMode(x,INPUT_PULLUP); to achieve two things at the same time - drive something else by the pin weakly down or up and measure the logical level there with digitalRead(x) to detemine, if that "something else" is input, or outputting some logical level.

Also I need I2C, Serial over USB and nothing else.

On Arduino UNO/nano/micro/pro it works just fine for Digital pins (except D0/D1 (RX/TX), D13 (LED as strong pull-down), A4/A5 (I2C) and A6/A7 which are not digital IO). The problem is limited number of pins, so I bought ArduinoMega.

The question is - which pins can be used that way there?
So far I am aware of D0/D1 (RX/TX), D20/D21 (I2C) and D13 (LED).
The rest (D2-D12, D14-D19, D22-D52 and A0-A15) seem aviable and usable.
Or I am missing something else?

Are there some libraries/objects I should disable to not interfere with my script?

Thank you.

All those pins should be available. But if you want to use Pin change interrupts, you have to check which pins are usable.


How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins? According to this:

  The Servo library supports up to 12 motors on most Arduino boards and
  48 on the Arduino Mega. On boards other than the Mega, use of the
  library disables analogWrite() (PWM) functionality on pins 9 and 10,
  whether or not there is a Servo on those pins. On the Mega, up to 12
  servos can be used without interfering with PWM functionality; use of
  12 to 23 motors will disable PWM on pins 11 and 12.

However, according to this:

  Digital I/O Pins 14 (of which 6 provide PWM output)

So how can the Uno control more than 6 servos if it only has 6 digital I/O pins that can provide PWM output?

Although I haven't looked at the source myself, in these types of situations they usually use interrupt timer 1, which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM on any digital pin, although it's not as good as the built in PWM options.

(source: bansky.net)

(Source)
The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.


What does an arduino sketch translate to before compilation? I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the .ino file usually looks like this:

#include "Arduino.h"
#include "ESP8266WiFi.h"
##Some includes

void setup()
{
...
##Will be only run once at the begining.
}

void loop()
{
##Runs this code in a constant loop
}

My assumption is that somewhere behind simplification, before the compilation takes place, there is a full blown source file. It includes the platform specific initialization and contains the calls to setup() and loop(). When I say full blown source file I mean something that can be passed to the compiler and will compile given that the dependencies are met.

My questions are:

Is this assumption correct?
If so, can someone share an example on how does the full blown source file look like, and where did you get it from?

The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like digitalWrite and so forth.

There is a main.cpp file that gets compiled which is pretty much nothing more than:

#include "Arduino.h"

int main(void) {
    //Initialise timers and things (internal)
    init();
    //Your initialisation stuff (setup)
    setup();
    //Loop forever
    for (;;) {
        //Calling your loop function
        loop();
    }
}

In terms of what your .ino file becomes, it is basically just copied to a temporary build directory and renamed to .cpp. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.

This process is actually why if you use your own header file which has some typedef in it which you then use in a function call, the code will break because the declarations get added above the #include statements meaning the custom type is used before it is defined.

If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the .cpp file with the same name as your .ino file.


`LOW` being defined as `0` and `HIGH` being defined as `1` - is this a part of external specification? Arduino.h defines LOW as 0x0 and HIGH as 0x1. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?

In other words, what is the intended purpose of these manifest constants: LOW and HIGH?

Is this purely cosmetic mnemonics added as an alternative for 0/1 and false/true, for those who like LOW/HIGH better?
Or is this an attempt to abstract/isolate the user's source code from the actual representation of LOW and HIGH (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

The underlying reason for this question is to figure out whether code like

digitalWrite(some_pin, true);
digitalWrite(some_other_pin, !digitalRead(some_other_pin));

  is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.

digitalRead() returns an int. digitalWrite() expects an int.  Using ! converts the int into a bool and then it's promoted back to an int again.

In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple int to an enum - and that struggles with casting through bool like that:

typedef enum {
  LOW     = 0,
  HIGH    = 1,
  CHANGE  = 2,
  FALLING = 3,
  RISING  = 4,
} PinStatus;

You can see the problems that causes here.


PushButton as LED Switch (does not work) #define LED 1//This pin goes to the LED
 #define SWITCH 7//From Switch$

void setup() {
      pinMode(LED,OUTPUT);
      pinMode(SWITCH,INPUT);
}
int state=0;//Initializing values of all three
int val;
int lastval=LOW;

void loop(){
      val=digitalRead(SWITCH);//Reads if switch is on or off
      if(val==HIGH&&lastval==LOW){//Basically activates if the button was just pressed
        state=1-state;//Changes state after button is pressed
        digitalWrite(LED,state);//Enforces changed state to LED on or off
        delay(50);//Just a simplistic debouncing
      }
      lastval=val;//Store last value
}

Based on your response to my comment, it sounds like you have a floating input.  When the button is NOT pressed, the pin isn't connected to ground or 5V so it is floating and picking up whatever stray electrical signals happen to be bouncing around the room.

The easiest way to handle buttons on an Arduino is to wire them between the pin and ground.  Then in the code you use INPUT_PULLUP instead of INPUT for the pinMode call.  Once you've done that then the pin will reliably read HIGH when the button is NOT pushed and will read LOW when the button IS pushed.  Note that this is backwards of how newbies tend to think, but is really the more common way to handle a button.