Arduino clone avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04 Hi firstly sorry for my english. I am using windows 10, IDE version 1.8.13. I sure for selected correct arduino(Arduino uno),port is correct, tried another cable. I uploaded sketch 3-5 times but after give this error. I using MAX7219 led matrix shield and shield is working and shown my lastest upload before error. Error:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

Problem not solved, but I can program it with a USBASP programmer. I burned a bootloader, but the USB connection didn't work.
I am now using it without a bootloader.


Connect 5V relay to ESP32 WROVER B board I need to use a ESP32 WROVER B based MCU board with a standard (cheap) one-channel 5V relay (e.g. to switch on a mains-power appliance). Attempted removal of excess solder around the headers permanently disabled the 5V power output line from the board (to power a relay or other modules); but other pins functional/board boots up correctly. So at present, there is only a 3.3V power source and 3.3V GPIO pins (and others such as for external microphone and speaker). I assume it is safe to connect a 3.3V GPIO from the MCU to IN and external 5V power source to VCC ad GND of the relay and connect the grounds of the MCU AND relay together to complete circuitry. The relay only needs to switch the appliance on when triggered (for example a lamp) and switch off when triggered again. I have a 3.3 ↔ 5V bidirectional level shifter, but don't think it is suitable here (unless it can be incorporated directly). An alternative may be is to use an arduino uno to connect with the relay, itself triggered by the ES32 and more complex circuitry (bearing in mind the ESP32 GPIO is 3.3V and arduino 5V).

Assuming a relay module: check if it is OK to drive it with 3.3V logic when it is on a 5V power supply, or show the specs for us to look at.
Driving a relay module with 3.3V logic is unlikely to harm the ESP32, but it may not drive the relay properly if the relay module expects 5V logic.
Generally, I would even prefer using an external power supply rather than the 5V pin on a microcontroller board to power a relay module.
As long as you connect everything as you describe, it should work just fine (if the relay module accepts 3.3V logic).


How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins? When programming an ESP-01 with Arduino IDE, how can I make the Tx and Rx into a generic I/O pins reliably? I think there's a command to swap the Tx and Tx with other pins. I  tried serial.swap() but it didn't work. So how to get done with Arduino IDE or is it even possible?. I am using an ESP-01, which means there will be four GPIO pins once this question in answered.

I want to achieve same as in the video, How to add more GPIOs to ESP8266 (ESP-01), but without soldering wire.

Add this to your code at the beginning of set void setup():

//********** CHANGE PIN FUNCTION  TO GPIO **********
//GPIO 1 (TX) swap the pin to a GPIO.
pinMode(1, FUNCTION_3);
//GPIO 3 (RX) swap the pin to a GPIO.
pinMode(3, FUNCTION_3);
//**************************************************

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.

To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set void setup():

//********** CHANGE PIN FUNCTION  TO TX/RX **********
//GPIO 1 (TX) swap the pin to a TX.
pinMode(1, FUNCTION_0);
//GPIO 3 (RX) swap the pin to a RX.
pinMode(3, FUNCTION_0);
//***************************************************

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.


What is the meaning of the preceding character on several library defines? I have been reviewing the code for several libraries,mostly by SparkFun, and looking at the defines for for instance the chip select pins for their hardware.

In the defines, rather than being a simple number or string, they have the following syntax:

#define P_MOSI  B,3

with others being preceded by a D instead.

I am surmising this may be a data type definition, but I don't recognise the syntax and am wondering

What does the syntax mean?
What is the effect of nominating the data type of a define?
Is this Arduino specific syntax or general to C/C++?
If I want to modify a value, is it as simple as changing the value after the comma?

I looked into one of these libraries, namely the SparkFun CAN-Bus
Arduino
Library.
The macro appears to be used inside other macros that require two
arguments, for example RESET(P_MOSI);. Given the following
definitions from the library:

#define RESET(x) _XRS(x)
#define _XRS(x,y) PORT(x) &= ~(1<<y)
#define PORT(x) _port2(x)
#define _port2(x) PORT ## x
#define P_MOSI B,3

the call RESET(P_MOSI); expands to

PORTB &= ~(1<<3);

PORTB is the name of an IO port of the MCU which controls the outputs
of the pins. It is actually a macro from
avr-libc that expands to something
like:

(*(volatile uint8_t *)(0x05 + 0x20))

where 0x05 is the IO port number of the register (the number depends
on the particular AVR chip) and 0x20 is an offset needed to get the
memory-mapped address from the IO port number. When the compiler does
constant folding, RESET(P_MOSI); resolves to

*(volatile uint8_t *)0x25 = 8;

which is then compiled into

cbi 0x05, 3

a single assembly instruction (Clear Bit in Io port) that executes in
two CPU cycles and sets to zero the bit 3 of IO port 0x05.

The same end result could be achieved in a much simpler way:

#define P_MOSI 11  // assuming digital 11 = PB3, as in the Uno
#define RESET(x) digitalWrite(x, LOW)

However, the function digitalWrite() is very slow, mostly because it
has to map an Arduino pin number to a port address and a bit number, and
it does it at run time. The SparkFun approach, though somewhat
convoluted, is way more efficient, because the mappings are performed
at compile time.


Difference between Arduino IDE giving me headaches For some time now I've been playing around with the latest version of Arduino IDE and my UNO and ATTiny with simple 433 RF links with the Manchester Library. It all worked fine, but for my next project I want to take the step up and use a better wireless thingy... like the nRF24l01 or the nfm12b.

And then starts the pain. Attiny does not have hardware serial, but people seems to have solved this by implementing software-serial. But then they have to use some other boards for ATTiny, because when I try to run the examples I get error messages that it could not find  and so on. I use the ATTiny boards I found over at google code.

Regarding the RFM12B I got something to compile. If I went back and downloaded Arduino IDE 1.5.0 (no other!) it actually work with the JeeLib - hurray! Why is this, why can't I use the latest version of the Arduino IDE?

Regarding the NRF24 chip this case is unresolved. I have not found the correct combination of boards, IDE and library versions. Could anyone point me in the right direction?

What are the difference between the Arduino IDE's? Why can I get stuff to work on 1.5.0 but not the latest 1.6.x?

To get RF24 working:

Download the latest IDE (not 1.0*)
Use the library manager to download the
latest RF24.
See https://github.com/TMRh20/RF24/issues/236#issuecomment-205354077
about what core to use.
Don't forget to define ATTiny in the sketch
Ex: #define __AVR_ATtiny84__
(84, 44, 24 are the choices)

ATTiny* do not have SPI, that's why it can't find SPI.h (SPI library).


Uno R3's a4 and a5 not working after installing itead SD Shield 3.0 I'm working on a data logging project and would like to use all six analog inputs on my Arduino Uno R3.  I've been able to get everything working, including writing to the SD card.  However, with the shield installed I'm getting junk readings from a4 and a5.  They work fine without the shield.

The shield has pull-up resistors for I2C/TWI on pins A4 and A5. Special care (resistor bridge) needs to be taken if using these as analog pins. Please see the schematics for more details.

https://www.itead.cc/wiki/images/4/46/Sch_sd_shield_3.0.pdf

Cheers!


How to merge two arduino sketches, one for relay's and one for Servo motor? Recently I uploaded individual codes for relay's and Servo motor seperately, it all worked fine. But when I combined these two codes and dumped in to the loop there is a delay in functioning of the relay's but the Servo motor is working fine.

I have to control these devices through Bluetooth HC-05 module.
Could you please help me with the code?

/*
simple LED test
*/
#include <Servo.h>
char val;         // variable to receive data from the serial port
int ledpin = 2; // LED connected to pin 2 (on-board LED)
Servo myservo;
int pos = 0;    // variable to store the servo position
int motor = 0;

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.print("Arduino control Servo Motor Connected OK");
  Serial.print('\n');
  Serial.begin(9600);       // start serial communication at 115200bps
  digitalWrite(ledpin = 2 ,HIGH);
  digitalWrite(ledpin = 3 ,HIGH);

}

void loop()
{

      if( Serial.read() == 'a' )    // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2

  }

  if( Serial.read() == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2

  }

  if( Serial.read() == 'b' )        // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3

  }

  if( Serial.read() == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3

  }

  if (Serial.read() == '\n')
    {

   motor = Serial.parseInt();
    pos = Serial.parseInt();
      myservo.write(pos);
      delay(15);
      Serial.print("Data Response : ");
      Serial.print(motor, DEC);
      Serial.print(pos, DEC);

    }

    }

A couple of things stand out in your code.

Whenever you perform a digital write you assign a value to ledpin:

digitalWrite(ledpin = 3, LOW);

This is not necessary as you do not do anything with the ledpin variable. Instead, just have the digital I/O pin number:

digitalWrite(3, LOW);

Or simply have 2 variables, one for pin 2 and another for pin 3. Eg.

redledpin = 2;
greenledpin = 3;

This also applies to the pinMode function calls in the setup function.
Each one of your  if( Serial.read() == xx) statements will read a serial character off of the serial buffer. Instead store the read character in a local variable:

readChar = Serial.read()
if( readchar == 'a')
...
if( readchar == 'A')
...
if( readchar == 'b')
...
if( readchar == 'B')
...

I would encase all of the code inside loop() with:

if ( Serial.available() )
{
    ...
}

The delay function is blocking and this will cause issues. I suggest deleting the delay altogether.
Due to the fact that you are sending commands to turn digital outputs on and off as well as sending an integer for motor and another for pos, I suggest that you define a packet structure and make your code follow that (with the necessary error handling). As the code currently stands you will miss information, depending on what character it sees first on the serial buffer.

I suggest something like:

A, B, 142, 090

Starting the packet off with a know character is a good idea. So is having a timeout period - in case only a portion of your packet is received.


Is it possible to transmit radio signal with cheap 433Mhz transmitter as strings and receive it with an RTL-SDR I have these Arduino transmitters and receivers.

They are very common. I am just trying to transmit a "Hello" Message using this code.

#include <RH_ASK.h>
#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;
// RH_ASK driver(2000, 4, 5, 0); // ESP8266 or ESP32: do not use pin 11 or 2
// RH_ASK driver(2000, 3, 4, 0); // ATTiny, RX on D3 (pin 2 on attiny85) TX on D4 (pin 3 on attiny85),

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);   // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
         Serial.println("init failed");
#else
    ;
#endif
}

void loop()
{
    const char *msg = "hello";

    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(200);
}

But they have to be received from the receiver module using another set of codes which I have done it.

But my question is, is it possible to receive the transmitted message with one of RTL-SDR's INSTEAD of using the receiver module? If so, How to do it?

In general you can use RTL-SDR to decode any AM and FM modulated signals (+some digital modulations) that lie within the frequency range form roughly 50MHz to about 1GHz. So 433MHz is confortably within that range.

There are many projects on GitHub that leverage the RTL-SDRs ability to decote 433MHz OOK modulated signals like:

RTL_433
Which comes with a ton of decoders for various appliances.

OOK_Decoder
Which will give you the demodulated raw output for you to decode the bits yourself.

I'm sure you will find more but those are in my opinion the most noteworthy for the 433MHz OOK space.


Can I change this code to use a potentiometer instead of a push button The following code is for a pyrograph power supply that uses an ATtiny85. I want to change it, so instead of a push button I have a potentiometer being the control of the temperature. Can anyone guide me on how to accomplish this with this code?

//Written by Tyler Gerritsen
//2017-10-21
//Pyrography Pen Power Supply Controller
//Written for ATTiny85 w/ Internal 1MHZ Clock

const byte btn = 2;
const byte led = 1;
const byte pwr = 0;
byte rate = 0;
unsigned long nextChange = 0;
boolean onOff = false;
unsigned long blinkyCount = 2000000000;
unsigned long nextBlink = 0;
unsigned long debounceTimer = 2000000000;
const unsigned int debounceDelay = 400;
const unsigned int onDelay[5] = {6800, 6300, 5800, 6300, 4800};
const unsigned int offDelay = 5000;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  digitalWrite(btn, HIGH);
  pinMode(led, OUTPUT);
  pinMode(pwr, OUTPUT);
  digitalWrite(pwr, LOW);
  debounceTimer = 60000000;
  while (digitalRead(btn)) {
    checkButton();
  }
  analogWrite(led, 0);
  nextChange = micros();
  debounceTimer = millis() + debounceDelay;
  blinkyCount = 1;

}

void loop() {
  runBurner();
  checkButton();
}

void runBurner() {
  if (micros() > nextChange) {
    if (onOff) {
      digitalWrite(pwr, LOW);
      onOff = false;
      nextChange += onDelay[rate];
    } else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

void checkButton() {
  if (!digitalRead(btn) && millis() > debounceTimer) {
    debounceTimer = millis() + debounceDelay;
    rate++;
    rate %= 5;
    blinkyCount = (rate) * 2 + 5;
    nextBlink = millis();
  }
  if (blinkyCount > 1 && millis() > nextBlink) {
    if (blinkyCount % 2) {
      digitalWrite(led, LOW);
      blinkyCount--;
      nextBlink += 150;
    } else {
      analogWrite(led, 10);
      nextBlink += 150;
      blinkyCount--;
    }
  } else if (blinkyCount == 1) {
    analogWrite(led, 10);
    blinkyCount = 0;
  }
}

This is a simple sketch that shows how to read a potentiometer and do something with the value, namely, adjust the delay of the blinking led.

[Source: https://www.arduino.cc/en/tutorial/potentiometer]

/* Analog Read to LED
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13. The amount of time the LED will be on and off depends on
 * the value obtained by analogRead(). In the easiest case we connect
 * a potentiometer to analog pin 2.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int potPin = 2;    // select the input pin for the potentiometer
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
}

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  digitalWrite(ledPin, HIGH);  // turn the ledPin on
  delay(val);                  // stop the program for some time
  digitalWrite(ledPin, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}

So, in every loop iteration you read the potPin and using that value for delay.

AnalogRead gives you a value between 0-1023, which you have to adjust to give the desired value for temperature control. That is all you need.

Use map function to adjust the value. Look at https://www.arduino.cc/reference/en/language/functions/math/map/


Can't Upload Sketch, Atmel SDM Chip Overheating I have a chinese CH340 clone arduino. It was working fine until now. The L light stays always on. The sdm Atmel chip is overheating to the point that I can't even touch it. The card is listed under com ports however I can't upload anything due to:

avrdude: stk500_recv(): programmer is not responding

Should I just throw it away or is there a way to save it?

u need to cool down the chip for a few minutes and it will work the uploads use a heatsink or something small enough to cover it


little pump isn't working I'm trying to use a little pump with my arduino nano:

void setup ()
{
  pinMode(waterPump, OUTPUT);
}
...
  while (val < valueWater)
  {
    Serial.println ("in while"); // testing purpose
    digitalWrite(waterPump, HIGH);
    delay(1000); // 1 second
    digitalWrite(waterPump, LOW);
    val = analogRead(sondeEau);
  }

When I try this one, pump isn't working. When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?

I tried to plug pump directly on 5V on arduino, pump works well...

This is the pump I bought: http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808

Thanks in advance to help me!

As Chris says, you should never plug a high current device like a motor directly into a pin on your Arduino. That motor is rated at 800 mA, which is more than you can draw from the entire 5V supply on the Arduino!

The digital pins are rated for 40 mA max, if I remember correctly. You tried to draw 20 times that much. There is a decent chance that you burned out the driver for that digital pin. I would try hooking an LED through a 220 ohm resistor and to ground and see if it still lights up when you send it a HIGH logic signal.

For a simple DC motor you should be able to use a high current transistor and an external power supply to drive it.

Edit:  If I were doing this I would use a logic-level MOSFET to drive the pump directly, plus a flyback diode. To use a relay, you will still need a transistor to power the relay coil, AND a flyback diode. Your circuit might look like this:

(Note that I made no attempt to pick the RIGHT kind of diode and transistor. Ignore the part numbers shown in the schematic. I just used the defaults.)


"expected primary-expression before '.' token" in debug code I'm making some code for school, and is adding debug code to it. When compiling, I get the error as written in the title. This is the code in question:

#define DEBUG 1

#ifdef DEBUG
#define Serial.println(x) DEBUG_PRINT(x)
#else
#define DEBUG_PRINT(x)
#endif

And the code in my void setup, which has Serial.begin:

#ifdef DEBUG
Serial.begin(9600);
DEBUG_PRINT("Asteroid");
#endif

What am I getting wrong? I get the feeling it's my define text, but I'm unsure.

Thank you for your time
Gaarden

In short: you have your macro backwards.

Macros are not formed as "Take this set of commands and call it X" but "Make this macro X and have it equate to this set of commands".

Where you have:

#define Serial.println(x) DEBUG_PRINT(x)

it should instead read:

#define DEBUG_PRINT(x) Serial.println(x)

When you call it, because the macro doesn't contain a semi-colon in it, you need to specify the semi-colon as if you were calling a function:

DEBUG_PRINT("Aardvark");

You can omit the semi-colon only if you have a semi-colon in your macro:

#define DEBUG_PRINT(x) Serial.println(x);

and then:

DEBUG_PRINT("Aardvark")

By doing it that way your "empty" macro now does become truly empty when used.  Without the semi-colon in the macro you would have to use:

DEBUG_PRINT("Aardvark");

Which for the empty variant would end up as:

;

Not always desirable, and can cause some problems.

So by adding the semi-colon into the macro you can omit it from the usage of the macro, and your empty variant now becomes:


How to run Arduino code on Linux? I want to use an MFRC522 module as explained in this video.

But is it possible to get around with Arduino and use a TTL to USB converter to connect RC522 directly to my PC running Ubuntu?

Using the RC222's UART interface, should I rewrite Arduino libraries from scratch for PC or is there a way to easily port the libraries?

Arduino libraries rely on the Arduino API to operate (usually). Things like the Serial object are expected to be defined.

Linux doesn't have any of that stuff, so you would have to implement it all yourself.

There is the "Wiring Pi" project for (obviously) the Raspberry Pi that implements the majority of the Arudino API, but whether that could be made to run on Linux on a PC is anyone's guess.

It may be simpler to just examine the existing library (and datasheet) and implement it yourself in your chosen language.


Disabling i2c internal pull up resistors How do you do this? I've been digging around and I can see that I should do this and supply my own external pull up resistors but I don't know exactly how to disable them. The pages I've been reading never explicity state how.

I'm trying to enable I2C between a leonardo and an uno, but I think the i2c bus is slowing down considerably because of the internal pullups. I want to switch to two 4.7k resistors but I can't figure out how to disable the internal ones. I know that the Wire library enables the internals by default, but how do I edit the library or disable the pullups in my sketch?

Maybe I just haven't been reading the right forums or articles, but if anyone could point me in the right direction that would be much appreciated.

EDIT: So the problem is probably with my setup or code, I'll put it down here. Everything I have before setup is importing libraries and variables like my mac, ip, placeholders for output, pwm, etc.

Master:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial){
  }

  Wire.begin();

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

  server.begin();
  if(server.available()){
    Serial.println("Client Available");
  }
}

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

  ethernetwrite();

}

void ethernetwrite() {
  EthernetClient client = server.available();
  while(client) {
    if(client.find("P")) {
      output = client.parseInt();
      pwm = client.parseInt();

      Serial.println("Begin Transmitting");
      Wire.beginTransmission(14);
      Wire.write(output);
      Wire.write('\t');
      Wire.write(pwm);
      Wire.endTransmission();
      Serial.println("Done Transmitting");

      Serial.print(output);
      Serial.print('\t');
      Serial.println(pwm);

    }
  }
}

Slave:

void setup() {
  Wire.begin(14);
  Wire.onReceive(wirewrite);

// *   - Base frequencies:
// *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
// *      o The base frequency for pins 5 and 6 is 62500 Hz.
// *   - Divisors:
// *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
// *        256, and 1024.
// *      o The divisors available p1on pins 3 and 11 are: 1, 8, 32, 64,
// *        128, 256, and 1024.

    // Leg 1
    pinMode(leg[1], OUTPUT); setPwmFrequency(leg[1],8); analogWrite(leg[1], offset);

    // Leg 2
    pinMode(leg[2], OUTPUT); setPwmFrequency(leg[2],8); analogWrite(leg[2], offset);

    // Leg 3
    pinMode(leg[3], OUTPUT); setPwmFrequency(leg[3],8); analogWrite(leg[3], offset);

    // Leg 4
    pinMode(leg[4], OUTPUT); setPwmFrequency(leg[4],8); analogWrite(leg[4], offset);

    // Mirror
    pinMode(leg[0], OUTPUT); setPwmFrequency(leg[0],clkdivisor); analogWrite(leg[0], 255);
}

void loop() {

    int time = 10;
    time = time*128/clkdivisor;

    // box(time, 255, 1); // box(delay time, radius pwm, pwm step size);
    // autodisplay();
    updateL();

}

void updateL(){
  if (output == 0) pwm = 255 - pwm;
  switch (output) {
    case 1: pin =  3; break;
    case 2: pin =  9; break;
    case 3: pin =  10; break;
    case 4: pin =  11; break;
    case 0: pin = 5; break;
  }
  //if (output < 5) {
    analogWrite(pin, pwm);
  //}
}

void wirewrite(int numBytes) {
  String message;
  while(Wire.available()>0) {
    char c = Wire.read();
    message.concat(c);
  }
  output = Wire.parseInt();
  pwm = Wire.parseInt();
}

When I send data to the master, on the serial monitor it freezes in the first wiring transmission or in the next few, and my slave doesn't seem to respond to the message being sent over i2c. My controls for my device and setup worked prior to my attempts with the Wire library, so there's no problem there.

EDIT: I also am sending a message that looks like this:
"P1 103"
every .4 seconds or so, but I usually can't get past the first transmission between the arduinos

From the datasheet:

  Note that the internal pull-ups in the AVR pads can be enabled by setting the PORT bits corresponding to the SCL and SDA pins, as explained in the I/O Port section.

To disable the internal pull-ups:

digitalWrite(A4, LOW);
digitalWrite(A5, LOW);

or

digitalWrite(2, LOW);
digitalWrite(3, LOW);


Why is their need of response time needed in esp8266 AT commands? I am writing an AT commands firmware for esp8266 via connecting it to atmega2560.
Now the question is how will I come to know the response time for AT commands for writing its firmware to read the response?
in fact prior to this thought, the question comes why is their need of response time in AT commands?
does response time concept is there in all modules where AT commands are used like gsm modules, HC05,etc.

Your esp8266 firmware isn't required to wait before responding to the atmega2560, but the reality is that it simply can't respond in zero-time. The esp will take some processing to interpret the command that was sent to it and to create the reply to the atmega. And that is even if it doesn't have to wait for some distant server.
If the esp has to send a WiFi request to a server (which has the same constraints of processing time, plus other requests ahead of yours), that only adds to the esp's delay in responding to the atmega.
The bottom line is that the esp isn't required to wait any amount of time to respond; its just however much time it takes to acquire any data it needs, plus processing time to format it and send it back to the atmega.


Use callbacks in Arduino with pointers to functions (will functions persist in memory?) As I been learning Arduino (micro controllers, c++, etc) I have learned that memory is very limited. I already understand how memory works when it comes to variables. But I do not understand how memory works when it comes to functions. Since I am a backed developer I try to stay away from interrupts and instead use callback functions. Another reason why I prefer to use callback functions is because I love the visual studio IDE. I create my core functionality of whatever project I am building on a c++ project targeted for Windows. Once my algorithms/logic works the way I want it I reference those libraries on Arduino.
Anyways I am using lambdas to pass functions to my helper libraries. That way I do not use the delay function to wait for a response and I am always listening for events. Basically my question is if it is correct to have code like this (function SendEvent):
/* MyRadioLibrary.h */
// I am not including all the code of `MyRadioLibrary` because that makes it hard to
// understand what I am asking. Instead I will try to use a lot of pseudo-code. Let me
// know if you want me to post the code as an edit.

class MyRadioLibrary
{

public:

    static void SendEvent(int typeOfEvent, void(*onEventCompleted)(bool x))
    {
        // I have an array of pointers to functions
        void(*onEventCompletedBuffer[10])(bool x);

        // I enqueue that event with a queue helper class

        // Send event ....

        // DO NOW WAIT FOR RESPONSE SINCE CALL BACK IS ALREADY SAVED
    }

    static void loop() {

         // listen for radio messages
         if(radio.available()){
                // get response
                // dequeue pointer to call back
                // execute call back
          }

    }
};

And my arduino sketch contains this code:
#include <MyRadioLibrary.h>

void setup()  {
    // setup pins etc..
}

void loop()
{

    if (isButton1Pressed())
    {
        MyRadioLibrary::SendEvent(1, [](bool didEventCompletedSuccessfully) {

            if (didEventCompletedSuccessfully)
            {
                // turn on green LED
            }
            else {

                // turn on red led
            }

        });
    }
    else if (isButton2Pressed())
    {
        MyRadioLibrary::SendEvent(2, [](bool didEventCompletedSuccessfully) {

             // call back function

        });
    }

    MyRadioLibrary::loop(); // listen for response events. When we get one fire call back.
}

Now the question
When I call the SendEvent function I am passing 2 things (1) an integer and (2) a pointer to a function that is the call back. The integer (1) is passed as value and that will be part of the stack of the SendEvent function. The pointer (2) will be stored on an array of pointers. But what about the lambda function? where will that be stored? Instead of using a lambda function should I declare those functions in global scope and pass the global function instead of a lambda? Will I run the risk of the pointer (2) pointing to a function that no longer exists if I use this way of coding?

Your functions won't cease to exist. All of the code in your compiled and linked code image gets loaded into code-memory (Flash) and it stays there throughout the run, through resets, and through power-cycles, until another image is loaded over it.
Are you confusing pointers to functions with pointers to a function's local variables which occupy RAM memory, specifically within the function's stack-frame which is transient, being created and "destroyed" as the function gets called and returns - and successive stack-frames won't necessarily be created in the same place.


Decoupling cap for self-powered LED matrix and LED strip Should I add a decoupling capacitor to my RGB 16x32 LED matrix powered directly via the 5V pin?

When I display a spectrogram, the current load is fluctuating quickly in the 100-250 mA range (on average, the full range is 50-300 mA).

If yes, which capacitor should I pick for this purpose?

I have 0.01 μF, 0.1 μF ceramic and 1 μF, 2.2 μF, 4.7 μF, 10 μF, 100 μF electrolytic caps.

EDIT: I'm also interested to know about this WS2812B LED strip i've connected to the 5 V pin to another Arduino.

After reducing the brightness it has similar current consumption and fluctuation of the LED matrix.

In this tutorial they suggest to add a 1000 μF cap, but in my case the currents are much smaller.

No, there is no need. The matrix already has plenty of decoupling on it, including a large electrolytic for the incoming power and a small ceramic on each of the chips.


Continue playing sound during interrupt routine I'm trying to play a tone (on an Arduino Mega through the tone library) and have the tone not be interrupted if an interrupt routine is called while the tone is playing. I'm not sure it's possible. The code block is below. Relevant functionality is:

-A while loop runs indefinitely until Button S1 is pressed. Pressing Button S1 triggers an interrupt routine in which interruptFlag_s1 is set to 1.

-This starts a tone playing for 300ms.

-There's a possibility that another button press interrupt is triggered during the 300ms tone. This interrupts the tone for about 0.5ms, enough to make a perceptible break in the tone that I'd like to avoid.

-Ideal scenario is that the audible tone isn't interrupted by the interrupt routine.

    while (restart == 0) {
      if (interruptFlag_s1 == 1 || interruptFlag_s2 == 1) {
        if (interruptFlag_s1 == 1) {
          primary_sensor = 1;
          interruptFlag_s1 = 0;
          rBot = false;
          gBot = true;
          bBot = false;
        } else if (interruptFlag_s2 == 1) {
          primary_sensor = 2;
          interruptFlag_s2 = 0;
          rBot = false;
          gBot = false;
          bBot = true;
        }

        interruptFlag_rtc = 0;
        finish_id = 0;
        button_flag = 0;
        time_diff = 0.00;
        alt_finish_time = 0.00;
        tone(speakerPin, 3000, 300); // Start tone
        restart = 1;
      }
    }

The sound is itself generated by an interrupt routine. Since only one interrupt routine can happen at a time, if your own interrupt routine takes too long, then you will get interruption in the sound.

There is nothing you can do about that other than making your interrupt routine short enough that it doesn't cause any interruption in the sound.


Controlling a LED array from Arduino NANO I have a project Im currently busy with that I need a lot of help with.

What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).

I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?

How would I manage the current for all the LEDs

Thank for taking the time to listen to a n00b like me :D

You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).

For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.

If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.

And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.


Reading out two sensors via Com-Port at the same time I have two Arduino Nano Every and a sensor connected to each of them. Here is what's happening:

I upload the sketch to the first Arduino on Com4 and see its output is correct via the Serial Monitor
I open a new instance of the Arduino-software, upload the same sketch to the second Arduino on Com6 and see its output is correct. However, in the meantime the Arduino on Com4 has stopped sending or receiving data
If I close the second IDE-instance and re-upload the sketch to the first Arduino on Com4, it starts working again.

So, essentially I have two Arduinos which I can't read out at the same time.

The sensors are not connected, so I don't know where the problem is. Shouldn't the Com-Ports be independent?

Shouldn't the Com-Ports be independent?

Not in the Arduino IDE, no. Basically the IDE is [expletive deleted] when it comes to using more than one board at a time.

You're better off using a proper serial terminal program, not the "serial monitor" in the IDE. Something like Teraterm or Putty, where you can have multiple instances on different ports at once.


Determine what size power supply I need to run stepper motors I have recently purchased two 7.4V, 1A, Planetary Gear Unipolar Stepper Motors as well as two Cytron 3A 4-16V Dual Channel DC Motor Drivers. I was told that I would need these to run the motors off an Arduino board. The question I forgot to ask was: what size power supply I would need for something like this?

I am just looking to learn how to code these arduino boards. I was hoping to get something that I could plug into a wall to save me from buying multiple batteries.

You can't run these off the Arduino board for several reasons:

the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
the Arduino board can provide about 20mA per pin, never 1A or higher
even if the board would only need to pass the voltage on, the total current were >2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

Arduino Uno board without any peripherals: ~45 mA
two Stepper motors: 1000 mA each
two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The datasheet is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.

A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.


how can I stop my Arduino code after 1 second? I want to send message NRF24L01 to NRF24L01. I want to see if I can send just one second. How can I stop code after 1 second?

You can use different ways:
Use setup only
Instead of putting code in the loop function,  put it in setup, which is only executed once (use a for loop to send around 1 second.
millis() excluding setup
It is better to use the millis function and compare it against the start of sending; when 1 second is reached, don't send anything or use an infinite while loop.
Use something like:
unsigned long time_start;

void setup()
{
    // Your normal code

    time_start = millis();
}

void setup()
{
    if (millis() - time_start >= 1000)
    {
        while(1) {};
    }

    // your normal code (which should not take many ms,
    // otherwise the above code is not reached.

millis() including saetup (Thanks to Edgar Bonnet):
 void loop()
 {
     if (millis() >= 1000)
     {
        while(1) {};
     }
 }

This will stop exactly after 1 s  after startup (excluding the setup). It will start counting after millis start counting, which is before the setup function.
Actually, in none of the above the Arduino 'stops', it just is doing endlessly nothing (well internally endlessly checking against the true condition which never changes).


Compiling sketch vi command line Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder here. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.


Can I control a Arduino from an apache server? So I have a PC running a few services for my house. I'm trying to automate my home a little and would like to control various things in my house. Is it possible to control an Arduino from my HTML Apache server? I was thinking about going from the PC -> Raspberry pi -> then serial connection to an Arduino but that seems over excessive.

If you attach a 'network adapter' to the Arduino, you can start a TCP server on Arduino. The server, a telnet server or a web server will listen for commands  sent from computer. In case of web server, you can send commands from web browser too. Other option is to use UDP communication. Arduino can listen UDP.

The options for the network are Ethernet or WiFi. Both are in form of shields or modules. For Ethernet Wiznet 5100 and 5500 chips are best supported and for WiFi the esp8266 is the common option.


Converting `millis()` to decimal seconds? I would like to get my Arduino to print milliseconds as decimals of seconds.  For example, instead of printing 10456, printing 10.456

I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal

The code I use is:

float ourtime = (millis() / 1000);
dataFile.print (ourtime);

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.

Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:

Serial.println(millis() / 1000.0, 3);

The 3 as the second parameter tells Serial.println() how many decimal places to print. The .0 at the end of 1000.0 forces the compiler to see 1000 as a float value (you can also use 1000f if you prefer).

Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):

uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now % 1000;

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

You could replace the % with a x1000 and a subtraction too if you like:

uint32_t now = millis();
uint32_t secs = now / 1000;
uint32_t ms = now - (secs * 1000);

Serial.print(now / 1000);
Serial.print(".");
if (ms < 100) Serial.print("0");
if (ms < 10) Serial.print("0");
Serial.println(ms);

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:

char num[10];
snprintf(num, 10, "%lu", millis());
uint8_t nlen = strlen(num);

for (uint8_t i = 0; i < nlen - 3; i++) {
    Serial.write(num[i]);
}
Serial.write('.');
for (uint8_t i = nlen-3; i < nlen; i++) {
    Serial.write(num[i]);
}
Serial.println();

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.


Is it possible to see a graphical view of digital and analog pin values? Using Visual Studio for my Arduino project I am struggling to know the states of various pins during operation.

I do use the Visual Micro debugger but I don't want to have to set a watch for every pin.

How can this be done easily?

The Arduino Dashboard project sounds promising but quite likely it loops through the I/O pins periodically and uploads the results to your PC. I'm guessing you want live monitoring (as opposed to snapshots) while your own program (not the Dashboard sketch) is running. In that case, you'd need to isolate the relevant parts of the Dashboard sketch and integrate them with your code, and unless your are looking for fairly low frequency signal changes, have a timer interrupt function that runs the Dashboard frequently, which will have an impact on your own code. If the signals are fairly low frequency you might get away with putting a call to Dashboard in your loop() function instead of running it from a timer interrupt. If you're looking for program bugs that are changing your outputs, once per loop() may be fairly useless. A timer-interrupt would be necessary, and might have to analyze the stack and output the names or addresses of functions that had run recently. At that point you'd be on your way to implementing a debuggerand may want to consider an in-circuit emulator or a bus analyzer to capture the event. Or get smarter about isolating the code responsible for the event until you have a manageable, printf-debuggable code segment.


Using Arduino microcontrollers without board I am new into Arduino. So if I program the microcontroller using the Arduino board and once it is doing what I want can I just take the microcontroller out of the board and use the microcontroller itself? If so could you please guide me to some tutorials on how to use it?

I have a post about a breadboard Arduino - in that I demonstrate the minimal amount of parts you need to use the controller (which is not much).

Example of wiring it up:

If you want to use an external crystal or resonator you can add that to the board like this:

8 MHz crystal shown, but you could use 16 MHz. Or change the fuses and use the internal oscillator.

Schematic showing how you could (if you wanted) add an ICSP header and an FTDI header:


Maintain delay with NEO-6M Ì am building speedometer with NEO-6M and have some problems with my code.
The scenario is that I send some data from our Arduino to another device via a TX pin with a delay of 50 ms. This delay of 50 ms needs to be maintained and should not exceed. The issue with GPS data, which arrives from the device, is that it is received every 1 second. This issue will cause the 50ms delay to be longer and exceed to 1050 ms. In my last code change delay is not maintained on 50 ms, it is all 1000 ms. Not sure what I did wrong.
My code is

original

#include <AD9850.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 0, TXPin = 1;
static const uint32_t GPSBaud = 9600;

const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN = 10;
const int RESET_PIN = 11;

double freq = 1;
double trimFreq = 124999500;

int phase = 0;

unsigned int speed = 0;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);
}

void loop()
{
  // Dispatch incoming characters
  while (ss.available() > 0)
    gps.encode(ss.read());

  {
    digitalWrite(outPin, HIGH);   // sets the pin on
    delayMicroseconds(50);        // pauses for 50 microseconds
    digitalWrite(outPin, LOW);    // sets the pin off
    delayMicroseconds(50);        // pauses for 50 microseconds
  }

  if (gps.speed.isUpdated())
  {
    Serial.print(F("SPEED      Fix Age="));
    Serial.print(gps.speed.age());
    Serial.print(F("ms Raw="));
    Serial.print(gps.speed.value());
    Serial.print(F(" km/h="));
    Serial.println(gps.speed.kmph());
    speed = gps.speed.kmph();
    //calculate the frequency with map()
    freq = map(speed, 0, 100, 0, 160);
    DDS.setfreq(freq, phase);
  }
}

revised

(replying to https://arduino.stackexchange.com/a/45657)
Thank you for help. Is it possible to put GPS speed in this code? https://pastebin.com/LdT7UHBQ I used your code and it works but my boss demands that we modify his code and make it maintain delay with it.

long prevTxTime = 0;
const int delayTime = 51;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);
}

void loop()
{

  int b, chunk = 0;

  if (Serial2.available())
  {
    b = Serial2.read();
    chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;
      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1] << 6);
        velocityfreq = bytes[2] + (bytes[3] < delayTime)
        {
          //speed from gps would most likely need to be set here as "speedfromgps"

          SendData();
          prevTxTime = millis();
        }
      }

      void SendData()
      {
        sprintf(charToSend, "%d|%d|%d|%d|%d\n\r",
                data1, data2, data3, data4, speedfromgps);

        Serial1.print(charToSend);
      }

What is outPin?
Don't start a SoftwareSerial object on the Serial port.  Just use Serial
The Serial Monitor window will have to use the GPS baud rate if the GPS is connected to pins 0 & 1.  This is a good choice, but you'll have to disconnect pin 0 to upload a new sketch over USB.
Don't use delay.  This prevents the sketch from reading GPS characters.  Eventually, the input buffer will overflow and characters will be lost.  Instead, save a timestamp and compare the current time with the timestamp.  When the difference is 50ms, simply toggle the pin and save another timestamp.
Try NeoGPS.  It's smaller, faster, more reliable and more accurate than all other GPS libraries.  There are many tips on the Installation and Troubleshooting pages, and the examples are structured properly.  If you want to use pins other than 0 & 1, be sure the read the section about choosing a serial port.  SoftwareSerial is the worst choice.

Here is your sketch, modified to use Serial and NeoGPS:

#include <AD9850.h>
#include <NMEAGPS.h>
NMEAGPS gps;

#define gpsPort Serial  // GPS on pins 0 & 1
static const uint32_t GPSBaud = 9600;

const int OUT_PIN   = 4; ???
const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN  = 10;
const int RESET_PIN = 11;

const double trimFreq = 124999500.0;

int phase = 0;

unsigned long lastToggle;

void setup()
{
  //Serial.begin(115200);  // NOT needed if gpsPort *is* Serial (pins 0 & 1)
  gpsPort.begin( GPSBaud );

  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);

  pinMode( OUT_PIN, OUTPUT ); // must be set to output mode
  lastToggle = millis();
}

void loop()
{
  // Toggle the OUT_PIN every 50ms
  if (millis() - lastToggle > 50) {
    digitalWrite( OUT_PIN, !digitalRead(OUT_PIN) );   // toggle the pin
    lastToggle += 50; // step to the next toggle time
  }

  // Dispatch incoming characters
  if (gps.available( gpsPort )) {
    gps_fix fix = gps.read(); // get a fix structure with all GPS fields

    Serial.print(F("SPEED km/h="));

    // for testing, use some random values (comment this out later)
    fix.valid.speed = true;
    fix.spd.whole   = random( 0, 35 );

    if (fix.valid.speed) {
      float speed=fix.speed_kph();
      Serial.print( speed );

      double freq = map(speed, 0, 100, 0, 160);
      DDS.setfreq(freq, phase);

      Serial.print( ' ' ); // for debugging, show the DDS frequency
      Serial.print( freq );
    }
    Serial.println();
  }

}

Notice that it checks to see if there is a valid speed.  The GPS device may not know the speed, depending on satellite reception.

If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.

UPDATE

For the code you posted (which is not a complete program) in an Answer (instead of editing your question :-/), you could do something like this:

#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#define gpsPort Serial  // GPS on pins 0 & 1 or whatever
static const uint32_t GPSBaud = 9600;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);

  gpsPort.begin( 9600 );

    ...other things?
}

void loop()
{
  // Constantly read GPS characters
  if (gps.available( gpsPort )) {

    // Update the global fix structure with the latest GPS info.
    //   The speed will be used later by SendData.
    fix = gps.read();
  }

  // Constantly read Serial2 characters (a sensor?)
  if (Serial2.available())
  {
    int b     = Serial2.read();
    int chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;

      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1]<<6);
        velocityfreq = bytes[2] + (bytes[3]< delayTime)  ??? "<" ???

        SendData();
        prevTxTime = millis();
      }
    }
  }
}

void SendData()
{
  // No need to use sprintf, just print the pieces.

  Serial1.print( data1 );
  Serial1.print( '|' );
  Serial1.print( data2 );
  Serial1.print( '|' );
  Serial1.print( data3 );
  Serial1.print( '|' );
  Serial1.print( data4 );
  Serial1.print( '|' );

  // use the current GPS speed, as set in loop
  Serial1.print( fix.speed_kph() );
  Serial1.print( F("\r\n") ); // F macro saves RAM for doubled-quoted string constants
}

I had to guess at the nesting of curly braces because IT IS NOT INDENTED, nor do the CURLY BRACES MATCH.  sad.


Unable to make a really basic sketch work I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the arduino website everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.
I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.
int button_pin = 2;
int button_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button_pin, INPUT_PULLUP);
}

void loop() {
  Button();
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state = LOW) {
    Serial.println(button_state);
  };
};

#define button_pin 2  //defining button pin as pin 2
bool button_state = 0; //button state is either 0/1 so using bool
void Button();
void setup()
{
    Serial.begin(9600);
    pinMode(button_pin, INPUT_PULLUP); //Setting input as input pullup
}

void loop()
{
    Button();
}

void Button()
{

    button_state = digitalRead(button_pin); //Read button state
    if (button_state == LOW)
    {
        Serial.println(button_state); //print button state when it is low
    }
}

In your code, you have used = operator in place of == in the if loop. Just if you change it, it will start working also you can use my above code it is same as yours just I have made some minor changes such as using bool in place of int and use of #define in place of pin declaration where you used int


Which Arduino is compatible for atmega164pa I am working on a project using 5 pins of ADC, 5 pins for PWM, and LCD. I need to use Atmega164pa. I would like to know how I can transfer it to Arduino. Is there any Arduino compatible with this chip?

There is an Arduino core for the '1284A, but it can be adapted to the '164A.


Convert a Serial string to a sketch command on Yun? How can I convert a string like the following:

"pinMode(2, INPUT_PULLUP)"

or

'Keyboard.print("Hello world")'

into actual code that the Arduino can act on?

There is a third option: install an interpreter on the Arduino, then
just send it the program you want it to run. There are a few such
interpreters available. A quick search showed:

Bitlash, a C-like language
iArduino, another
C-like language
FlashForth, a
Forth
implementation
FINF Is Not Forth, a Forth-like
language

There are probably many others.

The difference between this option and Majenko's option 2 is that this
would allow you to send a complete program, with functions,
conditionals, loops, etc., whereas with a Firmata or similar approach
you would keep the program logic (functions, loops, conditionals) on the
host computer, and only send simple commands to the Arduino.


Arduino can't write MPU6050 data to SD card I hope my MPU6050 sensor can write data to my SD card, it compiled OK, but to open the serial monitor I got error message:

Initializing I2C devices...
Testing device connections...
MPU6050 connection successful
filename :acc_0.txt
0, ax: -85, ay: 227, az: 3997
filename :acc_0.txt
error: opening att_0.txt for write failed
SD errorCode: 0X13,0XE5

Here is my code:

// Based on I2Cdevlib, MPU6050_raw
// Experiments to verify if any data loss when writing MPU6050 outputs to SD card

#include "I2Cdev.h"
#include "MPU6050.h"
#include <SdFat.h>

// SD card read/write
// MOSI - pin 11
// MISO - pin 12
// CLK  - pin 13
// CS   - pin 4
const int chipSelect = 4;

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;

SdFat sd;
SdFile myFile;

int count = 0;
int idx = 0;

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(38400);

    // initialize device
    Serial.println("Initializing I2C devices...");
    accelgyro.initialize();

    // change accel sensitivity to 8g
    accelgyro.setFullScaleAccelRange(MPU6050_ACCEL_FS_8);

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    // Initialize SdFat or print a detailed error message and halt
    // Use half speed like the native library.
    // change to SPI_FULL_SPEED for more performance.
    if (!sd.begin(chipSelect, SPI_HALF_SPEED))
        sd.initErrorHalt();
}

void loop()
{
    // read raw accel/gyro measurements from device
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    // dynamic create a file
    if (count == 0)
    {
        // dynamic filename
        char filename[11];
        sprintf(filename, "acc_%d.txt", idx);
        Serial.print("filename :");
        Serial.println(filename);

        // open the file for write at end like the Native SD library
        if (!myFile.open(filename, O_RDWR | O_CREAT | O_AT_END))
            sd.errorHalt("opening att_0.txt for write failed");
    }

    // write data to file
    Serial.print(count); myFile.print(count); myFile.print(", ");
    Serial.print(", ax: "); Serial.print(ax); myFile.print(ax); myFile.print(", ");
    Serial.print(", ay: "); Serial.print(ay); myFile.print(ay); myFile.print(", ");
    Serial.print(", az: "); Serial.println(az); myFile.println(az);

    // close file when every 1,000 records
    if (count > 1000)
    {
        myFile.close();
        Serial.println("Finish.");
        count = -1;
        idx  ;
    }

    count  ;
}

You seem to be expecting a statement of the form

idx ;

to increment a variable, but it will not, so your idx and count variables are forever 0 and you keep trying to re-open the same file without ever closing it.

To increment a variable, use the ++ operator as in

idx++;

count++;


Do I need more voltage to close this circuit? I'm hacking together a RF-controlled garage door opener. I'm tapping the "receiving" end in to the push button wires.

When the two wires touch, it toggles the garage door motor.

I'm trying to basically "close" this circuit through a 5V Trinket Pro with...

pinMode(A0,OUTPUT); in setup and digitalWrite(A0,LOW); in the loop.

Using the multimeter, it would seem that the wires for the push button are normally closed (I think that's correct) as I get a 15v read on the multimeter when I check the current.

When I touch the wires, the current drops to 0.

My understanding was that the digitalWrite(A0,LOW); would basically "complete" the circuit, but it doesn't seem to do anything.

So, my question is: Given I've only got 5v running through the Trinket Pro, is that not enough to toggle the garage door circuit given it's putting out  15v in it's NC state?

If that's the case, is there some other way around that without needing to push 15v of power?

The Trinket really doesn't want to see 15v across one of its I/O pins. You'll do better using a solid-state (SSR) or mechanical relay to close the 15v motor-start circuit, one that can be activated by the 5v output of the Arduino pin.

Update:
A relay has 4 specs that you need to consider up front:

The coil (or switching input of a SSR) voltage, and
The coil (or switching input) current;

These are what the Arduino or an add-on switching circuit will have to drive. And:

The contact max voltage, to limit arcing when they open
the contact max current, to limit them heating,

Or, in the case of an SSR, to prevent letting out the Magic Smoke that makes them work.

If you use a relay you'll need a driver circuit between the Arduino pin and the relay, with a snubber - a diode that grounds the reverse voltage "kickback" from the relay coil when you open its circuit - also to protect the Magic Smoke in your Arduino.

You're hacking into your remote "clicker", not the garage-door tractor itself, right? If that's the case, just about anything with a 5v coil 15v+ contacts will do. The remote button only has to switch a tiny transmitter on/off. If you do need to hack into the tractor, you'll want to find out what's behind its receiver terminal. It's probably not the motor but another relay, but....

A ready source of such a relay is your/another garage door remote receiver. It has a relay in it that is already doing that job.


Remove a sudden pulse on pin d3 of nodemcu when powering it up I am using node mcu and a 2 channel relay connected to the motor via pin d3.
When I power on the circuit, it shoots a pulse to the relay and i think it will damage the motor.
Please suggest me how to stop that pulse from turning on the motor.

D3 is GPIO0, which is used as an active low input to signal the ESP8266 bootloader to expect programming after a reset.
Use a different pin.


DFPlayer for Writing to SD Card Can you use the DFPlayer to write to the SD card?
Link for DFPlayer: https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299

Here's the goal of my project. I have a button that, when pressed, should a- play a song off an SD card that is hooked up to the DFPlayer and b- should log "button is pressed" to the SD card. Unfortunately, the DFPlayer library doesn't seem to have any functions for this, and I wasn't sure how to see whether the DFPlayer has the functionality to support writing onto an SD card. Are there modules that are Read-only for SD cards? If so, is the DFPlayer one of them?

PS - I'm using an Arduino Uno,
Thank you so much for your help! I am a complete novice for SD cards, so any help you give would be very much appreciated!

Unfortunately the DFPlayer cant write that data to the SD card. The Arduino has some non volatile memory of its own built in though. Theres 1K of EEPROM for the UNO. Notes on how to use it here: https://www.arduino.cc/en/Reference/EEPROM
If you can get what you need to done in 1K and its not important to your project that you be able to unplug the SD card and put it in another reader, then perhaps thats a nice, simple solution...


How can I use a transistor to "press" a button? I have a heater remote that I want to press the buttons of with my Arduino. I am powering both the remote and Arduino from an external 5V source so both grounds are connected.

Currently I have tried using an NPN transistor(TIP122) and it does work but is not very reliable. It probably works 80% of the time but isn't good enough for my purpose. Sometimes nothing happens and sometimes the button is pressed twice for no reason.

These are my connections.

I have the emitter connected to ground, collector connected to the button and the base connected to the Arduino with a 1k resistor. Are my connections OK?

I've also tried using a PNP transistor but pulling LOW instead of HIGH and LOW instead of HIGH.

The code is very simple, in the setup I have:

pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
delay(20);
digitalWrite(4, LOW);

Therefore when I restart the Arduino it should press the button, right?

I also have IRLZ44N and IRF540N, would either of these work better?

A glance at the TIP22 datasheet shows that this is a Darlington pair transistor, which means that it has very high DC gain (good), but at the cost of a very high Vbe_ON (bad).  The datasheet shows that the Vbe_ON is 2.5V, which means that the voltage across the 1K is only 2.5V max, which limits the base current to around 2mA.  This is probably not enough for good saturation.  In addition, the Vce_SAT for this device is about 2.0V, which may or may not be enough to look like a good GND to the button circuit.

I think a MOSFET like the IRF540N, connected as shown here (substitute button circuit for motor) might be a better choice
YMMV


SoftwareSerial + Serial.printlen() not working properly I want to read a SMS message , find it's length and do some "substring();" operation on received SMS. My last two(2) statements do not work . How can I get correct answers? What are correct codes ?

#include <SoftwareSerial.h>
#include <string.h>
#include <ctype.h>
SoftwareSerial mySerial(2,3);

String TelephoneNumberText="";

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

  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);

  mySerial.println("AT+CMGF=1\r");    //Sets the GSM Module in Text Mode
  delay(500);
}

void loop()
{

 while(mySerial.available())
  {
   char s;
   s = mySerial.read();
   TelephoneNumberText = TelephoneNumberText + s;
   }

 Serial.println(TelephoneNumberText);           // this statement works

 Serial.println(TelephoneNumberText.length());  // this statement dose not works

 Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works

} // end loop

Are you sure a string like this can be used?

Better anyway to not each time let a dynamic string be created, but use a fixed string e.g.

char TelephoneNumberText[16];

Set the length of the max number, and change other string functions accordingly.


SD begin affecting OLED display Okay, I'm using u8g2 library for my OLED display. After calling SD.begin(4) function, I cannot display anything on my OLED.

I'm using U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); constructor from u8g2 library since I'm using I²C for the display and SPI for microSD reader. I removed the CS Pin 4 from SD.begin() and I can now display something on the OLED.

How did supplying CS Pin parameter to SD.begin() function affected the I²C OLED display?

Pins 4 and 5 are the I2C pins that belong to the built in I2C peripheral on the Arduino. You have to put your CS line for the SPI SD card on a different pin.

EDIT:
The answer above is relevant to the Arduino ATMega328-based board, not ESP8266-based NodeMCU board. This answer is not relevant to ESP8266 or NodeMCU with regard to hardware I2C, as the ESP8266 does not have a dedicated hardware I2C peripheral.


Arduino baud rate 8 times too high? I'm having a strange issue where in order to get the expected serial output on my serial monitor, I have to set the baud rate on my serial monitor to be 8 times higher than the rate that i set in my Serial.begin(). For example, Serial.begin(4800) works with a serial monitor baud rate of 38400.

The setup is an atmega328P and an atmega8u2 built up on a breadboard similar to an UNO R1. I followed Nick Gammon's tutorial and his scripts to flash the 328P with the bootloader (http://www.gammon.com.au/forum/?id=11637), and I used the DFU programmer (on OS X) to flash the 8u2. When I plug my computer into the USB connector on the breadboard, the device correctly shows up as an Arduino Uno in my computer's devices list using lsusb. I can also flash sketches to the 328P using the breadboard tutorial (https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).

The fact that I get the expected results on my serial monitor (even though it's at the wrong baud rate) leads me to believe my hardware is set up correctly. I'm thinking that it could be a bit/byte confusion in the firmware, has anyone encountered something like this or have ideas? I currently can't flash sketches over the USB connector and I believe it is due to the baud rate mismatch.

There are two baud rates you need to diagnose.  One is the baud rate the ATMega8U2 runs at, and the other is the baud rate the ATMega328P runs at.

You need to work out which one is being calculated wrong:

The ATMega8U2's baud rate is set by the USB connection when you open the port
The ATMega328P's baud rate is set by your sketch

Obviously, the two have to match.  However, a baud rate isn't just set as a number, it's calculated as a fraction of the CPU clock.

If the CPU clock on just one of the chips is different to what the firmware or sketch expects then the calculation for the baud rate will be wrong.

An example:

Your ATMega328P is expected to be running at 1MHz - however, the fuse settings have it set to run from the internal 8MHz clock.  That means everything on that chip will run 8× faster than expected, so you have to compensate with a lower baud rate.

Another example:

Your ATMega8U2 is expected to be running at 16MHz - however, the fuse settings have it set to run at 2MHz.  That means everything on that chip (except the USB which is clocked separately) will run 8× slower than expected, so you have to compensate on the ATMega328P with a lower baud rate.

So check the fuse settings on both chips. Make sure they are set to the right speeds for your firmware and boards.txt file settings.

Also, you should look at getting a cheap oscilloscope or logic analyser. That would allow you to monitor precisely what is going on with the communication between the two chips and work out if the baud rate is actually 8× faster than expected (ATMega8U2 at fault), or the normal speed but you have to specify it as a lower number (ATMega328P at fault).


MQTT client on Arduino + SIM900 I have used the pubsubclient library for Arduino for communicating with an MQTT broker in the past, however the library works only with Ethernet connecction. I need to use GSM in my application and am using the SIM900 at the moment. However, I cannot seem to find any library for MQTT communication using an Arduino as MQTT client and SIM900 as gateway. I found this to be surprising as there must surely be many instances where one would want to upload data from Arduino to a MQTT broker in a mobile scenario where cellular network is the only option (in place of Ethernet). So my questions are:

Is it possible to use the Arduino as MQTT client and SIM900 as gateway for communicating with an MQTT broker? Are there any libraries for the same?
What is the current standard way (gateway / communication protocol) of uploading some sensor data from Arduino to an internet server in a mobile scenario (i.e., where Ethernet is not an option)?

MQTT Library for SIM800 GSM Modem is available at ElementzTechBlog, ElementzGithubRepository
Functionalities:
Auto connect
   Automatically connect to TCP and to MQTT server.

connect function
   This function can be used to connect your client to MQTT broker.
   Use only if you do not use Auto connect functionality.
   Optionally  you can use username, password, WILL topic and WILL Message.

OnConnect CallBack function
   This call back function is called when MQTT connection is established.
   You can call subscription and publish functions inside it (according to your need).

publish function
   This function can be used to publish messages to different topics.
   You can select  QoS levels and RETAIN flag according to your need.

subscribe function
   This function can be used to subscribe messages from different topics.

OnMessage CallBack function
   This callback function is called when messages are received from  subscribed topics
   Topic, TopicLength, Message, MessageLength are the arguments of  OnMessage callback function.
   Inside this, you can write your custom code.

unsubscribe function
   This function can be used to unsubscribe from a previously subscribed topic.

disconnect function
   This function can be used to disconnect your client from MQTT broker.

Keep Alive
   You can specify your KeepAlive duration while initializing.
   Ping requests are sent and received automatically.

Update
Nowadays the easiest solution is to use SIM7600 4G/3G/2G modem. It supports MQTT using AT commands !. For more details the following link can be useful to get started.
https://www.elementzonline.com/blog/using-mqtt-at-commands-with-sim7600-and-arduino-for-gsm-iot-projects


Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper First of all, I'm new to arduino. Check the EDIT line below the two codes.

I have connected motor shield to arduino uno. Connection between the two arduinos are A5 to A5, A4 to A4, 5V to 5V and GND to GND. I have a stepper connected to UNO, and a button connected to nano.

EDIT5: I deleted the messy previous codes, the question was answered.
However, I cant get the steppers to rotate(they only vibrate). Any advice is appreciated. The code right now is:

Master

#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(10);  // 10 rpm
  motor2.setSpeed(10);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave

#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}

There are many ways to do this. The master could be the central unit which makes all the decisions, or the slave could preprocess the information.

It is best to start with a single byte to make it work. But I have made examples for two bytes anyway.

The next examples requests two buttons via i2c. You can change the HIGH and LOW into an integer value, but this is a start to make it work.

Master (without checking)

void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  int button1 = Wire.read();
  int button2 = Wire.read();

  Serial.print("button1=");
  Serial.println(button1 == HIGH ? "HIGH" : "LOW");

  Serial.print("button2=");
  Serial.println(button2 == HIGH ? "HIGH" : "LOW");

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Master (with checking)

void loop()
{
  Wire.requestFrom(8,2);    // request 2 bytes from slave device #8
  if(Wire.available() == 2)   // are 2 bytes received ?
  {
    int button1 = Wire.read();
    int button2 = Wire.read();

    Serial.print("button1=");
    Serial.println(button1 == HIGH ? "HIGH" : "LOW");

    Serial.print("button2=");
    Serial.println(button2 == HIGH ? "HIGH" : "LOW");
  }
  else
  {
    Serial.println("The slave was not found");
  }

  // Some delay is needed, to prevent a 100% i2c bus load.
  // Perhaps 1 ms is enough, now 500 ms for testing.
  delay(500);
}

Slave (very simple)

void requestEvent()
{
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  Wire.write( (byte) buttonState1);
  Wire.write( (byte) buttonState2);
}

Slave (advanced, update button state in the loop)

#include <Wire.h>

const int button1Pin = 2;
const int button2Pin = 3;

// Variables that are used in a interrupt and also outside
// that interrupt must be declared as volatile.
// Then the compiler knows that they can change at any moment.
volatile byte buttonState1;
volatile byte buttonState2;

void setup()
{
  pinMode(button1Pin,INPUT);
  pinMode(button2Pin,INPUT);
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop()
{
  // keep the variables updated with the latest information.
  buttonState1 = (byte) digitalRead(button1Pin);
  buttonState2 = (byte) digitalRead(button2Pin);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
  // send the two bytes.
  Wire.write(buttonState1);
  Wire.write(buttonState2);
}


What is the correct folder structure for including local headers in my Arduino project? I am designing a "project" with 5 Arduino's (each with separate codes), communicating with each other using NRF24. All the 5 codes are different except they share a common header "MyHeader.h". The Arduino IDE forces the .ino filename to be same as the folder-name it is in. I currently have the following structure:

[parentfolder]
    MyHeader.h
    [arduino1]
          arduino1.ino
    [arduino2]
          arduino2.ino
    [arduino3]
          arduino3.ino
    [arduino4]
          arduino4.ino
    [arduino5]
          arduino5.ino

Now, if I use the following, I get an error that the IDE cannot find the header file:

#include "../MyHeader.h"

I am forced to use the above structure due to the IDE folder naming restrictions, whereas I would definitely like to have a structure like the following:

[parentfolder]
    MyHeader.h
    arduino1.ino
    arduino2.ino
    arduino3.ino
    arduino4.ino
    arduino5.ino

How should I organize my project so that I can include my header (without obviously duplicating the file inside every folder)? Thanks.

The reason why you can't reference the parent folder of your sketch when compiling is because the Arduino IDE doesn't compile your sketch in that folder. Instead it writes out the files from the IDE itself into temporary files in a "build" folder and compiles them in there - so the parent folder then does not contain your header file because the IDE has no clue about that.

So you need to put your header file somewhere that the IDE does know about - and the simplest place is where the libraries are.

A library is nothing more than a header file in a folder (both named the same) with optional source and other header files.  If you place your header in a folder in your libraries folder the IDE will see it as a library and you can include it into any sketch.

So you would have:

Documents/
    Arduino/
        libraries/
            MyHeader/
                MyHeader.h
    MyFancyProject/
        NodeOne/
            NodeOne.ino
        NodeTwo/
            NodeTwo.ino
        NodeThree/
            NodeThree.ino


Streaming audio from PC to Arduino over WiFi Say I wanted to, purely hypothetically, set up a pirate radio station by connecting an Arduino to a WiFi network away from home, streaming music to the Arduino, decoding it, and broadcasting it with an FM transmitter.

Given an Arduino (Genuino) Uno, a Sparkfun ESP8266 Thing Dev breakout board for WiFi connectivity, and an Adafruit Si4713 Stereo FM Transmitter breakout board, how would I go about the actual streaming of music (in MP3 or WAV format) from a (Windows) computer to the Arduino over WiFi? Would an Arduino Uno be powerful enough for this? Which components would I need to decode the audio?

Well, a sort of... You can stream 64kbps MP3, get it via wifi from esp8266. Then for all the rest, forget the Arduino.

You need a dedicated MP3 decoder chip (many out there, sta013 was one of the oldest beasts) which can take the digital mp3 stream and convert it to analog output.

You can feed the line level analog output to the FM Transmitter, and then you're golden.

Note that you shall develop some application on the PC to actually stream out the MP3 - an off the shelf solution such as a Shoutcast server may not work, as the usual web-radio stations inject station data and currently played track metadata into the mp3 stream what you have to remove from the MP3 decoder chip.

Since the actual wifi bandwidth with ESP is limited (as well as the processing power of the Arduino), you may switch to a more efficient compression format. For example, a 64kbps WMA sounds far better than a 64kbps MP3, and at 64kbps AAC is superior to any of the other formats. Ensure that your decoder chip can work well with a modern codec comperssion format.


Losing top brightness when using tip120 and PWM with 70w LED panel I have been experimenting with pwm dimming using TIP120 on various high powered LED's, and have noticed a marked drop in the top level brightness compared to original connection without the tip 120 in line.
For instance a 70w panel connected with heavier gauge cable (not using jumper cables) no longer reaches full brightness with pwm set too full.
im using tasmota on a nodemc8266.
Is there something inherent the hardware set up causing the loss that I am missing or is there a software limitation with PWM?
curious

thanks

Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.


How to find gain for this device? I am doing a project with Arduino to find CO2 in an environment. For this purpose, I bought a breakout board with an MG811 sensor on it. I bought it from eBay and it came with no datasheet. I searched on the internet and found the datasheet for the MG811.

With the help of the datasheet, I also found the formula to convert the input voltage to PPM. But later I realized that the device also has an amplifier on it, which is giving me higher voltages. I searched thoroughly and found the original device on Taobao.

Can someone please tell me how can I determine the gain so that I can convert the values I read to original values?

One more question. On the given web link, I also found that this device comes with a pin called TCM and with Google translate, I found that it shows temperature compensated output. Can you please explain me the use of this pin as well? If it is more advantageous for me, I'll use this instead of the normal analog output pin.

The MG811 spec gives you the range of measurement, but without the values and connections of the surface mount op amp on the board the only way to determine the voltage output for each CO2 concentration is with a Voltmeter and an already calibrated CO2 PPM meter, which you could perhaps borrow from a lab or university.  Once you have the CO2 values and Voltages that correspond, you can build a formula or function to convert the digital values to voltages and then to CO2 concentrations.

The other option is to trace the tracks on the PCB and create a schematic and then post the spec above and the schematic with resistor values included on the electronics Stack Exchange.


433Mhz transmitter interference when using long cable, only on Arduino Due When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:

-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).

-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from 0.1 uW/m2 to 3 mW/m2 a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.

The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.

I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.

I'm using the RCSwitch library. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

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

  // Transmitter is connected to Arduino Pin #8
  mySwitch.enableTransmit(8);
}

void loop() {}

Why am I having this strange behavior? Do you have any suggestions on how to fix it?

I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0

Likewise this page suggests the problem is a bug with the wiring_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0

In RCSwitch.cpp, this is the enableTransmit code:

void RCSwitch::enableTransmit(int nTransmitterPin) {
  this->nTransmitterPin = nTransmitterPin;
  pinMode(this->nTransmitterPin, OUTPUT);
}

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.

I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?

Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?


LEDs on TX/RX lines interfering with the programmig of the device I have recently designed a shield to my Arduino Duemilanove, which has 8 LEDs, on the digital GPIO, from 0 to 7, but it won't program with the shield on because the voltage drop is too much on the RX and TX lines. My question is: can I have a LED on the TX/RX line with a minimum resistor value that allows me to program the Arduino?

I just found this reference (using ICSP for output as well as programming -- essentially the same thing), and it suggests a 4.7kOhm.

I didn't have a 4.7k handy, and used a 15k instead and it works.

In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and GND. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).

If I put the resistor in series with it, the sketch uploads without fail.

You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use Serial.[anything]. Make sure to not even initialise the port.


Performing multiple Wire.writes() - does endtransmission slow things down? Here's a question for anyone knowledgeable of the ways of I2C.

I'm curious about sending multiple writes to a device and was looking at the code for a MPU9250 module.

There is a nice library that compiled straight off the shelf by Kris Winer here.

In one of his code examples he makes multiple calls to a function called writeByte():

// Wire.h read and write protocols
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
    Wire.beginTransmission(address);  // Initialize the Tx buffer
    Wire.write(subAddress);           // Put slave register address in Tx buffer
    Wire.write(data);                 // Put data in Tx buffer
    Wire.endTransmission();           // Send the Tx buffer
}

here is a (truncated) example of the code calling writeByte():

void initMPU9250()
{
  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
  delay(100);

  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
  delay(200);
  writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
  .
  .
  .
  etc
}

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:

Wire.beginTransmission(address);
Wire.write(data1);
Wire.write(data2);
Wire.write(data3);
Wire.write(data4);
Wire.endTransmission();

at least when it's possible?

No, Wire.endTransmission() doesn't "slow things down". It is, however, critical to the operation of the Wire library.

When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call Wire.endTransmission() does that data actually get sent out. The actual Wire.endTransmission() doesn't add anything extra to the transmission though.

In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.

Some devices though would allow <address><value><address><value> to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.

Other devices (most notably flash memory or SRAM chips) would allow you to do page mode accesses, which would be <address><data1><data2>...<dataN> where the address would automatically increment for each data byte. Again, some may, some won't.

It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.


What is the sampling-rate of the `analogRead()`? I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.

My code is very simple, here it is:

      // the setup routine runs once when you press reset:
  void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }

  // the loop routine runs over and over again forever:
  void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
  }

The ADC in default configuration will take 104 µs to make a sample (which agrees with Edgar Bonet's comment of roughly 9600 per second).

You can speed that up somewhat by changing the ADC prescaler from the default of 128. See ADC conversion on the Arduino (analogRead). A prescaler of 32 will reduce that to 26 µs and still give quite acceptable results.

You can also run the ADC asynchronously (in the background) so you can transmit the previous result while obtaining the next one. A higher baud rate than 9600 baud would be highly recommended in this case.

People have been doing FFT analysis using the Arduino Uno and similar. I suggest you Google for relevant posts about that.


Can regular Arduino pins be used during SPI? I have a circuit in which I'm using an Arduino Pro Mini to interface with an RF69 radio via SPI. The SCK pin on the Pro Mini is pin 13, which also happens to be the LED pin. Is it possible to write pin 13 high and low in the same sketch that I'm interfacing with the radio? I don't need to do SPI communication simultaneously with the LED. I can put the radio to sleep then use the LED. I'm wondering if this will some how mess up the SPI communication or if everything will be OK.

I did not check the datasheet of the RF69, but it is customary for SPI devices to have a “slave select” input pin. When such a device is not selected, it will leave its MISO pin in high impedance and completely ignore whatever may happen on the MOSI and SCK pins. This effectively disconnects the device from the SPI bus. In this situation you show be able to play with the LED without disturbing the device.

Beware that the slave select pin is usually active low: write it to HIGH to deselect the device.


Why did my program stop working when I eject the serial cable like it did an auto reset? Arduino Uno based on 328p micro-controller board only works while I am inserting the serial cable between the board and the computer and I can control the speed of my two motors and every thing is work properly, but when I eject the serial cable it works badly and there is no control, is that some thing occurs like auto Reset?

There is always 5 volt feeding the Arduino, I get 5 volt regulated from the battery using "5v regulator", this regulated voltage is always connected to the Arduino board.

Try increasing the voltage of the power supply. Maybe there might be a problem with the current. The Arduino has a 5V regulator on-board, try using a 9V battery. MAKE SURE THAT YOU CONNECT TO THE DC BARREL CONNECTOR.

Good luck!


Can I use arduino's 3.3 V output directly to esp8266? I just bought esp8266 and ftdi usb driver, I want to power the esp8266 with Arduino's 3.3 V output, is that possible?

I saw some tutorial on youtube in that they are suggesting us to use 3.3v regulator ic instead of directly power 3.3 V of Arduino or ftdi driver's 3.3 V output.

If I connect my ftdi or Arduino output directly into esp8266 is there a chance to damage the esp8266?

You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.

First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.

In your case, you should search for the electrical characteristics of the ESP8266. For instance here you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.

Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to the texas instruments webpage, with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.

As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.

As an example, the TTL-232RG has this datasheet. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.

If you have further questions, just ask here ;)