Switch a 12V 3.3A component from an Arduino I need turn off and turn on component from an Arduino UNO.

How can I do that? I am thinking about some transistor (IRF 530N) but I am not sure about it.

Please give me a beginner advice how to implement such a switch.

EDIT: Is this realy good for my problem?

A relay, as pictured, is a good choice. It provides complete galvanic isolation and switches the power properly.

Another option is to use a MOSFET that can handle enough current (an N-channel switching the ground as a low side switch, or a P-channel switching the power which is itself switched by an N-channel, as a high side switch).


Arduino how to loop a method Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.

void loadPrograme(){
   file = SD.open("/classes/basic.txt", FILE_READ);
   Serial.print("Reading, Checking and Compiling \n\n\n");

   for (int i = 0; i < arraysize; i++) {
      while (file.available()) {
         character23 = file.read();
         if (character23 == '\n') break;
         if (character23 != '^') {
            content += character23;
         }
      }
      content.trim();
      if (content != "") {
         result[i] = content;
         content = "";
         delay(1000);
      }
   }
   for (int i = 0; i <arraysize; i++) {
      if(result[i].substring(0,5) == "print"){
         printlnMethod(result[i]);

      }else
         if(result[i].substring(0,5) == "delay"){
            delayMethod(result[i]);
         }else
            if(result[i].substring(0,11) == "buttonPress"){
               buttonMethod(result[i]);

            }

   }

   file.close();
}

void buttonMethod(String s){
   s = s.substring(s.indexOf('{') + 1);
   s = s.substring(0, s.lastIndexOf('}'));
   String btn =" ";
   String daction = " ";
   String indaction = " ";
   btn= s.substring(s.indexOf('"')+1 );
   btn= btn.substring(0, btn.lastIndexOf('"'));
   daction = s.substring(s.indexOf(',')+1);
   daction = daction.substring(0, daction.lastIndexOf('('));
   indaction = s.substring(s.indexOf('~')+1);
   indaction = indaction.substring(0, indaction.lastIndexOf('~'));
   int buttonpressed;
   if(btn == "BUTTON_PIN_ENTER"){
      buttonpressed = 2;
   }else if(btn == "BUTTON_PIN_LEFT"){
      buttonpressed = 3;
   }else if(btn == "BUTTON_PIN_RIGHT"){
      buttonpressed = 4;
   }else if(btn == "BUTTON_PIN_DOWN"){
      buttonpressed = 5;
   }else if(btn == "BUTTON_PIN_UP"){
      buttonpressed = 6;
   }else if(btn == "BUTTON_PIN_ACTION"){
      buttonpressed = 7;
   }

   int btncheck = digitalRead(buttonpressed);
   if(btncheck == LOW){
      if(daction.substring(0,5) == "print"){
         printlnMethod(indaction);

      }else if(daction.substring(0,5) == "delay"){
         delayMethod(indaction);
      }
   }
}

}

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?

Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c  The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.

To loop and block on the last bit, if that is what you mean, you might try:

   int btncheck;
   ...
   while(btncheck = digitalRead(buttonpressed)){ // wait for button
      if(strcmp(daction.substring(0,5),"delay")){
         delayMethod(indaction);
      }
   }  // blocked until btncheck == LOW
   if(strcmp(daction.substring(0,5), "print")){
         printlnMethod(indaction);
   }

This has the blocking on non-pressed button feature, but also has the same logic as the original.  If the string equality tests do not match, it appears you want to do nothing and quickly pass on.

To loop buttonMethod(), put it in a loop:

while(1)buttonMethod(string);

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:

int buttonMethod(...
    int retVal = 0;
    ...

  if(btncheck == LOW){
     retVal = 1;
     ...
  }
  return(retVal);
}

...
while(!buttonMethod(result[i]));  // wait for the button


ESP8266 stuck in flash mode? I have the setup described here: https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/wiring

I currently have the reset pin set to float and the GPIO0 pin grounded, which should make it execute the uploaded program, but instead I get the flash mode output:

    writing flash
...................................................................................................................................................................................................................................................

How do I put it into execution mode?

I was stuck in a similar scenario. I managed to exit programming mode by floating GIPO0, then grounding RST for ~3 seconds, then floating it. If you power off the esp, and now turn it on, it should have exited programming mode. Powering it off is actually optional.


Arduino as ISP - program is being uploaded on Arduino, not breadboard I am following this tutorial, and have wired Arduino using this diagram:

This is what it looks like:

These options are selected in Arduino IDE:

This is the program I'm uploading:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

When I upload it, it's uploaded on the Atmega on arduino board, not the one on breadboard. Both chips are ATMEGA328P.

I also tried to put 10μF capacitor between GND and RESET pins of the arduino board, which led to following errors:

Sketch uses 936 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\Jakub\AppData\Local\Temp\arduino_build_319338/BlinkTestAtmega.ino.hex:i

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

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x12
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Note that I have a homemade ATTINY programmer shield for this arduino board and it works without problems.

Use the "Upload using programmer" in Sketch menu to upload a sketch over ISP

warning, it deletes the bootloader


Synchronous communication between two Arduino boards using two ESP8266 modules I am trying to establish communication between two Arduino boards to send data from sensors through a WIFI module. The problem is that I need them to connect to each other whenever they are in range of each other and send the sensor data.

The esp8266 WiFiMulti system allows to configure more access points and with the rigth code in loop it always searches the best AP.

Configure one of the esp8266 as AP and setup the other with WiFi Multi only for this one  access point.

You can then use events like onStationModeConnected to handle data exchange if the connection is established.


SD.h causing constant reboot I have a nice sketch running which monitors a few things and displays output on an OLED display. Now I want to save the data to an SD card, but with or without the card module attached I'm getting constant reboots when I add 1 single line of code:

#include <SD.h>

Any idea what may be happening?

The following libraries are probably used:

SD Card, using a buffer of 512 bytes (see also the comment of DataFiddler below).
SSD1306 OLED library, using a buffer of 1,024 bytes
Serial, using a buffer of 128 bytes (64 for RX, 64 for TX, see comment of Majenko below)

Since there is only 2,048 bytes of SRAM in an Arduino, this leaves 384 bytes. If you actually READ a file you are already above the maximum.

Your own global variables also will consume a considerable amount of SRAM.

Than, if you execute your sketch, parameters and local variables are stored on the stack (in SRAM), so even if your program starts well, it might/will run in problems when calling functions.


Rescuing an Arduino With a Broken Setup() I may have bricked my Arduino Pro Micro by writing a broken code into the setup() function. When I plug my Pro Micro into my PC, I see it register a COM port for a brief moment before it disappears. Grounding and ungrounding the RST pin causes the device to appear in my control panel again for a brief moment. Attempting to upload the blink example from the Arduino IDE fails, since the COM port disappears before the process can complete.

Is there an alternate way of flashing code to the arduino which I could possibly use to fix this? I have a working Pro Nano I could use if needed.

You can try running the code upload command directly using a precompiled hex file.

Here is how.

Go to preferences in Arduino IDE

Set the Show verbose output during: upload option.

Upload the blink sketch. (arduino does not have to be connected)

After the compilation, check the log window at bottom of the IDE.

You will find a line like this:

E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

That is the actual code upload command.

Copy the command line and paste it into a windows CMD window.

Edit the COM port to match your Arduino.

Reset the Arduino and immediately press Enter to run the command line.

You may get lucky and the upload "squeaks" through.

You can also move the hex file to another folder so that it is always available for doing a quick recovery.

You could also create a BAT file so that double-click on the icon runs the upload.


Could someone explain this code that sets up the software serial port data rate? I understand most of it. The part I don't understand is the is the code in for void loop. How does that set the data rate for the software serial port? I thought mySerial.begin(9600) did that? Please help.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup()
{
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    // set master
    mySerial.print("AT+ROLE1");
    delay(10000);

}

void loop() // run over and over
{

    // set the data rate for the SoftwareSerial port
    mySerial.print("test I am master  ");
    delay(10000);
    ***if (mySerial.available())
    Serial.write(mySerial.read());
    if (Serial.available())
    mySerial.write(Serial.read());***
}

You're confusing "data rate" with "baud rate".

The baud rate is the speed at which bytes are transmitted over the wires, and is set with mySerial.begin(9600);.

The data rate is the speed at which data is sent over the serial port, and that is set by the delay(10000); which dictates how often "test I am master  " is sent and any incoming data is checked for and echoed.


LEDs: difference between common anode and common cathode? What is the difference in using a common anode and common cathode of the 7 Segment in interfacing with the Arduino? How can you change the code if we need to add another 7 Segment display?

How can you change the code to have a counter in backwards (from 0 to 9)?

const int ANODE = 2;

const int LED1 = 3;
const int LED2 = 4;   // pin for led 2
const int LED3 = 5;   // pin for led 3
const int LED4 = 6;   // pin for led 4

// now bottom row

const int LED5 = 7;
const int LED6 = 8;
const int LED7 = 9;
const int LED8 = 10;

int DELAY = 0;

void setup() {
  pinMode(ANODE, OUTPUT);  // common anode is obviously an output

  pinMode(LED1, OUTPUT);   // led are output for low will be on
  pinMode(LED2, OUTPUT);   // led 2 is output
  pinMode(LED3, OUTPUT);   // led 3 is output
  pinMode(LED4, OUTPUT);   // led 4 is output
  pinMode(LED5, OUTPUT);   // led 5 is output
  pinMode(LED6, OUTPUT);   // led 6 is output
  pinMode(LED7, OUTPUT);   // led 7 is output
  pinMode(LED8, OUTPUT);   // led 8 is output
}

void loop(){

  if (DELAY == 300){
    delay(100000);
  }

  digitalWrite(ANODE, HIGH);

  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, HIGH);
  digitalWrite(LED4, HIGH);
  digitalWrite(LED5, HIGH);
  digitalWrite(LED6, HIGH);
  digitalWrite(LED7, HIGH);
  digitalWrite(LED8, HIGH);

delay(1000);

  digitalWrite(LED1, LOW);
  delay(500);
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, LOW);
  delay(500);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, LOW);
  delay(500);
  digitalWrite(LED3, HIGH);
  digitalWrite(LED4, LOW);
  delay(500);
  digitalWrite(LED4, HIGH);
  digitalWrite(LED5, LOW);
  delay(500);
  digitalWrite(LED5, HIGH);
  digitalWrite(LED6, LOW);
  delay(500);
  digitalWrite(LED6, HIGH);
  digitalWrite(LED7, LOW);
  delay(500);
  digitalWrite(LED7, HIGH);
  digitalWrite(LED8, LOW);
  delay(500);
  digitalWrite(LED8, HIGH);

  delay(100);

  DELAY = DELAY + 150;
}

A 7-segment is a packaged set of 8 LEDs (7 number-segments & 1 decimal point). Common anode means that the anode (positive) side of all of the LEDs are electrically connected at one pin, and each LED cathode has its own pin. So turning on any particular segment will involve running a current from this common anode (positive) pin to the particular cathode (negative) pin for the desired segment.

Common cathode means that the cathodes of all of the LEDs are common and connected to a single pin. The anode for each LED has its own pin. So driving one of these means running a current from the particular anode (positive) pin for the desired segment to the common cathode pin.

The way that you are diving the 7-segment involves using a separate pin to drive each segment, so you use 8 pins of the Arduino to drive the display. You will run out of digital pins if you try to add a second 7-segment. There are a couple of ways to address this. One is to add a 7-segment driver, like the CD4511. This limits you to being able to display only numerical digits, but uses only 4 pins of the Arduino per 7-segment.

Another, more versatile way is to add a serial-in to parallel out chip (74HC595, for example) to drive the 7-segment. This requires only two pins from the Arduino (data & clock), and they can be chained to have multiple 7-segments driven from those same 2 pins.


Unable to set LCD contrast using DAC pin on ESP32 I have followed the instructions at https://www.arduino.cc/en/Tutorial/HelloWorld and have my LCD displaying some text. I've also connected the LED back light (LCD pins 15&16).

I wanted to replace the potentiometer used to set the contrast, with a connection to the DAC pin. It needs to be about 0.8V.

When I connect the contrast pin from the LCD to my DAC pin on my ESP32 board, it doesn't work, the contrast is too high. Using a volt meter, it measures about 2.5V.

If I disconnect the LCD contrast pin from my DAC pin, the voltage measured is 0.8V.

Any ideas or examples on how to control the LCD contrast using a DAC pin?

I wondered if I need to add a resistor or something.

The DAC in the ESP32 is ok for sourcing current but not so good at sinking current, and that is what you need.

A amplifier set up as a voltage follower would work.


Can i use a sparkfun rfid qwiic without an id-xxla? Sparkfun rfid qwiic

id-20la

I am using an Arduino UNO R3.

You should assume that i don't know anything. If yes can you give some information about how to do it? Thanks for any help.

No. It is not an RFID reader. It just interfaces to an RFID reader. You need an RFID reader to read RFID tags. That Sparkfun board just controls the reader and reads the data from it.


Arduino capacitive touch sensor help So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay;

#include <CapacitiveSensor.h>
#include <CapacitiveSensor.h> //change '42' to any desired pin...

long time = 0;
int state = HIGH;
boolean yes;
boolean previous = false;
int debounce = 200;
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
// To add more sensors...
//CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
//CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    pinMode(13, OUTPUT);
}

void loop()
{
    long total1 =  cs_4_2.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH; }
        else state = LOW;
        time = millis();
    }

    digitalWrite(13, state);
    previous = yes;
    delay(10);
}

and here's the code for the two sensors and relays

#include <CapacitiveSensor.h>

int led = 13;
int led2 = 12;
long time = 0;
int state = HIGH;
long time2 = 0;
int state2 = HIGH;
boolean yes;
boolean previous = false;
boolean yes2;
boolean previous2 = false;
int debounce = 200;

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
    pinMode(led, OUTPUT);
    pinMode(led2, OUTPUT);
}

void loop()
{
    int total1 =  cs_4_2.capacitiveSensor(30);
    Serial.println(total1);
    int total2 =  cs_5_7.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}
    if (total2 > 60){yes2 = true;}
    else {yes2 = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH;
        }
        else
            state = LOW;
        time = millis();
    }

    if(yes2 == true && previous2  == false && millis() - time2>debounce){
        if(state2 == LOW){
            state2 = HIGH;
        }
        else
            state2 = LOW;
        time2 = millis();
    }

    digitalWrite(led, state);
    previous = yes;
    digitalWrite(led2, state2);
    previous2 = yes2;
    delay(10);
}

I think you are making a mistake initializing cs_5_7.

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.


ESP01 flashing error I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer.
I have removed the ATmega and grounded the RESET pin (quite useless without the uC though).
Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:

python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

However, both ways give me the same output:

A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.

I also followed esp8266 official forum advice to edit the Python script according to the following, but without success.

Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
Line 44 ESP RAM BLOCK = 0x400 //change this to 40

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

Your wiring sounds wrong.

Tie CHPD to Vcc (3.3v) to enable the device.

Tie GPIO0 to ground as you power up, to put it into programming mode.

RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.

That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.


Using Blynk to control stepper motor is jerky I am using Blynk to try and control a 28byj-48 stepper motor using the ULN2003 driver and an Arduino UNO from my iphone via USB withe the iOS Blynk App.

Without using Blynk, my stepper is smooth and works fine:

  #include <Servo.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor  pins to Arduino pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);

  int pos = 0;    // variable to store the servo position

  void setup() {
    myStepper.setSpeed(600);
  }

  void loop(){
     myStepper.step(-500);
  }

But when I use Blynk, the stepper is so jerky and stutters terribly:

  #include <SoftwareSerial.h>
  SoftwareSerial SwSerial(10, 11);
  #define BLYNK_PRINT SwSerial
  #include <BlynkSimpleSerial.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,4-step mode
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor pins to board pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4 blah blah
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);
  char auth[] = "my auth key here";

  void setup(){
    SwSerial.begin(9600);
    Blynk.begin(auth);
    myStepper.setSpeed(600);
  }

  BLYNK_WRITE(1){
    myStepper.step(param.asInt());
  }

  void loop(){
    Blynk.run();
  }

I am using a slider on the app to control the stepper by the way. I am not sure what I am doing wrong, any suggestions?

Blynk runs over a network and therefore cannot respond in real-time nor consistently. You could have the Blynk slider control set a local variable which the motor controller would use for motor speed, but the basic motor-drive timing needs to be locally controlled and independent of network operations. The SimpleTimer library is one way; a timer interrupt would be another.


Measuring Time Between Inputs I'm trying to measure the amount of time that has passed between every time a reed switch mounted on a wheel is activated to calculate the speed of a bike in miles per hour and display it on two 7 segment LEDs. This is what I have so far (without 7 seg code, as that works):

const int reed = A3;
float circumference;
float pi = 3.141592653589
unsigned long time0 = 0;
unsigned long time1;
unsigned long revolutionTime;

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

void loop() {
  circumference = (pi * 26); //26 = the diameter of the wheel
  int reedState = digitalRead(reed);
  if (reedState == HIGH) {
    time1 = millis();
    revolutionTime = (time1 - time0);
    time0 = time1;
    int mph = ((circumference / revolutionTime) * (3600000 / 63360)); //this is the conversion from inches/millisecond to miles/hour.
    Serial.println(mph);
    //And I'd print the result on the 7 segment displays here
  }
}

This code results in around 25 printed entries in the serial monitor from a single activation of the reed switch, all of which consist of randomly alternating values of either 0 or 4571.

Following each step of the code, I assume that the program would generate a garbage result for the first entry (because the time before the reed is activated for the first time could vary greatly), but that following entries would be the correct mph displayed on the 7 segment displays until the reed switch is activated again and a new mph is calculated.

So how would I go about modifying the code to get useful data?

Currently your code is not working, because Arduino is fast enough to check the closed switch state many times before it opens again, so before calculating a new speed value, you need to see LOW on the input.

Still, there are at least 2 better ways to do what you want.

pulseIn() - a function intended just for what you are trying to do: measuring lenght of a pulses. If your switch is active HIGH, you need to measure length of a LOW pulse:

unsigned long duration;
duration = pulseIn(reed, LOW);
// calculate speed basing on duration (in microseconds)

Keep in mind, that pulseIn() is a blocking function, so no code will be executed, until it receives the pulse. You can counter it bu specifying a timeout, after which, the program will continue.

External interrupts are an another approach. Interrupt handling routines are executed when a specified event occurs, no matter if the microcontroller is busy doing something else or not. They would guarantee, that you will not miss any pulse even if they would have frequency in order of kHz.

volatile unsigned long lastTime = 0;

void setup() {
    attachInterrupt(0, readTime, RISING);
}

void readTime() {
    unsigned long t = millis();
    // calculate speed basing on t - lastTime
    lastTime = t;
}

Interrupt handling routine should be as short as possible. Avoid using delays in it, doing Serial.print and other communications. Also, millis() and micros() will not increment during execution of interrupt handler.

Debouncing - even with above two methods, things may still not work properly. The most probable cause would be switch "bouncing". You can counter it by

software debouncing  - delaying after pulseIn() or ignoring interrupts for some period of time after first interrupt is detected
adding a small (10-100nF) capacitor at the input, that will act as a low-pass filter, cutting out short pulses
using not a reed switch, but a hall sensor with hysteresis


Rc car controller using the RC-switch library simulate this circuit – Schematic created using CircuitLab

(Newbie in arduino)
Hi so i have a project which involves creating an rc car which uses the 433Mhz rf module and an arduino nano with a servo motor and an ultrasonic parking sensor.

I'm having problems with the code both on the transmitter and receiver,
Here is the code for the transmitter.

 #include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
// Assigning controller buttons to Digital Pins
 const int forward = 8;
 const int reverse = 9;
 const int rightTurn = 10;
 const int leftTurn = 11;

 int Fwd = 0
 int Bwd = 0
 int Lt  = 0
 int Rt  = 0

void setup () {
  pinMode (forward, INPUT);
  pinMode (reverse, INPUT);
  pinMode (rightTurn, INPUT);
  pinMode (leftTurn, INPUT);
  mySwitch.enableTransmit(7);
  Serial.begin (9600);         // Debugging only
  Serial.println ("Transmitting");
}

void loop () {
  Fwd = digitalRead(forward);
  Bwd = digitalRead(reverse);
  Rt  = digitalRead(rightTurn);
  Lt  = digitalRead(leftTurn);

  if (Fwd == HIGH) {
    mySwitch.send('1');
    Serial.println ("Forward");
    delay(100);
  }

  if (Bwd == HIGH) {
    mySwitch.send('2');
    Serial.println ("Reverse");
    delay(100);
  }

  if (Rt == HIGH) {
    mySwitch.send('3');
    Serial.println ("Left Turn");
    delay(100);
  }

  if (Lt == HIGH) {
    mySwitch.send('4');
    Serial.println ("Right Turn");
    delay(100);
  }
}

And here's the code for the receiver

#include <RCSwitch.h>
#include <Servo.h>

const int IN1 = 3;
const int IN2 = 4;
const int trigPin = 5;
const int echoPin = 6;
int distance = 0;

RCSwitch mySwitch = RCSwitch();
Servo myservo;

void setup () {
  mySwitch.enableReceive(2);
  myservo.attach(7);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin (9600);    // Debugging only
  Serial.println ("Receiver Ready");
}

void loop () {
 if (mySwitch.available()) {

    int value = mySwitch.getReceivedValue();

      if(value == '1') {
        forward ();
        Serial.println (" = forward");
      }

      if(value == '2'){
        backward ();
        Serial.println (" = backward");
      }

      if(value == '3') {
        left ();
        Serial.println (" = left");
      }

      if(value == '4') {
        right ();
        Serial.println (" = right");
      }
      Serial.print(" ");
    }

}

void forward () {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}
long duration;
int value = mySwitch.getReceivedValue();
void backward () {
  if ((distance > 10)&& (value == '2'))
  {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, LOW);
  }
  else if ((distance < 10)&& (value == '2'))
  {
  digitalWrite (IN1, HIGH);
  digitalWrite (IN2, LOW);
  }
  delayMicroseconds(10);
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance); //distance is the returned integer,
}

void right () {
  myservo.write(0);
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

void left () {
  myservo.write(90);
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

The problem is when i run the code the buttons start getting pressed even if I'm not pressing them and even when i disconnect them from the arduino. and also the receiver cant receive any data.
Please help

As you wrote in your comment, you didn't use  pullup or pulldown resistors for connecting the buttons. In this case the pin is floating, whenever the corresponding button is not pressed. It will pick up random noise from the environment and change it's state randomly.

A pullup or pulldown resistor defines a specific value for the pin, if the button is not pressed (LOW or HIGH). The value of such is a resistor is not critical, as long, as it isn't a too big load. Pick some value in the kiloohms (for example 10kOhm).

But you don't need external resistors for this. The Atmega328, which is the heart of the Arduino Nano, already has buildin pullup resistors for each digital output pin. You can activate them by using

pinMode(pin_number, INPUT_PULLUP);

In this case you will have to change the if-statements to check for LOW instead of HIGH and connect the button to ground instead of 5V, because with a pullup resistor in idle state the pin will be pulled up to 5V and the button can then pull it down to ground.


Boost an audio signal for analog read - Envelope Detector I'm working on my first Arduino project and I have a sensitivity issue.

I'm building a module to listen to an audio signal and to start the power source of my speaker with a relay. Everything seems to work fine, but if I drop the volume of my sound, the analog pin doesn't record values (at maximum volume, it peaks at around 50, which is not a lot).

I thought about getting a capacitor but I'm really not sure on what I should get and how the wiring should be done.

it sounds like what you are wanting to do is to detect a minimum threshold of sound so that your speaker power source can be turned on when an audio signal is playing.

You need to amplify your signal while also avoiding voltages that exceed the maximum input specification and also don't go negative. One way to accomplish this is with an operational amplifier (op-amp) circuit. A specific type will accomplish all three requirements. An op-amp that is powered by a single-sided supply, for example +5V and ground, will prevent negative voltages and limit the maximum voltage exceeding what the Arduino can take.

For your application, you don't really care about making a high-quality audio amplifier. You care about not distorting the signal (music) that you are monitoring and detecting a threshold level. Op-amps are good because they have high impedance inputs (they don't draw much (or any) current from your music signal) and they work with few external components.

A classic text for learning about electronics is Horowitz and Hill. Alternatively, you can find references for circuit designs on-line with appropriate searches. For any op-amp that you buy, you can get a datasheet that tells you how to use it. The following reference goes into detail (maybe too much) about single supply op-amps.

Circuits (and search terms) that you might find useful are op-amp follower, single supply, bias, and capacitive coupling. You'll need to purchase components. A good supplier is DigiKey. DigiKey has an on-line catalog that allows you to do a parametric search to identify the components that you need. You'll need a breadboard, resistors, capacitors, and the op-amp in a dual-inline package (DIP).

One search filters the list of possibilities from tens of thousands to a reasonable number. The LM833 Datasheet here is a reasonable choice.

Test equipment, like a single generator and oscilloscope can be very helpful when building amplifiers. You might be able to digitize your amplified signal with your Arduino if you don't have access to test equipment.


How to increase Arduino's memory to save Dot Matrix Library? I need to display some dynamic Chinese characters to 12864 using Arduino. What to show is transported from my web server. The character is stored as a 16x16 dot matrix, needing 16*16/8=32 byte. And I need to show some sentences, which contains more than 100 Chinese characters.

The problem is that I can't storage all the dot matrix data in Arduino because it has too small memory.

If I get the dot matrix data from web server, I need to have 100*32B memory, but SPAM with EEPROM have only 3k. So that failed.
If I save the dot matrix "library" in the Flash memory, I need 3500*32B (There are 3500 Chinese frequent-used characters), but there is only 32K Flash. Saving the "library" means that I should storage the dot matrix data of all the 3500 chars in Flash, then the server only need to send the Unicode of characters, and I can get the matrix of the char.

Any help is appreciated!

Use a different Arduino or Arduino-clone with more flash memory
Store the character bitmaps in external EEPROM (example)


Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits I recently got to code my own driver for the One-Wire-Bus specifically with the ubiquitous DS18B20 temperature sensor in mind for an application.

I am running that code on an Arduino Mega 2560. Programming is done in Atmel Studio 7 and an AVR ISP mk2.

In the version as-of yesterday see here I get missing binary digits while trying to send the 0x55 One-Wire-Command (i.e. Match-Rom-Code).
It appears like it where the least significant two bits that are missing (Oscilloscope capture).

Today I tried to sort out that bug and "fixed" it by counting to 9 instead of 8 (even though I can't explain why this should work, it should rather break stuff [turns out it does]...) and subtracting 1 from my index variable. (See file "OneWire.c" line 83 and following for the old version).
Todays version is here (compare file "OneWire.c" line 81 and following).

In the new version (as-of today) I am able to get the 0x33 opcode (i.e. Send-Rom-Command) transmitted as wanted and get the ID of my specific sensor on the bus (atleast my oscilloscope shows the correct waveform). In the newer version I do the following chain of operations:

get the ID of the single sensor I have connected at the moment
send the Match-Rom-Command (just because that is something actually meaningful to do)
send the 64-Bit Rom-Code after that (or atleast what ever the statemachine of the getID function did end up writing in the output parameter)
send the 0x44 opcode (i.e. start temperature conversion)

This scenario yields me no correct Rom-code being sent on the bus, one byte more on the bus and another single bit too much on the bus for the temperature-conversion opcode. The Match Rom Code command does get transfered as supposed to and does not yield any extraneous or missing bits (no scope capture for that since that would not be possible to get into one shot that shows it all [at a workable scaling]...).

I would highly apprechiate anyone looking at my code and trying to figure out what is going wrong here since I am completely in the dark right now.

Before anybody asks:

I specifically did not want to use the readily available One-Wire-Libraries as they tend to be bloated and heavily rely on the delay function, which is fine if you are doing little else with your chip but not else. Since I have multiple sensors to read out (not yet but as soon as I got the drivers working) have to do some post processing on the raw data (i.e. put some sort of math to it) and transmit that data on a usually slow interface (I2C, Serial, you name it), which all takes time (and all that [periodically and as fast as possible of-course] on a poor 8-Bit Micro that runs at a underwhelming 16MHz...), I decided to keep polling and delay()-uses to a minimum and rather rely (heavily?) on a timer interrupt and a series of Statemachines...

It is not at  all obvious to me why the code does act in that way.

I managed to find the bug and fix it.
I was missing that after the reset pulse the master must be in RX mode for atleast 480us no matter what, even if the presence pulse did occur and even if it's rising Edge did appear already. This mistiming did lead to the missing bits that were corrected with sending more bits until now (which in turn lead to the extraneous bits later on in the transmission).


Writing elegant applications for Arduino Coming from a C background, I was taught that tight loops that just burn CPU aren't desirable.

Is there any programming style guides on Arduino? Is it common practice to just let loop iterate as a tight loop forever?

On a multiprocess system, like your typical desktop, you usually have
way more processes than logical CPUs. When programming such systems you
therefore have to avoid burning more CPU cycles than needed. Instead,
when your program has nothing to do, it should just sleep, and leave
the CPU available for other processes.

On an Arduino, you only have one single program running at a time. It is
then not that useful to keep the CPU idle. Also, the power dissipation
is so low that you will not notice the microcontroller getting even
slightly warm. The extra complexity of getting into and out of sleep
mode is therefore not that useful. Only when running on batteries do you
care about saving every possible milliamp: then learning about sleep
modes starts getting useful.


Best Arduino board to play sound I'm looking to purchase an Arduino for a little robot I'm going to make.  The reason I've chosen Arduino is because it's much easier to use with servos and LEDs than a Raspberry Pi, but a nice little touch would be to have it play some sounds (voice recordings and mechanical SFX).  I was just wondering (now I'm not after opinions here, but looking more at how each of the boards have been designed) what the best Arduino board for playing sound is, or if they are all pretty much the same in this regard.

(Note 'pins' was the best tag I could find for this post for lack of a 'sound' or 'speakers' one.  If you want to edit it to something more appropriate please do)

If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.


Can Digital/Analogue pins double as power supplies? I'm doing research into if the Arduino Uno has enough power pin slots to power multiple components, and I'm unsure if it's possible to convert some of the pins from the Digital and Analogue sections to be power/ground. Anyone know>

Only for very light loads (a few mA).

But why would you want to? The number of power pins doesn't dictate the number of devices you can power. Power pins can have as many things connected to one pin as you like. As long as you stay within the board's total power budget you are fine.


MPU6050 code explanation I'm new to arduino and electronics. I've been trying to use the MPU6050 with my arduino but I'm having difficulty understanding the code. I'm referring to the code put up on the arduino website (http://playground.arduino.cc/Main/MPU-6050#short). Is there any way I could get a line by line explanation of the code?

I've added in a bunch of comments for you:

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; // declare accellerometer and gyro variables
void setup(){
  Wire.begin(); // initiate i2c system
  Wire.beginTransmission(MPU_addr); // be sure we talk to our MPU vs some other device
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true); // done talking over to MPU device, for the moment
  Serial.begin(9600); // initialize serial port to 9600 bps so you can see your debug messages in Arduino IDE via debug channel
}
void loop(){ // main program loop
  Wire.beginTransmission(MPU_addr); // get ready to talk to MPU again
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // done talking to MPU for the time being
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  // all the fancy <<8| stuff is to bit shift the first 8 bits to
  // the left & combine it with the next 8 bits to form 16 bits
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  // the above lines have gathered Accellerometer values for X, Y, Z
  //  as well as Gyroscope values for X, Y, Z

  Serial.print("AcX = "); Serial.print(AcX); // share accellerometer values over debug channel
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX); // share gyroscope values over debug channel
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333); // delay a bit to not overwhelm you the user/programmer as you view the results
}


Arduino max power supply limit What is the maximum current that can be supplied to an Arduino Mega board before frying/breaking?

Basically i have several components connected to my board which draw a total current of 1.6A (which i calculated through a table), and thinking of using a 9V 2A power supply. I know that the arduino voltage limit is 7-12V but just wondering about the current as I can't find it on the datasheets?

Thanks in advance!

1A coming in thru the barrel jack connecor, then you risk blowing the 1A rated reverse polarity protection diode. The 5V regulator will overheat at high currents above 7.5V. The chip itself can have 800mA put thru if if properly cooled and the IO limits of current per port are respected.

So 1.6A, no way.


Arduino Uno and FastLED WS2812B Glitching I’m using an Arduino Uno and a fastLed WS2812B.
I have the leds set up correctly. Every 2 seconds, the lights pause of about a second and display seemingly random colors.

Does anyone know what's wrong?

My code:

#include <FastLED.h>

#define LED_PIN   7
#define NUM_LEDS  10

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}

void loop() {
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(0,0,255);
    FastLED.show();
    delay(100);
  }
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(255,0,0);
    FastLED.show();
    delay(100);
  }
}

I have run the code on the Arduino simulator online. If it is working in the Arduino Simulator chances are less that it has to do something with the code itself.
Hence, also as the root cause was found to be about sharing the ground @Majenko
This is also one example of solving the problem step by step. validating one section after the other. using the simulator you can verify that the code is working fine. later, proceed to verify the hardware. I hope this helps.
You can verify the FastLED code here (you can modify the parameters)


How to fix baud rate when hardware capacity has a low limit? I have a transmitter(simple 433 MHz transmitter) connected via digital pins on the Arduino. The receiver is connected to another arduino.
Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones.
But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc.
So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.

I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two.
So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec?
Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.

The transmitter you're using is very basic, and only transmits "on" and "off". As such it is protocol-agnostic. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.

One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.

The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via Serial on non-USB-native Arduinos as well as Serial1, Serial2, and Serial3 on Arduinos where they are present.

Additionally, SoftwareSerial can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.


How to assign two or more variables incoming from app I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables a,b,c. I need these variables in my Arduino to make whatever. Since all variables are read using Serial.read() how can I distinguish between them in my Arduino?

Example:

Variable a: 2
Variable b: 3
Variable c: 4

Arduino example code:

void loop() {
int a = Serial.read();
int b = Serial.read();
int c = Serial.read();

if(a == '0'){
digitalWrite(yellowLed, HIGH);
}

if(b == '0'){
digitalWrite(blueLed, HIGH);
}

if(c == '0'){
digitalWrite(redLed, HIGH);
}

In every loop, my Arduino does serial.read() 3 times, if I only send value b from my app, since int a = Serial.read() executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if Serial.read() doesnt read anything, will my values be changed to null or zero?

This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data.  However, it can be said that many solutions exist for this problem & that these are only 2 examples.

In the first case, the sender and receiver need to agree that all data will be sent in pairs.  A pair of bytes, for example, where the first identifies the data and the second is the data.  In this case the order of data does not matter.  And much more of one type of data can be sent than another.  This is good to use when the data rate is irregular and does not need to be fast.  Stock prices for example.

In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent.  Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data.  Usually, when there is no data to be sent, a zero is sent.  But if zeros are significant, then special null characters will have to be agreed upon.  This is good when the data rate is regular and needs to be fast.  Digitized audio for example.


What are the Arduino hardware options for experimenting with IoT? Just starting to learn about Arduino and IoT. I'd like to know what the Arduino hardware options are to try the following:

Use FreeRTOS as SO
WI-FI and BLE connectivity
Solderless board
Test OTA features
Experiment integration with different IoT Cloud platforms e.g. Azure IoT Hub
Build custom IoT devices

There are many options; which one is "best" for you I leave up to your own research, that could start here:
There's a list of Arduino's based on the SAMD21 that are supported by the FreeRTOS_SAMD21 library here; pick any one with WiFi and BLE.
There are probably a zillion clones out there that could also do what you want, and there is also a FreeRTOS port for the ESP32 (ESP-IDF FreeRTOS, and maybe other ones as well).


Portenta pinouts for ADC I wanted to have your comments about one of my questions.
I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts.   Below you can find the pinout diagram from the document page 1 available at the below link.
https://content.arduino.cc/assets/Pinout-PortentaH7_latest.pdf
I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector)  and analog pin A0 both separately.   What can be the difference between them ? or maybe I am interpreting wrong.
Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate?
I thank you for your time and opinion.

The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones.
Every pin that is on the edge of the board is also on the high density connectors somewhere.
Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors and the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers.
A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.


sprintf() to assemble String and float pieces locks up I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below.

When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the sprintf(); line, everything works fine — except no URL is parsed.

I've tried to debug to the best of my ability and am looking for thoughts on what may be happening.

I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the loop that is trying to piece together the URL.

  // Get update time
  Process date;
  date.runShellCommand("date --utc \"+%Y-%m-%d%%20%H:%M:%S\"");
  String utcDateString = "";
  while (date.available()) {
    char d = date.read();
    utcDateString += d;
  }

      char url[512];
      url[0]='\0';
      float humid, baro, windspeed, raingauge;
      int winddir;
      Serial.print("humid: ");
      Serial.println(humid);
        Serial.print("baro: ");
      Serial.println(baro);
        Serial.print("windspeed: ");
      Serial.println(windspeed);
        Serial.print("raingauge: ");
      Serial.println(raingauge);
        Serial.print("winddir: ");
      Serial.println(winddir);
 //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&PASSWORD=xxxxxx&dateutc=%s&temp=%2.2f&humidity=%2.2f&baromin=%f&winddir=%d&windspeedmph=%3.2f&rainin=%3.2f&softwaretype=Custom%%20Arduino&action=updateraw",
//         utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge);
        Serial.print("url: ");
      Serial.println(url);

double Thermistor(int RawADC) {
  double Temp;
  Temp = log(11100.0/((1024.0/RawADC-1)));  // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground
  Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
  Temp = Temp - 273.15;            // Convert Kelvin to Celcius
  Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  return Temp;
}

Here's the output from those Serial.print() calls:

humid: 0.00
baro: 0.00
windspeed: 0.00
raingauge: 0.00
winddir: 0
url:

I'm not sure how else to debug this because when I uncomment sprintf(); the Yun locks up and I have to press the 32U4 Reset button and power cycle the Arduino to get it to work again.

This variable:

String utcDateString = "";

Is a C++ String, not a character array like sprintf() is expecting.  To convert this string to a character array such that sprintf is expecting, you must use .c_str() in your sprintf, i.e.:

sprintf(foo,"This is a format for %s", utcDateString.c_str());

Doing this should prevent the sprintf line from causing a memory fault.


Is there possible implement websocket using AT Command? For example I have a sim800l module to communicate to a server using websocket (socket.io) but that module allows AT Command to operate.

I have successfully made an HTTP request, but I don't know how to make a request via WebSocket using AT Command.

thank you.

Yes, you can @Imanuel. You just need to establish a Simple TCP connection and then send the HTTP headers for upgrading the normal HTTP connection to WebSockets.


Sending data using Bluetooth SPP-C Module without a Breakout-Board tl;dr

I can't send data using the raw SPP-C Bluetooth module without a breakout board.
The communication via UART works fine as I am able to issue AT commands and get proper responses.
But when connected over Bluetooth the data passed over UART does not show up on my computer while the other direction works fine.
Has anyone tried that module yet without using a breakout board?

The long story:

I started my project by using a regular HC-05 module on a breakout board. The prototype worked just fine as there are also plenty tutorials available. The drawback using that breakout module is that it works with two voltages, 5V for power and 3V3 for communication. I have also more components in my project that run best at 3V3. That is why it came to my mind to use 3V3 as the only voltage. The raw HC-05 module without breakout board is also powered with 3V3. So everything looked just perfect.

Looking at the specs to the HC-05 I noticed that there is also more on that module like SPI and USB (page 12 bottom). So I got curious and off track.

Anyway. Instead of ordering raw HC-05 modules without breakout board I ordered cheaper SPP-C modules that don't have all this fancy stuff but just UART communication.

Following the description from Martyn Currey I was quicky able to issue AT commands and receive data over bluetooth. But I am not able to send data over Bluetooth.

I am using the same setup as it is shown on page 4 in the Chinese datasheet. (no I can't read that crazy symbols but I can read and understand the images)

I found a solution myself.
The modules are working as they are supposed to and are not faulty.
Also I did nothing wrong.

The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using minicom. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.

After that I turned over to my Windows and used Hype! Terminal. Everything worked!

Then I went to my Raspberry Pi and Linux. After pairing using bluetoothctl and issuing a few commands from Bluetooth as ttyUSB. Everything worked as well.

Then I tried BlueSPP on an Andriod phone. And again, it worked as it was supposed to.

So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.


How to ground a arduino with an external power-source? I have magnet hooked up to my arduino with a Darlington Transistor, like this:

The powersource is a 12V adapter

I'm pretty new to electronics but i'm told that the transistor won't work unless the ground on the arduino is the same as the ground on the external source. How do I do this in practice? Should I run a wire from the ardunio-ground to the negative pole on the powersource? How do I tell which one is the negative one?

Ground is usually (though not always, but in your case it is) the point of lowest potential in a circuit. In your circuit that is the "negative" connection of the power supply. Note that the "negative" isn't actually "negative", it is zero volts when measured from the reference point of itself.

So yes, you need to know which is the "negative" connection and connect that to ground on the Arduino.

Since you already have it wired up the negative is the one which connects to the emitter of your transistor. If you don't know which that is and you just randomly connected a random wire to a random pin then you need to investigate your power supply.

The simplest way is with a Digital MultiMeter (one of the most basic items you need to own if you are working with electronics - if you don't have one then go and buy one immediately). Set it to DC Volts in the right range then connect the two probes (correctly inserted into the right sockets on the DMM) to the power supply's output connections. If the voltage reads positive then the black probe is connected to negative. If it reads a negative value then the red probe is connected to negative.

If you cannot get a DMM but you have an LED (note: a bulb will not work) and a suitable resistor (say 2.2K) you can connect the resistor in series with the LED then connect the two to the power supply. The cathode of the LED (the pin with the flat side on the case) connects to negative. Connect the power both ways round. The way round that it lights the LED is the correct way round, and you know that the connection that goes to the cathode (flat side of the lip round the bottom of the LED) is the negative.


digispark - 2 pin push button to iterate through an hashmap I'm trying to create a project with my digispark where i can iterate through an hashmap, when i press the push button the digispark writes via digikeyboard the values from an hashmap. Each time i press the button it's supposed to write the first value, then i press the push button again and in the same line it cleans what was written in the first value and writes the second value and so on. when the last value is reached it goes again to the first value if the button is pressed.
Right now i'm trying to put the iterator to work preperlly, this is the code i have:

#include "DigiKeyboard.h"
#include "HashMap.h"

HashMap<String, String> hashMap;
int i = 0;

void setup() {
   //setup hashmap
  hashMap.put("key0","test0");
  hashMap.put("key1","test1");
  hashMap.put("key2","test2");
  hashMap.put("key3","test3");
  hashMap.put("key4","test4");

  DigiKeyboard.sendKeyStroke(0);
  pinMode(0, INPUT);
}
void loop() {
  int sensorValue = digitalRead(0);
      while(sensorValue ==1 and i < hashMap.count())
      {
        delay(100);
        DigiKeyboard.println( hashMap.valueAt(i));
        i++;
      }
}

when i plug the digispark it prints automatically the first and the second value ("test0" "test1") and every time i press the button i get nothing.

This is my configuration:
http://cdn.instructables.com/FZA/0UN8/HI3TXV8D/FZA0UN8HI3TXV8D.LARGE.jpg

Can anyone help me please?

Even with a "clean" button, your while() loop will whip through all 5 hashmap values before you can release the button.
Switches and button aren't clean. They will (appear to) bounce, sending many pulses before they settle down to a fully on or fully off state. Read Nick Gammon's tutorial on de-bouncing switches.
I'm not familiar with your display but if it is a one-line display, and you .println() at it, will the newline character "scroll" the line of text off the display? This could explain why you didn't at least see the final line. You may need a plain .print() call in order not to do that.
Most LCD displays have a set of control codes to clear it, move the cursor, etc., which you would have to embed into the text string you send, or send using separate .print() calls. I don't see any provision in your code for including or sending those, so you'll need to fix that, too. Right now, I expect your display receives something like
test0\ntest1\ntest2\ntest3\ntest4\nIt probably needs to see something more like\033Etest0, e.g., for the first one, etc. That cruft at the beginning of the string is the VT52-code,escE, for "Clear the display". (I have no idea what command set your display uses, but the VT-52 commands have been in use for ... um, hmmph! well, a long time, anyway. :)  You'll probably to replace it with whatever your particular device uses.


How close to 5 kHz can I set the PWM frequency on an UNO pin 11? I'm rebuilding a laser CNC machine and using LaserWeb4 as the control interface and GRBL 1.1 as the low-level interface to the stepper motors, limit switches and the laser. I have all the motion sorted out and am working on the laser control.

Figure 1. The GRBL 1.1 pinout. Pin 11 is used for spindle (cutter) speed on a milling machine or laser power control on a laser cutter.
The machine is using a Synrad 48 Series laser module which requires a 5 kHz PWM frequency (page 45 - 46).
The GRBL 1.1 sketch can be configured for a variety of PWM frequencies. See cpu_map.h.
  // Prescaled, 8-bit Fast PWM mode.
  #define SPINDLE_TCCRA_INIT_MASK   ((1<<WGM20) | (1<<WGM21))  // Configures fast PWM mode.
  // #define SPINDLE_TCCRB_INIT_MASK   (1<<CS20)               // Disable prescaler -> 62.5kHz
  // #define SPINDLE_TCCRB_INIT_MASK   (1<<CS21)               // 1/8 prescaler -> 7.8kHz (Used in v0.9)
  // #define SPINDLE_TCCRB_INIT_MASK   ((1<<CS21) | (1<<CS20)) // 1/32 prescaler -> 1.96kHz
  #define SPINDLE_TCCRB_INIT_MASK      (1<<CS22)               // 1/64 prescaler -> 0.98kHz (J-tech laser)

  // NOTE: On the 328p, these must be the same as the SPINDLE_ENABLE settings.
  #define SPINDLE_PWM_DDR     DDRB
  #define SPINDLE_PWM_PORT  PORTB
  #define SPINDLE_PWM_BIT     3    // Uno Digital Pin 11

It seems that my options are 62.5 kHz, 7.8 kHz, 1.96 kHz or 0.98 kHz.
Why does it matter? Two excerpts from the Synrad manual:

Tickle frequencies [a 'keep-awake' signal at zero power] lower than 4.5 kHz may compromise laser performance, ..., and stress the RF [radio frequency] electronics thereby reducing long term reliability while tickle frequencies greater than 5 kHz may cause unintended lasing.
Because laser output follows PWM input with a rise and fall time constant of ~100 µs, the laser cannot precisely follow Command signal frequencies over t kHz with duty cycles greater than 50%.

Can anyone see a workaround for this within the constraints of the GRBL configuration?
I can only think of a hardware solution to filter the PWM out and run it through another device to convert the analog signal to a 5 kHz PWM.
Many thanks.

No, you cannot have hardware PWM at 5 kHz on pin 11 of an Arduino
Uno. The closest you can get is 3.92 kHz. You get that by setting
the prescaler to 8 and configuring the timer for phase correct PWM,
instead of the fast PWM mode usually used by GRBL. Your options for
getting 5 kHz are to use either software PWM or change the pinout.

You can get a quite accurate 5 kHz PWM signal on pins 3, 9
and 10. You can do software PWM at 5 kHz on any pin, but this
is prone to have significant jitter, which your laser may well not like.


8 x 8 led matrix module I just bought 4 8x8 led matrix module from online store...when I connect the led module to arduino and computer without any program, the led shows weird pattern (isn't that is should show all 64 led lighted up???) attached with the photo

It still weird pattern after I programmed it

It seems that the 2 rows and columns have not been connected correctly.

In the diagram or with the example program you can find out to which pins these
should be connected and check if the wiring is ok (and the wires itself).

You can also switch two wires around to see if it makes a difference.

Note that some Chinese LED matrices might use different pins (and do not have a data sheet).


Person (phone) detector that trigger an event esp32 cam So me and my dad are trying to catch would be thieves and also someone leaving behind alcohol bottles. At his storage business the cameras don't reach to these spots.

Without being too invasive I want to sense bluetooth and/or wifi signals of relatively close phones sort of like a pax counter. This is in lue of using a pir sensor which I have always found finicky and I want to make use of the esp32' cam's wifi/ble chip.

So to start I researched for the past few days or week. I found that most phones don't use ble so maybe that is out. I also found that the esp32 cam is a bit finicky and I'm not sure if it is compatible with other code I have found.

One time I was able to get the light to come on when my phone was near using code I found for the esp32.

Any help or direction would be nice

Edit: I understand this sounds weird but mostly I would just like to get proximity of bluetooth or wifi to trigger an event. The device is powered by battery and I understand not everyone carrys phones.

Detecting a phone could be easily done by capturing WiFi probe requests which are sent by phones having at least one saved WiFi network. Note that such requests alone are often enough to identify the person, if their home WiFi SSID is set to something like "Davids_wifi".

Software-wise, this would be much easier to do on Linux (think Raspberry Pi or a similar device) which already have all the network sniffing software like tcpdump, which you would otherwise have to find or implement on ESP32.

I'm leaving out the legal implications of what you're trying to do as I don't know what country you are in, but bear in mind that hidden surveillance may be illegal in some cases.


What would be the architecturally-right place to put custom -D defines? What I am trying to accomplish is to include information about the state of my environment at build time in my code. For example, I may want the setup() code to print the git sha it was built against, and the time of build.

There are two related issues here:

How to include that information in the code
How to specify to the build environment what to generate in the first place.

The first can be addressed in a number of ways:

-D options can be generated at build time, and the corresponding defined macros expanded in the code. For example, the compiler could be invoked as g++ -DGIT_SHA=$(git rev-parse HEAD) -DDATE=$(date '+%Y%m%d-%H:%M:%S'), and my code could have something like #define strfy(_x) #_x followed by Serial.println(strfy(GIT_SHA));. Or the build tool could generate a header file that would define these as external string variables, which the main sketch could then include and print. Or any other number of tricks.

The question I am really asking is: how should I specify this sort of stuff for arduino-builder?

Ideally, it would be a custom recipe in platform.txt, but if there is a way to invoke shell commands in recipes and use the results to modify other variables (such as preproc.macro.flags), I haven't been able to find it (if there is documentation, it's really well hidden). Ideally I would want to be able to say preproc.macros.flags=-w -x c++ -E -CC -DGIT_SHA=$(git rev-parse HEAD) and have the shell command be executed at the point.

So, before I set out to hack arduino-builder, do people have any opinion on this? My main criterion is something that would be of general value and has a chance of being incorporated in the code, rather than a kludge that only works for me and which I have to patch every time I upgrade. Please do not suggest workarounds. I can think of several myself!

I did try to search, and this sort of issue has come up before, but I didn't see any satisfactory answers from people who knew what they were talking about.

Thanks!

/ji

That is a tough one...  Because arduino-builder is basically a custom go script you don't get the facilities you get in a Makefile, like shell execution.

I would be inclined to do this kind of thing outside that environment - use some external program or tool to generate a config.h file (maybe use something like GNU Autotools) that contains your custom defines. That can then be #included in your sketch.


Arduino keeps crashing I've got an Arduino with a WS2812 hooked up to it, powered by the USB on my computer and I am trying to run the following code:

#include <FastLED.h>

#define NUM_LEDS 144
#define DATA_PIN 6
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.show();
}

void loop() {
  for(int dot = 0; dot < NUM_LEDS; dot++) {
    fill_solid(leds, NUM_LEDS, CRGB::Red);
    leds[dot] = CRGB::Black;
    leds[dot] = CRGB::Blue;
    FastLED.show();
    leds[dot] = CRGB::Red;
    delay(30);
  }
}

void setAll() {

  FastLED.show();
}

What this does is sets all the LEDs to red, then goes through each one turning it off, then to blue and then back to red.

For some reason, it gets X number of LEDs along and then crashes.  By crashes I mean the Arduino disconnects itself from the computer, but the Arduino stays on with the LED strip still powered up.

Any ideas?  This is a genuine Uno and I can run any of the FastLED or NeoPixel examples for hours on end without an issue

It is inferred from your question that the Arduino is getting powered through the USB port.  As you say the Arduino appears "gone" from the computer when you light up too many LEDs.

All USB ports are only obliged to supply 500mA with out the USB Device (the Arduino) negotiating for more power from the USB Host.  If the load goes beyond 500mA, the USB Host (the computer) can limit the power my reducing the voltage.  At some point the Atmel processor on the Arduino will stop working.

There are many tutorial on how to use LED strips on the web.  Most will indicate power from a larger than normal power supply is necessary.  Also, that the LED strip power should be connected directly to an appropriately chosen power supply.

The following image from this web page illustrates this:

(Note: In this picture PIN 6 was chosen to communicate with the LED strip.  Your specific application (program or sketch) may use a different pin. Also, realize that the power supply in the picture is wired to only power the LED strip. The Arduino still needs to be powered.)


Arduino IDE won't upload sketches I recently updated my Arduino IDE to 1.8.5 from 1.6.9. I am getting issues with uploading sketches. The sketch compiles, but when I try to upload it I get this message:

Arduino: 1.8.5 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
ATmega2560 (Mega 2560)"

Sketch uses 642 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
java.io.IOException: Cannot run program "___REMOVE___/bin/avrdude": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at java.lang.Runtime.exec(Runtime.java:620)
    at java.lang.Runtime.exec(Runtime.java:485)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:11)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:207)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:713)
    at processing.app.SketchController.exportApplet(SketchController.java:686)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2168)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 10 more
An error occurred while uploading the sketch

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

I get this message whether or not an Arduino is connected. I also get the same message weather I connect my Arduino Mega or Uno. I tried my sketch, the blink sketch and a completely blank sketch, all with the same results.

Could I please get some help with this issue?

You may be able to fix this by taking some drastic action. Be aware this is somewhat advanced and will remove any boards you have installed via Boards Manager:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file. This will open the Arduino15 (or similar name depending on OS) folder.
Delete all files and folders under the Arduino15 folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
Restart the Arduino IDE.
Verify you can now upload before re-installing any boards via Boards Manager.


How to send signal ONCE when within constant range of sensor? I am working on a project to have a open/close a solenoid at certain ranges (using HC-SR04 ultrasonic sensor).

#include <NewPing.h>2

#define Relay1 7
#define Relay2 8

NewPing SonarRight(12, 11, 400);

void setup() {
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
}

void loop() {

  unsigned int uS1 = SonarRight.ping();
  delay(50);

  if (uS1 / US_ROUNDTRIP_CM > 15)
    digitalWrite(Relay1, HIGH);
    delay(100);
    digitalWrite(Relay1, LOW);
    delay(1000);

  if (uS1 / US_ROUNDTRIP_CM < 5)
    digitalWrite(Relay2, HIGH);
    delay(100);
    digitalWrite(Relay2, LOW);
    delay(1000);
}

I got the sensor to ping correct and the distances are reading accurately.  I have it to where once sensor reads that the object is more than 15cm away, the solenoid opens but it keeps clicking open until the object goes back to the dead zone (5-15cm).  Same thing when less than 5cm.  Essentially what i am trying to accomplish is to have the solenoid fill up a tank when the water level get low.  So when the water drops 10cm (x>15) the solenoid opens and then once the water is replenished (x<5), the solenoid closes.

How do i go about doing this without sending a constant OPEN/CLOSE to the solenoid?  Is there a way to make a loop to have it send a the signal only once until it exits that defined range?

Please note that i have not actually used it for its intended purpose im supply moving an object back and forth to simulate water distance.

Thanks

You have to add a (global) variable that stores the last send command (to open/close).

When you send a command, you save it in the global variable.

And you only send a command when it is different than the command send the last time, so only CHANGES are sent.

The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);

#define SOLENOID_OPEN  TRUE
#define SOLENOID_CLOSE FALSE

bool _currentSolenoidStatus = false; // Assume closed

In your loop:

...
if  ... condition when solenoid should be be opened
{
    SetSolenoid(SOLENOID_OPEN);
}
...
if  ... condition when solenoid should be be closed
{
   SetSolenoid(SOLENOID_CLOSE);
}

Function to open/close solenoid open (only when changed):

bool SetSolenoid(bool status)
{
    if (_currentSolenoidStatus != status)
    {
        // Send status to solenoid
        _solenoidStatus = status;
    }
}


WiFi UDP.endPacket() continuously fails I am attempting to send data from my Arduino to my computer using the WiFi shield.  However, my code is erroring out on UDP.endPacket(), and I do not understand why.  Here is my code:

#include <WiFi.h>
#include <WiFiUDP.h>

int status = WL_IDLE_STATUS;
char ssid[] = "NETGEAR31"; //  your network SSID (name)
char pass[] = "oddearth926";    // your network password (use for WPA, or use as key for WEP)

char  ReplyBuffer[] = "acknowledged";       // a string to send back

WiFiUDP Udp;

void setup()
{
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD)
  {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
  }
  Serial.println("Connected to wifi");
  printWifiStatus();
  Serial.println("\nStarting connection to server...");
  if(!Udp.begin(8765))
  {
    Serial.println(F("failed"));
  }

  // if you get a connection, report back via serial:
}

void loop()
{
  IPAddress ip(10,0,0,5);
  int port = 8766;
    // send a reply, to the IP address and port that sent us the packet we received
    if(!Udp.beginPacket(ip, port))
    {
      Serial.println(F("Failed beginning packet"));
    }
    Udp.print(ReplyBuffer);

    if(!Udp.endPacket())
    {
      Serial.println(F("Failed ending packet"));
    }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

And here is the log:

Attempting to connect to SSID: NETGEAR31
Connected to wifi
SSID: NETGEAR31
IP Address: 10.0.0.34
signal strength (RSSI):-63 dBm

Starting connection to server...
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet
Failed ending packet

It will continue to spit out "Failed ending packet" until I stop it.  Any ideas?

Fixed by updating firmware on Wifi Shield.


Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module) My goal is to send a string from an Arduino via an HM-10 bluetooth module to a Rasperry Pi. I do this today by connecting the HM-10 on the Arduino to another HM-10 module (master/slave) and then from that module to the Raspberry Pi via USB Serial adapter which gives me a /dev/ttyUSB0 that I can read. I would like to just have the Arduino's HM-10 connect up directly to the Bluetooth of the Raspberry Pi without any extra modules at all.

I found the app "Arduino Bluetooth Controller" (Android) that can connect to the module and serial communication is working.

I also have the HC-05 module and there I can solve it by using rfcomm bind 2 , but that doesn't work on the HM-10.

I'm open to any solution that can do this. Either bind the serial communication using rfcomm (or alternative) like on the HC-05, or try to build an app that is doing the same thing the Android app does, only on the Raspberry Pi.

HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth.
There is no standard BLE service for serial communication.
The best way on a Pi to use BLE is with the

noble and bleno modules for node.js.
Or start by playing with gatttool.

If you are fit in Phyton:
The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to
attach a 'delegate' call-back function to the Peripheral object,
and then wait for notifications.
The call-back can then process the received data.
You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device

import bluepy.btle as btle

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]

c.write(bytes("Hello world\n", "utf-8"))
p.disconnect()

Here is some code for reading from an Arduino HC-10 device

import bluepy.btle as btle

class ReadDelegate(btle.DefaultDelegate):
    def handleNotification(self, cHandle, data):
        print(data.decode("utf-8"))

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
p.withDelegate(ReadDelegate())

while True:
    while p.waitForNotifications(1):
        pass

p.disconnect()


Size of String array I am trying to find out the size of an array like this:

    String days[3] = { "Mon", "Tue", "Wed" };
Serial.printf("Size of array: %2d\n", sizeof(days));
for (int i = 0; i < sizeof(days); i++) {
    Serial.print(days[i]);
}

The result of the code above is 36 which is incorrect.

Do I have any other options considering that I don't know the size of the array to begin with?

No, the result is correct, you're just interpreting it incorrectly. If you want the number of elements in a statically-allocated array use:

sizeof(somearray) / sizeof(somearray[0])


Dim a led using a NPN transistor I know there are a lot of questions about this topic, but I've tried everything and any possible guide online without success.

I want dim (increase and decrease the brightness) some leds (3.5 Watt each). To do that I'm using an Arduino Nano, a 10k potentiometer and an NPN transistor (TIP41).

I was able to drive the potentiometer as a switch: on/off. Now I want to control its brightness using the potentiometer. I don't get what I'm expecting because the led is always on except when the potentiometer is turned all the way on the right (where is connected Vcc).

This is the schematic:

This is my Arduino code:

int pinPotentiometer = 0;
int pinTransistor = 3;

void setup() {
  Serial.begin(9600);
  pinMode(pinTransistor, OUTPUT);
  pinMode(pinPotentiometer, INPUT);
}

void loop() {
  int potValue = analogRead(pinPotentiometer);
  int outValue = map(potValue, 0, 1023, 0 ,255);
  Serial.println(outValue);
  digitalWrite(pinTransistor, outValue);
  delay(100);
}

The potentiometer is working fine because I read from the serial values between 0 and 255.

Am I using the wrong transistor? Or maybe I'm using it in the wrong way?

NOTE: to test my circuit I'm using a small 5mm led and not the 3.5 Watt one so I don't have any external power source.

Many thanks!

Try using analogWrite().

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz.

Source: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


Detect if MCU is ESP8266 or ESP32 I'm coding a library which handles sleep procedures.
Since I'm using both ESP826 and ESP32, which uses different sleep commands ( and WiFi ), I'm looking for a way to detect the MCU, while NOT using a boolean flag that indicates so.
Guy

I take this to mean that you do not want to have to ask the user of the code to configure a boolean flag.
The ESP8266 Arduino package provides -DARDUINO_ARCH_ESP8266 -DESP8266
command-line options these while calling g++.  These effectively #define feature test macros as though they were at the beginning of the source code.
For ESP32 it does likewise with -DARDUINO_ARCH_ESP32 -DESP32
You could perform tests in your code such as:
#if defined (ARDUINO_ARCH_ESP8266)
// do one thing
#elif defined(ESP32)
// do another
#else
#error Architecture unrecognized by this code.
#endif

There are likely also macros like these that are predefined by the xtensa g++ compiler.


Running an LCD keypad shield from a separate power source I need to use a motor shield and an LCD keypad shield simultaneously hooked up to a single Arduino Mega Board. Since I can't physically stack them, I decided to reroute all the pins used for the LCD keypad shield. When I reroute all pins except the two power pins, the LCD and keypad work fine. But when I disconnect those 2 pins and connect them to any other power source than the Arduino Mega, it fails. The screen becomes either blank / jumble of illegible characters / brief moments of expected output followed by the same jumble.

This behavior is really strange since the power pins don't carry any information, they are just power sources. The LCD keypad shield shouldn't be able to discriminate whether the power is coming from the Arduino Mega or not - but it does. I checked with a voltmeter that all power sources I tried are DC 5V.

At first I thought this is because the lcd.begin() function is called only once, so I rewrote my code to re-initialize the lcd at every iteration. This doesn't solve the problem.

Here is a picture of the setup that works. (rerouting all pins except the power.) Ignore the location of analog input cable, since it doesn't do anything in the current code.

And one that fails. The only difference from above is the power source.

And my code.

#include <LiquidCrystal.h>

// select the pins used on the LCD panel
LiquidCrystal lcd(28, 29, 24, 25, 26, 27);

void setup()
{
  lcd.begin(16, 2);
  lcd.print("Hello World!");
}

void loop()
{
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Hello World!");
  delay(1000);
  lcd.setCursor(0, 0);
  lcd.print("Hello Again!");
  delay(1000);
}

Any suggestions?

You can use a different power source, but the two circuit need to have a common ground, since all electrical signals are relative to ground. So connect a wire from GND on the LCD to GND on your Arduino and everything should work as expected.


Replace mechanical switch with electrical switch or relay I have a remote controller for a portable heater, and working on a small project to be able to control the fan on/off from an arduino with Bluetooh HM-10 module. I thought a solenoid might work by mounting on top of the remote but it doesnt have enough force, I want to remove/desolder the mechanical button and figure out a way to control it without the switch but kind dont really know what circuit
I should use, kind of just learning how to use arduino.

Images of remote and button traces below.

Any idea how I could wire this up to arduino via some switch/relay circuit? Any circuit design / schematic would be helpful

I would unsolder the switch then solder in a FET in the configuration shown below. The FET will act as a switch and may be controlled with any digital output from your Arduino board. When selecting a FET makes sure you find something that will fit the foot print you have to work with on your board, and the gate-source threshold voltage is rated to handled 5V.


ESP8266 stops responding when isolated relay is connected to AC tubelight I'm completely new to Arduino and do not have an electronics background.
I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.
I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.
I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html.

This is my code.
#include <SoftwareSerial.h>

#define DEBUG true
int relay = 8;
SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different
  pinMode(relay, OUTPUT);
  digitalWrite(relay, LOW);

  sendData("AT+RST\r\n", 2000, DEBUG); // reset module
  sendData("AT+CWMODE=3\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWJAP=\"xxxx\",\"xxx\"\r\n", 5000, DEBUG); // configure as access point

  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
}

void loop()
{
  if (esp8266.available()) // check if the esp is sending a message
  {

    if (esp8266.find("+IPD,"))
    {
      delay(1000);

      int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns
      // the ASCII decimal value and 0 (the first decimal number) starts at 48

      if (esp8266.find("=="))
      {
        Serial.print("State : ");
        char c = esp8266.read();
        Serial.print(c);
        if (c == '1') {
          digitalWrite(relay, HIGH);
        }
        else {
          digitalWrite(relay, LOW);
        }
      }
      String webpage = "A";

      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend += webpage.length();
      cipSend += "\r\n";

      sendData(cipSend, 1000, DEBUG);
      sendData(webpage, 1000, DEBUG);

      String closeCommand = "AT+CIPCLOSE=";
      closeCommand += connectionId; // append connection id
      closeCommand += "\r\n";

      sendData(closeCommand, 3000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

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

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {

      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

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

  return response;
}

The above code works perfectly until I connect the tube light to the relay.
The power supply used in 9v 1A wall adapter.
The relay used is http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&redirect=true&ref_=oh_aui_detailpage_o03_s00.
The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.
I'm really struggling hard to proceed here. Any help or hint would be much appreciated.
Thanks in advance.

I suspect that you've connected the relay wrong. I think that the LNP of the relay is supposed to be connected to D8 and the v+ to 5/3.3V and GND to GND....


Can ESP8266 send AT commands to self? I'm having some problems with my ESP8266 stopping transmission of MQTT messages after a while.
Therefore I'm writing some error handling messages, and I want to publish some AT data to MQTT.

It's probably a simple solution, but how can I, though the code, send AT messages from my 'own' device?
Also, does AT messages get parsed at a higher level than any other user input, so it can't get stuck in any user made input loop?

Many thanks!

The AT command set for the ESP8266 is implemented through custom firmware which has to be flashed to the chip to use.

If you've written your own software which is running on the ESP8266 then that's what's flashed to it - the AT command set will not be available because you've overwritten it with your own software. So there's no way to send AT commands to yourself because if you've written software that could do that, then it's present and the AT command-interpreting software is not.

In that case you should look deeper into the Arduino core for the ESP8266 to find the equivalents to the AT commands you wanted to use. This is the code that calls setup() and loop() and implements Arduino-compatible functions like pinMode(). It also provides libraries like ESP8266WiFi. There are many un- and under-documented functions in the code. You can almost certainly find the equivalents to anything that you can do with an AT command in here.