System crash after using sprintf My Arduino crashes after using sprintf, To reduce system ram am trying to move away from strings to char and now this happened. Loop not working properly and it's not going to webrequest, spent 2 days to find a solution nothing worked yet. My project is to send temp and humidly to my server i was using strings and after one day of use system very slow to send data to server then i realized stings are the culprit then i changed to char
char ventionoroff[6];

char Foggeronoroff[6] ;

char Exhuastonoroff[6] = "OFF";

char current[4];

char today[10];

bool running = false;
bool isFoggerRunning = false;
bool isExhaustFanRunning = false;

Time t;

void loop() {

 t = rtc.getTime();

  hum = dht.readHumidity();
  temp = dht.readTemperature();
  delay(1000);

  if (isnan(hum) || isnan(temp)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  val = digitalRead(powerStatus);

      byte MIN = t.hour;
      byte SEC = t.min;

  char timeStamp[20];
 snprintf(today, "%02d:%02d",  MIN, SEC);

   Serial.println(today);

if (millis() - lastConnectionTime > postingInterval) {
   Serial.println("reaching here2");
    httpRequest();
  }

  if (val)
  snprintf( current , "YES");

  else
 snprintf( current , "NO");

  if (running == false) {
    snprintf( Foggeronoroff , "WAIT");

  } else {
   snprintf( Foggeronoroff , "READY");

  }

    ventilationfan();

void httpRequest() {
Serial.println("shit reached here");
  client.stop();
  char data[10];
  const char phpScript[21]  = "/farmsensor/add.php";
  const char server[20]  =  "www.gstorefresh.com"; // also change the Host line in httpRequest()

   char strt[6];
   char str[6];
  sprintf(strt, "te=%d", temp);
  strcpy(data, strt);
  strcat (data,"&ti=");
  strcat (data,today);
   strcat (data,"&mot=");
   strcat (data,ventionoroff);
   strcat (data,",");
   strcat (data,Foggeronoroff);
    strcat (data,",");
    strcat (data,current);
     strcat (data,"&mo=");
     strcat (data,Exhuastonoroff);
      sprintf(str, "&hum=%d",hum);
      strcat (data,str);

 Serial.println(data);
   int len = strlen(data);
  if (client.connect(server, 80)) {
    client.print("POST ");
    client.print(phpScript);
    client.println(" HTTP/1.1");
    client.println("Host: www.gstorefresh.com");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    client.print("Content-Length: ");
    client.println(len);
    client.println();
    client.print(data);
    restartnet = 0;
     data[0] = 0;
     Serial.print("data after sucessfull connection");
     Serial.println(data);
     Serial.print("freeMemory after connection");
     Serial.println(freeMemory());
    lastConnectionTime = millis();

  } else {

     Serial.println(F("Failed"));
     data[0] = 0;

  }
}

There are quite a few points that could be improved in this code. The
main ones have already been shown in the comments:

the data buffer was not large enough to hold the whole string,
which leads to a buffer overflow, memory corruption and, ultimately,
the crash you are experiencing.

The second parameter to snprintf() should be the size of the
provided buffer.

Here I will add a few points that, although not really defects of this
program, could help improved it and save memory.
Here:
char current[4];
// ...
if (val)
    snprintf(current, "YES");
else
    snprintf(current, "NO");

you are not using the current buffer to build a string, but only to
store one of two pre-existing strings (the literals "YES" and "NO")
that are already stored in memory. Rather than making a copy, you could
instead reuse those pre-existing strings, and have current be a
pointer to the relevant one:
const char *current;
// ...
if (val)
    current = "YES";
else
    current = "NO";

This only saves two bytes (size of the buffer minus size of the
pointer), but this pattern happens multiple times in the program, and
the savings add up.
Now, another small optimization. Here:
char strt[6];
sprintf(strt, "te=%d", temp);
strcpy(data, strt);

you do not need the extra strt buffer, as you can write directly into
the data buffer. Better yet, you can write everything into the
buffer in a single call to snprintf():
snprintf(data, sizeof data,
        "te=%d&ti=%02d:%02d&mot=%s,%s,%s&mo=%s&hum=%d",
        temp, t.hour, t.min, ventionoroff, Foggeronoroff, current,
        Exhuastonoroff, hum);

If you don't like this approach, and would prefer writing the data in
separate calls to snprintf(), you can do so without using auxiliary
buffers. You have to remember (with a pointer) where within the buffer
you finished your previous write, and pass this address to the next
snprintf() call. Note that you also have to keep track of the room
that is still available, which is easy to do with a second pointer that
points to the end of the buffer:
char *p = data;                  // current writing position
char *end = data + sizeof data;  // end of the buffer
p += snprintf(p, end - p, "te=%d", temp);
p += snprintf(p, end - p, "&ti=%s", today);
// ...


arduino send logged data over wifi I am working on air quality measuring project. it should be able to record gps and air quality data into a SD card and then when wifi is available it should send it to a server. Please help me decide the required hardware for this.
Can i use ESP8266 module to send this data

You need:

SD card + reader
GPS module
Air sensor
WIFI ESP 8266 should be ok
Arduino Uno or Mega, depending on if everything fits and calculations to be performed

Start with finding each component, read examples how to use them, than combine them.

Looks like a big project to start with if you are new to Arduino.


motor shield directly to PC? WITHOUT ARDUINO! Is there a way to connect and control motor shield board WITHOUT Arduino at all.
can i connect it directly to my PC ?
i'm getting confused since i red lot of topics that people use existing pins on motherboard.

To a normal PC? No. You can't. A PC doesn't have the GPIO pins etc that are needed.

You could wire it to a Pi though.


Comparing button presses to correct sequence I am creating a memory game with the Arduino. It has four buttons, each for a different colored led. The leds will blink in a random sequence and either fail or add another light in the next sequence if the user presses the correct buttons. I have also attached an lcd screen to late implement a score tally.

Right now, the welcome lights display and the sound is working fine, but when the sequence starts, it will act as though I am pressing a button and proceed through the fail light method. I think the last method is causing this issue where I am comparing the button pressed to the sequence.

I would appreciate any help!

This is essentially my wiring just with different pins chosen:

I found that I did not need the pull down resistors for each button since I had declared the pinMode for each button to be INPUT_PULLUP. So instead of the schematic above, I took out the resistors for the buttons and instead wired one side of the buttons to ground.


State machine doesn't function My goal is to make a logic controller for a cassette tape mechanism, right now I'm simply trying to get the mechanism to engage and disengage the pinchroller arm which is motorized, spin the reels/capstan to advance the tape for playback; and stop the process by stopping the capstan motor, and retracting the pinchroller arm.

Currently this code doesn't respond to any of the button inputs, and I'm unsure as to why that is. I have another program that allows manual control of the motors, and that works fine, this however does not.

Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!

Here is my current full code:

const int motor1Pin = 5; //If motor1 is HIGH and motor2 is LOW,  the motor will spin one way, if motor1 is LOW and motor2 HIGH then the motor will spin in the opposite direction.
const int motor2Pin = 4;
const int motor3Pin = 2;
const int motor4Pin = 1;
const int enablePin = 6; //turns pinch roller arm motor on or off
const int enablePin2 = 3; //turns capstan motor on or off
const int limitswitch1Pin = 7; // end of top travel limit switch
const int limitswitch2Pin = 9; // end of bottom travel limit switch
const int cyclePin = 8; //switch that cycles the pinch roller arm depending on limit switches
const int reversePin = 10;
const int forwardPin = 11;
const int stopPin = 12;

int state;
int buttonState;
int limit1State;
int lastlimit1State;
int limit2State;
int lastlimit2State;
int reverseState;
int forwardState;
int stopState;

enum State_enum {STOP,PLAY};

bool enableState = false;
bool enable2State = false;

void setup() {

  pinMode(motor1Pin, OUTPUT);
  pinMode(motor2Pin, OUTPUT);
  pinMode(motor3Pin, OUTPUT);
  pinMode(motor4Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);
  pinMode(enablePin2, OUTPUT);
  pinMode(reversePin, INPUT_PULLUP);
  pinMode(forwardPin, INPUT_PULLUP);
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(limitswitch1Pin, INPUT_PULLUP);
  pinMode(limitswitch2Pin, INPUT_PULLUP);
  pinMode(cyclePin, INPUT_PULLUP);
  pinMode(A0, INPUT);

  buttonState = digitalRead(cyclePin);
  limit1State = digitalRead(limitswitch1Pin);
  limit2State = digitalRead(limitswitch2Pin);
  reverseState = digitalRead(reversePin);
  forwardState = digitalRead(forwardPin);
  stopState = digitalRead(stopPin);

}

void loop() {

  if (buttonState == LOW) int state = PLAY;
  if (stopState == LOW) int state = STOP;

  switch (state) {
  case PLAY: //Plays the cassette
    if (stopState == LOW) {
      state = STOP;
    }
    if (limit1State == LOW) { //running the pinchroller arm clockwise from the top to bottom

      digitalWrite(motor1Pin, HIGH); // set leg 1 of the pinchroller motor H-bridge high
      digitalWrite(motor2Pin, LOW); // set leg 2 of the pinchrooler motor H-bridge low
      analogWrite(enablePin, 176); //set pinchroller motor speed

    } else if (limit2State == LOW) { //pinchroller arm is fully down (at bottom)
      digitalWrite(enablePin, LOW); //disable pinch roller motor
      digitalWrite(motor3Pin, LOW); // set leg 3 of the capstan motor H-bridge low
      digitalWrite(motor4Pin, HIGH); // set leg 4 of the capstan motor H-bridge high
      analogWrite(enablePin2, 200); // set capstan motor speed
      digitalWrite(enable2State, true);
    }
    break;

  case STOP: //Stops the cassette
    if (enable2State == true && limit2State == LOW) {
      digitalWrite(enablePin2, LOW);
      digitalWrite(enable2State, false);

    } else if (enable2State == false && limit2State == LOW) {
      //running the pinchroller arm counter-clockwise from the bottom to top

      digitalWrite(motor1Pin, LOW); // set leg 1 of the motor H-bridge high
      digitalWrite(motor2Pin, HIGH); // set leg 2 of the motor H-bridge low
      analogWrite(enablePin, 176); //set pincroller motor speed

      if (limit1State == LOW) {
        digitalWrite(enablePin, LOW);
      }
    }
    break;

  }
}

I don't know enough about how tapes work to comment on the sense of what you're doing, but some problems with the code:

You are reading the input and setting buttonstate once only in setup(). You need to read it repeatedly, by putting it in loop().

You also have three variables called state: one global which is never set, and two with very restricted scope which are set but never used - they go out of scope immediately. Remove the ints where you set state in your loop().

This part is useless because you've already done it just above, but probably not hurting anything:

if (stopState == LOW) {
    state = STOP;
}

That's as far as I got. If that doesn't fix it, consider adding trace: you'd have found these two problems pretty quickly if you'd printed out the variables to check your assumptions.


Connecting multiple component's VCC wires to one Arduino UNO R3 5V Pin Apologies for the title gore and whether this seems to be a fairly basic question, I'm an Arduino noob.

I'm working on a wearable sensor system project at my university using an Arduino UNO R3 to handle all the sensors and power them. I'm currently powering the board with a USB connection and will be powering my components from the board's 5V pin as they can all safely operate with that voltage. The individual components do not exceed their I/O pins max current and their combined current usage doesn't exceed the boards maximum current.

My question comes in here: in the past if I've needed to connect multiple components to the ground and 5V pins of an Arduino board, I was always taught to use a matrix board to solder my component's 5V and GND wires to, where they could then be powered from two soldered wires from the microcontrollers 5V and GND pins.

Given that this is a wearable system, I would like to minimise any unnecessary hardware and so proposed to my supervisor that we cut out the matrix board and simply solder the VCC wires of the components together to one header pin which we can then plug into the 5V pin on the board to draw power. He strongly cautioned against this but wasn't able to provide a concrete reason as to why it would be a problem; as far as I can see the fundamental theory is the same and we are simply cutting out an unnecessary middle man.

Is there something I'm missing here or does this solution seem like it would work fine? Additionally, if this solution works for VCC, would the same principle work for sharing a grounded connection?

Assuming you have suitable soldering skill, there are some considerations when you solder lots of wires to one header:

Lots of wires means lots of weight. The strain of several wires may degrade your connection or header over time, especially for a wearable system, where I assume the parts would be subject to some movement.
The width of the connection when all the wires are soldered to it. It might touch adjacent pins, or lean on them, creating mechanical stress. Heatshrink or sleeving can help with the electrical contact issue, but won't remove the mechanical risk.
Lots of wires soldered to one point may make the system more difficult to service. Instead of desoldering the wire to one component, you have to either desolder them all, or cut the wire to the one suspect component and then solder together wire stubs later to replace it.

When referring specifically to power supply pins, you'll need to consider the peak current requirements of anything you power from it. Based on https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations it seems like you shouldn't be pulling more than 200mA from the Vcc PIN. Check the maximum current draw of all of your components that you want to power, add them together, and make sure it's under the limit of the Arduino board.


How can I identify GPS sattelites in TinyGPS++? I can see about 15 satellites (about 10 GPS + 5 Glonass) in u-center, but I see only about 10 satellites using TinyGPS++. I suspect that TinyGPS++ can see GPS only. I see lines containing $GNRMC $GNVTG $GNGGA $GPGSV $GNGLL $GNVTG $GLGSV in the input, so there are information from both constellation. But how can I check which constellations TinyGPS++ takes into account for the output:

  Sats=10 Nums=1 3 8 10 11 14 20 22 24 27 28 31 32 36 40  Elevation=46
  17 45 31 69 59 1 43 5 24 9 1 60 36 32  Azimuth=304 255 215 66 267 137
  77 263 28 184 316 140 89 181 150  SNR=12 0 0 17 8 20 0 11 0 11 0 0 21
  0 0

There is a bug in TinyGPS++ as it only counts GPS satellites. See https://github.com/mikalhart/TinyGPSPlus/issues/52

PRN numbers are used to identify satellites:

  GPS = 1 to 32

  SBAS = 33 to 64 (add 87 for PRN number)

  GLO = 65 to 96


Powering an Arduino Mega with external USB Power Bank? I am making a robot with arduino mega r3. I want to power the arduino with a usb power bank. How should I do that?

I have a "USB power bank" with two USB ports, which I use to power some projects.

I have discovered that my bank (i.e. your mileage may vary!) shuts off unless my project draws at least 50mA. If your project does draw at least that at ALL times, you should just be able to plug a USB cable directly from the powerbank to the project.

For some other projects, I have bought a USB cable (USB A to USB A) which I cut in half, stripped the wires, then used a multimeter set to "Volts" to work out which wire was +5V and which was GND; I connect these straight to the 5V/GND on my project. To make sure at least 50mA was drawn at all times, I put a 100 Ohm resistor from +5V to GND (at LEAST 1/4 watt!!). This obviously wastes a lot of power (turning it into 1/4 watt of heat), but it keeps the power bank "awake". By using a USB A to USB A, I now have two cables.

My power bank also has a "torch" (led) integrated; if the torch is on, it also stays awake.


keypad storing problem (void value not ignored as it ought to be) I am trying to input 11 numbers only by the use of keypad but the problem is whenever i use this code. It gave me this error.

Here's my code. Help please.

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6, 5);
int table[] = { 0, 0, 0 };
#include <Keypad.h>
#include <Wire.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    { '1', '2', '3' },
    { '4', '5', '6' },
    { '7', '8', '9' },
    { '*', '0', '#' }
};
byte rowPins[ROWS] = { 2, 3, 17, 16 }; //connect to the row pinouts of the keypad
byte colPins[COLS] = { 15, 14, 13 }; //connect to the column pinouts of the keypad
int count = 0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13]; // This can hold up to 4 digits
int i = 0;
char n1, n2, n3;
char buf[15]; // i put here***
void setup()
{
    Wire.begin();
    Serial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3); // request 6 bytes from slave device #2 for(int i=0;i<3;i++) {

    int c = Wire.read(); // receive a byte as character
    Serial.print(c);
    table[i] = c;
    Serial.print('\t');
    // print the character } Serial.print('\n'); Serial.print(table[0]); Serial.print('\t'); Serial.print(table1); Serial.print('\t'); Serial.print(table[2]); Serial.print('\n');

    //if(table[0]<=8) //{ //Serial.print("Flame Detected!"); //Serial.println("Level1");
}
void ask()
{

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n1 = GetNumber(buf, sizeof(buf) - 1);

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n2 = GetNumber(buf, sizeof(buf) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n3 = GetNumber(buf, sizeof(buf) - 1);

    Serial.println(n3);
    delay(1);
    Serial.println(n1);
    Serial.println(n2);
    Serial.println(n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}
void GetNumber(char* result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0; // how far through buffer we are
    while (key != '#') {
        switch (key) {
        case NO_KEY:
            break;

        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':

            lcd.print(key);
            if (i < maxLength) {
                result[i++] = key;
                result[i] = 0; // terminating null
            }
            break;

        case '*': // backspace
            if (i > 0) {
                i--;
                result[i] = 0; // terminating null
            }

            break;
        }

        key = kpd.getKey();
    }

} // end of GetNumber

Your GetNumber function is defined to return void (nothing) while you use it as if it returns the number typed.

change GetNumber to return a int and the end of it do a atoi using the buffer and return the result.


Is this assignment valid or needs casting? I have this assignment and while i don't get any error not even warning from the compiler.

uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

The Buffer is an unsigned short but as you can see inside there are float values inside.

The program does not work as expected.

Also i have another case where i am not sure if i need casting as this time, the final value is a float value.

int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

Is this valid? Does it need casting? Or there is not reason to declare floatVal as float?

First part:

uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
  Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

Buffer[n] will be filled with an uint16_t and implicit casting to an uint16_t will be used. I suggest you do such implicit castings explicitly (so add (uint16_t) ... if you want).

However, if you do not want this, either define the Buffer as float, or at least add + 0.5 to give better roundings (if that is improving, depends on your situation, but mathematically it is better).

thus:

static const uint8_t BUFFER_SIZE = 40000;
uint16_t Buffer[BUFFER_SIZE];

for (int n=0; n<BUFFER_SIZE; n++)
{
  Buffer[n] = (int) (0.99 * cos(((2.0*PI)/BUFFER_SIZE)*n));
}

The next one:

int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

This is also 'compiler-correct', and an int value can be more easier converted to a float. You will not lose digits. However, to make it clear an explicit cast with (int) ... is better.

Thus:

int intVal;
float floatVal = (float) (intVal - intVal*Buffer[intVal]);


Doorbell for someone with hearing issues I have an Arduino Uno with the basic kit, not very good at coding it however.

How could I make a doorbell that lights up an LED instead of making a noise?

I'm trying to make a doorbell for someone with hearing issues.

A simple LED lighting up would be more than enough. Would I need a wifi shield if it's not close enough to be hard wired?

Thanks

I know you are keen on using your Arduino.  But simpler solutions abound.  For instance, if the door bell already works at a lower then main voltage it might be easier to determine the feasibility of connecting a low voltage lamp to the door bell.

However, I can see a situation that an Arduino can fit very nicely into:

Events: 1) The door bell rings. 2) The Arduino senses this and starts turning on and off a room light at about 5 second intervals. 3) This can last until someone notices and resets the Arduino.  4) If no one is home to reset the Arduino, the Arduino stops turning on and off the room light after a minute passes (12 flashes).

There are 2 tricky bits that may need explaining.  The first is how to sense the door bell.  If mechanical you could use a micro switch:

That way you don't need to worry about isolating the Arduino from what is likely a strong electrically noisy solenoid.  The other tricky bit is controlling a room light.  I would suggest using a COTS remote controllable light switch (I just did a search and there are loads of them in every price range) and hack the (battery powered) remote control into the Arduino.


Swapping 5V and GND for a 2 wire motor I have a 2-wire brushed DC motor in a servo housing which either pushes left or right (and "center" when unplugged).

To push to one side I connect a wire to 5V and the other to GND, to push to the other side I just need to swap the wires.

How can I achieve this with the arduino without any physical rewiring?

I think you need arduino motor shield.

Click Here

Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.


Pullup on compatible Arduino Mega I've got an Arduino mega compatible board, called Ethermega, from Freetronics (ATmega2560).
Schematic here.
In setup, I've written this code:
Serial.begin(9600);
  pinMode(4, INPUT_PULLUP);
  digitalWrite(4, HIGH); // Optional, I tried with and without
  while (1)
  {
    if (digitalRead(4) == HIGH)
    {
      Serial.write("Up!\n");
    }
  }

(Don't worry about the fact I'm not using loop)
When I connect input 4 with 5V, I see "Up!". Rest of the time, I see nothing.
Considering I have enabled the internal pull-up, I'm expecting it should be up/high by default, and I would have to connect it to GND to get it low...
Another thing that puzzles me is I can find heaps of examples that use a tactile switch and no pullup/pulldown at all...
So what am I missing or doing wrong? Seems like whatever I do, I've got some kind of pulldown enabled...

As @Juraj mentions, pin 4 is the CS pin for the SD card. That pin has a volage divider of 1kΩ + 2.2kΩ on it (a total of 3.2kΩ) to ground. So yes, you do have a pulldown on that pin. 3.2kΩ is about 1/10th of the value of the typical pullup resistor internal to the chip, so pulls the output low enough to be seen as LOW unless you manually override it.
You can't use that pin as an active low input on that board - choose another, or use it as active high.


SIM800L HTTP request is not reliable I have a question regarding SIM800L and HTTP GET request. I'm using this https://exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L simple code to communicate with SIM800l with AT commands. To perform the HTTP request, I use the following set of AT commands:

AT+CFUN=1
OK

AT+CSTT="internet","",""
OK

AT+CIICR
OK

AT+CIFSR
10.180.xxx.xx

AT+CIPSTART="TCP","84.42.xxx.xx",80
OK

CONNECT OK

AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

10
time201908191820
0

CLOSED

The problem is that sometimes. Or every other time, I don't get the whole HTTP answer. I usually get only the beginning. Something like this:

AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apac

and then after a couple of seconds, the connection closes.

CLOSED

Do you know what could cause that? It's literally random. I need the information from the webpage (it's the current time) and currently, it's really unreliable.

Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is the current time from printed from PHP.

Thank you very much!

Thank you for your answer. The code is as follows:

#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(12, 8); // RX, TX

String GET = "GET /bakalarka.php/? HTTP/1.1\r\nHost:84.42.xxx.xx\r\n\r\n";

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(19200);

}

void loop() {

  AT("AT+CFUN=1");
  AT("AT+CSTT=\"internet\",\"\",\"\"");
  AT("AT+CIICR");
  AT("AT+CIFSR");
  AT("AT+CIPSTART=\"TCP\",\"84.42.xxx.xx\",80");

  int get_length;
  get_length = GET.length();

  AT("AT+CIPSEND=" + String(get_length));
  AT(GET);
}

void AT(String AT){

  gsm.println(AT);

  if(gsm.available()){

    Grsp = gsm.readString();
    Serial.println(Grsp);
  }
}

I was thinking about a couple of things that could cause this.
1. Hardware design - some noise could cause a freeze of the GSM module while getting the answer from the server. After thinking through I don't think it's likely to be that. The power supply is made to be really beefy and there are enough bypass caps to reduce the noise and provide enough energy during current spikes. Also, the module doesn't freeze. It's still connected to the server, after a couple of seconds it closes the connection exactly as it should be.

Serial buffer gets somehow full. This was just a quick thought. The buffer of Arduino could get somehow full so it's not able to save any more incoming data. I think it's nonsense, but...

Thank you for your answers.

Krystof


Arduino code is not working for unipolar stepper motor I am using unipolar 1.8 degree stepper motor. I have written code to rotate stepper motor i.e. when A0 pin becomes HIGH it should rotate in clockwise and when A1 pin becomes HIGH it should move anti clockwise but motor is rotating only once when I am making A0/A1 HIGH and then stops. After that it is not rotating even if i am making A0, A1 pin high. I am very new to this please tell how to solve this problem. I am using microstepping drive, nema 17 stepper motor and Arduino Uno board.

#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = A0;
int buttonBpin = A1;
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}

I have mentioned in the comments that you should read the buttons with analogRead(). But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:

#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = 4; //connect button to digital pin 4 on arduino
int buttonBpin = 5; //connect button to digital pin 5 on arduino
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}


Velleman KA02 not working on Mega 2560 r3 I have a Velleman KA02 audio shield. When I use this shield on an Arduino UNO R3 with this sample code, it works. And by "work" I mean when I interact with the Serial Monitor (by pressing Y, for example), I hear the playback.

However, if I place this audio shield on a Mega 2560 R3, the shield no longer works (pressing Y does nothing). I read about the SPI library, and the document seems to suggest that MISO, MOSI, SCK and SS are different for the Uno vs the Mega. For the Uno,

MOSI: 11
MISO: 12
SCK: 13
SS: 10

and the article is consistent with the constants defined in the ISD1700.h file. For the Mega,

MOSI: 51
MISO: 50
SCK: 52
SS: 53

I can modify ISD1700.h for use with the Mega easy enough. However, I do not think I can just sit the audio shield right on top of the Mega with the modified code and have it work. I used some (male to female) jumper wires to connect from the Mega pins 50, 51, 52, 53 to the audio shield pins 12, 11, 13, 53 (correspondingly). Additionally, I have jumper wires connecting the power and ground from the Mega to the audio shield. What works is that the audio shield has power and I am able to press the physical buttons on the audio shield to record and playback. What does not work is that when I enter Y in the serial monitor to force a playback, although the character is read and the switch case is reached, the playback never happens.

Any ideas on what I am doing wrong? On the Velleman site, they seem to suggest that this audio shield only works with the Uno, but the Illustrated Assembly Manual says that the audio shield should work with the Mega.

Nevermind, I solved it. There's 6 pins located on the Uno and Mega labelled ICSP, and those were the key. I simply connected the MOSI, MISO and SCK pins on the Mega to the audio shield (along with GND and 5V) and also the 10 pin (audio shield) to the 53 pin (Mega) via a male to male jumper. The header code was modified to work with the new values, and now I am able to send character signals via the serial monitor.


Strage delay needed after Serial.read() I'm using a RedBear Duo to read the Serial writes from a RedBear Nano v2. Basically, I use a digital pin of the Duo to raise an interrupt on the Nano. Once, the nano catches the interrupt it writes on its Serial.

You can find a minimum working example below:

RedBear Duo

#include <Wire.h>

/*BLE and WiFi setup*/
#if defined(ARDUINO)
SYSTEM_MODE(MANUAL);
#endif

char incomingByte;   // for incoming serial data

void setup() {
    Serial1.begin(115200);     // opens serial port, sets data rate to 9600 bps
    delay(500);
    Serial1.println("Begin!");
    Serial2.begin(115200);

    pinMode(D5, OUTPUT);
}

void readSerial() {
    while (Serial2.available() > 0) {
        incomingByte = Serial2.read();
        Serial1.print(incomingByte);
    }
    Serial1.println(" ");

}

void loop() {
    digitalWrite(D5, HIGH);
    readSerial();
    delay(2);     // Here's the delay I'm talking about
    digitalWrite(D5, LOW);
    delay(1000);
}

RedBear Nano

uint8_t fire;
void task_handle(void) {
    fire = 1;
}

void setup() {
    Serial.begin(115200);
    fire = 0;
    pinMode(D4, INPUT);
    attachInterrupt(D4, task_handle, RISING);
}

void loop() {
    if (fire == 1) {
        fire = 0;
        Serial.write("hello ");
        // Serial.println("fire");
        digitalWrite(D13, HIGH);
    }
    delay(150);
}

I found this question (https://electronics.stackexchange.com/questions/28739/arduino-delay-of-1ms-necessary-between-serial-read-and-serial-write), and I understood that the problem might be the fact that it takes a while to empty the Serial buffer.

However, I tried to bring the baudrate at 500000 (more than 3x) and still if I change the delay to delay(1), the code is not printing what it has received on the Serial.

I'm trying to understand what is really going on and why I need this delay(2).

Thanks a lot in advance!

Try this code: first delay produces 1ms pulse on pin D5. Without this delay the pulse could be too short for the nano to catch it (you can use delayUs and try finding the shortest interval that produces reliable result). We know that after this pulse, nano sends some data. So wait 100ms to collect it. If you call readSerial right after the pulse was sent, you won't get anything, because you need to wait at least for single byte transmission

void loop() {
    digitalWrite(D5, HIGH);
    delay(1);
    digitalWrite(D5, LOW);

    delay(100);
    readSerial();

    delay(1000);
}


20x4 LCD shows alternating blank lines I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".

The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:

The below schematic is exactly how I've connected the display, which should be correct.

simulate this circuit – Schematic created using CircuitLab

I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.

The dead-simple example program is following:

#include <LiquidCrystal.h>

// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
    // Print a message to the LCD.
    lcd.begin(20, 4);
    lcd.print("hello, world!");
}

void loop() {
}

Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.

A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.


Programming Micro controllers using Arduino ISP Can I burn my Arduino Code into this:

http://www.microchip.com/wwwproducts/en/ATSAM3A4C

or something similar by just using just the Arduino ISP?

Page does nog exist (404).

Also, to run actual Arduino code on it, you'll most likely have to port the Arduino library, if this hasn't been done before.

You may opt for something as easy as a teensy 3.2, they probably meet your requirements and work well in combination with Arduino.
Or fetch one of the newer Arduino models that have comparable microcontrollers

If you still want an M3 (without development board?) you'll be entering a somewhat advanced usecase, in which you probably don't even want to rely on or use Arduino. There are far better IDE's.


Can Arduino Sketch be used for production There are lot of device support with the help of Boards Manager today and is on going in Arduino IDE.
So I am curious to know about can one use those for production purpose. Or it is recommended for quick prototyping purposes only...

There's a lot of controversy on this issue, but if it works for your needs, absolutely do it!
Basically, there are 2 questions you have to answer:

Should I use actual Arduino boards in production?
The answer is generally "no", simply because you need to customize the boards to add components to support your project, and to make them more robust, and cheaper, if possible. So, use an Arduino schematic as a guideline, then modify it to suit your needs.
One big exception to this, however, could be if you create a "mother board" onto which you will plug in a "daughter board" such as an Arduino Nano, Pro Mini, Pro Micro, or similar. You could make the Nano removable by soldering male headers onto it, and female headers onto the main "mother board", then you just plug in the Nano into the headers on the main board. Or, you could make it permanent by soldering male headers onto the Nano and then also solder that straight onto the "mother board" directly into the holes where female headers would otherwise be soldered. Both of these are great options, and this vastly simplifies your design and assembly process as you learn to get started manufacturing. Legal Arduino Nano clones are ~$1~$4 each, with shipping, on Ebay, and Pro Minis (not as good--here I recommend the Nano) are about the same, so buying a pre-made Nano is generally cheaper than buying just the raw chips on the Nano anyway, oddly enough. And again, this vastly simplifies your design and makes designing and assembling boards and products much much easier for the beginner/entry-level manufacturer (you) or micro business. It also allows you to make hand-made boards using perf-boards or proto (prototyping) boards, as I show in my other answer here.
For designing your own board, I recommend KiCad, which is Free and Open Source, and no cost ("free" == "free to modify"; "free" != "no cost"!), and actively developed by a volunteer team of about 6 people on a daily basis (I'm on their mailing lists and see this daily). It is a great product and is highly-capable. It is used by hobbyists and professionals alike, and has been used on many professional products world-wide. CERN, Arduino, and DigiKey have all contributed to KiCad in one way or another (see the list here: https://kicad-pcb.org/about/kicad/). The CERN Open Hardware Repository states here:

We think that KiCad can do to PCB design what the gcc compiler did to
software: ensure there are no artificial barriers to sharing so that design and
development knowledge can flow more freely.

That's an incredibly exciting mission!
There is also Autodesk Eagle, which is also popular among hobbyists and small businesses. It is a paid product, but has a no cost version for hobbyist, non-commercial use. It is also actively developed, by a tiny team of paid software developers on a pier in San Francisco. I've been to their office, and they are very excited about their work on it. They are doing a great job at making it a more-professional product. They've made some great improvements to Eagle over the last few years, hence why its price has gone up. It is also a great product.
Both products work on Windows, Mac, and Linux.
The Arduino board schematics are open-source hardware, so follow the licenses and provide attribution to where your design stemmed from. Ex: here's the Uno schematic. It shows the CC BY SA license logo at the bottom. I don't see a license version, but if it's 1.0, here's that license in plain terms. So, if you copy parts of the original schematics, release your design under the same license, and give credit to the original design.
You can NOT, however, use the Arduino logo or name. Those are trademarked and copyrighted, respectively. Arduino clones which do NOT use the Arduino name or logo are legal, and any clones which DO use the Arduino name or logo are illegal. There's no excuse for making an illegal Arduino clone. The schematics are intentionally open-source.
See also: Since Arduino uses Creative Commons licenses, do I also need to do that on my product?

Deriving the design of a commercial product from the Eagle files for an Arduino board requires you to release the modified files under the same Creative Commons Attribution Share-Alike license. You may manufacture and sell the resulting product.

And: Can I design my own Arduino board and sell it?

Since the hardware designs of Arduino are open source it is allowed to copy and further develop them. However this is not the same thing as making an Arduino board, only the company Arduino can design and produce Arduino products.
Your finished product is a product compatible with Arduino which should have its own name and brand. In case a copy uses the Arduino name and/or logo on it, this board is no longer a copy but a counterfeit which is illegal to manufacture and produce.

Should I use the Arduino software (build system and core libraries, and my program / "sketch") in production?
The answer is generally, "yes". This may be using the IDE for building or using the Arduino CLI command-line build interface.
The Arduino core and build system works great and has tons of internal and 3rd-party library support. The Arduino IDE itself is released under the GPL license (see below), and the core libraries are LGPL-licensed, which means if you modify them for your project, and put your project result into someone else's hands, you MUST release your modifications you made to the core code and libraries to those who have your project in their hands. See the main license file here:

this file includes licensing information for parts of arduino.
first, the gnu general public license, which covers the main body
of the processing/arduino code (in general, all the stuff inside the 'app'
and 'core' subfolders).
next, the gnu lesser general public license that covers the arduino core
and libraries.

But, you can keep your programs/"sketches" and main bits of project closed-source if you wish. Your programs are your own. They are copyrighted solely by you and you can license, use, and/or sell them however you wish. This includes the right to sell your Arduino/C and C++ programs as software or as firmware within a commercial product.
As a matter of fact, the GPL and LGPL licenses on the Arduino IDE and source code even allow you to sell the Arduino IDE and source code itself if you wish! This is really important, and is a fundamental right that "free and open source" software grants you. The Free Software Foundation, which is the owner of the copyrights on the license text itself, and the author of the GNU GPL and LGPL and other free and open source licenses, has this official guidance about selling and even reselling free software (they strongly encourage it!) (italics added):

Selling Free Software
Some views on the ideas of selling exceptions to free software licenses, such as the GNU GPL are also available.
Many people believe that the spirit of the GNU Project is that you should not charge money for distributing copies of software, or that you should charge as little as possible—just enough to cover the cost. This is a misunderstanding.
Actually, we encourage people who redistribute free software to charge as much as they wish or can. If a license does not permit users to make copies and sell them, it is a nonfree license. If this seems surprising to you, please read on.
The word “free” has two legitimate general meanings; it can refer either to freedom or to price. When we speak of “free software”, we're talking about freedom, not price. (Think of “free speech”, not “free beer”.) Specifically, it means that a user is free to run the program, study and change the program, and redistribute the program with or without changes.
Free programs are sometimes distributed gratis, and sometimes for a substantial price. Often the same program is available in both ways from different places. The program is free regardless of the price, because users have freedom in using it.
Nonfree programs are usually sold for a high price, but sometimes a store will give you a copy at no charge. That doesn't make it free software, though. Price or no price, the program is nonfree because its users are denied freedom.
Since free software is not a matter of price, a low price doesn't make the software free, or even closer to free. So if you are redistributing copies of free software, you might as well charge a substantial fee and make some money. Redistributing free software is a good and legitimate activity; if you do it, you might as well make a profit from it.
Free software is a community project, and everyone who depends on it ought to look for ways to contribute to building the community. For a distributor, the way to do this is to give a part of the profit to free software development projects or to the Free Software Foundation. This way you can advance the world of free software.
Distributing free software is an opportunity to raise funds for development. Don't waste it!
In order to contribute funds, you need to have some extra. If you charge too low a fee, you won't have anything to spare to support development.

This is only the first portion of their stance on the topic. Read the rest of the Free Software Foundation's encouragement to sell free software here.

That's the gist of it.
I am not a lawyer, and even if I was, none of my words herein are official legal advice.
When words come from the Free Software Foundation, who authors the GPL and LGPL licenses, however, those words are automatically extra legitimate.
Related:

Using Arduino for Industrial process
LGPL and Arduino in Commercial Products


24v LED strip with common anode? I have a 5m strip of 24v tunable white LEDs and I'm trying to figure out what I need set it up. There's a pad for V+ and then one for brightness and one for warmth. If I plug the V+ in V+ on a 24v supply and the two others to V-, the whole thing lights up full intensity. The strip draws 16 Watts per meter (80 for the whole thing). As I understand it, you vary the two anodes by varying the resistance to ground. I've seen some instructions that this can be done with PWM pins, but I'm assuming that given the voltage and current, no arduino or similar can handle that much. Do I need transistors then? What specs do I look for to understand the limitations?

Your strip has 2 LEDs with different color temperature directly besides at the same spot for every element of the strip. So the adjusting of the overall color temperature is done by changing the relative brightness of both LEDs. If the LED with the warmer light is brighter, the overall color temperature will also be warmer. Common Anode means, that V+ is the connected to the positive pin (anode) of both LEDs, so it has to be connected to +24V. The electrical circuit is completed by connecting the pins W and C (Warm and Cold) to ground. To control the individual brightness of the warm and cold LED groups, you have to use PWM.

You are right, that an Arduino cannot handle currents this big. You need a transistor for this. I would suggest using a MOSFET, since this is the easiest and most efficient possibility. By one MOSFET for every channel (Warm and Cold), which is capable of handling the needed power (Important! Or you will fry the MOSFET). Also it should be a logic level MOSFET, that is well in saturation of the gate voltage for the output voltage of your Arduino. Connect the MOSFETs Drain pin to the channel on the strip, the Source pin to ground of your power supply and the Gate pin to a PWM pin of the Arduino. Also connect the ground of the power supply with the ground of the Arduino.

Now you can control the brightness of the Warm and of the Cold LEDs by adjusting the PWM duty cycle with the Arduino.


Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound My Dad and I are just learning how to use my new UNO.

We have learned how to make leds flash at the touch of a button. We have also learned how to make a passive buzzer sound at the touch of a button and change tone to sound like a police car.

We have just learned that we cant run more than one loop so we have combined the buzzer code and the LED code twice (for blue and red LEDs) and it works... but the delay on the LEDs is ruining the buzzer sound. Is there anything we can do?

The code is below.

Thank you!

Code:

int buzzerPin = 9;    // the number of the buzzer pin
int BlueLEDpin = 5;   // the number of the blue LED pin
int RedLEDpin = 7;    // the number of the Red LED pin
float sinVal;         // Define a variable to save sine value for buzzer
int toneVal;          // Define a variable to save sound frequency for buzzer

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT); // Set Blue LED pin to output mode
  pinMode(RedLEDpin, OUTPUT); // Set Red LED pin to output mode
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

void RedLED() {
  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.


PIR motion sensor (HC-SR501) false results with NodeMCU I have a PIR sensor which I use to detect the motion and turn ON and OFF the lights on the basis of it.

I have PIR connected with NodeMCU (ESP8266) based board. I find that sometimes it trigger false positive value. Even when there is no motion. As per my understanding I think any of the following reasons can be there:

I have NodeMCU close to it. So may be because NodeMCU heatness triggers it.
Some hot air blow near it. But I don't know. It trigger the false positive even in mid-night.
It can be trigger by mosquitoes.
I have my other electric wires going from near by.

I am considering these scenarios correct? If yes then how can I prevent from them?

I tried to put it in a box and make it tightly pack. but still its false trigger. I checked even with multiple sensors and have same problem.

Any suggestions to protect this? I also check people put capacitor to smooth it. And put some resistance on Vin.

My Vin of PIR is connected to 5v and OUTPUT pin to D2.

For reference I am having this code for checking.

#define SIGNAL_PIN D2

void setup()
{
  Serial.begin(115200);
  pinMode(SIGNAL_PIN, INPUT_PULLUP);
//  digitalWrite (SIGNAL_PIN, LOW);
}

void loop() {

    static uint32_t lastSeenHigh = millis();
    static bool pirState = false;
    Serial.println(digitalRead(SIGNAL_PIN));

    // If it's active then record that fact along with the time
    if (digitalRead(SIGNAL_PIN) == HIGH) {
        lastSeenHigh = millis();
        pirState = true;
    } else {
        if ((millis() - lastSeenHigh) > 10000) {
            pirState = false;
        }
    }

    if (pirState == true) {
        Serial.println("Pir Is active");
    }
//
    if (pirState == false) {
      Serial.println("PIR sensor inactive");
    }
    delay(1000);
}

I had the same issue. PIRs have very sensitive circuitry and can be triggered by the WiFi signal from the ESP8266. The answer is to move them apart and with some decoupling of the power supply lines you should see much better performance. My PIR and ESP are now a couple of metres apart and I use shielded cable to connect them together.


Buy a genuine arduino board or a sainsmart board? Arduino Day is so popular! Many boards are cheap during arduino day. So should I buy a genuine arduino board or a sainsmart board?

Buying an official board can be a good choice for a couple of main reasons. First of all, you're guaranteed a good quality board which conforms to the official schematic, and is definitely compatible with any relevant official software and hardware. If the board turns out to be faulty when you get it, you'll be able to get it replaced. Additionally, buying official boards means some of the money you spend goes towards funding future Arduino projects.

As you've no doubt seen, cloned (i.e. unofficial) boards based on Arduino are often much cheaper. Nonetheless, many of the boards are very good. Functionally, you might not see any difference whatsoever from the official/genuine boards. Some of them actually have some additional features which you might find useful depending on your project, such as switching the IO pins between 3.3v and 5v.

However, not all cloned boards are worth using. Some of them may have lower quality components. It's even possible that they weren't designed/constructed correctly in the first place. This could lead to a range of problems, from incompatibilities through to outright failure of the hardware. Given the geographic location of some of the manufacturers/sellers, you may not have any way to get a refund if something goes wrong.

If you choose to use a clone, look for a brand which other people have had success with. Also do your best to ensure the board uses the correct microcontroller (e.g. the Atmega328 for boards based on the Uno).

Ultimately, the decision is up to you. There's no 'right' answer necessarily.


MPPT using preassembled 'adjustable' buck/boost IC This is more of a thought experiment, as I don't know if I'll have the time to work on it.

Items:

Arduino
Homebrew MPPT controller from Instructables
LM2596 Adjustable Buck Regulator

Idea:

Looking at the Instructable, that seems like a fairly interesting and robust circuit, originally developed by one Tim Nolan whose website no longer seems to exist.

I'm somewhat lazy/fearful of messing things up when building from scratch, so I like to get preassembled modules and tinker instead. So, my thought is simple (ish). Looking at the LM2596 module, the output voltage is determined by the setting of the multiturn pot. I'd like to replace that pot with, say, a PWM controlled voltage from an Arduino, which I can then adjust using Tim Nolan's code to achieve MPPT.

So to be very specific, the question is: can I safely remove that pot and use a PWM'd voltage in its place, in order to control the output for MPPT?

No.

The switching frequency of the LM2596 is 150kHz, but the sampling frequency of the Arduino is only 10kHz (on a good day).  You won't be able to adjust the PWM quickly enough to fine-tune the LM2596 output voltage.  The LM2596 uses the 1.23V feedback voltage to change what it's doing.  But the feedback voltage will only change as fast as the Arduino can change the PWM feeding it (and that the RC smoother will allow).

It will be like pushing a shopping cart backwards, blindfolded.  By the time you feel the directional change in the cart, it will have steered off course by quite a bit.  Then you have to compensate wildly to bring it back on course.

The same would probably happen here: the LM2596 would begin adjusting the output voltage to make the feedback voltage come back towards 1.23V.  But the Arduino doesn't respond in time.  The Arduino has to do an ADC conversion, do some calculations, change the PWM, which eventually changes the RC output voltage, which is the feedback voltage.  So the LM2596 changes some more... and even more.  Eventually the feedback voltage does change, but by this time the output voltage has changed significantly.

Another way to look at is that the LM2596 is like another "processor", trying to optimize its own function, output voltage instead of MPPT.  It's running much faster than the Arduino, so there's no way the Arduino can trick the LM2596 into doing what it really wants, MPPT.


Can I simply unplug the Arduino usb if serial communication is active? So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it.
Should be safe as long as nothing is uploading.
But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?

if the sketch is uploaded, it wont hurt it to unplug. Just give it another source of power and it will run its sketch.


Trigger external interrupt on Arduino Uno R3 with an LED and a button I want to cause the external interrupt on digital pin 2 (PD2 on ATmega328). I have chosen any logic change mode. Here is my code:

void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}

ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

Here is how I connect things.

NOTE: I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

The problem is when I push the button no interrupt occurs. What am I doing wrong?

Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.


Using a rotary switch I don’t have a sketch for this project, just doing some thinking before I pullout the keyboard (this is my phone).  I was interested in writing a program that uses a predetermined time limit, for instance having a definition like...

#define RUNTIME 30000

So the game runs for 30 seconds.
By doing this it would be a simple matter of changing the 30000 to 60000 and uploading to the Arduino.

After thinking about that a while, I would prefer to be able to adjust the time using a selector switch.
So my question is....  if I use a 1p4t (on-on-on-on) rotary selector switch,  assign each position to a pin and run 5v to the common. Each pin would defined as RUNTIME and a different time limit, 30000, 60000, 90000, 120000, three pins would be LOW and one HIGH depending on position.
Then using IF and ELSE statements in the loop setup would I be able to switch the times?  I know once the Arduino is powered up the selector switch would need to be at the correct location and if you choose to change the “RUNTIME” a reset would need to be pressed.

Thank you for any assistance or ideas.

If I understand you well, it's very easy.

Assuming the 4 outputs of the switch will be connected to 4 GPIO's you just can check for the state of each GPIO and act on it

// Pin numbers where switch 1 to 4 are attached to.
#define PIN_SWITCH_1  8
#define PIN_SWITCH_2  9
#define PIN_SWITCH_3 10
#define PIN_SWITCH_4 11

unsigned long timer_value = 1000; // No switch selected

void setup()
{
     // Set switch pins to input mode.
     pinMode(PIN_SWITCH_1, INPUT);
     pinMode(PIN_SWITCH_2, INPUT);
     pinMode(PIN_SWITCH_3, INPUT);
     pinMode(PIN_SWITCH_4, INPUT);

     // Check switches
     if (digitalRead(PIN_SWITCH_1) == HIGH)
     {
         timer_value = 30000;
     }
     else if (digitalRead(PIN_SWITCH_2) == HIGH)
     {
         timer_value = 60000;
     }
     else if (digitalRead(PIN_SWITCH_3) == HIGH)
     {
         timer_value = 90000;
     }
     else if (digitalRead(PIN_SWITCH_4) == HIGH)
     {
         timer_value = 120000;
     }
     else
     {
         // Keep default value
     }
 }

 void loop()
 {
     // Here you can use timer_value to check for the end of the game.
 }


iterate through values in an array of strings to print I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?

The code is as follows:

Declarations:

//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

Use (note the fake if statement for the question)

  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
  }

Instead I get random characters most of the time, sometimes nothing.

In case its a memory thing, please know that:

Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.

I think this is the correct way to create an array of C strings:

    char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    char * displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:

    String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }


Leonardo with xbee shield? I'm trying to get a XBEE shield to operate on an Arduino Leonardo. Usually i use the AltSerialLibrary to emulate an extra serial for the xbee. However since the Leonardo comes with two sets of serial, i figured I use that instead.

//#include <AltSoftSerial.h>

//AltSoftSerial XBee(5,13); // RX, TX

void setup() {

  Serial1.begin(9600);
  Serial.begin(9600);

}

void loop() {

  Serial.println("Odds");
  Serial1.println("Ends");

  delay(1000);

}

The code above aims to write values to both the serial monitor (serial) and xbee (serial1). However in the Xbee's XCTU program, the remote xbee does not recieve any data.

Any feedback on how I might fix this will be appreciated.

You said you are using a Xbee shield.  What shield is it, and what pins does it use for Serial communications?

If you were using software to emulate the second serial port on other arduinos, you were probably using different pins, and so if the shield is designed to communicate over (as an example) pins 2 and 3 then it will most likely not work with pin 0 and 1 without moving jumpers or switches.  For example, this
Xbee Shield: http://core-electronics.com.au/xbee-shield.html/?acc=9f61408e3afb633e50cdf1b20de6f466 has a switch to switch between pins 0 and 1 and pins 2 and 3.

You could also try some code that reads from Serial and prints the data to Serial1 and visa versa.  This means you can experiment to get a greater understanding of the problem.


Good quality sound using a microcontroller I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

Problem statement :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)
I have tried : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below
https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.

Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one.
I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.

Thanks in advance.

One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "

I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us

I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.


How long should TinyMPU6050.h calibration run for? I just found a lightweight library for the MPU6050 gyro. Example below.
mpu.Calibrate() never seems to end. I'm keeping it very still. When I take this out, the rest of the code works fine.

https://github.com/gabriel-milan/TinyMPU6050/blob/master/examples/ArduinoIDE_All_Gets_Example/ArduinoIDE_All_Gets_Example.ino

I feel so sorry about the previous releases of TinyMPU6050. I've just released v0.5.0 that shall soon be available at the Arduino Library Manager index.

The calibration method indeed was messy, so I decided to keep it simple. I also removed dependencies of String objects and Serial stuff and it seems to work pretty fine now.

If you keep having issues with that, please let me know!

The official link to release 0.5.0 follows:
https://github.com/gabriel-milan/TinyMPU6050/releases/tag/0.5.0


Using an Arduino for learning embedded C programming I'm a computer systems engineering student and was planning to buy an Arduino to learn embedded C programming. After researching I found mention that an Arduino may not be a good choice for a beginner that wants to learn about programming embedded systems using C.

I'm not sure if that is true, can an Arduino be programmed in C without using C++ and the other included class libraries? I'd prefer to learn how to program things at a fairly low level and not rely on libraries that hide details of the underlying hardware. Can the Arduino be used as a general AVR / microcontroller development platform to learn embedded C programming?

The Arduino is a great place to start embedded C programming. You can use both C and CPP. There are tons of tutorials online and there are a bunch of books available. In addition there are lots of libraries available on GIT HUB for interfacing with all types of hardware like RF24 Wireless Transceivers.

If you want to go into more low level programming, you can. For example, you can set all Port B pins to Output:

// the setup routine runs once when you press reset:
void setup() {

  // initialize the digital pins as an output.
  DDRB = 0xff;
}


I2C: What is the difference between A4&A5 and SCL&SDA pins? On tutorials are most people using the A4&A5 pins with the Wire.h library. But i have an arduino with dedicated I²C pins. How can i use them?

They are the same pins. They are physically connected to each other on the UNO board. (So SDA is connected to A4. SCL is connected to A5)


Opening a program in administrator with Arduino (DigiSpark/DigiSparkKeyboard) I am quite new to Arduino and DigiSparkKeyboard so I don't know much about them. I am trying to get by DigiSpark to open CMD in administrator mode but it just doesn't work. I know that I need to get it to press control, shift and enter at the same time in order for it to run as administrator but it doesn't work.
At the moment my code looks like:

#include "DigiKeyboard.h"
#define MOD_SHIFT_LEFT      (1<<1)  //00000010
#define MOD_GUI_LEFT        (1<<3)  //00001000
#define MOD_CONTROL_LEFT    1
#define KEY_ENTER   40
#define KEY_C       6
#define KEY_M       16
#define KEY_D       7
void setup() {
  // put your setup code here, to run once:
  DigiKeyboard.update();
  DigiKeyboard.sendKeyStroke(0);
  DigiKeyboard.sendKeyStroke(0, MOD_GUI_LEFT);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(KEY_C);
  DigiKeyboard.sendKeyStroke(KEY_M);
  DigiKeyboard.sendKeyStroke(KEY_D);
  DigiKeyboard.delay(1000);
  DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER);
}

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

}

Looking at the code, the first argument should be the key, and the second the modifiers. So DigiKeyboard.sendKeyStroke(MOD_CONTROL_LEFT + MOD_SHIFT_LEFT + KEY_ENTER); should become:

DigiKeyboard.sendKeyStroke(KEY_ENTER, MOD_CONTROL_LEFT + MOD_SHIFT_LEFT);`


manual square wave period is off I'm generating a square wave with my Arduino UNO using the following:

#define pin 10 // data pin to control servo

// pulse width (in microseconds)
int pulsewidth = 2500; // 400 Hz

// wave period in microseconds
int period = 20000; // 50 Hz

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

void loop() {

  // turn pulse on for pulsewidth duration
  digitalWrite(pin, HIGH);
  delayMicroseconds(pulsewidth);

  // turn pulse off
  digitalWrite(pin, LOW);
  delayMicroseconds(period - pulsewidth);

}

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).

Why is this exactly?  Is it because digitalWrite() is slow?

From Arduino reference on delayMicroseonds:

  Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if delay > 16383, a look at the actual code explains this (in wiring.c):

/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us)
{
...
#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards

    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can substract 5
    us -= 5; // = 2 cycles,
...

    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

The line us <<= 2; explains why us should not exceed 16383, otherwise the left-shifted value will overflow (unsigned int is 16 bits on AVR).

In your situation, (20000-2500) << 2 will not be 70000 or 0x11170 in hexa (that does not fit into unsigned int), hence the result will be truncated to 0x1170 i.e. 4464, which will make the last part of the function (the busy wait) wait for the wrong duration.

In order to fix it, you have to split your second delayMicroseconds in one delay in milliseconds plus one delayMicroseconds:

delay(17);
delayMicroseconds(500);


Showing chronometer on PC controlling the begining and end of time by Arduino I'm really new on this Arduino thing, so I don't know whether what I'm gona ask is feasible or not.

I'd like to make a chronometer in the computer but the controlling button (beginning and end of count) not to be some computer key. So I was wandering if I could make a button controlled by the arduino - maybe via a piezoelectric element?

Besides the problem of not knowing what to use as a button, I don't really know if it's possible to make a graphical interface (i know how to programme in C, Python, ...) showing the numbers in the screen of the computer and the beginning and end of counting controlled by that button. Is this possible to do?

Thanks for any help to both questions!

It's perfectly possible to do, and the way I would probably do it is to use one of the ATMega32U4 based Arduinos (such as the Arduino Leonardo or the somewhat smaller Arduino Micro) to act like a keyboard. A keyboard with just one key - your chosen button.

Then you program the computer to respond to the keycode the Arduino sends to start and stop the chronometer. You could even use an off the shelf chronometer program that starts and stops with a specific keypress and tell the Arduino to send that keypress. It would probably take about 5 minutes to write the software - if that.


avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x17 Every time I try to upload code to my arduino I always get this error : avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x17. How do i fix it ?

Welcome to the community! I'm not able to comment yet so i'll answer here.
Try changing the connection to other USB port.
If that doesnt work check this question, the solutions can be similar (Juraj is right in the comments) :
avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

Good Luck!


Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega I used the code from this project... to build an oscilloscope-like project. It worked fine with Uno and Nano.

Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:

------------------------------------------------------
// set up 8 MHz timer on pin 9
pinMode (9, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
OCR1A =  0;       // output every cycle
---------------------------------------------------------

And like:

Data.Values[i]=PINC;

I have very little knowledge about these registers.

Please help me port this code to Mega and make it work...

There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your project is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet here
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):

and find proper pin and corresponding register from ATmega2560 datasheet.
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:

and

You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)


Why are LED's receiving different voltages connected to Arduino I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:

  digitalWrite(blue1, HIGH);
  digitalWrite(green1, HIGH);

  digitalWrite(blue2, HIGH);
  digitalWrite(green2, HIGH);

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

Why is this happening and how do I get them all to light up the same?

After trying another Arduino I realized the problem. I did not use pinMode in the setup for all of the pins. Darn.


Should I use motor driver or Motor driver shield? I want to run 4 microgear motor for an RC car with Arduino. Should I use L293d motor driver/L298n motor driver/L293d motor driver shield?? I am using N20 microgear motor with following rating: 6 V, 200 RPM and 120 mA with no load, 40 oz-in (2.9 kg-cm) and 1.6 A at stall.

The right driver module or shield depends on the motor. Do you know the voltage and the stall current of the motors ?

The L293D uses bipolar transistors for the output stage inside the chip and can only drive 600mA. It has a large voltage drop: the motor gets less voltage than the power voltage applied to the driver. Therefor it can be used with small 12V motors, but it does not work very well with 6V.
The L298N also uses bipolar transistors and also has a large voltage drop.
A mosfet driver like the DRV8833 works better with 6V, because it has a low voltage drop.

In small RC toys with four AA batteries, sometimes a H-bridge is made is transistors instead of using a special driver chip.

The very cheap motor shield with two L293D chips (originally designed by Adafruit) can drive four motors, but it uses many pins.

Bottom line: Everything depends on your motors. I suggest to use a mosfet driver.


Powering Moisture sensor via arduino pin Can someone help me. I have this sensor

I just connected it to the 3V pin of my arduino only I read online that its better to connect it to a Arduinopin for power so you can put it off when not measuring. How do I do this? Can I just connect it to, let's say D4 and put this to HIGH and LOW or do I need something more. I googled a bit but found all kinds of different solutions. Some even talked about the need to PULLUP and PULLDOWN. whats the best way to do this.

The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).

I think it would be OK to use digitalWrite(pin_number, HIGH) to power the circuit board, then use digitalWrite(pin_number, LOW) to turn the power off.


What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module? I have seen commercial Xbee / Zigbee clones using HC-05 integrated inside.
Are they any different than regular HC-05 bluetooth modules?

What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

Bluetooth and Zigbee are two different communication protocols. The Xbee clones you are talking about a called BTbee.

As far as im aware the BTbee modules are the same hardware/firmware wise as the hc05/hc06 modules. The only difference being the BTbee modules are in the Xbee footprint, allowing you to plug them into Xbee/Zigbee sockets.


Arduino writes file to SD but not content to file I'm using an Arduino UNO, the Extended Database Library (EDB), and an microSD Card to read/write 2 database tables. I've managed to create both ".db" files on the SD (they show up in Finder when I load the microSD directly onto my Mac).

I can also populate them with placeholder data, but this data does not seem to be actually written to the file (and thus doesn't survive reboot).

Also, trying dbFile = SD.open(db_name1, FILE_WRITE); returns false, even though the files do exist on the drive?

Here's my create code:

#include <SPI.h>
#include <SD.h>
#define SD_PIN 10  //SD read/write pin
#define TABLE_SIZE 8192  //256*32
#include "Arduino.h"
#include <EDB.h>

char* db_name1 = "/DB/SENSOR1.db";
char* db_name2 = "/DB/SENSOR2.db";
File dbFile;

struct sensorLog1 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog1;
struct sensorLog2 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog2;

// Setting up EDB object
inline void writer (unsigned long address, const byte* data, unsigned int recsize) {
  dbFile.seek(address);
  dbFile.write(data,recsize);
  dbFile.flush();
}
inline void reader (unsigned long address, byte* data, unsigned int recsize) {
    dbFile.seek(address);
    dbFile.read(data,recsize);
}
// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup() {

  Serial.begin(9600);

  createDB(db_name1, "sensorLog1");
  createDB(db_name2, "sensorLog2");

  dbFile = SD.open(db_name1, FILE_WRITE);  // Doesn't work!
  if (!dbFile) { Serial.println("File does not exist"); }

}

void loop() {}

void createDB(char* db_name, char* table_name) {

  // create file
  dbFile = SD.open(db_name, FILE_WRITE);
  db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

  // populate with placeholder data
  for (unsigned int i = 1; i <= 20; i++) {
    table_name.id = i;
    table_name.input = 0;
    table_name.timestamp = 0;
    EDB_Status result = db.appendRec(EDB_REC table_name);
  }

  // check data
  Serial.println(db.count());  // returns '20'

  // close file to write
  dbFile.close();

}

db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

The third parameter is the record size! sizeof doesn't work on data, it works on types, so your getting the size of a char* instead of the size of your sensorlogN struct.

Your code as written shouldn't compile! a char* doesn't have a .id member.

table_name.id = i;
table_name.input = 0;
table_name.timestamp = 0;


mcufriend 2.4 tft mega 2560 Please help me w/ my 2.4 mcufriend TFT on my Mega2560.

I've followed any instructions I can find, including:

2.4" TFT LCD Shield isn't working on Arduino Mega

I still get a show white screen. I wonder if my TFT is different or is it broken? Mine looks like this:

I did run the example code from SWtft. I got this output on serial:

TFT LCD test

LCD driver chip: 6TFT LCD test
LCD driver chip: 6767
Benchmark                Time (microseconds)
Screen fill              1786024
Text                     413024
Lines                    2569212
Horiz/Vert Lines         226196
Rectangles (outline)     176972
Rectangles (filled)      4682244
Circles (filled)         2703104
Circles (outline)        1119540
Triangles (outline)      815028
Triangles (filled)       2867288
Rounded rects (outline)  469268
Rounded rects (filled)   5733992
Done!

I have one of these TFT LCD shields, but mine is a ILI9335. It has taken me nearly 2 weeks to find a working Library and code for my 9335 driver and I am now setting about creating sketches based around my working Library.
  Library - TFTLCD using st7783 controller
Unfortunately most sellers of these shields (excluding good reputable companies) do not adivise of which Driver is onboard the shield and it becomes difficult to locate a working Library for the driver of the purchased shield.

ALSO, check that the Libraries you have are working for your version of Arduino IDE. Some of my libraries would not compile in v1.0.5 but will in v1.6.3 (and vice versa)
If there is no Library specific to your 6767 Driver (and I must say I have not seen one in my searches for the 9335 Driver) then you may have to download as many different Libraries to locate a sketch that works for yours.
Once you have a working Library then it is just a matter of modifying it for your purposes.

Good luck in finding a working solution for your shield.

Lance..


Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch? I was reading in the OpenWRT wiki that you can indeed connect to the serial TTY console of an Open WRT roouter using the serial console if you're careful aabout the voltages.  https://wiki.openwrt.org/doc/hardware/port.serial.cables#method_b_no_physical_changes_to_arduino_board

However, I don't know anything about the voltages of my particular model of OpenWRT router a Netgear WNR2000v4.  I know that it is accessible via 3 holes on the board but I know nothing of the voltages.  Does anyone know or have experince with this about what voltages / wires to use to access it via the serial console?

The WNR2000v4 serial port is at JP1: 115200 8N1 at 3.3V. Pads are, from left to right with the ethernet ports on right: [GND] [Rx] [Tx] [Vcc]

Source: https://wiki.openwrt.org/toh/netgear/wnr2000, PCB picture: https://wiki.openwrt.org/_detail/media/netgear/wnr2000/wnr2000v1_pcb_detail_small.jpg?id=toh%3Anetgear%3Awnr2000


Recognize Morse-like code words In a line there're voltage levels representing words of dots and dashes. In particular, the device is intended to raise an output each time a given pattern of five short/long signals (say 1s and 2s durations, respectively) is recognized (and restart if nothing comes in for a given time). A sort of Morse code recognizer (Arduino Uno preferred, but others are also OK) would be a good starting point. Any hint is welcome, I'm new in this community.

Use a GPIO of an Arduino and check (at the speed you need) the HIGH/LOW state.

Depending on the speed at which is sent, you can check the dots and dashes being sent, e.g. by keeping a timer since the last change checking if it is a short or long 'HIGH'.

You have to sample often enough to check if there is a drop (between dots/dashes).


How to upload Arduino sketches to Atmel chips I am new in this Arduino coding world and I was trying to make a project. I normally used Arduino Unos all the time, but I was facing a problem and that is that the Arduino Uno has only 13 digital pins and 6 analog pins, and some of my friends advise me to use an Arduino Mega, but that costs too much, some to my friends also tell me that I could use only a Atmel chip, which will save money.

But the problem is that I can not burn these chips without a burner. I see online that Arduino Uno has Arduino ISP options also that will allow you to bootload or upload Arduino sketches to those kind of chips, but I have been trying for over 3 months and I cannot figure out how to do that

At present I am working with the ATmega8 chip.

This is my problem:

Using stk500v1 but the problem is not resolved

First thing you need to do in this situation is to crank up the verbosity level on the invocation of avrdude. You do this by adding one or more -v flags to the command line. With -v -v -v -v, you get maximum verbosity.

From your two logs, it appears that the initial handshake with the microcontroller was successful (which would indicate that your connections were good), but then the signature reading turns out quite badly. This is a rather unusual combination which makes me wonder whether you may have misidentified what microcontroller you have.


How can I store the received data from nRF24l01+ module in an array (code in description)? This is my sample RX code for 4 Tx and 1 Rx nRF24l01+ modules. I want to store all the data received from 4 pipes into an array (recArray).

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

const uint64_t pipes[4] = {0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4LL};
char text[32] = {0}; #received data
int recArray[4]={0, 0, 0, 0}; # array to store the received bytes

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, pipes[0]);
  radio.openReadingPipe(2, pipes[1]);
  radio.openReadingPipe(3, pipes[2]);
  radio.openReadingPipe(4, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

I would suggest to send 2 bytes to this module
the first byte is the pipe number (0xE1,0xE2,0xE3,0xE4)
and in the second byte Data

void loop()
{
  if (radio.available())
 {
  radio.read(&text, sizeof(text));
  for (int i=0; i < 4 ; i ++)
   {
     if( text[0] == ((unsigned char *)(&pipes[i]))[0]
        recArray[i] = text[1];
   }
  Serial.println(text[1]);
 }
}


Logic level converter not working? I'm trying to connect a 3.3v depth sensor to an Arduino uno. The logic level converter does not seem to send any current over (the sensor does not work and the voltmeter reads nothing). I tested the depth sensor separately, so I know it works, meaning it must be the converter. Why wouldn't it be working?

I've tried two logic level converters so far, but neither seems to work. This is basically how I connected it:

Here's the LLC:

Did I mess something up soldering it or by plugging it in wrong earlier?

Based on your schematic, you need to provide a 3.3v power source to the 3.3v side of the logic level converter. You can use the 3.3v pin on the Arduino.

Also, it's really hard to evaluate your soldering with such a shaky picture. Just make sure none of the pins are connected. A visual inspection usually will do, but if you want to be sure, use your multimeter's continuity function. Test all adjacent pins to confirm they are not bridged.


Solar powered ESP8266. WiFi module usage optimizations Above all, I am quite new to the ESP8266 and micro controllers development as a whole. I am now working on a project which is quite simple for now. It basically looks like this:

As you can see, I have an ESP8266 and some input peripheral. Everything works perfectly fine for the moment, I can read the inputs from the motion sensor and 4x3 keypad. And, respectively I can output on the relay and the 5mm LED. In order to make it a real IOT, I have connected it to the internet via Thinger.IO. So, I have my ESP8266 constantly connected to this platform and I can track it anytime, from anywhere.

This is great. But, my optimal goal is to power my configuration from a solar panel and make it independent of the electricity distribution network.

The average working current of the whole system is about 313mA (10000 mAh battery gets completely drained for 32 hours. Its output is 5V, 2.1A).

So, I am now in a search of the best solar panel to fit my needs. An ultimate one would have the following maximal dimensions: 30x35 cm. I am not sure there's a single panel that I can use but I am interested to hear your opinion in this.

Another aspect, that I'd like to optimize is the constant internet connectivity. Basically, I need to have my configuration connected to the internet only when keypad input was made or motion sensor detected something. During the rest of the time, I don't need to be connected to the internet and I assume WiFi module could be suspended somehow. Currently, my code uses SmartConfig and is looks like this:

#include <ESP8266WIFI.h>

void connectToWifi() {
  WiFi.mode(WIFI_STA);
  WiFi.beginSmartConfig();

  while(!WiFi.smartConfigDone()){
    delay(500);
  }
}

void setup() {
  connectToWifi();

}

void loop() {

}

Everything works well. But, as I said, I'd like to be able to start/stop the WiFi module. I tried using the following API:

void toggleWifi(bool isWakeUpCall) {
  if(isWakeUpCall)
    WiFi.forceSleepWake();
  else
    WiFi.forceSleepBegin(30000000);

  delay(500);
}

but without much of a success. Once it gets into this portion of code, it gets completely disconnected and doesn't get connected anymore. I am now struggling with it.

I've read about the sleep modes offered by the ESP8266 but I don't think they are suitable for my case because I can not simulate external interrupt (or maybe I can?).

I am really curious to hear your opinion on this. :)

As described here the ESP8266 can be waken up using Timer Wake Up or external interrupt. The idea is simple: almost everything inside the ESP is powered down (including Wi-Fi and/or System clock or even the CPU) with only a timer running which was told when to activate before the ESP went to sleep. After the desired amount of time has passed the timer triggers GPIO 16 or D0 and if that is connected to the reset pin of the ESP is resets and starts executing code again until it goes to sleep again. For your case you can configure your motion sensor to output a LOW when motion is detected and connect is to a GPIO pin and the reset pin, so it will trigger a restart when motion is detected and in the startup sequence you look at the pin where the sensor is connected and do what you have to do. For the keyboard to work you can have the timer set to reset every 5 seconds, so you would have to hold a button for 5 seconds waiting for the ESP to wake up and accept your input or you could make a dedicated button for waking up the ESP if you want to enter the code. In that case the you don't need a timer, since as you described the ESP only has to do anything if the keyboard is activated or if the motion sensor is triggered and since they can be connected as external interrupts they will wake up the ESP if needed. I would recommend to check out this link for further details about the code and hardware.


Arduino fried? Onboard blink ok; offboard blink not ok EDIT :

I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.

I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.

Here's the sketch :

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

void loop() {
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.

However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.

May I assume the arduino is fried?

Here is a thumbnail of the circuit :

Here's a guide posted by Nick Gammon for checking if your Arduino is bricked Is My Arduino Bricked ?


What is a cheap way to measure co2 or o2 level in air? I am making an air purifier which also increases o2 level as a school project but facing some difficulties. I plan to run the purifier whenever the co2 level is higher than usual or o2 level is lesser than usual but the sensor available in the market are quite expensive. So is there any cheaper alternative or any other method to detect a change in concentration?

Well, MQ 135 sensor is very cheap general air quality measurement device. It costs around 3$. There is another similar on AliExpress, not even worth mentioning. What is your budget? Gravity from Adafruit seems proper, yet it is at 56$. One that seems actually serious is K30 sensor, but that is around 100$. That 3$ stuff is general, and will work when temperature is constant, humidity is constant and Mars is aligned with Venus.

I think 56$ is ok if they want to have something proper. Remember that you get what you pay for.