Calibrate motors using arduino I'm trying to create a car that's being controlled by an Arduino.
I'm using the following chasis:
http://www.aliexpress.com/item-img/New-2WD-car-chassis-DC-gear-motor-wheels-easy-assembly-and-expansion-car-toys-robot-toys/32310649967.html

And L298N motor driver.

The problem is it's hard to make the car go straight. Giving the same PWM value to the motors still makes them spin in different speeds, trying to calibrate the value is hard and every time I recharge my batteries the value changes.

What are my options on making the car go straight when I want (well, sometimes I'll want to turn it around of course)?

I've thought about using an encoder but I wish to avoid that since it will complicate the whole project, is there any other viable option? and even when using an encoder, Does it means I will need to keep track all the time and always adjust the motors value continuously? is there some built-in library for that?

Thanks in advance!

I used a simple optical encoder and the little disks that came with my kit.  The encoders cost < £1 for 2 of them.

Failing that use an accelerometer and measure the lateral motion, should also cost about £1.


How to post JSON data from Arduino? I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.

For example:

if data=15, it is converting into string.

String st=String(data);

Now I want to post st every 5 seconds.

    int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
    Serial.print("Sensor Status: ");
    Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).

Can anyone help me with this issue?

Thanks in advance.

The string

"{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:

"{\"AssetSensorDistance\":\""+st+"\"}"


Hall Effect Current Sensor Wiring I need help with wiring this current sensor so that I can read the output voltage as an analogue input. - http://www.tamuracorp.com/clientuploads/pdfs/engineeringdocs/L03SXXXD15.pdf

This is how I have it wired right now -
1 - +15v
2 - 15v ground
3 - output to arduino
4 - arduino ground

This seemed simple but reviewing the wiring diagram again I have a hunch that this is not at all how I should be wiring this up.

Thanks

Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.

I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).

What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.

Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with analogRead.

Something like this:

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.

With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

As Majenko pointed out, there is a voltage drop over the diode. You can make a Precision Rectifier out of an op-amp and a few other parts, like this:

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).

If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.


RS232-TTL Data Transmission I'm developing an computacional module to create risk maps in agriculture, I am using one arduino mega as "GreenSeeker", generating "fake" data to transmit via RS232 connection to one Raspberry PI, where she is process the data and generate the maps with GPS coordinates.

But, I have this cable.

I need to transmit data throught Arduino mega, and catch this data in the Raspberry PI.

I`ve have doubt about where connect the Serials pins on Arduino, the USB go on connect on the Raspberry PI USB, and the Serial go on Arduino, i need the right pins and where to connect them, and some code example.

I think you just want a normal USB A-B cable, exactly like you'd use on a PC.

You probably could use the cable you picture, but you'd need a female DB-9 connector.  If you really want to do that for some reason, you need to connect the Tx pin on the DB-9 (pin 2) to the Rx pin on the Mega, and the Rx pin on the DB-9 (pin 3) to the Tx pin on the Mega.


Nodemcu 1.0 and boot mode (1,6) after soft reset I have a problem with a nodemcu 1.0 (lolin) board. Sometime a soft reset is performed from the watchdog and the board freezes in boot mode (1,6) (I have to manually reset the board to restart it).
I have read many thinks on this topic and I have carefully avoided to use the GPIO0, GPIO2 and GPIO15. I have also verified that these pins are correctly pulled-up (GPIO0 and GPIO2) and pulled-down (GPIO15) but when the board frezes I have noticed that the voltage of the GPIO0 is not 3.3V but 2.0V.
Has anybody experienced a similar problem? Could you help me in solving it?

I wish you all a happy new year.
Cheers.

The esp8266 has a bug (documented). After Serial upload the program is started without reset and then at soft reset the state of "start bootloader" is still active.


Why am I getting this error- "exit status 1 expected ';' before '{' token " void setup()
{

  pinMode{13, OUTPUT};

}

void loop() {

  digitalWrite{13, HIGH};

}

Try parentheses instead of curly braces:

void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

}


Why I cannot change array values even if a statement is successfully called? TFT Touch Screen #include <Adafruit_GFX.h>    // Core graphics library
#include "LGDP4535.h" // Hardware-specific library
#include <zTouchScreen.h>
#define BOXSIZE   40
// Assign human-readable names to some common 16-bit color values:
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

LGDP4535 tft; // Using the shield, all control and data lines are fixed

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

// You need to calibrate to fit your LCD
#define TS_MINX 930
#define TS_MINY 903
#define TS_MAXX 142
#define TS_MAXY 117

#define PENRADIUS 3
#define MINPRESSURE 10
#define MAXPRESSURE 1000

int matrix[2][3]; // Initial Declaration
int array[3]

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// array = start with 1 but the variable read start with 0
String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"};
boolean ActiveMenu=true;

void setup(void) {
   Serial.begin(9600);
   tft.reset();
   tft.begin();
   ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE);
   tft.fillScreen(BLACK);
   DrawIt(CYAN, "draw");
   DrawIt(BLACK, "text");
}

void loop() {//SOME OTHER STUFF}

unsigned long DrawIt(uint16_t color, String CurrentAction) {

  int timedcycle=0;

  if (CurrentAction == "text") {
     int matrix[2][3]={{25,150,265},{45,100,155}};
     int array[3]={3,3,3};

     tft.setRotation(3);
     tft.setTextColor(BLACK);
     tft.setTextSize(1);

     Serial.println("Text Columns");
  }

  else if (CurrentAction == "draw") {
    int matrix[2][3]={{260,140,20},{40,150,95}};
    int array[3]={3,3,3};
  }

  Serial.println(CurrentAction);

  for(int j=0; j<3; j++) {
     for(int i=0; i<array[j]; i++) {

       if (CurrentAction == "draw") {

         if (timedcycle == 7) {
           tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color);
         }

       }
       else if (CurrentAction == "text") {
         if (timedcycle == 4) {
           true;
           //tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.setCursor(matrix[0][j], matrix[1][i]);
           tft.println(ButtonAction[timedcycle]);
         }

       }
     timedcycle++;
     }
  }
}

So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value.

If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.

I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!

It's because you are defining a new array every time, not modifying the existing one.

int matrix[2][3]={{25,150,265},{45,100,155}};

That line doesn't assign new values to the existing matrix array, instead it creates a new array called matrix which only exists within the current scope - that is, within the {...} defined by the if that it is within.

Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use {...} to assign them in bulk):

matrix[0][0] = 25;
matrix[0][1] = 150;
... etc ...

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them.  This can be done with the right kind of pointer. For instance:

int textMatrix[2][3] = {{260,140,20},{40,150,95}};
int (*matrix)[3];

void whateverTheFunctionIs() {
    if (whatever...) {
        matrix = textMatrix;
    }
}

In that example matrix is a pointer to an array of pointers, which is basically what a 2D array is internally.  It starts off by not being assigned to anything at all - it's just "dangling in the breeze".  When the if in your function is triggered the address that the matrix pointer points to is changed to that of the textMatrix 2D array, so any access to matrix[x][y] will be identical to accesses to textMatrix[x][y].


Prevent hardware and library examples from showing in the Sketchbook menu I have various subdirectories in {SKETCHBOOK}/hardware/ and {SKETCHBOOK}/libraries/ that contain an examples/ subdirectory. These examples are showing up in File | Sketchbook | hardware and File | Sketchbook | libraries. Is there any way I can prevent them from showing up in that menu without moving them under the system-level Arduino directory?

Looking at the code it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.

The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.


Hc-05 bluetooth module pairing issue Module light is blinking/working but it's not showing for pairing in my smart phone.I have supplied it 3.3 volts and have tried different phones.

It won't pair directly you will need other apps for pairing the modules. Try using this app. It will solve your issue for sure


the code and the actual output didn't match i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.

  int hasil
  int reado;
  int z;
  int baca;
  bool en = false;
  void setup() {
  // put your setup code here, to run once:

  TCCR1A = 0b00100010;
  TCCR1B = 0b00011001;
  TCCR0A = 0; TCCR0B = 0;
  ICR1 = 100000;//disable millis, delay and mciroseconds function
  //disable millis, delay and mciroseconds function

   // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(A2, INPUT); pinMode(A3, INPUT);
  pinMode(9,OUTPUT); pinMode(10,OUTPUT);
  }

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

 hasil = analogRead(A2);
 baca = digitalRead(A3);
 for (z=0; z<=hasil; z++)
 reado = map (hasil, 0, 255, 0, ICR1);
 if (hasil > 30 && baca == HIGH)
 {analogWrite(9,hasil); analogWrite(10,0);}
 else if (hasil >30 && baca == LOW)
 {analogWrite(9,0); analogWrite(10,hasil);}
 else if (hasil<30)
 {analogWrite(9, 0);
 analogWrite(10, 0);}}

You wrote:

  when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's
doing exactly what you asked for: a PWM output that switches between two
different output pins. The program should work as expected, with only a
few caveats. Let me comment it in some detail:

ICR1 = 100000;

Here you are setting ICR1 to 34464 (i.e. 100000 modulo
216). This is likely not what you mean...

Serial.begin(115200);

There is no point in initializing the serial interface if you are not
going to use it.

for (z = 0; z <= hasil; z++)
    reado = map(hasil, 0, 255, 0, ICR1);

There is no point in calculating many times the exact same value.
Actually, there is no point in calculating it even a single time, since
you are not using the result anywhere in your program.

analogWrite(9, hasil);

Here you are setting the duty cycle to some number between 31 and 1023.
Given that the top value of the timer is 34464, the actual duty cycle
will always be less than 3%. This is the reason why it looks like a
series of narrow spikes on the virtual scope.

But maybe what you really meant is

reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
analogWrite(9, reado);

I would not recommend using analogWrite() with a non-standard top
counter value. There is a special case handled in analogWrite() where,
if the argument happens to be 255, you get instead a
digitalWrite(pin, HIGH). This is most likely not what you want. Now
that you started controlling the timer with raw IO access, you should
continue this way.

else if (hasil < 30)

Did you consider what the program should do if hasil happens to be
exactly 30? None of the if/else cases would then match. You probably
meant

else if (hasil <= 30)

but, as suggested by user11249082's answer, a plain else is the best
way to ensure you did cover all possible cases.


Error while boot loading Atmega 2560 using Arduino Mega 2560 I have developed custom board using Atmega 2560. I am doing boot loading process using the process of migrate from an Arduino board to a standalone microcontroller.

I have followed this steps...

1) Upload the ArduinoISP sketch onto your Arduino board.

2) Wire up the Arduino board and microcontroller as connections mentioned on Arduino Site.

3) Select "Arduino/Genuino Mega/ Mega 2560" from the Tools > Board menu.

4) Select "Arduino as ISP" from Tools > Programmer

5) Run Tools > Burn Bootloader

While doing this process I am getting this Error...

  avrdude: Yikes!  Invalid device signature.
           Double check connections and try again, or use -F to override
           this check.
  Error while burning bootloader.

I have done connection like this...

MISO  -  D50
MOSI  -  D51
SCK   -  D52
Reset -  D53/Reset
+5V   -  Vcc
GND   -  GND

What wrong I am doing? Or any step I have missed?

You wired the whole thing backwards. The proper wiring is

Your board - Arduino
     MISO  -  D50
     MOSI  -  D51
     SCK   -  D52
     Reset -  D53
     Vcc   -  5V
     GND   -  GND

This is kind of obvious from the picture: you would normally use the ISP
connector of the target board.


Determine XBee Packet Route I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode).
Setting up the network and sending packets is easy enough.

Is it possible to trace the route a packet travelled from the end-device to the coordinator?

Example:
I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator. Path: end-device->routerB->routerA->Coordinator.
Is it possible to know the end-device is in area B as it is the first router device the packet travelled through?

It is done by using Source Routing

The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.


Error - invalid conversion from 'char' to 'const char*', Not able to connect on pubnub server using node mcu I have node mcu with ESP8266 wifi module. When i am trying to upload an example code then its not working.

This is the Error:-

inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)

                      ^

exit status 1
invalid conversion from 'char' to 'const char*' [-fpermissive]

Code:-

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

char pubkey = 'pub-c-4a9cdbca-5688-4939-a852-f63cf6743980';
char subkey = 'sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094';

char pubchannel = 'demo_keyset';
char subchannel = 'demo_keyset';

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

       Serial.println("Connecting to ");
       Serial.println(ssid);

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

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Code is taken from pubnub arduino github example - https://github.com/pubnub/arduino/blob/master/examples/AdafruitFeatherM0WINC1500/AdafruitFeatherM0WINC1500.ino

problem was in the declaration of API keys and channel on the above code

Here is the right code:-

const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";


Understanding analog pins in pinMode When passing the pin number in pinMode its possible to use A0 - A7, does it apply only to that methode?
How can pinMode expect a number (is it int?) type in case of digital pin another (is it then string?) in case of analog pin?
I want to use that in my class methode, is there a way to use that and have my code more readable or should I use the pin numbers?
P.S. I have tried to read the source code but I don't understand the uin8_t (I know its a byte, but not how it can understand A5 as an int)

Tnx a lot

pinMode is actually declared as void pinMode(uint8_t, uint8_t);  in arduino.h

A0 is a defined as a number (somewhere depending on the actual hardware), on an Uno/Nano it translates to 14, and when executing pinMode it translates to the appopriate bit in the correct DDRx register.


Edit variables through Serial? Hello in a previous question i was able to set variables through if statements

    const uint16_t inputLength = 512;
int ss = 0;
int bHold = 0;

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

 void loop() {
  if ( Serial.available() > 0 )
  {
    static char input[inputLength];
    static uint16_t i;
    char c = Serial.read();

    if ( c != '\r' && c != '\n' && i < inputLength - 1)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "ss", 2) )
      {
        char* p = input + 2;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10); //

        for ( uint8_t i = 0; i < j; i++ )
        {
          ss = array[i];
          Serial.println(ss);
        }
      }

      if ( !strncmp(input, "bHold", 5) )
      {
        char* p = input + 5;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10);

        for ( uint8_t i = 0; i < j; i++ )
        {
         bHold = array[i];
         Serial.println(bHold);
        }
      }

      if ( !strncmp(input, "Whos There", 10) )
      {
        Serial.print("me");
      }
      if ( !strncmp(input, "hello", 5) )
      {
        Serial.print("hi");
      }
      if ( !strncmp(input, "sa", 2) )
      {
        Serial.print("  ss= ");
        Serial.print(ss);

        Serial.print("  bHold= ");
        Serial.print(bHold);

        Serial.println(" ");
        Serial.println("==============================");
      }
    }
  }
}

if works! but if i keep adding variables i have to keep adding if statements and this will get longer. so then i went with code like this that allows me to set all variables at once

  #define INPUT_SIZE 30

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

}
void loop()
{

  while (Serial.available() > 0) {

    int _mode = Serial.parseInt();
    int _ss = Serial.parseInt();
    int _bHold = Serial.parseInt();

    if (Serial.read() == '\n') {
      ss = _ss;
      bHold = _bHold;
      mode = _mode;

    }
  }

}

this works awesome! but i have to set all variables at once. my question is is there a way i can simply input a command like ss = 10 press enter then bHold = 30 and not have to input any other variable?
thanks i advance. please point me in right direction  Maybe make a function?

Somewhere along the line you have to tell your program how to map names to actual variables. Once you have compiled your program it forgets the names of the variables - those only exist in the source code.

So you have to have some other manual list of those variable names - be that in the form of if(...) statements, or an array of structs with the name in them, or whatever.

There's no getting away from it - you need that manual mapping in some form or other.

The closest you could get would be to set up some kind of hash system using structs and linked lists, whereby you could set any key/value pair, but then of course your program would still have to know to look for certain keys in the hash to do things with them, so that would be pretty pointless since you've just moved the variable mapping from one place to another.


Do we need ARM build for arduino while interfacing R-pi and arduino I wonder whats ARM build for Linux? Do we really need ARM build when we work with arduino? I need to integrate arduino and raspberry pi over wi-fi, I don't know whether I need ARM in this case. Also any quick learning tutorial for interfacing two of these hardware is appreciable

A newbie to Arduino. I hope fun learning with it

The ARM build of the IDE is for running the IDE on ARM systems. If you want to run the IDE on the pi then you need the arm build. However if you want to run the IDE on your PC then you need the IDE build that matches the architecture of your pc.

There are a million and one ways of communicating wirelessly between an Arduino and a pi.


availableForWrite() function return error when compiling for Arduino nano 33 BLE I used availableForWrite() function as below in my code. When I compile it for nano 33 IoT, everything is OK and compiles perfectly. However, when I change the board to nano 33 BLE, I end up with two scenarios:
1. using Arduino IDE as compiler > gives no error but the board doesn't after programming.
2. using the web-based compiler in Arduino website > give the following error:

error: 'class Arduino::USBSerial' has no member named 'availableForWrite'; did you mean 'available'?"

my code:

NoreplyTime=millis();
TimePassed= millis()-NoreplyTime;

         while(!Serial.availableForWrite()){
         TimePassed= millis()-NoreplyTime;
         if (TimePassed>1000){
         return false;
         }
        }

even simply having:

while (!Serial.availableForWrite());

generates error ONLY for nano 33 BLE board!

Thoughts?

The new Arduino cores use a common API maintained in a separate repository. This was copied from AVR core long time ago and doesn't contain some function added later to other cores. The function Stream.availableForWrite was added to Arduino API repository 5 months ago.

For the Arduino Mbed core they created a branch in the Arduino API repository to move the Arduino core in C++ namespace 'arduino'. But this was before availableForWrite was added. So the API version used in Mbed core doesn't have the function.

I reported it as issue. Even if they add the function to API I doubt they add an implementation of it to Serial.


Arduino Temperature sensor with a LED I want to program a temperature sensor with a LED using Arduino.
the goal is to make a sensor, when the temperature is over than Temperature max, the LED turns off and when the temperature is small than temperature max we turn on the LED.

my problem is when I programed the void setup() as followed, the LED doesn't work, and when I comment Serial.begin (9600) the LED work but I cannot diplay the value of the temperature.

void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}

here you find my complet code:

    int tempPin = A0;   // the output pin of LM35
float Max_temp = 24.0;
int led = 1;

float  temp, cel;
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}
void loop() {
      cel = readTemp();
  if(cel< Max_temp) {        // if temp is higher than tempMax
      digitalWrite(led, HIGH);  // turn on led
      delay(300);
     }
     else {                    // else turn of led
       digitalWrite(led, LOW);  // turn on led
      delay(100);
  }
   Serial.print("TEMP: ");
   Serial.print(cel);      // display the temperature
   Serial.print("C ");
   Serial.println();
   delay(300);
}

float readTemp() {  // get the temperature and convert it to celsius
  temp = analogRead(tempPin);
  return temp * 0.48828125;
}

thank you very much in advance

int led = 1;

You do know that pins 0 and 1 are the serial port don't you?

Take your pick.... Either use pin 1 for the LED OR use pin 1 for the serial connection.  You can't do both!

As it says in the manual:

  In addition, some pins have specialized functions:

  Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.


Sensors to measure wrist bending I'm working on gesture gloves project, which means it detect hand movement or current position, to be used in something else such as controlling a car.

I wanted to measure how much the wrist joint is bending, i used flex sensor, but when the wrist is bending while the fingers are pointing to upward ( _| ) the flex sensor became more longer in length than the wrist.. which make it hard for sewing ..

is there any alternative sensor?

It sounds like you have not allowed the flex sensor to slide through a sheath attached to the back of the hand.  Consider attaching a sheath to the back of the glove the width of the flex sensor.  It's length should be equal to or greater than the flex sensor when the glove is worn and the hand is fully dorsiflexed.  Anchor only the wired end of the flex sensor to the glove.  If there is still not enough room for the sensor when the hand is fully dorsiflexed, revers the sensor position and anchor the wired end to the back of he hand.  Allow the sensor to travel beyond the cuff of the glove if necessary.


Why doesn't this motor turn? When I upload the code, the DC motor makes a humming noise, but doesn't turn.
//2-Way motor control

int motorPin1 =  5;    // One motor wire connected to digital pin 5
int motorPin2 =  6;    // One motor wire connected to digital pin 6

// The setup() method runs once, when the sketch starts

void setup()   {
  // initialize the digital pins as an output:
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
  rotateLeft(150, 500);
  rotateRight(50, 1000);
  rotateRight(150, 1000);
  rotateRight(200, 1000);
  rotateLeft(255, 500);
  rotateRight(10, 1500);
}

void rotateLeft(int speedOfRotate, int length){
  analogWrite(motorPin1, speedOfRotate); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRight(int speedOfRotate, int length){
  analogWrite(motorPin2, speedOfRotate); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

void rotateLeftFull(int length){
  digitalWrite(motorPin1, HIGH); //rotates motor
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
  delay(length); //waits
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
}

void rotateRightFull(int length){
  digitalWrite(motorPin2, HIGH); //rotates motor
  digitalWrite(motorPin1, LOW);    // set the Pin motorPin1 LOW
  delay(length); //waits
  digitalWrite(motorPin2, LOW);    // set the Pin motorPin2 LOW
}

Why doesn't this work?
Update:
I plugged it into a different port (5v) as it is a 5v motor, but now it only turns left, not right. It just hums when it goes right.

The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.

To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.

These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).

You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.

Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.

=============

Responding to your edit, by  changing connections to place the the motor between one pin and the 5v supply, you have done two things:

1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.

2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor.  That change is almost a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.

But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.

If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.

If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.


How to discard same string received at Arduino I don't want the same string to be printed again and again. I'm getting the data into an Excel sheet.

byte readValue1=0;
byte readValue2=0;
int add=0;
int row=0;
int Zigbee1=0,Zigbee2=0,Zigbee3=0;
void setup() {
    Serial.begin(9600);
        Serial.println("CLEARDATA");
        Serial.println("LABEL,Time,Zigbee,a1,a2,a3,a4,a5,a6,a7");
        row++;
}

void loop(){
  String a1,a2,a3;
  String c1,c2,c3;
  int b;

  if (Serial.available()>21){
        if(Serial.read() == 0x7E) {
            for(int i=0; i<10; i++){
                byte discard = Serial.read();
            }
                        add = Serial.read();
                       if(add == 33)
                        {
                        a1 = func1();
                        if(a1==c1){
                          b=0;
                        }
                        else
                        {
                          b = a1.length();
                        }
                        if(b != 0)
                       {
                        Zigbee=1;
                        Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                        Serial.print(","); Serial.println(a1);
                        row++;
                        }
                        }
                      else if(add == 48)
                        {
                        a2 = func1();
                        b = a2.length();
                        if(b != 0)
                      {
                        Zigbee=2;
                        if(a2!=c2){
                       Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                       Serial.print(","); Serial.println(a2);
                        }
                        c2=a2;
                       row++;
                        }
                        }

                       else if(add == 69)
                        {
                          a3 = func1();
                          b = a3.length();
                          if(b != 0)
                         {
                          Zigbee=3;
                          Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                          Serial.print(","); Serial.println(a3);
                          row++;
                    }
                        }
}
}
}

Only print the string when he has changed?

String previousString = "";
String newString = "";

if(newString != previousString){
   println(newString);
   previousString = newString;
}

I'm not sure if it's applicable in your situation, just the first thing that came to my mind. You (kinda) should make a function of it, so that you don't have to copy/paste it all the time and it'll look way better.

EDIT:

A fuction could be made like so:

String previousString = ""; //Put this above your setup code (global variables)

void NoSpamString(String input){ //Put this block before the setup
   if(input != previousString){
      println(input);
      previousString = input;
   }
}

You can then use: NoSpamString("text"); to print a line withouth spamming it.


Arduino: Reading PPM values from MQ-131 Ozone sensor I have this sensor MQ131 by sainsmart: https://www.amazon.co.uk/gp/product/B00NL8XIQG/ref=ox_sc_act_title_1?ie=UTF8&psc=1&smid=A3DRI1TTHCTDIG

All I can read is the analog value which does not reflect the gas concentration. Any Arduino code for that to read the ppm concentration?
How long does the sensor needs to be preheated?

First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.

I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.


Environment Variable to change build Is there a way to get the build to see an environment variable so that all the files can be built differently with one Environment variable change.  Such as

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

Not environment, no.

If you have access to the compilation command line you can do the equivalent of #define from there:

avr-gcc ... blah blah ... -DUseFirstDir

That is most effective if you are using a Makefile build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).

A better IDE, though, can do it. Facilities for setting control flags like that exist within UECIDE and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).

Or you can just have a list of #define options at the top of your sketch:

/* Uncomment this to use the first directory. */
// #define UseFirstDir

// .... later ....

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif


How to detect Arduino serial port programmatically on different platforms? I am trying to write a little program that needs to detect Arduino ports automatically. I have tried many methods but haven't found any reliable way.

I can see that the Arduino IDE can detect it, by showing /dev/cu.xyz (Arduino Uno) or COM6 (Arduino Uno) etc.

How could I detect if the device connected to the serial port is an Arduino or not? Preferably without pre-flashing the Arduino with specific firmware.

I found this Python version, which uses serial.tools.list_ports.comports() here,  but it didn't work when I tested it on Windows and MacOS.

The best I can get is by using go-serial's USBManufacturer, I can get 'Arduino (www.arduino.cc)'.

I also found this post, about the same question, but without any solution.

Here is a solution:

On Windows, Arduino IDE comes with a tool named listComPorts.exe, which will list all COM ports and their USB info like VID & PID. There is also a file named arduino.inf in drivers folder contains all known device types and their VID&PID etc, and we can look for the connected device.

On *nix, the IDE take advantage of libusb and no such a tool, and it's easy to find a tool to list usb info on these platforms.

This go package mentioned in the question is a good choice, which also uses libusb and could build on all platforms. (On windows, you have to install mingw to build the C code, cygwin & msys don't work, I tried TDM-GCC and it works. You also have to add LDFLAGS: -lsetupapi (in serial.go) to successfully link the code.) After list all serial ports, you can search for 'Arduino' to determine the port. 'CH340' is also a keyword to search as many modified boards use this chipset.

New version of the IDE don't have listComPorts.exe, they all uses libusb. I find this tool from version 1.6.5.


MegaCore ATmega2560 PB7 activation randomly at boot I uploaded in my custom board (ATmega2560 with an external oscillator 16MHz) the MegaCore bootloader using the AVR pinout. I found that when I switch on the board the pin PB7 is activated 2 short times. This happens even with a blank Arduino sketch.
I found out that the problem was the reset pin connection. When the reset pin (for uploading a new sketch) is connected to the board I got the previous behaviour.
How can the reset pin affect only the pin PB7?
PS I found this issue even in the Arduino Mega standard bootloader.

PB7 is pin 13. That's the traditional LED pin.
The bootloader blinks that LED to indicate it's active.
If you want other behaviour then you will have to compile your own version of the bootloader that doesn't blink the LED.


Reuse Makerbot SMD-2.3 Stepper Driver with Arduino I'm building a small 2-axis CNC machine. For this purpose I want to use parts from an old Makerbot 3D printer. I've taken out the stepper motors and they're working perfectly with an Arduino and an external driver.

However I want to reuse the drivers that come with the makerbot to run the stepper motor. As you can see in the picture there's a socket for power, one for the Stepper connection and the wires coming out are what connect with the motherboard of the printer. I want to use these to connect with the Arduino instead somehow. Any idea how I should go about this?

From http://reprap.org/wiki/Stepper_Motor_Driver_2.3#IDC_Connector

IDC Connector

Pin     Name    Function

N/C     Not Connected to anything
GND     Connect this to your uC to share a common ground.
Step    A pulse on this line will make the stepper motor advance one step in the desired direction.
Dir     If this pin is high, the motor will rotate forward, low it will rotate backwards.
!Enable    This pin allows you to turn the motor on and off. It is an inverted pin to avoid noise turning the driver on. By default it is disabled (pulled high). A high signal means off, low signal means on.
Min     This is the signal from the 'min' sensor. The definitions of high/low are determined by your opto endstop.
Max     This is the signal from the 'max' sensor. The definitions of high/low are determined by your opto endstop.
GND     Connect this to uC to share a common ground.
GND     Connect this to uC to share a common ground.
GND     Connect this to uC to share a common ground.


card.init(SPI_FULL_SPEED,SD_CS_PIN) returns false for Arduino Mega I am working with a music shield, I have got my code from this site https://www.waveshare.com/Music-Shield.htm it works fine with arduino UNO but when I try to use it on MEGA it give me errors, Well I found that the problem is with this line

card.init(SPI_FULL_SPEED,SD_CS_PIN)

in uno SD_CS_PIN=10 I tried to change it to 53 based on this map

SPI   Uno   Mega
SS   10   53
MOSI   11   51
MISO   12   50
SCK   13   52

which is available on https://forum.arduino.cc/index.php?topic=165170.30 but still it returns false. What other options do I have to make it work on MEGA?

Thing that I am trying

#define SD_CS_PIN=10
#define VS_XRESET A0
#define VS_DREQ   A1
#define VS_XDCS   A2
#define VS_XCS    A3
void VS10XX::init(void)
{
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  pinMode(53, OUTPUT);

  pinMode(VS_XRESET, OUTPUT);
  pinMode(VS_DREQ, INPUT);
  pinMode(VS_XDCS, OUTPUT);
  pinMode(VS_XCS, OUTPUT);
  digitalWrite(VS_XDCS, HIGH);
  digitalWrite(VS_XCS, HIGH);

  reset();
}

In setup I added used this code but still does not work

void setup()
{
  Serial.begin(115200);
  pinMode(53, OUTPUT);//setting pin 53 to input
  player.begin();
}

the error code when I attempt to init sd card is 0 which says

/** timeout error for command CMD0 */

53 is a SS pin if the Mega is SPI slave. Pin 10 is connected to shield to select it as a listening slave. So let the parameter set to pin 10. Additionally on Mega set pin 53 to output, otherwise the Mega can 'fall' into SPI slave mode.

SPI pins 50, 51 and 52 are connected to the ICSP header too. The 6 pin ICSP header is on the same place relative to Uno an Mega common pin headers.


combination of arduino uno and mega? I am new to Arduino. Can I combine Arduino UNO and MEGA in 1 project? Arduino UNO is for audio output and MEGA for LCD display. If I am wrong, is there any ideas how do combine both LCD display and audio output in one microcontroller?

When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.

It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.

Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.


Rotary Encoder problem with LCD Display Program reads rotary encoder correctly without bouncing in this code:

int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
}

void loop() {
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++; Serial.println(val);}
        }

but when i use lcd to show the result, i get massive bounces (i think) in this code:

#include <LiquidCrystal_I2C.h>

#include <Wire.h>

LiquidCrystal_I2C lcd(0x27,20,4);
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  lcd.begin();
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
  lcd.home();
}

void loop() {
  lcd.print(val);
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++;}
        }

it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.

This is what i use to debounce:

A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                         |
                         |
                         =0.1uF C
                         |
                         ---------------------GND

I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.

Note that use of Serial.println() within your clkRise() interrupt handler is problematic, because Serial.println() uses interrupts itself. As far as I know, println() is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous println() calls finish their background processing.  The bits of extra delay introduced by LCD code may merely be exposing a problem.

There is no need for either hardware or software debouncing on quadrature inputs.  A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.

For some state machine code, see for example answer 16420/3917 and also see answer 18221/3917.  Also see answer 19109/3917.


Using SDA and SCL with analog inputs at the same time I'm trying to build a robot arm based on Arduino UNO and PCA9685 controlled by few potentiometers. The easiest way that I figure out and find on internet is using two Arduino's, one as master and second as slave.
This is where my question comes from, there is a way to use single Arduino UNO instead of two by using at the same time SDA and SCL with analog inputs? Maybe there is another way to do that?

That's my actual code:

#include <Arduino.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwmDriver = Adafruit_PWMServoDriver(0x40);

void setup()
{
  pwmDriver.begin();
  pwmDriver.setPWMFreq(51);
}

int tempPotVal = 0;
int adcPin[4] = {A0, A1, A2, A3};
int pwmRisingTime = 0;
int pwmFallingTime = 0;

void loop()
{
  for (int id = 0; id < 4; id++)
  {
    tempPotVal = analogRead(adcPin[id]);
    pwmFallingTime = map(tempPotVal, 113, 842, 102, 512);
    pwmDriver.setPWM(id, pwmRisingTime, pwmFallingTime);
  }
}

No. You can't. Not unless you could come up with some way of disconnecting one set of devices and connecting the other.

Instead you could add an I2C ADC chip to the existing SCL/SDA bus to expand the number of ADC channels you have available. Or use an analog MUX chip on one of the other ADC pins to expand the number of devices you could connect to it. Or you could add an SPI ADC chip to pins 10-13 (SPI bus) to give you more analog inputs.


High power consumption during power down mode I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).

avr/power sketch:

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

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

  // Ensure no floating pins
  for(i=0; i<20 ; i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  // Power-down board
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();

  // Disable ADC
  ADCSRA &= ~(1 << ADEN);

  // Power down functions
  PRR = 0xFF;

  // Enter sleep mode
  sleep_mode();
}

void loop()
{
}

rocketscream/Low-Power sketch:

#include <LowPower.h>
void setup() {
}

void loop() {
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}

I tried your first sketch on my "bare-bones" board.

With the sketch exactly as written, it used 197 µA.

I wondered why it was that high, so I commented out this line:

  Serial.begin(9600);

That reduced consumption to 122 nA.

See Power saving techniques for microprocessors.

You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.

Of course, if you need the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.


Apply patch to library for custom changes in Arduino IDE I wish to obtain unix epoch timestamps in millisecond precision. I am using an ESP32 along with DS3231 RTC breakout board from adafruit.

Apparently the Repository is not maintained often but I see a PR which overcomes the rollover for software timer and the developer provided a patch in the comment to use the unix timestamps in ms.

I went to the libraries folder where all the downloaded adafruit repos exist. But when I did  git status it mentions that the library download (from the library manager) is not a git repository.

I wan't to inculcate the changes to the RTClib library by using the patch provided. Should I just change the code directly via the Arduino IDE editor?

Save the patch to a file, put it in the directory holding the library,
open a terminal on that directory and type:

patch -p1 < patchfile

You may have to install the "patch" utility if you don't have it yet. On
a Debian-like OS (I don't know for other OSes):

sudo apt install patch


How to write IF/Else using a threshold range of values basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.

In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.

Here is the code, any suggestions?

int sensor=0;
int threshold=200;

void setup (){
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  Serial.begin(9600);
}

void loop() {
  sensor=analogRead(0);
  Serial.println(sensor);
  if (sensor > threshold) {
    digitalWrite(2, HIGH);
  }
  else {
    digitalWrite(2, LOW);
  }
}

To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.

To test if a value is between two numbers, you could use the && AND operator to see if both conditions are met.  For example:

if (sensor > loLimit && sensor < hiLimit) {
    digitalWrite(2, HIGH);
} else {
    digitalWrite(2, LOW);
}

Here's a shorter way to write that:

digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.

Another approach is to test if abs(sensor-midLimit) < halfGap, where midLimit is (loLimit+hiLimit)/2 and halfGap is (hiLimit-loLimit)/2.  Turn on the light if abs(sensor-midLimit) < halfGap, else turn it off.


DT-06 program using arduino uno I'm working to program DT-06 wireless wifi module.

And right now when i'm trying to program i get the following error message :
espcomm_send_command: can't receive slip payload data

Module RX - Arduino RX

TX - TX

VCC - 5v

GND - GND

Right now i can upload black program to arduino and send serial AT commands to my module and alson getting response.

How can i program ?

Thx

Appendix:

Module:  https://www.banggood.com/Geekcreit-DT-06-Wireless-WiFi-Serial-Port-Transparent-Transmission-Module-TTL-To-WiFi-p-1141047.html

Just program it like you would program a normal ESP8266.

The documentation is here:

https://github.com/SmartArduino/SZDOITWiKi/wiki/ESP8266---TTLtoWiFi

The datasheet provides the schematic of the module

So SW2 is the reset button and "SW1" is the "FLASH" button. To enter the bootloader mode in which the ESP8266 can be programmed, you first have to hold down the "FLASH" button then press "RESET" once.

For programming you would ideally get a 5V USB-UART adapter make the connections

VCC to 5V (it has a regulator to generate the actually needed 3.3V)
GND to GND
EN to 5V (e.g. via a pullup)
TXD to RX of UART adapter
RXD to TX of UART adapter

After the ESP is in the bootloader mode as described above, you can just program it normally through the Arduino IDE. Follow the instructions at https://github.com/esp8266/Arduino to install the ESP8266-Arduino core in the board manager.

Refer to the similiar procedure:

https://www.hackster.io/harshmangukiya/program-esp8266-esp-12e-with-arduino-using-ftdi-cable-2310c9


LCD from Arduino Starter Kit not displaying text I've been tinkering with my new Arduino a bit and I was adding an LCD from the starter kit, using information from the eleventh project in the project book, "Crystal Ball." When I connect the Arduino to my computer, the LCD lights up, but no text is displayed on the screen.

Here are some screenshots of my connections:

Finally, here's the code that I uploaded to the Arduino:

#include <LiquidCrystal.h>

// Create this display with the pins that I wired
LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

void setup()
{
    // This is a 16x2 display
    lcd.begin(16, 2);

    lcd.print("hello!");
}

void loop()
{
}

edit: Additionally, I tried adding a potentiometer to control the display, but to no avail. Below is the wiring for this (back pin goes to the third to last pin for the LCD).

Looking at your first picture it looks like you are wired on 12 and 13 not to 11 and 12 like your sketch specifies.

Double check your wiring against this : https://www.arduino.cc/en/Tutorial/HelloWorld

Also take your multi-meter out and buzz your connections.


How to pass a string pointer to a function I'm working on a project, where I wish to use pointers. I had a very quick overview of using pointers in C in collage, but I don't know how to use them.

I want that function uses input String (answer) as pointer.

Calling function in setup block

void setup() {
    sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");
    sendCommand("AT+CWSAP_CUR=\"mega\",\"password123\",10,3\r\n", 4000, DEBUG, "OK");
}

String sendCommand(String command, const int timeout, boolean debug, String *answer)
{
    String response = "";

    Serial1.print(command); // send the read character to the esp8266

    long int time = millis();

    while ((time + timeout) > millis())
    {
        while (Serial1.available())
        {
            // The esp has data so display its output to the serial window
            char c = Serial1.read(); // read the next character.
            response += c;
        }

        //Waiting for the right answer and breaking a while loop
        if (response.indexOf(*answer) > 0)
        {
            break;
        }

    }

    if (debug)
    {
        Serial.print(response);
    }

    return response;
}

What you have there are not String objects, but string literals. Their type is const char *

You should avoid using String objects if at all possible. Instead use character arrays.

To get a character array out of a function it is best to create one outside your function and pass it to the function as one of the parameters. The return value of the function can then be a status value indicating if the call worked or not.


L293D motorshield with batteries doesn't power Arduino Recently I came across a video about a guy building a remote Bluetooth-controlled Arduino car and I was quite amazed. So I decided I wanted to build it too. I have no Arduino or electronics experience at all other than being an IT professional.
So I bought the parts he used in the video (he advised a knockoff Arduino in the description).
After putting it all together the motors work through Bluetooth (yay!). But the issue is that the batteries connected to the motorshield don't give power to the Arduino at all (because the lights don't turn on).
When plugged in the laptop with the USB cable the Arduino gets powered and the motorshield light turns on just a bit, but not enough to make the motors and Bluetooth work.
So in short:
USB powered: Arduino works, motorshield light barely turns on, motors don't work, Bluetooth lights go on, but is not emitting a signal.
2x 18650 battery powered: motorshield light shines bright, Arduino doesn't work, Bluetooth lights don't flicker.
Both: everything works.
So for some reason, the batteries connected to the motorshield don't power the Arduino.
Video used:
https://youtu.be/Q36NbjPMV5k
Circuit diagram:

Knockoff arduino:

L293D motor shield (I'm aware that the ground of the power isn't plugged in)

Parts used:

Geekcreit UNO r3 ATmega16U2 AVR
L293D motor shield
Geekcreit HC-05 bluetooth
4 TT motor
2x 18650 3,7-4.2v 2200mah batteries

I really don't know what I did wrong, since I followed the video and did exactly what the person did. Maybe the batteries aren't powerful enough?

The problem was that the 2 pins on which the jumper sits, the jumper or the board was broken (idk exactly). I might've caused that myself by turning on the batteries + powering it through usb at the same time.
I bought a new L293D board then made sure I didn't connect usb power to the arduino while the L293D was sitting on top of it. I uploaded the code, then disconnected the usb, put the L293D on top, powered it all and it works like a charm!


Is there a way to disable modules like ADC without a sleep mode? I'm working on a binary watch project. I want my circuit to live off of batteries for as long as possible, so I want to decrease the power consumption of my chip.

I'm using a barebones ATmega328P-PU with two 74HC595 shift registers. The ideal situation would be to keep the CPU, clock, flash, and I/O going so my program can continuously count the time on its own, but disable everything else that I'm not using, such as the ADC, BOD, TWI, timer1 and timer2, USART0, etc.

I took a look at the ATmega328P datasheet for the sleep modes, and it seems as though they all disable the CPU/Clock. Is this true? And if so, are there ways to disable the modules without enacting a sleep mode?

Certainly there is.

  // disable ADC
  ADCSRA = 0;

You can disable lots of internal modules like this:

  power_all_disable();  // turn off all modules

See my page about power saving.

Majenko commented that turning off the ADC, while leaving the processor running was pointless. The real way to save battery power is to sleep, and it is possible to do that and still keep track of the time.

On my page about timers there is code to use a 32.768 kHz clock crystal to sleep and wake every second, which you could then use to alter the display on your watch.

Code from that page:

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

const byte tick = 3;

// interrupt on Timer 2 compare "A" completion - does nothing
EMPTY_INTERRUPT (TIMER2_COMPA_vect);

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

  // clock input to timer 2 from XTAL1/XTAL2
  ASSR = bit (AS2);

  // set up timer 2 to count up to 32 * 1024  (32768)
  TCCR2A = bit (WGM21);                             // CTC
  TCCR2B = bit (CS20) | bit (CS21) | bit (CS22);    // Prescaler of 1024
  OCR2A =  31;              // count to 32 (zero-relative)

  // enable timer interrupts
  TIMSK2 |= bit (OCIE2A);

  // disable ADC
  ADCSRA = 0;

  // turn off everything we can
  power_adc_disable ();
  power_spi_disable();
  power_twi_disable();
  power_timer0_disable();
  power_timer1_disable();
  power_usart0_disable();

  // full power-down doesn't respond to Timer 2
  set_sleep_mode (SLEEP_MODE_PWR_SAVE);

  // get ready ...
  sleep_enable();

  }  // end of setup

void loop()
  {

  // turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);

  // sleep, finally!
  sleep_cpu ();

  // we awoke! pulse the clock hand
  digitalWrite (tick, ! digitalRead (tick));

  }  // end of loop

Whilst asleep, the processor uses very little power. In the example sketch I measured 1.46 µA current consumption, when the output was LOW, if running from 5V power supply, and 1.1 µA if running from 3.3V power supply.

Example setup:

I have two decoupling capacitors (the blue ones). A pull-up resistor on Reset.
A 32.768 kHz crystal between pins 9 and 10. A 22 pF capacitor between each leg of the crystal and ground.

A current-limiting resistor and a LED. It works, and toggles at 1 Hz. When asleep (LED not on) it draws 1.46 µA as mentioned above.


Possibly fried a new atmega328p? I have a new atmega328p IC that I wanted to program. To do so I placed it into the socket of an arduino uno. I accidentally placed it the wrong way around (180° rotated), and powered it via USB and tried to upload the blink sketch, which obviously did not succeed. After I noticed it I turned it around and placed it into the socket the right way. I tried again uploading the blink sketch again without success.

Have I fried the atmega328p by placing it in the socket the wrong way?
Is there something else you need to do to new atmeag328p before you can program them the usual way?

Update: It seems that just rotating the IC did not damage it in the state where there was no bootloader programmed. And and the bootloader needed to be programmed first before the IC could be used.

Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?

You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.


Fastest way to read an array of numbers from python I'm trying to send an array of numbers from python to Arduino over the serial connection. I can reliably read a small incoming set of numbers (for example 123435678) from python, which I can then parse since I know how many digits are supposed to be in each number (for example, 1, 23456, 78). I do this with my Arduino code:

void getInput() {
     char buff[9];
     int field1;
     char field2[6];
     char field3[3];

  Serial.readBytes(buff, 8); //read 8 bytes from the Serial port
  buff[9] = '\0'; //null terminate the string we just read
  Serial.println(buff); //check that we got it
  for(int i=0; i<buff_len;i++) { //now we divide up the string into separate numbers
    if(i==0) {
      field1 = buff[0] - 48; //turn it into an int using ASCII
    }
    if(i>=1 && i<6) {
      field2[i-1] = buff[i];
      field2[5] = '\0';
    }
    if(i>=6) {
      field3[i-6]=buff[i];
      field3[2] = '\0';
    }
  }
  for(int i=0;i<buff_len;i++) { //clear the buffer
    buff[i]=0;
  }
}

But if I wanted to send a whole array whose contents I don't know in advance, for example like this:

for i in range(200):
    ser.write(i)

What's the best way to get these numbers to Arduino and file them away in an int array? Should I make the array in python first as a numpy.linspace() and send that?

If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends.  I usually use < and >, so the data packet might look like <12345678>.  You don't have to use those particular characters, just pick something that you know won't show up in your data.


Can an a Arduino make music or speech without a speaker? I have an Arduino Leonardo that can turn a relay off and on and the click is audible on the relay -this is simply done by making one of the control wires HIGH in the program code to turn the relay on and make the same control wire LOW to turn the relay off. In this way it can turn a set of relays on and off. By varying the patterns of on and off timings to the relay it make distinct sounds-it reminded me of a piezoelectric speaker for some of the programmed values. At fast on or off puling this 6V relay makes a buzzing noise. I was wondering if the sound emitted from the relay could be used as a crude speaker- I'm not talking about a quality speaker- just good enough to recognise a melody or speech. So my question
I was thinking the problem maybe be simplified if a set of relays is used buzzing at a certain frequency-corresponding to tones heard in the human voice to make it sound like speech. Im no expert in acoustics.

My questions are

1) is  it theoretically possible to use the clicking noise from a set of relays only to act as a a crude speaker (so hear a crude known melody or a crude speech)?

2) Is there such a circuit (if so what is it exactly and the theory of how it works) that can be built with an arduino?-so it only used the noise from a relay to act as a crude speaker.

I personally think it possible it would be an interesting circuit to build as I have not seen a relay used like this before. I just think it sounds interesting that music or speech can possible be made by a circuit without using a speaker type component. Maybe there's another non-speaker component (i.e. a component that was not originally designed to make a sound) that can be used instead of a relay.

I'd love to know the answers.

Update
I started on this. And the relays do make different tones-thats as far as I got.
So music seems to be possible; something like a famous melody of a song. I havent got any ideas yet for a another component instead of a relay.

Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.

To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.

A function that takes agreements of pitch and duration, something like:

 note(hz, ms)

would give you a fairly easy way to describe the music you wanted to play.

Just for fun, here are a few examples of "speakerless devices" making music:

Floppy disc drive music
Lotus F1 car plays Happy Birthday


Two Leonardos on one USB hub - not working properly I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:

const byte SWITCH = 12;

void setup ()
  {
  Keyboard.begin();
  pinMode (SWITCH, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  if (digitalRead (SWITCH) == LOW)
    {
    Keyboard.println ("foo");
    delay (2000);
    }
  }

Now I program a second Leonardo with the same code but send "bar" rather than "foo".

Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.

However ...

If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.

Doing lsusb shows this (along with other irrelevant devices):

$ lsusb
Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

This happens in both cases (if they are both in the USB hub or not).

My question

Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).

Or, is this a bug in either:

The Leonardo USB interface?
My USB hub?

Update

Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.

Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!

Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.

Following Majenko's suggestion:

  You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:

T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

Second one:

T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=8036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=Arduino Leonardo
C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
/usr/bin/usb-devices: line 79: printf: (none): invalid number
I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

Tentative conclusion

Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.

Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.

Those error messages above must be relevant, but I don't know enough about it to say in what way.

There is no reason I can think of that would stop it working as it should.

lsusb is showing both the devices, so they are being detected by the kernel.

You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:

T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=2341 ProdID=0036 Rev=01.00
S:  Manufacturer=Arduino LLC
S:  Product=USB IO Board
C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

The important bit is the I: lines - they show the individual USB interfaces and what kernel driver has been associated with them.   For the keyboard, of course, it's the last entry, which is assigned to the usbhid driver.

Another good diagnostic is dmesg -w

Run that with both Leonardos disconnected.  Plug one in and it should show it registering as a USB device.  A few moments later you should get a pair of lines like:

[ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
[ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

That is the board being associated with an input device (in this case input 2).

Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).

The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub.  It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.

USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers.  For instance my Leonardo above is identified as:

1-1.4.1

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device.  Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.


Arduino Connect Long Wires/Cables i am completely new to hardware programming and micro controllers and i am unable to figure out what search-engine search-term to use to find the answer i am looking for.
the project
i am working on a project that will use an arduino to control the opening and closing of a window; in a shed. the project i am trying to achieve is further described here.
the question
i want to know what are the limitations of wire length in an arduino project and what do i need to have to be able to extend that wire length capacity?
i currently have those "common" 20cm wires you get off ebay... which i dont think will be long enough.

The stepper motor 28byj-48 seems to be a 5V motor (datasheet). I've seen it being used with a A3967 driver, which means that it does not draw more than 750 mA of current.

I'll go with the length you mentioned in the comments:

  for this example lets say 3m

The rest is Physics: the resistance of a wire is

R = p * l/A

where l is the length of the wire and A is the area (dependent on the diameter).

A voltage drop calculator can now tell you how much voltage is left at the end of the wire.

I would have estimated a 0.75 mm² (AWG 18), but you might even be fine with 0.5mm² (AWG 20) according to the calculator. But: better safe than sorry.

Also from the comments:

  i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements)

A stepper motor needs a totally different setup than a servo. The servo is connected with simple 4 pins, the stepper needs a motor driver (H-bridge). Connecting the stepper motor directly to the Arduino may destroy your board.


Eclipse Arduino Leonardo Pro Micro ATMega32U4 Programming Issue Help Needed as I am little bit lost. I've procured a Pro Micro Board from sparkfun. Great little board and it work like clock work when using the standard Arduino Programming IDE.

Well Copied the code thru to the Eclipse Project, Hit compile and all seems well. But Trying to write the code to the device the following happens.

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:/Users/vente/.arduinocdt/packages/arduino/tools/avrdude/6.3.0-arduino14/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = "F"; type = @
    Software Version = �.u; Hardware Version = �.
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

avrdude done.  Thank you.

I've setup the Programming interface a as a Leonardo Board. AVR ISP.

For some reason It seems as if and it might be me that the usb does not reset? and go into programming mode.

Please Help

I assume you use Eclipse Sloeber plugin for Arduino. For serial upload over USB using bootloader choose programmer Default. All other programmers are for flashing over ICSP.


How to create a 1 hour timer with ATtiny13A microcontroller? I want to control an AC load such that it powered on for 1 minute, then off for 1 hour, then on again for 1 min, and so on, in a loop.
I just modified the blink sketch to do:

Turn A1 on
Then delay for 60,000 ms
Then turn A1 off
Then delay for 3,600,000 ms (3,600 sec, or 1 hr)

...but it doesn't seem to work.
It looks like the LED connected to A0 turns on but instead of turning off after 1 min, it turns off after 8 min 30 s.
Any suggestions?

I rectified the sketch. Now its takes 1 sec as actual 1 sec 1 choose 1 MHz clock in IDE.
int ledPin =  A3;      // the number of the LED pin
int ledState = HIGH;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
unsigned long OnTime = 60000;           // milliseconds of on-time
unsigned long OffTime = 10000;          // milliseconds of off-time

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis;  // Remember the time
    digitalWrite(ledPin, ledState);  // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis;   // Remember the time
    digitalWrite(ledPin, ledState);    // Update the actual LED
  }
}

then it turns on for 1 sec and then turn off for 1 sec,
then randomly turning on at 30 sec or 1 min 30 sec.
I want to make it on for 1 min every hour.
I tried blink sketch modified as follows:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(900000);
}

but it still turns on for 1 min and turns off for 1 min.
I also tried this:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(3.6e+6);
}

No matter what I do on time and off time always remain same.
I just wanted to know one thing: can I set 1 hour off and 1 min on timer using ATtiny13A or not?
Tried 1.2 MHz, 1 MHz, all clocks in the IDE, nothing seems to work.

As the unchanged blink sketch blinks with 8.4 seconds, I think my assumption is right. The clock of the Attiny is running 8 times slower, than the code thinks.
When you have installed the Attiny core, there should be a menu entry for the clock frequency. Most likely the standard is 8MHz. But having 8MHz set does not mean, that the Attiny is using 8MHz. To choose between different clock sources and frequencies, you must change the fuses of the microcontroller (which are just some bits of special non-volatile memory in the chip, that set special hardware configuration; more information in this question). This is done, when you burn the bootloader to the chip. That's the easy version. Alternatively you can use the avrdude command directly to set the fuses. That's the advanced way.
Currently the fuses of your Attiny seem to be set to the 1MHz internal clock. But the compiler uses the frequency, that you have chosen in the menu, hence 8MHz internal clock. So the compiler thinks, that the chip runs at 8MHz and thus generates the timing code for this execution speed. But your chip is currently 8 times slower, than the compiler thinks.
TL;DR: Burn the bootloader onto the chip to let the Arduino IDE set the right fuses for your clock frequency.


Arduino pins vs Esp8266MOD I had used Arduino Uno & RFID but now i want to run same code in Esp8266MOD.
i have installed all the drivers and everything else to run esp8266 in Arduino IDE but i dont know how to connect rfid in esp8266. Can someone please compare which arduino pin & esp8266 pin are similar

 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             ?
 * SPI SS      SDA(SS)      10            ?
 * SPI MOSI    MOSI         11 / ICSP-4   ?
 * SPI MISO    MISO         12 / ICSP-1   ?
 * SPI SCK     SCK          13 / ICSP-3   ?

table filled

 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             any, recommended 5
 * SPI SS      SDA(SS)      10            any, recommended 4, possible 15
 * SPI MOSI    MOSI         11 / ICSP-4   13
 * SPI MISO    MISO         12 / ICSP-1   12
 * SPI SCK     SCK          13 / ICSP-3   14

io 15 is SS if esp8266 is slave. but this pin must be LOW at boot. you can use it as SS if SS pin of reader doesn't pull-up.

io 4 and io 5 are untroubled pins.

io 0 and io 2 are with io 15 boot configuration pins and can be used only if they don't change the required boot state.

io 1 and io 3 are Serial interface

io 16 is RTC pin and is used for wake up from deep slepp

warning: does the reader work with 3.3 V?


ESP32 send data to another ESP32 without establishing a wifi connection Originally I was creating a project consisting of the Atmega328P and NRF24L01 to create multiple arduinos that could talk to each other.  Basically I was creating something like this:

As the network grows I am starting to run out of memory when using the atmega328P. I have to be careful about allocating memory and more. So I will like to replace the NRF24L01 with the ESP32.  The price of the ESP-WROOM-32 by itself is also cheaper than buying an NRF24L01 + the atmega328.

Question
How can I send data from one ESP32 to another ESP32 without establishing a WiFi connection? Just like the NRF24L01 where you specify a writting pipe where you want to send the data and the other NRF24L01 is listening on that pipe.

I know I can do that with ESP-NOW. This video explains how. The problem with ESP NOW is that I have to know in advance the mac address of the ESP32 where I intend to send a message. I plan to be able to keep adding smart home devices without having to know the mac address.
My algorithm with NRF24 that I already created is as follows:

There is a master node listening on address 2
If I add a new  node A to the network it listens on address 1.
Master discovers all devices that have address 1 every few seconds.
So eventually node A receives a discovery packet message that comes from master. Node A listens now on a random address and replies to master with that random anddress.
So node A is now connected to the network.

The cool thing about this algorithm is that I can keep adding new nodes to the network without knowing in advance its address. I will like to do the same thing with the ESP32. How can I send a simple message betweenn 2 ESP32 modules?

Finally I found a way how to do it. If you use the mac address FF:FF:FF:FF:FF:FF that works as a broadcast address. This is the working code on how to send a message from the master to another esp32 without knowing its mac address. Later the slave can reply with its real mac address:
Code for master (tx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success 1" : "Delivery Fail 1");
  if (status ==0){
    Serial.println("Delivery Success 2");
  }
  else{
    Serial.println("Delivery fail 2");
  }

  Serial.println();
}

void setup()
{

  Serial.begin(115200);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

   // Register peer
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

   // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }
}

int dataToSend = 1;
void loop()
{
    dataToSend++;

    // Send message via ESP-NOW (size of an int is 4 bytes on ESP32)
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &dataToSend, 4);

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    }
    else {
      Serial.println("Error sending the data");
    }

    //Serial.println(WiFi.macAddress());
    delay(1000);
}

Code for slave (Rx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
{
  int dataReceived;
  memcpy(&dataReceived, incomingData, sizeof(dataReceived));

  Serial.print("Data Received: ");
  Serial.println(dataReceived);

  Serial.println();
}

void setup()
{

  Serial.begin(115200);
  delay(100);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // print our mac address
  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

}

void loop()
{
}

You can also reply back on the receiver code if you want. It will be the same code.


How to combine strings and text together? I'm trying to combine two strings (strings/int) together with text in below code:

int foo = String((char*)payload).indexOf(' ');
int message1;
int message2;

message1 = String((char*)payload).substring(0, foo).toInt();
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

client.publish(msg, String(message1 + " " + message2).c_str(), true);
// published value: 1 0

Instead of publishing "1 0" its publishing some weird values, what am i missing?

I wouldn't use the String class, but instead use the C functions to concatenate strings (like strcat, strncat).

You can use the itoa function to convert an integer to a string, see:

  https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c

Or use the sprintf function.

These are all standard C functions which gives you complete control of the buffer sizes to use. Handy because the Arduino Uno has just 2 KB.


Port Manipulation and serial communication i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board

You can modify a single or multiple bits in a register by using a Read-Modify-Write approach. Essentially something like this:

byte temp = DDRD;
temp = (temp & ~(bitmask)) | bits_to_set;
DDRD = temp;

In the above code, bitmask is some value with the bit or bits you want to modify set - e.g. if you want to change bits 4 and 5, it would be (_BV(4) | _BV(5)) or just (0b00110000). bits_to_set is a value with all bits that you want to be one set - e.g. if you want bit 5 to be a 1, it would be (_BV(5)) or (0b00100000).

What the code does is to first get the current value of the register you want to manipulate. Then it will clear only the bits which you want to modify to 0 by using bitwise AND on the temp value. Next it will set only the bits you want to change to be set by using a bitwise OR. Finally it writes it back to the register.

If you are using interrupts which, you may wish to do this atomically (so that the register is not changed by an interrupt occurring before the new value is written back). You can do this by wrapping the above code in:

byte oldSREG = SREG;
cli();
...
SREG = oldSREG;

Which will clear the global interrupt flag to pause any interrupts, and then will restore the value of it afterwards.

If you just want to change a single bit in a register you can optimise this code down to one of the following examples:

DDRD |= _BV(4); //Set bit 4
DDRD &= ~_BV(5); //Clear bit 5

Again you may want to do this atomically as it may compile to a Read-Modify-Write access.


Need to filter low voltage from a piezo buzzer circuit I have a 6-28VDC piezo buzzer I'm using at 24VDC. The line has 3-4 VDC when the output is off, which has a soft but annoying buzzer constantly.  What the the easiest way to filter that out so I only get buzzing when the output is activated?
I tried using resisters which works, but then decreases the overall sound level (of course)

Not every buzzer is a piezo buzzer and not every buzzer does the buzzing by itself. Some buzzers have only a piezo disc and for those a tone signal is needed to make it beep. Other buzzers only need a DC voltage and they start buzzing at a fixed frequency. The actual sound can be generated with a piezo or a electro-magnetic element (like a mini speaker).

I'm not sure which buzzer you have. I think it will not draw a lot of current, therefor a zener diode of 5.6V should work.