Multiple variant.cpp entries for same physical pin Some variant.cpp files have more than one entry that points to the same physical pin. For example (from Arduino Zero's file):

// 14..19 - Analog pins
// --------------------
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // ADC/AIN[0]

...

// 43..45 - Alternate use of A0 (DAC output), 44 SWCLK, 45, SWDIO
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, DAC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // DAC/VOUT

The first entry sets up the pin as a regular analog input pin on A0. The second entry sets it up as a DAC on pin IDE pin 43.

The corresponding variant.h file defines the DAC pin and A0 as entry 14, rather than 43. I also have seen plenty of examples online that use the DAC via A0 when working with an Arduino Zero.

/*
 * Analog pins
 */
#define PIN_A0               (14ul)
#define PIN_A1               (15ul)
#define PIN_A2               (16ul)
#define PIN_A3               (17ul)
#define PIN_A4               (18ul)
#define PIN_A5               (19ul)
#define PIN_DAC0             (14ul)

Finally, I see other variants, like this one that don't even bother to create a DAC-specific entry. So presumably it doesn't actually matter? If not, then why is it in the Arduino Zero variant.cpp file at all?

A related question: How does using a pin for multiple purposes work? For instance, if I had a pin I've configured for SPI MOSI (in variant.cpp), and I wanted to also use it for PWM (given the datasheet says the pin is on a SERCOM and a timer), do I actually need two entries in variant.cpp and thus two different IDE pins to use in my sketches (one that has a pin type of PIO_SERCOM and another with PIO_PWM)? I can think of plenty of times working with an Arduino UNO, for instance, where I've just used the same IDE pin number for general IO as well as SPI (MOSI).

The analogWrite function checks the PIN_ATTR_ANALOG attribute from pin description in variant.cpp to determine if the pin has DAC capability. Then it checks if the pin is ADC_Channel0 or DAC_Channel0. This is unnecessary and redundant. There is no other use for DAC_Channel0.

In Arduino SAMD core and derived cores the pin 'map' in variant.cpp defines pin capabilities used by Arduino core. It is not a complete copy of the mux table from the datasheet. In some variant.cpp files comments contain the additional mux options of the pin.

For PWM the analogWrite function configures the pin and for SPI, the SPI library configures the pin.

If you want to use the pin for other SERCOM function, the function pinPeripheral is used to set up the pin. Here is a tutorial.

Arduino core doesn't support a configuration of a different wave output then analogWrite. To configure a different wave output or capture, a third party library or direct registers configuration is necessary.

The Arduino pinPeripheral(pin, peripheral) function uses the variant.cpp mapping and the possible parameters are:

PIO_EXTINT=0,     /* The pin is controlled by the associated signal of peripheral A. */
PIO_ANALOG,       /* The pin is controlled by the associated signal of peripheral B. */
PIO_SERCOM,       /* The pin is controlled by the associated signal of peripheral C. */
PIO_SERCOM_ALT,   /* The pin is controlled by the associated signal of peripheral D. */
PIO_TIMER,        /* The pin is controlled by the associated signal of peripheral E. */
PIO_TIMER_ALT,    /* The pin is controlled by the associated signal of peripheral F. */
PIO_COM,          /* The pin is controlled by the associated signal of peripheral G. */
PIO_AC_CLK,       /* The pin is controlled by the associated signal of peripheral H. */
PIO_DIGITAL,      /* The pin is controlled by PORT. */

If you are good with the Arduino variant.cpp configuration, then for direct registers access configuration the pin 'map' from variant.cpp and the pinPeripheral function can be at help if the pin should not be hardcoded. Example from peripherals setup for 'phase cutting' with a Triac in my project:

const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);
bool periF = (pinDesc.ulPinAttribute & PIN_ATTR_TIMER_ALT);

// setup the pin as TCC wave out pin
pinPeripheral(triacPin, periF ? PIO_TIMER_ALT : PIO_TIMER);

TCC->CC[tcChannel].reg = PULSE_PERIOD;


How do you benchmark an Arduino? I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?

long num = 0;
long startTime = 0;
long endTime = 0;
int duration = 0;
String buffer;

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

void loop(){
  startTime = millis();
  benchmark();
  endTime = millis();
  duration = endTime - startTime;
  Serial.print(startTime);
  Serial.print(", ");
  Serial.print(endTime);
  Serial.print(", ");
  Serial.println(duration);
}

void benchmark() {
  num = 0;
  for(num = 0; num < 1000000; num++);
}

I'm using an Uno, if that matters.

No.

That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.

Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).


Nextion Display not getting updated data I am using an Arduino Mega to display the readings of 4 pots on a Nextion Display as well as store it in an SD Card with the time stamp. I keep getting:
recvRetCommandFinished err
on the serial monitor and the display does not update with time.
I have attached my code below:
#include "Nextion.h"
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// Declare your Nextion objects - Example (page id = 0, component id = 1, component name = "b0")
NexText tDate = NexText(0, 1, "tDate");
NexText tPot1 = NexText(0, 6, "tPot1");
NexText tPot2 = NexText(0,7, "tPot2");
NexText tPot3 = NexText(0, 8, "tPot3");
NexText tPot4 = NexText(0, 9, "tPot4");

File myFile;

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

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //rtc.adjust(DateTime(2016, 11, 19, 19, 45, 0));   // <----------------------SET TIME AND DATE: YYYY,MM,DD,HH,MM,SS
  }

  delay(100);

  // You might need to change NexConfig.h file in your ITEADLIB_Arduino_Nextion folder
  // Set the baudrate which is for debug and communicate with Nextion screen
  nexInit();

  SPI.begin();

  int pot1 = 0;
  int pot2 = 0;
  int pot3 = 0;
  int pot4 = 0;

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");
  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
}

void loop(void) {
  myFile = SD.open("testpot1.csv", FILE_WRITE);
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to testpot1.txt...");

    while(1) {
      DateTime now = rtc.now();
      myFile = SD.open("testpot1.csv ", FILE_WRITE);
      int pot1 = analogRead(A0);
      int pot2 = analogRead(A1);
      int pot3 = analogRead(A2);
      int pot4 = analogRead(A3);
      myFile.print(now.hour());
      myFile.print(":");
      myFile.print(now.minute());
      myFile.print(",");

      myFile.println(pot1);
      myFile.println(",");
      tPot1.setText(pot1);

      myFile.println(pot2);
      myFile.println(",");
      tPot2.setText(pot2);

      myFile.println(pot3);
      myFile.println(",");
      tPot3.setText(pot3);

      myFile.println(pot4);
      myFile.println(",");
      tPot4.setText(pot4);

      Serial.print(pot1);
      Serial.print(",");
      Serial.print(pot2);
      Serial.print(",");
      Serial.print(pot3);
      Serial.print(",");
      Serial.print(pot4);
      Serial.print(",");

      delay(2000);
      myFile.close();
    }
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

How do I get the pot values on my display? Any help or tips would be helpful!

recvRetCommandFinished err means something is wrong with the serial communication between the Arduino and the Nextion display; it is what recvRetCommandFinished() prints when there is an error.
Check if you are using the right pins (TX1 and RX1 for Serial1) for the serial connection to the display, the actual connections you made (RX1 to TX, TX1 to RX), the baud rate, and the cable.


LED fading effect using a push button Guys please help me out in verifying my program for my project -- led fading effect using a push button.
My project is simple, I want to start the LED fading effect (i.e., glowing and dimming one after another) at one click on the push button that is pushing and then leaving the push button and on my another click I want the effect to get off.
The main problem is coming in the programming part and rest all the circuit and components are fine.
THIS IS MY SKETCH :-
int ledpin = 9;
int buttonpin = 8;
boolean buttonpressed = false;   // to check whether the button was pressed //
int brightness = 0;
int fadeamount = 5;

void setup ()
{
pinMode (ledpin, OUTPUT);
pinMode (buttonpin,INPUT);
digitalWrite (ledpin,LOW);
}

void loop ()
{
if ( digitalRead (buttonpin) == HIGH)
 {
  buttonpressed = true;
 }

 else {
     if ( buttonpressed = true && digitalRead(ledpin) == LOW)
       {
           brightness = brightness + fadeamount;
           if ( brightness == 0 || brightness == 255)
            {
             fadeamount = -fadeamount;}
             analogWrite(ledpin, brightness);
             delay (30);
             buttonpressed = false;
        }
      if (buttonpressed == true && analogRead(ledpin) == brightness)
        {
          digitalWrite(ledpin,LOW);
          buttonpressed = false;
        }
   }
 }

THIS IS THE CIRCUIT DIAGRAM

The 1k (pulldown-)resistor must be placed at the other side of the button (the pin8 side, not the 5v side).

The led needs a resistor, to limit the current.

There is no need for the buttonstate variable, as you can just check the brightness to see if the PWM value must be changed.

int ledpin = 9;
int pushbutton = 8;

int brightness = 0;
int fadeamount = 1;

void setup ()
{
  pinMode (ledpin,OUTPUT);
  pinMode (pushbutton,INPUT);
}

void loop ()
{
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in led
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out led
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);
  }

}


Serial communication between arduino and raspberry pi works once, then stops working I'm using a Arduino Uno Rev 3 connected over usb to a Raspberry Pi Modell B+ running Rasbian.

Here ist the arduino code:

int input = 0;
String command = ""; // beinhaltet den aktuellen befehl
int Action = 1;

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

void loop() {
  if (Serial.available() > 0)
  {
        input = Serial.read();
    char currentChar = input;

    if(currentChar  == '!') // frage nach trennzeichen
    {
      Serial.println(command);
      //Serial.write(Action);
      Action = command.toInt();

      command = ""; // befehl wieder leeren
    }else
    {
      command = command + currentChar ; // falls noch kein trennzeichen vorhanden, erweitere kommando
    }
    }
}

Here is the Raspberry Pi code (in python)

import serial
from time import sleep as sleep
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0]
while True:
        ser.write(b'2!')
        a =  ser.read(1)
        print a
sleep(2)

It always works if once after the code was uploaded to the arduino, but if I stop the script on the pi and restart it it stops working. What is the problem here?

"It always works if once after the code was uploaded to the arduino...."
Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.

Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!


Connecting LCD TFT shield to NodeMCU I have the following screen:

I want to connect it to a NodeMCU device:

I read somewhere that it is not possible. However, I am not interested in the touch ability nor the SD card. I just want to draw something on the screen.

Is it possible to make the connection in somehow?

The driver chip was identified by https://www.waveshare.com/wiki/2.8inch_TFT_Touch_Shield and https://www.waveshare.com/w/upload/8/84/2.8inch-TFT-Touch-Shield-UserManual-EN.pdf as being the HX8347D.

At https://github.com/jshnaidman/UTFT_ESP8266_HX8347D there seems to be a library, with which you can use the HX8347D display type to instantiate a UTFT object, with which you can draw. You can build upon this demo code.

The connections for the SPI interface are detailed here. BL (backlight) pin is detailed here. The pin number for the D/C pin must be given in the code in the constructor and can be chosen freely.

Other reference code (which you might have to port) are:

HX8347D by Majenko
Code from Watterott


Thin battery to power arduino micro with nRF8001? I'm building a project which needs to fit in a wallet. I have an Arduino Micro hooked up to a nRF8001. I attempted three button cells wired in series, which provided a solid 7.5 volts, but only 20mA.

A 9V battery successfully powers it, but that's too big to fit in a wallet. I was considering using an A27 battery, but even that's thicker than I would like.

Is there any battery I can use that's a reasonable thickness, and won't explode on me? Thanks!...

I think you should use a 3.7v mini battery that are around 200-300mAh capacity. These batteries are variable on online stores and are very thin. Now as you require 5v there are mini DC-DC boost converters available what you can use with them.


Wire Library Timer Usage I would like to know if the Wire Library is using a Hardware Timer from the Arduino Mega 2560. And If so which Timer it is.
As I am using the Timer 1. After implementing the Wire Library I have some strange things happening that are probably due to the Timer.
Thanks a lot.

No, it's not.
It has its own timer called the "Bit Rate Generator Unit" which is controlled using the TWBR register.  It takes its time source direct from the main CPU clock and divides it down.


Calculate the Li-Po Battery Level in ESP-Wroom-02 I am very new to micro controller and circuits. I am not at all with this field. But trying to create a home project where I have a device image attached below.

This is 18650 Lipo battery powered device. Here I want to calculate the battery level. After doing some research on google I found that I need to have Voltage Divider which I think I already included in this with 220k ohms and 100k ohms

People are using different ways to calculate it. Which I found in few examples. Which I am not able to understand at all, that what formula or values they are referring to calculate it.

if someone can help to understand that will be helpful. Here is how I am coding it which I saw somewhere on internet itself.

      #include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
//#include "DHTesp.h"

#define DHT_PIN       16

//SSID and Password of your WiFi router
const char* ssid = "Asus";
const char* password = "Xmv02488!!**";

ESP8266WebServer server(80); //Server on port 80

/***************************************************************
 * SETUP
 **************************************************************/
void setup(void){
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.on("/", handleRoot);      //Which routine to handle at root location

  server.begin();                  //Start server
  Serial.println("HTTP server started");

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(A0, INPUT);

}
/***************************************************************
 * LOOP
 **************************************************************/
void loop(void){
  server.handleClient();          //Handle client requests

}

/***************************************************************
 * This function converts IPAddress struct to a String
 **************************************************************/
String IpAddress2String(const IPAddress& ipAddress)
{
  return String(ipAddress[0]) + String(".") +\
  String(ipAddress[1]) + String(".") +\
  String(ipAddress[2]) + String(".") +\
  String(ipAddress[3])  ;
}

/***************************************************************
 * This rutine is exicuted when you open its IP in browser
 **************************************************************/
 void handleRoot() {
  IPAddress ip_address = WiFi.localIP();
  String ip_str = IpAddress2String(ip_address);

  int nVoltageRaw = analogRead(A0);
  float fVoltage = (float)nVoltageRaw * 0.00486;

  float fVoltageMatrix[22][2] = {
    {4.2,  100},
    {4.15, 95},
    {4.11, 90},
    {4.08, 85},
    {4.02, 80},
    {3.98, 75},
    {3.95, 70},
    {3.91, 65},
    {3.87, 60},
    {3.85, 55},
    {3.84, 50},
    {3.82, 45},
    {3.80, 40},
    {3.79, 35},
    {3.77, 30},
    {3.75, 25},
    {3.73, 20},
    {3.71, 15},
    {3.69, 10},
    {3.61, 5},
    {3.27, 0},
    {0, 0}
  };

  int i, perc;

  perc = 100;

  for(i=20; i>=0; i--) {
    if(fVoltageMatrix[i][0] >= fVoltage) {
      perc = fVoltageMatrix[i + 1][1];
      break;
    }
  }

  server.send(200, "text/plain", "Hello from esp8266!\n\rIP: " + ip_str +
    ".\n\rTemp: " + "NO" +
    ", Hum: " + "NO" +
    "\n\r" + "NO" +
    "\n\r" + "Voltage: " + fVoltage +
    "\n\r" + "Charge: " + perc + '%');
}

This is a copied code. Where I am not sure about where they got the this formula and how they got the value of 0.00486

I copied this code from different source references. But I hope this will help you to understand the issue.

Any suggestions will be helpful!

Thank you! (In advance)

Another problem you can run into is that a lot of the A/D converters use the VCC as a voltage reference. Which means that as your input voltage drops (what you are trying to measure) the reference voltage also drops which means the values you are recording will not appear to change or at least will not give an accurate reference.


Delaying pushbutton input to microcontroller while it's busy processing I/O I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.

Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.

Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.

I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?

Below is the simplified code

#include <SPI.h>
#include <Wire.h>
byte Input=1;
volatile byte Check=1;
volatile byte Output=1;

int j;
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 13;
////Pin connected to DS of 74HC595
int dataPin = 11;

int interruptPin=2;

int espPin=7;

char arduinoStatus[100]="\0";

 void pin_read(){

    for(j=0; j<50; j++)
    delayMicroseconds(1000);

    Check=1;
    for(j=0; j<8; j++){
      digitalWrite(latchPin, LOW);
      delayMicroseconds(500);

     SPI.transfer(Check);
     SPI.transfer(Output);

     digitalWrite(latchPin, HIGH);

     delayMicroseconds(500);
    if(digitalRead(interruptPin)==HIGH){
      //Serial.println(Check);

      if(bitRead(Output, j)==1)
      bitWrite(Output, j, 0);
      else
      bitWrite(Output, j, 1);
    }//dig check

    Check = Check<<1;

    }

    digitalWrite(latchPin, LOW);
    delayMicroseconds(500);
    SPI.transfer(255); //to push buttons
    SPI.transfer(Output); //to LEDs

    digitalWrite(latchPin, HIGH);
    delayMicroseconds(500);

}//pin_read

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(espPin, OUTPUT);
  pinMode(interruptPin, INPUT);//Input from buttons

  delay(1000);
  // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();
  SPI.transfer(255);
  SPI.transfer(255);
   //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);

    Serial.begin(115200);
    attachInterrupt(0, pin_read, RISING);

    Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
  Wire.onReceive(receiveEvent);

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

void loop() {
  Serial.println("Interrupting...");
 digitalWrite(espPin, HIGH);

 while(digitalRead(interruptPin)==HIGH){}
  delayMicroseconds(500);
 digitalWrite(espPin, LOW);
 delayMicroseconds(500);
 Serial.println("Done...");
Serial.print("Output:");
Serial.println(Output);
delay(3000);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  int i=0;
  Serial.println("received::");
  while (Wire.available()) { // loop through all
    char c = Wire.read(); // receive byte as a character
    arduinoStatus[i++]=c;

    Serial.print(c);         // print the character

  }
  arduinoStatus[i]='\0';
  Serial.println("###");
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Serial.println("Sending...");
  Wire.write("hello"); // respond with message of 6 bytes
  Wire.write(Output);
  Serial.println("Sent");
  // as expected by master
}

Without looking any further than the first delaymicroseconds() command I would say that that's where the trouble lies. The delay() functions are very handy for getting the beginner's first LED to blink and are a big problem after that. The problem is that the CPU is completely tied up during the delay and can't do anything else other than interrupts and you only have a limited supply of those. Your button press is missed.

You need to develop your own timers in the code and keep the main loop running constantly checking on each pass to see if the delay is complete.


Converting Random Binary Data to PWM Signal I am using a Arduino Due. I am doing a project on Visible Light Communication. I need to convert a binary data into a PWM Signal. Can anyone suggest me a method of generating that PWM Signal based on the binary data given?

Thank You.

So, if you simplu has to convert the binary data to PWM signal there are few things you need to cover:

If the binary data that you are receiving from the sensor is linear or non linear.
What is the size of binary byte. Ex: int(16 bits),char(8 bits),long (32 bits).
If it is linear, then if the data is multiplied by some number it will output a value betwen 0-255.
If the data is not linear than you just need to create an giant array with the pwm intensite value direct without any particular mathematical function. Ex: array[1024] = {0,1,1,2,3,4,5,5,6,6,10,9,...}; (1024 values because if you are using analog input. Then you can direct output the values from array:

analogWrite(3,array[x]); //x being your data

Here's the linear Example:

   //map(value, fromLow, fromHigh, toLow, toHigh);
    y = map(x, 0, 1023, 0, 255);

Doing this, y will receive a value from 0 to 255. You just need to first do a simple serial program that prints you through arduino serial window the binary data and see if the data increases or decreases conform your light project.

I don't know about your programming levels or if you are using a digital sensor or analog sensor, but if you are using a digital sensor, so you are probaly using SPI communication or i2c. Then you just need to read that binary data and take where the values bits are with bit wize manipulation.

y=(x & (0xfff<<3))>>3;

Tell me more about the source of data, how this data is and how is the behavior of the data so i can help you a lot more. Thanks


PROGMEM: do I have to copy data from flash to RAM for reading? I have got some difficulties understanding the memory management.

Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory. I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture. I want to make use from that to make my UI menu on a LCD possible.

But I'm bewildered by those instructions to just read and print data from program memory:

strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
    Serial.println( buffer );

Why on earth do I have to copy the damn content to RAM before accessing it? And if this is true, what happens to all the code then? Is it also loaded to RAM before execution? How is the code (32kiB) handled then with only 2kiB RAM? Where are those little goblins carrying floppy disks?

And even more interesting: What happens to literal constants like in this expression:

a = 5*(10+7)

are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

AVR is a modified Harvard architecture family, so code is stored in flash only, whereas data exists primarily in RAM when being manipulated.

With that in mind, let's address your questions.

  Why on earth do I have to copy the damn content to RAM before accessing it?

You don't need to per se, but by default code assumes that data is in RAM unless the code is modified to specifically look in flash for it (such as with strcpy_P()).

  And if this is true, what happens to all the code then? Is it also loaded to RAM before execution?

Nope. Harvard architecture. See the Wikipedia page for the full details.

  How is the code (32kiB) handled then with only 2kiB RAM?

The preamble generated by the compiler copies the data that should be modifiable/modified into SRAM before running the actual program.

  Where are those little goblins carrying floppy disks?

Dunno. But if you happen to see them then there's nothing I can do to help.

  ... are 5, 10 and 7 really copied to RAM before loading them into registers?

Nah. The compiler evaluates the expression at compile time. Whatever else happens depends on the lines of code around it.


IDE does not create prototypes I'm running Arduino IDE 1.6.10 on Mac OS X 10.12.1.
I read on the Arduino official sote that the IDE should create function prototypes for me, and it always did. But now I'm writing a 1500 lines program, with dozens of functions, and this tool wold be quite useful (although I obviously don't really need it)... and it doesn't work.
Is that a known issue?

There are some times when it can't make prototypes, and some when it just gets it plain wrong. It struggles if you do fancy things with any of your functions, such as adding attributes or using anything that's even slightly out of the ordinary.

Also sometimes it places the prototypes in completely the wrong place, especially if you are working with structs, etc.


Rewrite part of the example code from Adafruit FONA Recently, I bought the FONA 800 shield from Adafruit. I have got it running with the examples and it plays very nicely.

I want to use the part of the example code which handles a call in my own sketch. The example code waits for a number to call which should be entered in the serial. I want to do the exact same thing, just with the phone number supplied from a variable in Arduino.

I have two possibilities: To supply the whole number when the call should be performed and to build up let's say an array every time a number is entered.

The code for performing a call:

// call a phone!
    char number[30];
    flushSerial();
    Serial.print(F("Call #"));
    readline(number, 30);
    Serial.println();
    Serial.print(F("Calling ")); Serial.println(number);
    if (!fona.callPhone(number)) {
      Serial.println(F("Failed"));
    } else {
      Serial.println(F("Sent!"));
    }

The flushSerial function:

void flushSerial() {
  while (Serial.available())
  Serial.read();
}

And the readline function:

uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;

while (true) {
  if (buffidx > maxbuff) {
    //Serial.println(F("SPACE"));
    break;
  }

while (Serial.available()) {
  char c =  Serial.read();

  //Serial.print(c, HEX); Serial.print("#"); Serial.println(c);

  if (c == '\r') continue;
  if (c == 0xA) {
    if (buffidx == 0)   // the first 0x0A is ignored
      continue;

    timeout = 0;         // the second 0x0A is the end of the line
    timeoutvalid = true;
    break;
  }
  buff[buffidx] = c;
  buffidx++;
}

if (timeoutvalid && timeout == 0) {
  //Serial.println(F("TIMEOUT"));
  break;
}
  delay(1);
}
  buff[buffidx] = 0;  // null term
  return buffidx;
}

It is the readline function which should be edited. Right now it retrieves the number entered from serial.

I am kind of a newbie myself so I am not that familiar with data types and so on.

Thank you very much for any answers.

EDIT:
The function without readline:

if (!fona.callPhone("12345678")) {
        Serial.println(F("Failed calling"));
      } else {
        Serial.println(F("Calling ..."));
      }

I had to enter the numbers as a string. Also I found out that I had set the variables in a wrong way.

The library for the FONA Shield needs the number to call as a string. They are creating it by assigning the input from serial to a char.
The problem was that I tried to input numbers. Also, I found out that when I tried to work with variables instead of hard coded numbers I messed around in data types.

Final conclusion:
When calling the fona.callPhone function, you have to put in a string containing the numbers instead of actual numbers.


Pattern detection in sensor data I'm using a heart rate sensor along with an Arduino for a project of mine. I have to determine whether the heartbeat is following a particular pattern (eg: when when heartbeat regularizes a lot after a period of increased or largely varying, I need to trigger an alarm to show that it has regularized).

Can anyone give me suggestions on how I can go about doing this? Are there any libraries or software for doing basic statistical analysis on data like this?

This Arduino topic is an over-simplification and not very robust, but it presents in code the basic principle of threshold detection and the subtraction of adjacent pulse times (period).  BPM = 60.0 / period in seconds.

If you want something that would work under a larger range of conditions, you can add the three primary missing features used by medical instrumentation.

Automated zeroing, which can be accomplished with an analog filter and pull-up or with a digital high pass filter that attenuates frequencies below 0.3 Hz.  This can be done with a series capacitor leading to the analog input being sampled, with a pull up resistor to V+ and another resistor to ground to center the Voltage to an appropriate positive steady state value.
Attenuation of frequencies above those representing a pulse to avoid false triggers from high frequency noise, cross-talk, or transients, which can be accomplished with an analog filter or with a higher sample rate and a digital low pass filter that attenuates frequencies above 100 Hz 1.
Dynamic range compression, which detects the trend in pulse amplitude and continuously adapts the trigger threshold accordingly to avoid false indication of beats or the missing of weaker but legitimate beats.

To do the filtering digitally, you may want to read up on DSP (digital signal processing).  There are several great books on it, and you can search for simple algorithms for both low pass filters and high pass filters in GitHub or elsewhere in the open source community.

[1] Wikipedia's article on low pass filters


Analog vs Digital Accelerometers - pro's and con's? For my project i need to measure accelerations up to 16g. My options are either digital accelerometers such as the MPU6050 or MPU9250 or an analog accelerometer such as the ADXL326.

What are any major pro's and con's of each. number of wires would be almost equal. the digital accelerometer is less pins on the board but i could easily use analog to digital convertors to bypass that. sampling rate is lower at 550Hz for the analog vs 4000Hz for the MPU9250. However i believe 550Hz would be more than adequate. And the biggest difference for me. £2 for an MPU9250 and £12 for the ADXL326!

Does anyone have any general advice on the main differences when choosing between analog and digital? I am measuring suspension motion on a motorcycle and need 5 of these accelerometers.

The biggest difference is where the measurement (the conversion to digital) is done.  On the digital accelerometer, it is done in the accelerometer itself. On the analog one it is done at the MCU.

For simple arrangements where the accelerometer is near the MCU that makes no difference. However the analog one is more susceptible to noise. With longer wires / traces between the accelerometer and the MCU you can get less accurate results with an analog one since it picks up noise which you are then sampling and including in your results.

The digital one is more immune to that kind of interference - instead it is susceptible to digital noise - corruption of the data as it traverses long wires. But that is less of a problem since it takes far more induced voltage to corrupt a digital signal than an analog one.

One other main difference is that you are limited to the ADC that is in the digital accelerometer. If you want a different resolution you have to use a different accelerometer. With analog, since it has no inherent resolution, you sample at the resolution of your MCU's ADC.

Digital is also easier to interface in modern systems.  Many SoCs don't have analog inputs. So adding an analog accelerometer would mean adding an ADC chip as well - and you don't really want to do that in something like a mobile phone.

So in summary:

Digital is the most convenient, reliable and suitable for current basic uses
Analog is more of a niche product that is rarely used in consumer electronics


Long range wireless communication between two arduinos? I'm working on a project that will require two arduinos to be able to relay information to each other from long distances (up to about 10 miles or around 16 km).  WiFi won't be guaranteed to be available to either arduino as this is a wilderness application.

What are my options for long range wireless communication?  I haven't decided on an arduino model yet so if one particular model would be best for this application let me know.

Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.

If you aren't licensed:

In the USA, unlicensed (or lightly licensed) radio options include GMRS (General Mobile Radio Service), FRS (Family Radio Service) and CB (Citizens band radio).  GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for.  CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long.  I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.

If you are licensed:

2-meter band radio might be a good choice.  Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere.  Per wikipedia,

  The license privileges of amateur radio operators include the use of frequencies within this band  for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

If cell service is available:

Consider a GSM shield, eg the Arduino GSM Shield.

To access the cell network you would need to buy a SIM card for each GSM shield.

GPRS (General Packet Radio Service) on GSM provides data rates between 10 and 240 kbs.  Other GSM protocols may be faster or slower.  Data rates depend also on whether 3G service is available or only 2G.


What bootloader does the Arduino Micro come with? I've been looking to modify the Arduino Micro bootloader (specifically changing the VendorID and ProductID) of the Arduino. What bootloader comes pre-installed on the Arduino Micro? and how would I go about building and uploading a modified bootloader?

Try looking at https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/caterina/Descriptors.c

Inside that is:

/** Device descriptor structure. This descriptor, located in SRAM memory, describes the overall
 *  device characteristics, including the supported USB version, control endpoint size and the
 *  number of device configurations. The descriptor is read out by the USB host when the enumeration
 *  process begins.
 */
const USB_Descriptor_Device_t DeviceDescriptor =
{
    .Header                 = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},

    .USBSpecification       = VERSION_BCD(01.10),
    .Class                  = CDC_CSCP_CDCClass,
    .SubClass               = CDC_CSCP_NoSpecificSubclass,
    .Protocol               = CDC_CSCP_NoSpecificProtocol,

    .Endpoint0Size          = FIXED_CONTROL_ENDPOINT_SIZE,

    .VendorID               = DEVICE_VID,
    .ProductID              = DEVICE_PID,
    .ReleaseNumber          = VERSION_BCD(00.01),

    .ManufacturerStrIndex   = 0x02,
    .ProductStrIndex        = 0x01,
    .SerialNumStrIndex      = NO_DESCRIPTOR,

    .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
};

...

/** Product descriptor string. This is a Unicode string containing the product's details in human readable form,
 *  and is read out upon request by the host when the appropriate string ID is requested, listed in the Device
 *  Descriptor.
 */
const USB_Descriptor_String_t ProductString =
{
    .Header                 = {.Size = USB_STRING_LEN(16), .Type = DTYPE_String},

    #if DEVICE_PID == 0x0036
    .UnicodeString          = L"Arduino Leonardo"
    #elif DEVICE_PID == 0x0037
    .UnicodeString          = L"Arduino Micro   "
    #elif DEVICE_PID == 0x003C
    .UnicodeString          = L"Arduino Esplora "
    #else
    .UnicodeString          = L"USB IO board    "
    #endif
};

  and how would I go about building and uploading a modified bootloader?

You would run the Makefile which is in the same directory as the above file. Then send the resulting .hex file to your device.


avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47 So I'm following a beginners arduino book and I made a blinking program and now I've coded another program but when I try to upload it, avrdude(whatever that is) gives me the errors in the title and repeats them 10 times.
I have tried this so far:

Restarting my windows 8
Pressing the reset button on my arduino uno R3

My guess is that since it worked the first time, my blinking program must be clogging up the space in my arduino.How can I fix this problem. Or if my guess is right, how can I get the blinking program out of arduino and go home to my bots folder?

My IDE is arduino 1.6.7 and my port is CPU1. and lots of people mention tools>serial port but there isn't a "serial port" button on my IDE.

I had the same exact problem and fixed it, just by molding the two reset pins on the arduino together. Just check if they are properly connected as the error probably is caused by that.

If that doesn't work, check the LEDs on the board. When you are uploading a sketch both RX and TX should be lightning up.


Running a HC-SR501 PIR Sensor constantly using battery I am not sure if this is the correct forum since I tend to use the ESP8266 standalone and not together with the arduino nano.
However, here is what I am planning.

I have a HC-SR501 PIR sensor, which I want to use to constantly track movements of animals outdoor. I dont want to go into further details, but 10 impulses per minute are expected (max. is 30/min) except for the night maybe.
I am planning to count the impulses for one hour, than send the sum to a webserver using wifi and reset the counter.
For powering I want a battery/akku solution (non-negotiable). Since the input of the PIR sensor is 4.8-20V I will directly connect it to the battery (provided the Voltage is high enough like with a 9V battery) and the ESP8266, which is used as WIFI station will be connected via an AMS1117 generating 3.3V.

WIFI Router which is connected to the internet is available and several sensor systems will be used to check several areas. Basic knowledge of using AT cmds or programming with Arduino IDE is given.

Questions:

Can the ESP8266 module count impulses during one of the sleep modes?
Do you have a less current consumpting module in mind allowing wifi transmittance? (LoRa or the NRF Module are not an option atm, since the router has to be used)
What kind of battery/akku would you suggest? Having sufficient voltage and capacity (mAh) and still being easy to handle?

Optimum lifetime for the beginning would be 1 month for the first prototype. Afterwards a SolarModule + Akku solution will be implemented, but the first prototype has to be finished simple and fast yet satisfying :)

kind regards

This are multiple questions in one. But I will do my best to tackle them one by one.

  Can the ESP8266 module count impulses during one of the sleep modes?

The ESP8266 has different power modes. Short answer: As long as the CPU is running, yes.

Long answer: The ESP8266 has quite a few power modes. They are easily put:

No-sleep (as high as 170 mA while communicating)
Modem-sleep (15 mA Wifi is off, everything else is running)
Light-sleep (0.9 mA CPU is put to sleep and system clock stopped, can be waken up by a external interrupted)
Deep-sleep (20 uA Everything is off, basically it's powered down, but can wake itself on set intervals or reset it to wake it. everything in RAM is lost, except RTC RAM)

So if your sensor gives a pulse, you can use that as a interrupt and go to light-sleep. If you need to pull it, all you can do is modem-sleep.

ESP8266 power modes

  Do you have a less current consumpting module in mind allowing wifi transmittance? (LoRa or the NRF Module are not an option atm, since the router has to be used)

Modem-sleep is your friend. Only connect to the router if there is data to send.

You can set up an AVR and use it in ultra low power mode and only turn on the esp if there is data to send. But explaining how to set that up goes way too far out of this scope.

  What kind of battery/akku would you suggest? Having sufficient voltage and capacity (mAh) and still being easy to handle?

I can't choose a battery for you, there are just too many of them. But what I can do is tell you about how batteries work.

Take for example a 9 volt battery (not my first choice, you will see in a bit).

We take an energizer 522. It's a Alkaline battery and has 600 mAh. That means it can deliver 600 mA in one hour. But there is a catch. the more you draw from a Alkaline battery, the less capacity it will have.

It is 9 volts right? yes and no. you see. the voltage potential will drop (quite dramatically) over its lifetime.

A liniar voltage regulator (AMS1117) will take the needed mA of the output on the input and drop off the extra power as heat. So the battery will always have the same load (Yes, the esp8266 is a dynamic load, but lets keep it simple)

so lets say it's in modem-sleep (15mA). Lets divide 600 by 15, that is 40 hours of runtime. For simplicity I don't count the sensor itself.

9 volt block datasheet

The AMS1117 needs 1.5 volts more then its output voltage for ensuring a stable output. So that is 4.8 volts or higher. But no higher than 12 volts.

AMS1117 datasheet

Choose a battery that has enough mAh and isn't more then 12 volts and not lower than 5 when depleted. If using outside, check if its operating temp range is wide enough.

So basically try to lower your energy footprint as far as it can possibly go and then based on the new average power usage, find a battery that is big enough for the task.

Better yet, get a solar cell and a rechargeable battery. It has a full list of other problems, but this answer is a bit too long already and that topic is out of the current scope.


Arduino Uno outputs 8V when pin is set to HIGH I am doing the following in setup:

 pinMode(13,OUTPUT);
 digitalWrite(13, HIGH);

When I check with the multimeter, I get an output voltage of 8V rather than 5V. What may be the problem and how do I troubleshoot it?.

You have a badly calibrated multimeter.

Try it on something where you know what the voltage should be, such as a 9V battery and see what it reads.


Running Pthreads (POSIX) on an Arduino So I have a project where I need to run pthreads (coded in C) on an Arduino Uno. I've written and compiled the code and the output is what we need when I use a C compiler. But I'm having trouble running it on the board. I've installed the Pthreads library in the libraries folder of the Arduino, but it still gives me erroneous errors.

I'm jumbling back and forth without finding a solution, can anyone give me any tips?  It's become so annoying that I'm thinking of buying a Pi.

Any help is much appreciated.

Edit: let me rephrase: the professor wants us to implement pthreads on an Arduino or Pi. I didn't decide pthreads is the solution, it is the requirement.

I need to run pthreads ...

You probably don't need to run pthreads. This sounds like an X-Y problem.

What you are probably saying is "I need to do multiple things at once" (such as flashing LEDs whilst taking ADC readings, or play sounds at the same time as moving a vehicle forwards).

You could get better answers if you described the project (X) and not your proposed solution (Y) which you think is pthreads.

I have a web page about How to do multiple things at once ... like cook bacon and eggs which goes into this sort of thing in some detail.

Some example code from that page which blinks different LEDs at different rates is:

// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

  It's become so annoying that I'm thinking of buying a Pi.

Sure you can do that. You can buy a Mac or a Windows PC. You can buy 5 Arduinos. But if you want to learn how to do multiple things on an Arduino you can learn how to manage a "state machine" and do it all on $5 of hardware.

As an example of what can be done see this post about a retro arcade game called Toorum's Quest written by Petri Häkkinen and run on an Atmega328P (same chip as in the Arduino Uno).

Hardware and screenshots:

In his code (which I compiled using the Arduino IDE to test it) he has:

Multiple sprites on a TV screen with a resolution of 104x80 with 256 colors.
Sprites are multiplexed so you can have as many as you want on the screen.
He moves them around according to game logic
He plays music and sound effects at the same time
He reads from a game controller


Reaction timer using millis I've written this code for a reaction timer game. The reaction time is to be displayed in milliseconds to the serial monitor as accurately as possible. The reaction time is not being displayed correctly. I'm including my timer setup routine and where I increment milliseconds.

TCCR1A=0;
TCCR1B=0;
timer1_counter=65536;
TCNT1=timer1_counter;
TCCR1B |=(1<<CS12);

TIMSK1 |=(1<<TOIE1);
interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1=timer1_counter;
  int_flag=1;
 }

  digitalWrite(LED,LOW);
  randomSeed(analogRead(A1));
  NumSecs=random(1000,7000);
  delay(NumSecs);
  digitalWrite(LED,HIGH);
  while(digitalRead(PUSHBUTTON) == HIGH)
  {
  }
  if (int_flag==1){
  millisecs++;
  int_flag=0;
  }

Your ISR is not counting the elapsed milliseconds. Instead, it just sets
a flag and lets the main program do the counting when it sees the flag.
Here:

while(digitalRead(PUSHBUTTON) == HIGH)
{
}

you are waiting for the user to press the button. The program does
nothing else during the wait. It doesn't event count the time. Here:

if (int_flag==1){
    millisecs++;
    int_flag=0;
}

you increment once the millisecond count after the wait.

The obvious solution is to count the milliseconds while waiting for the
button press:

millisecs = 0;  // don't forget to reset the stopwatch!
while (digitalRead(PUSHBUTTON) == HIGH) {  // button not pressed
    if (int_flag) {
        millisecs++;
        int_flag = false;
    }
}

(side note: int_flag should be a bool).

There are still many issues with this program. First of all, it should
check that the user did not press the button before the LED came up.

Then, the interrupt period is not one millisecond, because the interrupt
takes some time to be processed by the CPU and to go through its
prologue. By the time you do TCNT1=timer1_counter; you are at least
several tens of cycles late. You should instead configure the timer to
keep the correct period by itself, typically using CTC mode.

Also, there is no point in letting the main program count the
milliseconds when the ISR could do it. E.g.

ISR(TIMER1_OVF_vect)
{
    millisecs++;
}

// Avoid a race condition when reading millisecs.
static inline unsigned int getMillisecs()
{
    noInterrupts();
    int millisecsCopy = millisecs;
    interrupts();
    return millisecsCopy;
}

Note that the time keeping variables should be unsigned in order to
avoid undefined behaviour on overflows.

Finally, it may be a good learning experience for working with
interrupts, but in the end just using millis() or micros() would be
the easiest way to achieve what you want.


Using an Arduino to switching a grounded load powered by a 12 Volt supply I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.

This is what I have tried so far.

The load must be between my mosfet and my car battery GND.

In your existing arrangement.
Swap to P Channel FET
Swap drain and source leads (right hand two).
This will work for up to 5V feed to LEDs.
To get 12v operation you will need to add a driver between the FET gate and the Arduino.
see circuit diagram below.

To operate with FET on the HIGH (V+) side when V+ is greater than the rduino's supply voltage, the FET must either

Be P Channel with FET source to +12V and FET drain to load+ or

An N Channel with gate drive above V+.
The gate drive to the FET must go to about +12V to turn it off.
The Arduino will only drive it to +5V.

As you are unlikely to want to provide an extra high side drive the P channel option is preferred. This could be eg:

A "jellybean" bipolar transistor or small FET worth a few cents) and a few resistors, or a small N Channel MOSFET and one resistor

or

An opto isolator.

Transistor driver:
Bipolar transistor NPN (BC337 / BC817 or similar)(ANYTHING NPN will work).
R1 = 10k resistor Arduino out to base.
R2 = 10k FET gate to +12.
If an N Channel MOSFET is used for Q1 then R1 is not needed.
This could be a  5LN01SP IF you can get them - no stock Digikey.These have a very low Vgsth (turn on voltage)
Otherwise you can use a 2n2222, VN2222, BS108 or similar logic-gate N channel MOSFET.
eg VN2222. Many variants of these are widely available and low cost.

simulate this circuit – Schematic created using CircuitLab


Problem regarding getting split data of JSON - Another issue In my recent project, I'm working with Arduino and JSON. I've successfully split the JSON data I want. My JSON data length is fixed. So, I used the length() function and I'm getting the length of my data.

Now, my input JSON data is:

{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

Using the length() function, its length is 39.

But when I use an if statement like if(len == 39) and put my logic inside this, I'm not getting the split data. Below is my whole code.

Here, I'm displaying my data on LCD.

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";
String response = "";
bool begin = false;
int counter = 0;
int len = 0;
char in;
float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available() || !begin) {
    in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      counter++;
      response += (in);
      len = response.length();
      if(len == 39) {
        if(counter >= 9 && counter <= 12) {
          data_TPS_Json += (in);
        }
        if(counter >= 22 && counter <= 25) {
          data_MAP_Json += (in);
        }
        if(counter >= 36 && counter <= 37) {
          data_LOAD_TM_Json += (in);
        }
      }
    }

    if(in == '}') {
      break;
    }
    delay(1);
  }
  TPS_Json = data_TPS_Json.toFloat();
  MAP_Json = data_MAP_Json.toFloat();
  LOAD_TM_Json = data_LOAD_TM_Json.toFloat();
  lcd.setCursor(0, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(8, 0);
  lcd.print(MAP_Json);
  lcd.setCursor(0, 1);
  lcd.print(LOAD_TM_Json);
}

I don't think your loop handles the situation where the data comes in too slowly. Looking at your while condition:

while(Serial.available() || !begin)

Once you receive the start char, this becomes:

while(Serial.available())

Now, if there is a delay in the serial buffer, the loop exits before you have the entire message.

You should change the loop so it only ends when you have all 39 chars.

void loop() {
    while (39 != response.length()) {  // Keep going until full msg {
        // Check for data in serial buffer
        if (Serial.available()) {
            in = Serial.read();
            .....
        }
        // No data?
        else {
            delay(10);
        }
    }

    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    .....
}


The arduino can't seem to output correctly i am a beginner at python and I am average at Arduino and I had the idea of using both of them together for a project. I have been trying to make a Arduino + Python car which I can control with my computer. I have used Pyfirmata and the code seems perfect to me. When I run the code from CMD i have a weird bug/issue.
I have uploaded Standard Firmata to the arduino UNO. I get no errors while uploading or running its just that its output is messed up.

Here's the Python Code:

from pyfirmata import Arduino, util
import time

board = Arduino("COM3")

MotorLeft = board.get_pin('d:10:o') # Assigning output to PIN
MotorRight = board.get_pin('d:11:o') # Assisging output to PIN

play = True

while play:
    control = input(
        print("Enter W, A or D to move forwards, left or right. Enter 0 to exit"))

    if control != 0:
        if control == "W" or "w":
            MotorRight.write(1)
            MotorLeft.write(1)
            time.sleep(1)
            MotorRight.write(0)
            MotorLeft.write(0)

        if control == "A" or "a":
            MotorLeft.write(1)
            time.sleep(1)
            MotorLeft.write(0)

        if control == "D" or "d":
            MotorRight.write(1)
            time.sleep(1)
            MotorRight.write(0)

        else:
            print("Invalid Commmand")

    else:
        print("Exited Succesfully")

    play = True

Currently I have not built the car, I am using a pair of LEDs to do what the motors function and to test out the code.

Heres the CMD response:

Here is the link for the output video. I entered "W" which should ideally turn on both of the LEDs however, both of them turn on then off and then turn on off one by one.

https://youtu.be/DjUkkpzF0so

I cannot check it, but I guess you have to change the or commands like:

if control == "W" or "w":

Change to

if ((control == 'W') or (control == 'w'))

And similar for the other if statements.

Also, you can do not need to check for control == 0, since it will not be a character otherwise.

Besides that, the elif (else if) construct is normally used in Python, so instead of:

if control != 0:
    if control == "W" or "w":
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    if control == "A" or "a":
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    if control == "D" or "d":
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

You can write:

if ((control == 'W') or (control == 'w')):
    MotorRight.write(1)
    MotorLeft.write(1)
    time.sleep(1)
    MotorRight.write(0)
    MotorLeft.write(0)

elif ((control == 'A') or (control == 'a')):
    MotorLeft.write(1)
    time.sleep(1)
    MotorLeft.write(0)

elif ((control == 'D') or (control == 'd')):
    MotorRight.write(1)
    time.sleep(1)
    MotorRight.write(0)

else:
    print("Invalid Commmand")

Also, you can combine the or in a list (but I cannot check it, no python compiler at hand), e.g.

if (control in ['W', 'w']):


Why can only some digital ports output PWM and the others not? If it matters, I'm talking about the arduino uno v3.

Check out the ATMega328p datasheet: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.

It's a limitation, but so is everything else.

If you do not like it, you can always choose a different microcontroller, either AVR or something else.
Certain models might  be designed to have more units of a specific type than you would find on generic microcontrollers.


Unexpected results when creating 32-bit int from byte array I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing 0x00, 0x04, 0x04F, 0x45 results in 4F45 (expected result would be 44F45). I must be overlooking something fundamental here.... can anyone see where I went wrong?

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

void loop()
{
    uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(250);
}

uint32_t byteArrayToInt32(uint8_t* bytes)
{
    uint32_t i = 0;
    i |= bytes[0] << 24;
    i |= bytes[1] << 16;
    i |= bytes[2] << 8;
    i |= bytes[3];
    return i;
}

The problem is that you are trying to shift uint8_t more than 8 bits and then OR it with int32_t.

You have to cast the uint8_t to int32_t before doing the shift.

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

void loop()
{
    uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(1000);
}

int32_t byteArrayToInt32(uint8_t* bytes)
{
    int32_t i = 0;
    i |= (int32_t) bytes[0] << 24;
    i |= (int32_t) bytes[1] << 16;
    i |= (int32_t) bytes[2] <<  8;
    i |= (int32_t) bytes[3];
    return i;
}


Weird RTC DS3231 Output only when saving the dates to variables I am sorry to ask this question as I think it has more to do with my mediocre C++ programming skill than with the arduino.
I do have a project where I want to use an RTC DS2131. I started out by using all the separate examples of the modules I need and put them together. But the RTC give me a headache :-(
The example ran fine where it just output the date to the serial port. Somthing along this:
Serial.print(RTC.getDay());
Serial.print("-");
Serial.print(RTC.getMonth());

Now I want these values in different variables because I want to save them on an SD card as well.
Thus I came up with this simple test program:
#include <Wire.h>
#include <RTC.h>

static DS3231 RTC;

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

void loop()
{
int yearNow;
int monthNow, dateNow, hourNow, minuteNow, secondNow, weekNow;

if (RTC.isRunning())
  {
    yearNow=RTC.getYear();
    monthNow =RTC.getMonth();
    dateNow=RTC.getDay();
    weekNow=RTC.getWeek();
    hourNow=RTC.getHours();
    minuteNow=RTC.getMinutes();
    secondNow=RTC.getSeconds();

    Serial.print("Weekday: ");
    Serial.print(weekNow);
    Serial.print('  Time:');
    // Finally the hour, minute, and second
    Serial.print(hourNow);
    Serial.print('-');
    Serial.print(minuteNow);
    Serial.print('-');
    Serial.print(secondNow);
    Serial.print(" ##  ");
    Serial.print("Date: ");
    Serial.print(yearNow);
    Serial.print('/');
    Serial.print(monthNow);
    Serial.print('/');
    Serial.println(dateNow);

  }
}

Now I would expect this output:
Weekday: 4  Time:16-10-36 ##  Date: 2020/7/28
But this is what I get:
Weekday: 42591416-10-36 ##  Date: 2020/7/28
As a sidenote the variables in this sketch are declared as "int". After having looked into the header files of the library I tried uint8_t resp. uint16_t for the year.
But nothing changed.
I am sorry but I have no clue as what beginner mistake I am achieving this time?? :-(
Thanks for your help.

You used single quotes instead of double quotes. Single quotes are for single characters. Double quotes are for strings (or character arrays).
Serial.print('  Time:');

should be
Serial.print("  Time:");


Set an arduino software clock Me and my friend are having some trouble setting up an software clock to our arduino uno.

It's for a school project and we´ve never done any programming before. thanks!

There is a Time library which you can import.

Here are things that I found on the Arduino website.

hour();            // The hour now  (0-23)
minute();          // The minute now (0-59)
second();          // The second now (0-59)
day();             // The day now (1-31)
weekday();         // Day of the week, Sunday is day 1
month();           // The month now (1-12)
year();            // The full four digit year: (2009,
                //  2010 etc)
setTime(t);              // Set the system time to the
                      //  give time t
setTime(hr,min,sec,day,month,yr); // Another way to set
                               //  the time
adjustTime(adjustment); // Adjust system time by adding
                     //  the adjustment value

timeStatus();   // Indicates if time has been set and
             //  recently synchronized
             //  returns one of the following
             //  enumerations:
* timeNotSet    // The time has never been set,
             //  the clock started at Jan 1 1970
* timeNeedsSync // The time had been set but a sync
             //  attempt did not succeed
* timeSet       // The time is set and is synced
             //  Time and Date values are not valid if
             //  the status is timeNotSet. Otherwise
             //  values can be used but the returned
             //  time may have drifted if the status is
             //  timeNeedsSync.

setSyncProvider(getTimeFunction);// Set the external time
                              //  provider
setSyncInterval(interval);    // Set the number of
                           //  seconds between re-sync

And obviously,

#include<Time.h>

Tell me in the comments if you need more help.


What are the advantages of "Arduino compatible" boards There are countless boards called "Arduino compatible board". Some of them have specialized hardware features such as WiFi, SD card readers etc., but most of them seem like plain Arduino copies to me.

Sure, they are a bit cheaper, but for me the price difference doesn't make me favor the money I'd safe over the potential issues I have yet to discover.

Question: What are the benefits (or disadvantages) of Arduino compatible boards (the ones without the "extras") in general? Do you know an Arduino compatible board that you would recommend for some extraordinary features?

While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - see here - Logo and here Trademark
and here What makes an Arduino board an Arduino? and FAQ

As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim.

As karan notes, some Chinese sourced Arduino compatibles "have issues".
however, I have had no problems at all with Arduino compatibles manufactured and supplied by this Chinese supplier. As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices  - usually in batches of 10. As you will see -  Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!
Uno compatible here is $3.80 in 10s.  The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers.

NB: (1) I have NO commercial connection with this company except as a very happy customer.
(2) I'd expect you to have no problems with these or other products from them but I of course have  no responsibility for what they sell.


Program stops working after a minute I have made this small program to lighten up in sequence 8 LEDs, it starts fine, but it stops working after a minute or so and the first 2 LEDs stay permanently ON, its like the chip stoped, here is the code :

// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

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

  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<9; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  right();
  left();

}

void left (void) {
  for (byte i = 0; i<9; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (byte i = 8; i>0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

I am using a very old arduino duemilanove.

Your loop conditions aren't quite right, which could be resulting in undefined behaviour. I highly doubt it would cause it to stop working spontaneously, but it's possible in theory.

In each loop that counts upwards, you basically need to stop before the counter reaches 8. For example:

for (byte i = 0; i<8; i++) ...

Note that it's i<8 instead of i<9.

The reason is that the array is only 8 elements long, so the indices run from 0 to 7 (inclusive). Currently, your loops are going all the way up to and including 8, which means it's trying to read past the end of your array.

You'll need to fix that in setup() and left().

The loop that goes downwards in right() is a little more difficult. At the moment, it runs through indices 8 to 1, meaning it has the same problem of reading past the array. However, it also never actually reaches index 0.

It's harder to fix because byte is an unsigned type, so you can't use i>=0 as your condition (as it will never terminate). Personally, I would rewrite the loop to count upwards, but then reverse the index order inside the loop, so that 0 becomes 7, and so on. For example:

for (byte i = 0; i<8; i++) {
    digitalWrite(led[7-i], HIGH);
    delay(50);
    digitalWrite(led[7-i], LOW);
}

Like I said, I doubt this will actually solve your problem. It's worth trying though.


Arduino subtracting chars from strings Hello I have an Arduino programme that has a string with the words hello in it.
I can add characters and other strings to the end of that one using:

   String test = "hello";
   test+=" jack";

it would then say "hello jack"
The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

You may use remove() method to remove last character.

String s = "1234567890";
while(s.length() > 0) {
    int lastIndex = s.length() - 1;
    s.remove(lastIndex);
    Serial.println(s);
}


If I use a biasing circuit for a signal going into an analog input pin, will it affect the ADC operation? If I have a single 100Hz AC signal biased by two 1 M-ohm resistors (as per schematic below), and then output to an Arduino UNO analog input pin, with the UNO sampling at around 1 kHz using delays, would there be any issues with the ADC result?

(Source of schematic: http://tinyurl.com/ycprqsdx)

From the Atmega328P's spec sheet (the UNO's microprocessor) it recommends an output impedance of 10 k-ohms or less, as shown below.
If I used the pair of 1 M-ohm resistors as a biasing circuit and then deliberately slow down the sampling with delays (i.e.: in loop, do analogRead, then delay, then do analogRead, etc.), would it still be okay?

It will give bad results. You're not slowing down the sampling, you're taking samples at a longer interval - a very different thing.

The Arduino uses a Successive Approximation ADC. That uses a clock to control the output of a DAC and compare that voltage with the incoming voltage stored in the S&H capacitor.

In order for the S&H capacitor to get charged to the correct level it has to be connected to the GPIO pin long enough. Since there is only one ADC and 6 analog input pins, it goes through a MUX first.

The delay that needs increasing is the delay between the pin being connected to the capacitor and the capacitor being connected to the ADC.  This is called the acquisition time.

The analogRead() function does these basic operations in sequence:

Connect the SHC to the GPIO pin through the mux.
Wait
Disconnect the SHC from the GPIO and connect it to the ADC
Clock each bit from the comparator to the result registers.

Putting a delay between each analogRead would just delay the connecting of the SHC to the GPIO pin, not increase the time it's connected to the GPIO pin.

You would have to manipulate the ADC registers to do your own sample timing.  Or, just reduce your output impedance.


Why is there a need of use delay() after using Serial.flush() in the program This code is a part of a long code for understanding serial communication and the functions related to it.
char buffer[18];
int red, green, blue;
int RedPin = 11;
int GreenPin = 10;
int BluePin = 9;

void setup()
{
Serial.begin(9600);
Serial.flush();
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}

void loop()
{
if (Serial.available() > 0) {
int index=0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if (numChar>15) {
numChar=15;
}
while (numChar--) {
buffer[index++] = Serial.read();
}
splitString(buffer);
}
}

In void setup(), Serial.flush() is used. On internet, I have read that it flush out any character present in a serial line. After calling it we can be sure that all the data has been sent before moving on to the next line of the program.
In void loop(), in the first if condition, delay(100) ensures to fill the buffer. Basically, buffer is the place in memory where the received serial data is stored prior to processing.
The question is that is there any need of using delay(100), if we call the Serial.flush() initially because it ensures that all the serial data has been transmitted (as in serial transmission one bit is transmitted at a time)? Does it takes further time to store the transmitted data in the memory (buffer) and does this is the reason to use delay(100)? Please clarify why delay(100) is used after calling Serial.flush(), I am confused.

The Serial.flush() is doing nothing. It delays until all bytes have been sent out of the UART. Since nothing has been sent it's not got anything to wait for.
The delay after the available call is very bad practice. It's a really really bad way of dealing with serial reading.
You should read this for a better understanding of serial communication.


Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.” I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

My Code:

//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }

Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).

You can confirm your connections and baud rate with:
EspSerial.println("AT");
You should receive `OK' in reply.


Read int from Serial with the following sketch I should be able to read and store what is entered in the Serial monitor

void setup() {
  Serial.begin(115200);
  while(!Serial);
}

void loop() {

  Serial.println("Enter Zone Number: ");
  while(!Serial.available()){
  }
   int zone = Serial.parseInt();
   Serial.println(zone);

}

if I enter "1" I would except this:

Enter Zone Number:
1

but unfortunately I have this:

Enter Zone Number:
1
Enter Zone Number:
0

What am I missing?

.parseInt() reads incoming text up until either it times out or until it reads something that isn't a number.

You are sending a number, and most likely a line-ending. If that line-ending is a simple \n then that will trigger the "end of number" and will be discarded and the number returned.  However, if you are sending \r\n (i.e., CRLF) then you effectively have two line endings there:

1\r\n

Parsed as:

1\r => return 1
\n => return 0

Relying on the (poorly written) Arduino stream parsing routines is not good. Not only are they blocking, but often they just don't work right.

Instead you should be reading the serial properly, taking account of line endings, and then converting the string you have read into a number using the likes of atoi().

Tutorial on reading serial:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


Changing ESP-12E NodeMCU to ESP-01S - how to trigger sketch? I had my sketch up and running with a NodeMCU and a Leonardo Pro Micro and decided I wanted to minimize the footprint of the project and use the smaller ESP-01S board instead.

The ESP-01S is programmed to send a push notification to Pushover and my old code works - the only problem is that I don't know how to trigger it from the Pro Micro.

With the NodeMCU I just setup it up to listen on Pin 2 and I triggered a high/low from my Pro Micro and it sent the push notification - at the moment as soon as I power the ESP-01S up it just sends the push notification over and over and doesn't see the connection from the Pro Micro to stop it doing this.

Here is my current code on the ESP-01S

#include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "Redacted";
const char* password = "Redacted";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "Redacted";
char userkey [] = "Redacted";
int length;
WiFiClient client;
void setup() {
  pinMode(0, OUTPUT);
  digitalWrite(0, LOW);
  pinMode(2, INPUT);
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
if(digitalRead(5) == 1) pushover("Deployment Completed");
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

and my Leonardo Pro Micro code is as follows

#include <HID-Project.h>
#include <HID-Settings.h>
int buttonPin;
int buttonPin2;
char chr;   // for incoming serial data, type char is signed 8-bit, -128 to 127, ASCII is char codes. Save 1 byte over type int.

void setup() {
  pinMode(5, OUTPUT);
  pinMode(7, OUTPUT);
  BootKeyboard.begin();
  Keyboard.begin();
  Mouse.begin();
  Serial.begin(115200);
  buttonPin = 4; //White Button
  buttonPin2 = 6; //Black Button
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  delay(5000);
  digitalWrite(5, HIGH);
  delay(100);   //short wait time
  digitalWrite(5, LOW);
  }

Obviously I want the digital pin 5 of the Pro Micro to trigger the ESP-01 to send a push notification when it's trigger.

Just for the record I'm using a 3.3v Pro Micro btw so there's no issue with the voltage here, before I was using a Logic Converter with a 5v board.

I have the ESP-O1S setup with the 3V3 and EN are connected to the 3v VCC on the Pro Micro, the GND to GND and I tried IO0 and IO2 to Digital Pin 5 on the Pro Micro.

Could someone point me in the right direction?

Use io 0 as the esp-01S pin wired to Micro, but change the logic for pull-up, because esp-01S has a pull-up resistor on io 0 of the esp8266. Use LOW to trigger the action and HIGH as normal state.

On Arduino Micro side set the output pin HIGH before you set it as OUTPUT. This will avoid the LOW state. While the Micro pin is in INPUT state after power-up, the pull-up resistor on esp-01S will pull io 0 HIGH.


Hibernate Arduino for 12hrs with rtc1302 module ok, Good morning, guys, with a data acquisition project, in this, I get data every 12 hours, even if it's only 12 hours, the arduino gets connected directly, and it's being powered by a 9v battery, for longer life of this battery, to try to hibernate the arduino with real time, using the real time clock 1302, you could help me to make a code for this clock, for I have never used it before! thank you

You need 3 pieces of code and one replacement:

1) Ditch ds1302 and get yourself an RTC with an interrupt pin (like DS3231 which Jot suggests). It will make your life easier.

2) Setup your RTC to fire an interrupt every 12 hours.

3) Since you have successfully implemented a sleep mode, try to wake your Arduino up using a hardware interrupt. See Nick Gammon's guide for interrupts, and read carefully about waking your micro with an external interrupt. You can prototype it using a pushbutton, which will either connect your interrupt pin to GND or Vcc. Use an appropriate resistor as well. This guide has good information for starters.

To sum up: you'll have your Arduino sleep at all times and your RTC set to fire a hardware interrupt. When fired, the interrupt wakes Arduino, and the interrupt code will handle your measurements.


How to get full response json SIM900 + Arduino? void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

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

  mySerial.println("AT+HTTPINIT");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CID\", 1");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"URL\", \"www.example.test\"");
  toSerial(500);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(500);

  mySerial.println("AT+HTTPACTION=0");
  toSerial(4000);

  mySerial.println("AT+HTTPREAD");
  delay(3000);

  while(mySerial.available())
  {
    Serial.write(mySerial.read());
  }

  Serial.println("");
  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:

AT+HTTPREAD

+HTTPREAD:39
{"pinRed":0,"pinGreen":1,"pinYello

I expect messages:

{"pinRed":0,"pinGreen":1,"pinYellow":0}

Okay, I've found a solution. To start with, you need to download the server response length and loop according to the response length.


Smart Chess-board (possibly using RFIDs?) I'd like to make a chess-board with the ability to detect the position of each piece.

The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.

However, apart from the obvious cost (64 readers!) I'm concerned that:

Maybe RFID readers are too large for the squares of an ordinary chessboard
RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.

Is this just stupid? And is there a better technology to use for this kind of application?

If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.


how does serialEvent work? I have come across several examples about serialEvent() function, which look like this:

void serialEvent(){
  if(Serial.available()){
    \\do something
  }
}

The serialEvent() function is called when data is available, so which is the necessity of the if (or while) structure since that would be always true?

(In several cases I have excluded the if structure, and the code works fine)

As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.

The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:

while (true)
{
    loop();
    if(data_available)
        serialEvent();
}

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.

But if you want to read multiple bytes at the same time, you would have to wait until the loop() is executed again to read the next byte.

You will solve that problem if you write your  serialEvent()  like this:

void serialEvent()
{
    while (Serial.available())
    {
        // do something
    }
}

That way, you will read all the information available at once and then return to the loop.


Does the SPI library use the internal USART? I was reading the detailed datasheet for the ATmega328p and noticed that it has an option to use the built-in USART to drive the SPI interface. I just wondered if the arduino SPI library makes use of this? I suspect unlikely because I suppose that the USART is used by the USB on a arduino.

I had a look at the source code for the SPI library. As suspected, it does not use the internal ATMega328 USART. This is useful to know because it means that the USART remains potentially available for other uses in any sketch that is using SPI. I suppose that it also makes the SPI library more portable because perhaps not all arduinen microcontrollers have a built-in USART


Integer array definitions: Length I'm defining a variable as integer and want to use thati

int specLength = 17;
int spec[specLength-1];

When I do this, I get the following error message:

 TestProgram:34: error: array bound is not an integer constant before  ']' token
 int spec[specLength-1];

But when I set it up as

int specLength = 17;
int spec[16];

it all works fine.

What is the magic here?

Many thanks

You have to use a constant expression, one that produce always the same value.

const int specLength = 17;
int spec[specLength - 1];

Otherwise, the compiler won't know how much space reserve for the array.

The problem with C/C++ is that the compiler doesn't really know if a variable is modified somewhere or not (thru pointers, for example). You have to tell the compiler that something is static, not changing.

You can also use a #define for the same porpuse:

#define SPEC_LENGTH 17
int spec[SPEC_LENGTH]

Why both? const int val=17 means that val has a type (int). Using #define is just a text search-and-replace before compiling. So, SPEC_LENGTH has no type at all. If needed, you have to use a cast, like (int) SPEC_LENGTH.


Arduino Nano + RFID RC522 + Ethernet shield W5100 I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.

For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.

Does anybody have some ideas, what I'm doing wrong right here?

I had almost exactly this situation with one of my projects.

The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).


How to restart ESP32 on any exception? While developing a lot of projects (In Arduino IDE) for ESP32 one common issue I am facing is termination of program execution on unhandled exceptions. There are various exception I get.  For example: stack canary watchpoint triggered (looptask), invoke_abort, etc. I have no idea how to handle them, hence I prefer to restart the ESP manually.
Is there any way where I can restart the ESP32 automatically on all unhandled or unfortunate exceptions other than handling the exceptions ?

I don't know if I understand your question well, but if what you want to do is reset MCU programmatically, watchdog is good solution.
The orther way is connect IO port and reset port by using wire, and send a signal(send LOW or HIGH voltage to reset port) to reset port.
Or use asm code.


Possible to connect 3 MPU9250 to Node MCU without multiplixer? Is the idea of connecting AD0 pins of MPU9250 is still valid like the 2nd answer of this question? - How to change i2c address for mpu9250?

I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didnt work. What could be the solution?

Code to control 1 sensor:- It worked when I set AD0 to high and changed address to 0x69

#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU(Wire,0x68);
int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
  // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelY_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelZ_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroX_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroY_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroZ_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagX_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagY_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagZ_uT(),6);
  Serial.print("\t");
  Serial.println(IMU.getTemperature_C(),6);
  delay(100);
}

Code to control 2 sensors:-

#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU1(Wire,0x68);
MPU9250 IMU2(Wire,0x68);

int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);

}

void IMU_1() {
  digitalWrite(D7, LOW);
  digitalWrite(D8, HIGH);
  IMU1.begin();
  IMU1.readSensor();
  Serial.print("IMU 1 is active: "); Serial.print(IMU1.getAccelX_mss(),6);
  digitalWrite(D8, LOW);
}

void IMU_2() {
  digitalWrite(D7, HIGH);
  digitalWrite(D8, LOW);
  IMU2.begin();
  IMU2.readSensor();
  Serial.println("IMU 2 is active: "); Serial.print(IMU2.getAccelX_mss(),6);
  digitalWrite(D7, LOW);
}

void loop() {

IMU_1();
IMU_2();

  delay(500);

}

Result:- It Shows reading on one sensor but the 2nd sensor shows '0' every time.

What's the best way to use 3 I2C sensors when there is only 1 I2C bus?

It sounds like the MPU9250 has a pin, AD0, that lets you switch the device between 2 fixed I2C addresses.

That gives you an easy solution if you need to use 2 of them.

For more, the post you linked suggests keeping them all at the same AD0 state except the one you want to talk to. You’d switch that one’s AD0 pin to the other state, which would cause it’s I2C address, and then talk to it at that address, which would be unique on the I2C bus.

That approach should work, but it’s a bit of a hack.

You say "I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didn't work." What didn't work? What happens? What output do you get What pins on your mcu are connected to AD0 on your 3 different MPU9250 modules? Where is the code that manipulates the digital pins to select one and only one of your MPU9250 modules for reading?

You need to throughly explain your setup, including the different pin assignments and how they are supposed to work. Don't leave us to read your code and try and figure out your intentions.

Looking at your code it looks like you're using D7 and D8 on your mcu to try to control which MPU9250 is active. However i don't see any code the sets D7 and D8 as outputs.

Why don’t you want to use an I2C address mapping chip? They are readily available, and the ones I’ve seen would let you address up to 8 I2C devices that are hard-wired with the same address.