Is it possible to measure analog output? I'm using PWM to control LED brightness using MOSFET, using analogWrite(pwmPin,val), while val is a 12 bit bit value.

pwmPin is defined as- pinMode(pwmPin, OUTPUT);

Since val changes in time due to external lightning, I wish to measure PWM value, for later use in code. Using analogRead(pwnPin) yielded a changing value ranges 7-14.

Is there a way to measure PWM value defined as an output ?

EDIT 1:

Saving val's value won't save the problem I'm looking for, since code reaches a deepSeleep phase, which val can be stored, but I want an actual incidication of its value, and if it actually on.

First: Why would you need to measure the PWM value. You already know it; it's saved in the val variable. Why not just use this variable for later use in code?

Second: Doing the analogRead on the same pin as the PWM output is not going to work. Internally there are 2 different hardware peripherals, that are responsible for these functions: The ADC is responsible for measuring analog voltages, while one of the Timers is responsible for generating the PWM output. Only one of them can connect to the pin at any time. Thus you are not measuring the PWM signal, when you do an analogRead(pwmPin). This function set's the pin for measuring analog voltages (means it connect it to the ADC and configures the ADC) and thus disconnects the Timer hardware.

Third: Doing an analogRead() directly on a PWM signal is not going to work. PWM is still a digital signal, so measuring it's analog voltage would yield only values around 0 and 1023. This signal is transformed to a real analog voltage through a low pass filter, either electrically or mechanically (here I mean because mechanical elements often cannot follow the relatively fast PWM signal - like a motor or a speaker - which results effectively in a low pass filter).

How to measure a PWM signal then? First you definitely need to use a different pin, than the PWM output pin. Then you have 2 ways of measuring the current PWM value:

You can connect the PWM output to a low pass filter (combination of resistor and capacitor; you can google this and get very detailed descriptions), and the output of the low pass filter to an analog input pin of the Arduino. Then you can do analogRead()s to measure the current value.
You can measure the PWM signal directly, meaning measuring the actual pulse width of the signal. There are multiple ways of doing this, one being the pulseIn() function, which wait's for a pulse to complete and returns the length of the pulse.


Arduino status of bit Is the a way to check the status of a bit in an arduino Uno?

Like how in Atmel AVR, there is bit_is_clear or bit_is_set

you can do it in a single line:

bool isSet = (var & (1 << bitNumber)) != 0;

1 << bitNumber is a bit shift in this case it means that the 1 will be multiplied with the power of 2

& is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.


"return" not working to break out of a loop I'm fairly new to this, and I haven't been able to find any answers after searching repeatedly.

I have a Startscreen() function that I run during my setup sequence, and within that function i use various while loops and if/else conditionals. This function runs the startup screen of my program on my touch screen.

Well, when certain conditions are met inside a switch case, inside a while loop, I want to load my main screen and then immediately stop the whole Startscreen() function, like this:

LoadMainScreen();
return;

However, I end up seeing my main screen load up, and then my Startscreen() function continues!

Apparently, "return;" does not work as advertised. If I wanted to break out of the current loop, I'd use "break;", right?

So my question is, does it matter that I'm using return; inside a while loop, inside a switch case? How do I exit the whole top-level function completely?

I already tried breaking out of the function and going straight to my main loop this way:

LoadMeasScrn();
loop();
return;

and the same thing happens.

So here's (most of) my entire code:

//////////REMOVED/////////THANKS FOR YOUR ANSWERS/////////////

Your second outermost if() clause in StartScreen(), the one that begins with if (frametype == 0 || frametype == -1), contains an infinite while loop. That loop contains no break statements, and calls StartScreen() -- it recurses into itself!

Without my trying to follow the program logic, I can at least posit that the code is in a second or higher recursion when it calls return, thus returning to where it had called itself. So, yes, if that is correct, it will still be executing within StartScreen() after the return statement. The return statement wouldn't have "failed" in that case; it would have resumed the at the point where the its prior instance called itself.

If that sounds convoluted, it's because it is! There can be good reasons to recurse, if you intended to, your know in what circumstances the code will recurse, and you know that recursiing will stop before you run out of stack space. Carefully review your program logic; this may not be one of those instances....


How can I obtain the .hex of a file I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY_USERNAME\Local Settings\Temp".

Where can I obtain the .hex of any file I have compiled, and how?

As noted in comments, enable verbose compilation and look at the output to find the temporary-directory location. (Click File, Preferences, verbose compilation.)

Note, after you click File, Preferences and the preferences window appears with its half-dozen items, you should also see a note about directly editing preferences in the preferences.txt file.  Edit that file (using a plain-text editor, not a word processor) when the arduino IDE is not running.  Change the line

preproc.save_build_files=false

to

preproc.save_build_files=true

so the .hex files in the temporary directory have a better chance of sticking around.

(I'm not able to test this suggestion on an MS-Windows system.  On my Linux system most build files stick around anyway in /tmp/)


Neo 6M + ESP32 unable to take a fix on battery but works fine with laptop USB I am using Neo 6M GPS module with ESP32 and 2 X 3.5V(7 v in series) 18650 lithium ion battery stepped down to 5V using LM2596 buck converter.
Problem which I am facing is when I power ESP32 using 5V output of LM2596 by connecting Vin pin and powering Neo6M using 5V output of buck converter or 3.3 V of ESP32 then my Neo 6M is unable to fix on satellite, however when removing battery and LM2596 and powering ESP32 using laptop usb cable and Neo 6M using 3V pin of ESP32 then its able to take a fix in 1 minute.
Any idea what mistake I could be doing.
Note - When using battery ESP32 is working as normal and able to connect to wifi and submit Tiny GPS++ output everysecond.
Please let me know in case more information required.

With full battery charge to 3.7V this issue was resolved also using 10uf capacitor between vcc and ground help to improve


What are the benfits of global variables over static class members? On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.

So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.

I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?

I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.

I can see no specific drawback in using static class members instead of global variables on Arduino. They will be managed the same in the end program.

The only difference I can see may arise based on how you design your classes (if design is correct, then no special problem shall arise):

Let's suppose you decale a class A:

class A {
    public:
    void f();
    void g();
    ...
    static void z();

    private:
    static int myStaticField;
    ...
};

if you need an instance of A for method f(), which does not need myStaticField, then that field exists anyway in your SRAM space.

But this is a corner-case, as in good OOD, myStaticField should be needed as soon as you need to work with class A (whatever method youwant to use).


Arduino Uno: Driving a small LED strip with 2N3904 NPN I'd like to know why I cannot dim the small LED strip with my design. I can only turn them on and off. This is a problem for me as I wanted to have a fade effect. Here is my circuit:

The voltage from the power jack is 5 volts. My NPN transistor is a 2N3904 (from left to right: emitter, base, collector).
For the Arduino I am only using the fade exemple sketch:

int led = A2; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
   pinMode(led, OUTPUT);
 }

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
     fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

By the way, this is my first post so please tell me if something is wrong with it! Thank you for your help!

Have a nice day.

The analogWrite works only on PWM pins (in your scheme it's marked by ~). On the other pins it's possible to set only LOW/HIGH (values under 128 are translated to the LOW)

Not to mention weirdly used NPN with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k).
This is how we usualy use PNP transistor (again with 1k resistor and emitter to the Vcc, not the collector). But PNP won't work with 5V logic and higher Vin than 5V as there will be current flow from 0V or 5V to the Vin.


Connecting a 5v dc fan to ultrasonic sensor I am currently doing a simple uni project where i want the distance read by an ultrasonic sensor to control the speed of a dc 5v fan. I have attached a schematic of how i think i can link the ultrasonic sensor and fan components in order to achieve my main goal. Please tell me if this circuit is right or wrong and give some helpful feedback, thank you!

It's wrong.

A fan is a motor. A motor is a power hungry inductive device.

Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.


NodeMCU (ESP8266) Defining static IP, stops Firebase processing Hello i am new to NodeMCU (ESP8266) i am building a small program to connect with WIFI (with internet) and if internet is not available i want to process request over IP address.

I am using firebase as a database / server to fetch the status. And process command through a URL like http://192.168.1.223/on?pin=04 if internet is connected then no problem i can update firebase entry, but with same network (LAN) connection over wifi i want to process i need to have static IP. But the concern is i am not able to make this IP address static, and if i make it static then my NodeMCU is not able to connect with firebase.

Here is how my code looks like:

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include <ESP8266WebServer.h>

#define FIREBASE_HOST "pushst-56f2c.firebaseio.com"
#define FIREBASE_AUTH "mhBpzrNyhhwEGwmFxkVFTIEylwrXMw0gm"
#define PATH "/clients/devicename/watermotor"

IPAddress ip(192, 168, 1, 223);  //Node static IP
IPAddress dns(192, 168, 1, 223);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

char ssid[] = "MyNetwork";
char password[] = "Qwert98!!";

int wifiStatus = WL_IDLE_STATUS;

ESP8266WebServer server(80);

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

      delay(100);
      Serial.println();
      Serial.println();
      Serial.print("Your are connecting to;");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.config(ip, dns, gateway, subnet);

      while (WiFi.status() != WL_CONNECTED) {
        digitalWrite(WIFI_CONNECT_LED, HIGH);
        delay(500);
        Serial.print(".");
      }

      wifiStatus = WiFi.status();

      if(wifiStatus == WL_CONNECTED){
          digitalWrite(WIFI_CONNECT_LED, LOW);

         Serial.println("Your IP address is: ");
         Serial.println(WiFi.localIP());

         Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
         Firebase.set("/clients/devicename/watermotor/name", "Motor");
         Firebase.set("/clients/devicename/watermotor/relay_status", "off");
         Firebase.set("/clients/devicename/watermotor/device_status", "online");
         Firebase.stream(PATH);

         server.on("/on", handleOnRequest); //Associate the handler function
         server.on("/off", handleOffRequest); //Associate the handler function

         server.begin(); //Start the server
      }
      else{
        Serial.println("");
        Serial.println("WiFi not connected");
      }

}

void loop() {
    server.handleClient();
    if (Firebase.failed()) {
      Serial.println("streaming error");
      Serial.println(Firebase.error());
      delay(1000);
      return;
    }

    if (Firebase.available()) {
        Serial.println();
        Serial.print("Firebase available");
        Serial.println();
        FirebaseObject event = Firebase.readEvent();
    }
}

I am not sure if its there is some problem with FirebaseLibrary or its just the ESP8266!

Any suggestions will be helpful, thanks in advance! :)

You have wrong DNS server IP address. In your sketch it is the same as the static IP address you assign to esp. Then the name of the firebase host can't be resolved by DNS.

The DNS server is usually the router/gateway.

IPAddress dns(192,168,1,1)


How to connect RFID Module to Arduino UNO I brought 860mhz-960mhz UHF rfid reader module for chip card skimmer from follow link:

https://www.alibaba.com/product-detail/860mhz-960mhz-UHF-rfid-reader-module_60312310172.html

I want to do communication with arduino uno so is it possible to connect

VCC to VCC
GND to GND
RX to TX
TX to RX

and what is meaning of EN and GPIO if any one know please help me to do serial communication.

Its just a simple RFID module based on UART working on 5V.  EN stands for enable, to enable the chip. It has to be connected to VCC too. Because its active high signal. GPIOs are general purpose io pins. No need of them if you are just reading from RFID.


How exactly is voltage measured on an Arduino? How do the analog pins on an Arduino measure voltage?

Do they either measure current and calculate the voltage with Ohm's law? (If so, why can we only read voltage and not current directly?)

Or do they compare the unknown input voltage with a known internal one? (If so, how does that work? What's the known voltage?)

Known voltage is usually provided by a diode or similar reference. The atmega328p chip has a separate aref pin so you can choose your own reference.

An ADC or analog to digital converter http://en.m.wikipedia.org/wiki/Analog-to-digital_converter is a collection of comparators. A comparator is a logic gate that simply tells which of two inputs has more voltage. This aref voltage is divided evenly into 2^10 values (it's a 10 bit ADC). Then the incoming signal is compared against all of these and the largest comparator which triggers is the reading you get in your arduino code.


Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino? I want send and receive a 9 bit async-serial protocol with 4800 baud on my Arduino Uno, i have read on the specification from the ATmega328P that the uart can do that.
My aim is that when my Uart receive the 9th bit as a 1 he must throw a interrupt. On this interrupt i can recognize that this byte was an adress byte.
When he receive a zero he sould do nothing spezial, only transmit it as hex-byte over usb to the pc.

My Problem now, i can´t initialize the Uart right because the command Serial.begin(4800, config) is not enough, i must throw the interrupt and translate the data to hex-bytes.
My Question can i modify the Serial.begin() source code respectively where can i find the source code for the Serial.begin function?

When there is no possibility to change the code has someone a other option for me to send and receive the 9 bit protocol with an Arduino Uno?

If you want to set the UART to 9-bit mode, you will have to set the
UCSZ02 bit of the _ucsrb register to 1 in
HardwareSerial::begin().
For example:

void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Mostly unchanged... but by the end:
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
  sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
}

Notice that you do not need to modify the Arduino core library for this:
you could set that bit in your setup(), right after calling
Serial.begin().

Then, in the HardwareSerial::_rx_complete_irq() interrupt
handler,
you will have to read the 9th bit as the RXB80 bit in UCSR0B, before
reading the low byte from _udr (emphasis in the datasheet). For
example, you could replace the line unsigned char c = *_udr; by:

bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
unsigned char c = *_udr;                // then the other bits
if (is_address) {
  do_something_with_address(c);
  return;
}

where do_something_with_address() is the stuff you wanted to do in
another interrupt (no need for that, you are already in interrupt
context).

It is worth noting that, with an Arduino Uno, you will not be able to do
all this while sending data to the PC. This is because the communication
with the PC uses the only UART of the ATmega328P.


MemoryFree library showing Irregular Behaviour..! I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :

#include <MemoryFree.h>
String str="rajat";
int flag=0;
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}

void loop()
{
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    str=str+"rjt";
    Serial.println(str);
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    Serial.println("");
      delay(1000);
}

Free memory can be found in two forms:

The free space between the heap and the stack. This is usually the
main chunk of free memory.
Heap “holes”, i.e. pieces of unallocated memory within the heap. The
presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones
only report the main chunk between the heap and the stack. The more
sophisticated ones walk the malloc()'s free list in order to also count
the heap holes. Which approach is better? I would argue that the naive
version is fine, as heap holes is something you should not count on,
because it is never guaranteed that a particular allocation will fit in
any of those holes.

You are visibly using one of the naive versions. As you grow your
string, the object calls realloc(), which in some cases copies the
string's character array and frees the original one, potentially
creating a heap hole. Eventually, small holes can coalesce into a
larger one big enough for the next allocation, and
realloc() can end up using this large hole and freeing the chunk at
the top of the heap. When this happens, the heap shrinks, and the main
chunk of free memory gets larger, which is what freeMemory() is
reporting to you.

In summary, it's normal and expected behavior. If you want something
less surprising, use a version of the library that does count the holes.
But then you may run into a more displeasing surprise: a heap–stack
collision, or an out-of-memory condition, can happen even with loads of
memory buried inside heap holes.


My Arduino freezes if power removed from the HMI I have an Arduino (Pro Mini) connected to an HMI display over serial. When the user pushes a button on the HMI screen, it activates a relay attached to one of the digital pins on the Arduino.

For safety reasons, if the Arduino loses communications with the HMI, I want it to turn off the relay. So, when the button has been pushed, it triggers a polling sequence to verify that the button is still being pushed (I'm not relying on the button release event, again for safety).

The following code works perfectly if I disconnect either of the signal lines (tx or rx) or ground from the HMI. If I disconnect the +5 volts, however, the Arduino freezes completely, and therefore never shuts down the relay.

What could be causing this, and what can I do to overcome the problem?

The code is as follows, however, it works as expected if the data lines or ground are severed.

int getNumber(const char *reqString)
{
  sendString(reqString);

  long startTime = currentMillis;
  long waitTimer = currentMillis - startTime;

  bool responded = false;
  int endcount = 0;
  byte inbyte;
  byte bytebuffer[80];
  int bytecount = 0;

  while (waitTimer < 100 && !responded)
  {

      if (HMI.available())
      {
        inbyte = HMI.read();

        if (inbyte == 0xFF)
        {
          endcount++;
          if (endcount == 3)
          {
            responded = true;
            endcount = 0;
          }
        }
        else
        {
          endcount = 0;
        }

        bytebuffer[bytecount] = inbyte;
        bytecount++;
      }

      // Update the wait Timer.
      waitTimer = millis() - startTime;
  }

  // If we received a response, return the first data byte. If not, return 0
  if (responded)
   {
     Serial.println("Received response");
     return bytebuffer[1];
   }
   else
   {
 Serial.println("No response");
     return 0;
   }
}

It seems that Software Serial is waiting for "high" on RX

Only a hardware solution comes to my mind

simulate this circuit – Schematic created using CircuitLab

This way Arduino RX will be released on HMI power loss

Later edit

You can also use the watchdog timer to unfreeze your code when unresponsive. It will reset the Arduino if wdt_reset() is not called in a given amount of time and you can make the cleaning you need before using Software Serial again. Here is a useful tutorial.


GSM module connected with arduino uno giving garbage values in response I connected a GSM module with the Arduino UNO. The connections are as follows:

  Gnd of gsm -----> Gnd of arduino

  TX of gsm  -----> pin 9 of arduino

  Rx of gsm  -----> pin 10 of arduino

GSM is powered from a 9V-1Amp wall adapter.

The GSM is performing according to all the AT commands (like making a voice call, hanging a call, answering a call) which are given, but it is displaying garbage values on serial monitor in response.

Here is the code:

#include <SoftwareSerial.h>
SoftwareSerial myserial(9, 10);

void setup() {
    Serial.begin(115200);
    myserial.begin(9600);
    myserial.println("ATDXXXXXXXXXX;");
    delay(30000);
    myserial.println("ATH");
}

void loop() {
    if (myserial.available()>0){
        Serial.println(myserial.read());
    }
}

What could be reasons for the GSM to output garbage values and how can I resolve it?

Serial.println(myserial.read());

myserial.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.

You then print that integer, each one on its own line.

So the response "OK\r\n" from, say, "AT\r\n" would look like:

79
75
13
10

Instead you need to write the data, not print it:

Serial.write(myserial.read());

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.


How does coordinator XBee receive data from router? I have two XBees S2, one is configured as an API coordinator connected to Arduino and the other as an AT router.

The coordinator sends a frame to the router to switch on a LED. I want to switch off that LED with a button and the router send a message to the coordinator to tell him that it switch off the LED.

How can I do this?

I have one Arduino with the coordinator. I'm asking what I have to put in the script to make the coordinator receive the data.

Here is my code, how the coordinator sends the data to the router:

String inputString;
int led = 13;
void setup() {
pinMode(led, OUTPUT);
Seria.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
setRemoteState(5);

}
inputString="";
}
}

void setRemoteState(char value){
Serial.write(0x7E); // start byte
Serial.write((byte)0x0);
Serial.write(0x10);
Serial.write(0x17);
Serial.write((byte)0x0);
// id of recipient or use 0xFFFF for broadcast
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write((byte)00);
Serial.write(0xFF);
Serial.write(0xFF);
// 16 bit of reciepent
Serial.write(0xFF);
Serial.write(0xFE);

Serial.write(0x02);

  Serial.write('D');
  Serial.write('2');

 Serial.write(value);

long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
Serial.write(0xFF - ( sum & 0xFF) );
Serial.print(sum,HEX);
}

When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.

You should first define which mode you want to use them and start coding.

If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).

If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:

if (led == 1)
   Serial.println("ok");
else
   Serial.println("error");

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some libs out there you can achieve this.

On the other side, the coordinator will receive the message and interpret it.

If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.


SPI Communication Failure I am trying to program an AD5930 with my Arduino Mega, and I suspect that I have a software issue or a broken Mega. I am fairly new to coding Arduino's so I am hoping someone here knows better.

Here is my code:

#include <SPI.h>

#define DATAOUT 51//MOSI
#define SPI_CLOCK  52//sck
#define SLAVESELECT_1 53//ss
#define CNTRL 36//ss

int freq1 = 0;
int BurstLength1 = 0;
int freq2 = 0;
int BurstLength2 = 0;
int PRF_RATIO = 100;

void setup(){
  Serial.begin(9600);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);
  byte i;
  byte clr;
  pinMode(DATAOUT, OUTPUT);
  pinMode(CNTRL, OUTPUT);
  digitalWrite(CNTRL, LOW);
  pinMode(SPI_CLOCK, OUTPUT);
  pinMode(SLAVESELECT_1,OUTPUT);
  digitalWrite(SLAVESELECT_1,HIGH); //disable device
  SPI.begin();
  digitalWrite(SLAVESELECT_1,LOW); //Enable device
  SPI.transfer(0x0E);  //Send  Fstart Write Enable to Control Reg
  SPI.transfer(0x13);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0xC7);  //Send Frequency to Fstart one byte at a time
  SPI.transfer(0x4C);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0xD0);  //Send Frequency to Fstart one byte at a time
  SPI.transfer(0x93);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x06);  //Send  Fdelta Write Enable to Control Reg
  SPI.transfer(0x13);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x20);  //Send Frequency to Fdelta one byte at a time
  SPI.transfer(0x00);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x30);  //Send Frequency to Fdelta one byte at a time
  SPI.transfer(0x00);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x10);  //Send Number of Increments
  SPI.transfer(0x02);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x40);  //Send tINT Register
  SPI.transfer(0xEB);
  digitalWrite(SLAVESELECT_1,HIGH);
  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0x80);  //Tburst Register
  SPI.transfer(0x0A);
  digitalWrite(SLAVESELECT_1,HIGH);
  SPI.end();
}

void loop() {
  digitalWrite(CNTRL, HIGH);
  delay(1);
  digitalWrite(CNTRL, LOW);
  delay(25);
}

I hooked up the Arduino to a logic analyzer and it looks like the code inside the setup function isn't happening. In the logic analyzer we can see that the control pin is being toggled which is the instruction in the loop method.

I know that I am getting a whole cycle as you can see the control pin toggle in the past as well when I trigger on the reset button in the logic analyzer.

This same result of nothing is happening in the ICSP header and pins 51(Data), and 52(Clk).

I hope I am just making a stupid mistake in the code.
Thanks to whomever takes pity on me.

I tested your setup with my Mega, and it worked OK after a couple of changes.

You should really set SS high first, before even making it an output. That way the pull-up is activated, and then the moment you make it output it stays high, rather than going to low, then back to high, which looks to the target like a SS pulse.
You don't need to do pinMode() calls on the other SPI pins.
Call SPI.begin() last - after setting SS high.

void setup(){

  Serial.begin(9600);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);

/// -----CHANGES--------
  digitalWrite(SLAVESELECT_1,HIGH); //disable device
  pinMode(SLAVESELECT_1,OUTPUT);
/// -------------

  SPI.begin();

  digitalWrite(SLAVESELECT_1,LOW); //Enable device
  SPI.transfer(0x0E);  //Send  Fstart Write Enable to Control Reg
  SPI.transfer(0x13);
  digitalWrite(SLAVESELECT_1,HIGH);

  digitalWrite(SLAVESELECT_1,LOW);
  SPI.transfer(0xC7);  //Send Frequency to Fstart one byte at a time
  SPI.transfer(0x4C);
  digitalWrite(SLAVESELECT_1,HIGH);

  ...

As you can see from the logic analyzer, the output is OK:

The numbers look right too:

Time [s], Analyzer Name, Decoded Protocol Result
-0.000001752000000,SPI,MOSI: 0x0E;  MISO: 0x00
0.000001248000000,SPI,MOSI: 0x13;  MISO: 0x00
0.000014496000000,SPI,MOSI: 0xC7;  MISO: 0x00
0.000017496000000,SPI,MOSI: 0x4C;  MISO: 0x00
0.000030744000000,SPI,MOSI: 0xD0;  MISO: 0x00
0.000033744000000,SPI,MOSI: 0x93;  MISO: 0x00
0.000046992000000,SPI,MOSI: 0x06;  MISO: 0x00
0.000049992000000,SPI,MOSI: 0x13;  MISO: 0x00
0.000063240000000,SPI,MOSI: 0x20;  MISO: 0x00
0.000066240000000,SPI,MOSI: 0x00;  MISO: 0x00
0.000079488000000,SPI,MOSI: 0x30;  MISO: 0x00
0.000082486000000,SPI,MOSI: 0x00;  MISO: 0x00
0.000095736000000,SPI,MOSI: 0x10;  MISO: 0x00
0.000098734000000,SPI,MOSI: 0x02;  MISO: 0x00
0.000111984000000,SPI,MOSI: 0x40;  MISO: 0x00
0.000114982000000,SPI,MOSI: 0xEB;  MISO: 0x00
0.000128232000000,SPI,MOSI: 0x80;  MISO: 0x00
0.000131230000000,SPI,MOSI: 0x0A;  MISO: 0x00

Try the changes to the code, and see what happens.


Using serial communication in .c-files I am currently trying to connect my Arduino Uno to my computer and let them communicate via UART. I started using a project from Github (here), which I'm trying to modify to get the next step via UART. Because of that, I'm not able to switch programming languages and also need to override the bootloader.

However, I can't get the serial connection to work.

#include "Joystick.h"
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

These are the #include statements at the top, but <Arduino.h> can't be found...

If I remove these statements, Serial can't be found (from the main-Method: Serial.begin(9600);)

It's my first time to program with C, did I overlook a stupid mistake? Thanks for any help...

I would consider using HoodLoader2 instead of that LUFA project. If you can't do that, you can compile parts of the Arduino Core together with the LUFA project.

The main steps:

Add the necessary Arduino source files to the SRC variable in the Makefile.
Add the Arduino core folder to the include path by appending to the CC_FLAGS and CXX_FLAGS variables.
Move the main function to a new main.cpp file and add it to the Makefile SRC as well.
Include the Joystick.h file in your main file in an extern "C" block.
Include the HardwareSerial.h file in your main file as well.

My files after these changes:

Makefile

# Set the MCU accordingly to your device (e.g. at90usb1286 for a Teensy 2.0++, or atmega16u2 for an Arduino UNO R3)
MCU          = atmega16u2
ARCH         = AVR8
F_CPU        = 16000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c main.cpp $(LUFA_SRC_USB)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =

ARDUINO_PATH = ${HOME}/.arduino15/packages/arduino/hardware/avr/1.8.1/cores/arduino
SRC         += $(ARDUINO_PATH)/HardwareSerial.cpp
SRC         += $(ARDUINO_PATH)/HardwareSerial1.cpp
SRC         += $(ARDUINO_PATH)/Print.cpp
CXX_FLAGS   += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2
CC_FLAGS    += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2

...

main.cpp

extern "C" {
#include "Joystick.h"
}

#include <HardwareSerial.h>

// Main entry point.
int main(void) {
    // We'll start by performing hardware and peripheral setup.
    SetupHardware();
    // We'll then enable global interrupts for our use.
    GlobalInterruptEnable();
    // Initialize the UART
    Serial1.begin(115200);
    Serial1.println(F("Hello, world"));
    // Once that's done, we'll enter an infinite loop.
    for (;;)
    {
        // We need to run our task to process and deliver data for our IN and OUT endpoints.
        HID_Task();
        // We also need to run the main USB management task.
        USB_USBTask();
    }
}

Joystick.c
Deleted the main function.

To get it to compile after these changes:

# (inside of the snowball-thrower folder)
git submodule add https://github.com/NicoHood/HoodLoader2.git HoodLoader2
make

This compiles without problems for me, but I have no idea if it actually works.

Edit:

You'll notice that the program uses more RAM than the ATmeg16U2 has available. You could solve this by moving the step array to PROGMEM, or by shrinking the Serial buffers.

avr-size --mcu=atmega16u2 --format=avr Joystick.elf
AVR Memory Usage
----------------
Device: atmega16u2

Program:    5076 bytes (31.0% Full)
(.text + .data + .bootloader)

Data:        527 bytes (102.9% Full)
(.data + .bss + .noinit)

 [INFO]    : Finished building project "Joystick".


Double Speed Operation for USART on Arduino Mega 2560 I happened to be looking through the HardwareSerial.cpp file that contains the functions used for Serial communication for Arduino.  While looking through the HardwareSerial::begin(baud, config) function, I noticed that the ucsra register has its U2X0 bit set.  When I looked through the datasheet, it says that the U2X0 bit is set to start Double Speed Operation.  From what I'm reading, this means that the baud rate is doubled.
I've been using this Arduino on this computer for a while now with no complaints for the baud rate being at an incorrect speed. What is Double Speed Operation?  Why does it seem to be set in the code by default? I attached the code and section in the manual below.

void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

  _written = false;

  //set the data bits, parity, and stop bits
  #if defined(__AVR_ATmega8__)
    config |= 0x80; // select UCSRC register (shared with UBRRH)
  #endif
  *_ucsrc = config;

  sbi(*_ucsrb, RXEN0);
  sbi(*_ucsrb, TXEN0);
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
}

When in double-speed mode, as noted in the manual, fewer samples are used. In Asynchronous serial communication, there is no clock signal, so the clock that keeps the two devices in sync is extrapolated from the data signal. Each end of the communication has it's own clock source (crystal oscillator, ceramic resonator, R-C oscillator, etc.), and you'll rarely find two that are calibrated identically.

The receiver samples the signal at a higher rate than the actual baud rate so that it can better determine where, relative to it's own clock, the data-signal edges go up or down and continually adjusts its offset to compensate for clock drift.

By operating in double-speed mode, the receiver has fewer samples to work with, and so if your transmitter has a clock source that is different enough than the receiver, or is not stable, or you have long or noisy wires or fluctuating temperatures (etc.) then you may experience less stable communication.

If your particular use-case works fine, then stick with it. But if you start to notice errors in communication, the first troubleshooting step would be to disable this mode, since the clock recover is less robust in this mode.


SD Card Read/Write Arduino Mega Fail I have an Arduino Mega 2560 where I have used a MicroSD Card Module to Read/Write Data on the Micro SD Card.
I have tried using the Example in the Arduino IDE but the data is not being written or read by Arduino to the SD Card Module. The connections with the module is exactly how it is described in the Sketch.
I have attached pictures of the Connection and the module I use for the same.

The Example sketch for the SD Card Read/Write is also attached.

If there is a problem that you can notice, please let me know what the problem is and if it can be solved.

Thank you in advance.

/*
SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SPI.h>
#include <SD.h>

 File myFile;

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

 Serial.print("Initializing SD card...");

 if (!SD.begin(4)) {
 Serial.println("initialization failed!");
 return;
  }

  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.
   myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
    if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
     } else {
     // if the file didn't open, print an error:
     Serial.println("error opening test.txt");
   }

    // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
   Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
     while (myFile.available()) {
     Serial.write(myFile.read());
     }
    // close the file:
    myFile.close();
     } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
     }
    }

    void loop() {
   // nothing happens after setup
     }

Connection with Arduino
SD Card Module

The SPI wiring described in the SD card example sketch is for Uno. On Mega the SPI pins are 50 MISO, 51 MOSI and 52 CLK.


Will a magnetometer give distorted values if there is a magnet near? I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?

Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.

In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.

The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.
Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of about 1 Tesla at a distance of  1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.


How can I connect nearly 450 LEDs to an arduino without drawing too much current? The question seems simple, but there's more to it:

I'm connecting 4 74HC595 shift-registers to an arduino pro micro.
28 of the 32 outputs will be used to control LED segments of numbers.
Each segment uses 14-20 LEDs and so I will be using a transistor for each segment.
Now here's my problem: With the maximum amount of LEDs activated (at time 08:08), the LEDs will draw nearly 10A. How can I use another transistor to make the shift-registors work with the arduino even though it shouldn't be drawing all current from the arduino, but from an external power source. I have found a suitable adapter from 230V to 5V 12A. The 12A is just to ensure that nothing goes wrong. The LEDs alone will draw 9.76A.

I know how to connect the arduino to the power source, but how do I run extra wires from the power source around the arduino to provide the LEDs their power?

First you should consider changing your whole idea so that your LEDs don't draw nearly 10A.

I am assuming that for each segment you have 14-20 LEDs wired in parallel, each with its own current limiting resistor. That is very wasteful.

Instead you should be grouping the LEDs in chains of series LEDs which you then place in parallel.

Assuming you have normal red LEDs with a forward voltage of around 2V and a typical current draw for maximum brightness of 20mA, you can connect them up in chains of, say, 5 LEDs with one current limiting resistor, and power them from 12V not 5V.

3 chains of 5 LEDs (15 LEDs) would be 3x20mA = 60mA per segment. 4 chains of 5 LEDs (20 LEDs) would be 4x20mA = 80mA.

With 08:08 displaying that's 26 segments plus dots. Assuming each segment has 20 LEDs that's a total of 26x4 = 104 chains of 5 LEDs, totalling 520mA.

And then you should do away with the resistors as well, and use constant current LED sinks, such as the TLC59116, which can handle the higher input voltage.

If you don't want to do that, then more transistors will be needed:

simulate this circuit – Schematic created using CircuitLab

I have only showed 2 digits, 2 segments, 2 chains per segment, and 2 LEDs per chain to save space.

To drive it you need 1 GPIO per segment in one digit and 1 GPIO per digit. So for 4 digits at 7 segments that's 11 GPIO.


What is this shield? (AST Space Arduino Kit) I recently got a box with Arduino components from someone who didn't want it (in part, because the manual was (probably) in Chinese). However, to my surprise, I could not find this kit on the internet. I would like to know: is this a copy of another kit?  Or, is there documentation available for this particular kit?

Box contents:

Arduino Uno
Unknow shield "by AST Space" with

AI-THINKER wi-fi module
Songle relais
YLB3641AH 4-digit LED display
DHT-11 relative humidity, temperature sensor
IR receivers, switches, microphone/buzzer, light sensor, connectors to the other components

MPU6050 accelerometer
HC-SR04 ultrasonic rangefinder
QAPASS LCD unit
"Car MP3" IR remote
2x green, 2x red LED, 5x resistor
17x10 green breadboard
2x DC motor, 1x geared stepper motor
40-wide female-female jumper ribbon cable
USB connector cable (black)

It came in an intricate folding box, bright orange. The QR code links to http://weixin.qq.com/r/2kgtNVXEKwhUrRFW9x3I (which did not get me anywhere - visiting this link is at your own risk). Pictures:

My name is Bing Zhu. I the host of ASTSpace a community open lab sponsored by Zhejiang Association for Science and Technology(ZAST). AST is situated inside the Zhejiang Museum of Science and Technology. We are non-profit. The Kit you have gotten must be from someone got it free at one of ASTSpace's events. I remembered that we had brought some with us to the Manchester Science Festival where we did a tinkering activity for the public, 3 years ago.
This kit was designed by one of our members who is currently a Ph.D. student of automation at Zhejiang University. It was developed for the purpose to increase public experiences in a 90 minutes session. Therefore, in order to shorten the time of wiring while most times participants with no backgrounds or exposures to electronics make no sense anyway, we purposely had most of the functioning parts soldered on. In this way, we think it would be more manageable as well for teaching as most times one instructor has to manage more than a room full of over 25 participants. Making sure that parts are connected and in place can be a life-saver. We had it designed this way so the kit can be used in classes by schools in remote areas. These kits are given away and the introduction sessions are free to the public, and we intended to provide online help to those who decide to venture on with this kit at their own time. But, it never took off for time and resource restriction.  With this kit we have gone through two major cities in the Zhejiang Province and 4 remote rural areas.
All our expenses are supported by ZAST through two projects, one to make it and one to distribute it. When we did what we did, it was always for the public to know electronic control and coding was made easy by Arduino where it was first invented by an Italian who wanted to teach artists electronics.
This kit was used to demo how easily and readily everything can be controlled and through these electronics, we can take the parts of the physical world into our hands to follow our wills. We did use it to demo the on and off lighting system of the entire science center and controls of a remote camera inside the security room.
So, ASTSpace Arduino kit is a tailor-made kit for a specific purpose. We did not change anything but redesigned the wiring of the sensors for easy use for our events.


Timing push button code I am trying to time how long button is held for. The code seems to work but with two problems:

the millis values are being read wrongly. If you hold the button for 1 second, it returns holdTime of about 3000 ms. A quick click returns holdTime of about 1000 ms.

Each successive button press adds to the previous millis value so holdTime just gets higher and higher and doesn't measure how long the button has just been pressed for

Any ideas or advice for newbie welcome!
#include <LiquidCrystal.h>

const int button1Pin = 1;  // pushbutton 1 pin
const int ledPin = 13;     // LED pin

int button1State, button2State;  // variables to hold the pushbutton states
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int startPressed = 0;
int endPressed = 0;
int holdTime = 0;

void setup() {
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
\
}

void loop() {

  while (digitalRead(button1Pin) == LOW) {}

  button1State = digitalRead(button1Pin);
  startPressed = 0;
  endPressed =0;
  holdTime = 0;

  // if button1 or button 2 are pressed (but not both)
  if (button1State == LOW) {
    digitalWrite(ledPin, LOW);   // turn the LED on
    startPressed = millis();
  } else {
    digitalWrite(ledPin, HIGH);  // turn the LED off
    endPressed = millis();
    holdTime = endPressed - startPressed;
  }
  lcd.print("You pressed for");
  lcd.setCursor(0, 1);
  lcd.print(holdTime);
  lcd.print("ms");
  while (digitalRead(button1Pin) == LOW) {}
  lcd.clear();
  startPressed =0;
  endPressed =0;
  holdTime = 0;
}

Your source has several flaws, and one error that generates the output you see. This is the analysis of the error.
In loop() you start by waiting for the button pin to get HIGH, following by another read of the pin's state that will most probably return the same, HIGH. Note: Only if your button bounces with just the right timing, this last read will return LOW.
while (digitalRead(button1Pin) == LOW) {}
button1State = digitalRead(button1Pin);

Next you check the pin's state, and let's assume that it is HIGH. Only the else part is executed, and it calculates the holdtime as the difference of endPressed and startPressed. The former has the current value of millis(), but the latter is 0 as you initialized it.
That's why you're getting always growing values.
How to solve?
Think about the while loops, do you need them? Remember that loop() is already called repeatedly.
You may need a state variable that stores the last pin's state, so you can detect changes.


Why Commenting Serial.print() gives me a different value? I am working on with Cypress and Arduino.I am trying to transfer the data from cypress and printing it to the Serial Monitor or Arduino. but the thing is when I am using Serial.print(j) it is showing the right value of i (See in the code about what is i and j), but when I comment or remove Serial.print(j) it is showing the wrong value of i
For example, suppose cypress is sending data 00001934a
and then I am reading this value using

int j = mySerial.read()-'0';
// -'0' is for chaging ascii data to normal integer
//for example ascii value of `0` is 48
//so mySerial will read 48
// and exprerssion value will become `48-48 = 0`

My code

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
Serial.begin(57600);
 while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

mySerial.begin(4800);
}

int  i = 0;
int j = 0;
void loop() {
if (mySerial.available()) {

        while(j!=49){
        i = i*10 + j;
        j = mySerial.read()-'0';
         //49 is the ascii value of a, I am using this for acting like
         //a flag, so that i can see the break in data

        Serial.println(j);//commeting this line is causing the problem
      }
   Serial.print(i);
   }
}

when the line is not commented the output was

0
0
0
0
1
9
3
4
49
193 //this is the value of i which is correct one

but when I comment the line Serial.println(j) the output was

   14569 // I don't know what the hack is this.

Hopefully the problem is understandable, but still, you can comment for more detail.
BTW I am using SoftwareSerial.

Majenko has correctly diagnosed your problem, and the blog post he
linked to is definitely a must-read. The suggested solution, namely
buffering the input until you can read a complete message, is presumably
the most standard way of dealing with an input stream.

It is, however, not the only option. Your idea of building the number
digit by digit can work, if implemented properly, and it can save you
the memory cost of the buffer. The key is to only read bytes when they
are available.

Below is a non-blocking implementation of a number reader that works
along the lines of your own code. This function only reads positive
numbers. It returns the number it just parsed upon reading a non-digit
character. In every other case it returns -1 to tell you there is no
input number available:

// Read an positive integer from a stream.
// Returns -1 if a complete integer is not available.
int readInt(Stream &link)
{
    static bool got_a_digit = false;  // did we get a digit so far?
    static int i = 0;                 // the integer we are building
    if (link.available()) {
        char c = link.read();
        if (isdigit(c)) {
            i = 10 * i + (c - '0');
            got_a_digit = true;
        } else if (got_a_digit) {  // non-digit: return the number
            int i_copy = i;
            got_a_digit = false;   // reset for next reading
            i = 0;                 // ditto
            return i_copy;
        }
    }
    return -1;
}

And here is how you would use it:

void loop() {
    int i = readInt(mySerial);
    if (i != -1)
        Serial.println(i);
}


Cryptic compiler errors I'm getting the error:

    left_hand:3:20: error: expected ']' before ';' token
     #define HAND_ROWS 5;
                        ^

on this code:

    #include <Keyboard.h>

    #define HAND_ROWS 5;
    #define HAND_COLS 6;
    #define ROW_PINS {9, 8, 7, 6, 5};
    #define COL_PINS {10, 16, 14, 15, 18, 19};
    #define LOOP_SPEED = 10;

    const char keymap[HAND_ROWS][HAND_COLS] = {{0xB1, '1', '2', '3', '4', '5'},
                                               {0xB3, 0x81, 'q', 'w', 'e', 'r'},
                                               {'6', 0x80, 'a', 's', 'd', 'f'},
                                               {'7', 'z', 'x', 'c', 'v', 'b'},
                                               {'h', 'j', 0x82, ' ', 'k', 'l'}};
    boolean pressedKeys;
    int keymapIndex;

help, please? This makes no sense to me...
If I try to use Keyboard.LEFT_SHIFT and equivalent constants for the hex-codes in the keymap, they tell me 'expected unqualified-id before numerical constant'
What does this even mean? I'm so lost...

You mustn't terminate a #define with a ;.  Semicolons are for C and C++ statements. #define is a preprocessor statement.

#define creates a literal string replacement, so when you use it you end up with:

const char keymap[5;][6;] = {...

which is, of course, wrong.


Error while trying to drive relay through the state of a digital input pin in Arduino I'm trying to change the state of a relay according to the state of a digital input in an Arduino with an ethernet shield. It works sometimes and some other times it doesn't work.

My code:

const int led1 = 2;
const int enable1 = 4;
boolean led1_OnOff;

void setup() {
  led1_OnOff = false;
  pinMode(enable1, INPUT);
  digitalWrite(enable1, LOW);
  pinMode(led1, OUTPUT);
}

void loop() {
  if(digitalRead(enable1) == HIGH) {
    if(led1_OnOff == true) {
      led1_OnOff = false;
    } else {
      led1_OnOff = true;
    }
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}

My schematics:

Relay 5v -> arduino 5v
Relay gnd -> arduino gnd
Relay in -> digital pin 2
Relay com -> 220 AC
Relay NC -> 220 AC
Push button pin 1 -> Arduino 5v
Push button pin 2 -> digital pin 4

Pin 2 is connected to the relay enable pin and pin 4 is connected to a push button and the boolean is used for saving the state.

Can anyone tell me what the problem is, and why the relay doesn't work most of the time?

Assuming your circuit is correct (and perhaps it is, since you imply that it works some of the time), the first obvious problem is that when you press the button, the code will repeatedly toggle the output, very very fast.  It may seem to you like you're only pressing the button for a moment, but the code will loop many many times.  When you release the button, it's a 50/50 chance whether it leaves the relay on or off.

To solve this, you can wait until the button is released before checking again.

In addition to this, you may have switch bounce.  There are nicer ways of fixing this, but for your stated purpose, waiting 0.1s after a releae before checking the button again is probably sufficient.

....
void loop() {
  if(digitalRead(enable1) == HIGH)
  {
    if(led1_OnOff == true)
    {
      led1_OnOff = false;
      //+digitalWrite(led1, LOW);
    }
    else
    {
      led1_OnOff = true;
      //digitalWrite(led1, HIGH);
    }

    // Wait for the button to be released
    while(digitalRead(enable1) == HIGH)
    {
      // do nothing, just wait
    }
    // Poor-man's debounce
    delay(100);
  }

  if(led1_OnOff == true)
    digitalWrite(led1, HIGH);
  else
    digitalWrite(led1, LOW);
}


Can't read from DHT sensor when motor is running I've been following this tutorial and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs.

This only happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.

Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).

I've attached a diagram I made of my circuit in fritzing -

The problem may be electrical noise from the motor, or
you may have a wiring problem (an incorrect or intermittent connection).

Kira San’s comment “try to add a 100nF ceramic capacitor between the motor terminals” is directed toward suppressing electrical motor noise.  As brushes make or break connections on a motor's commutator, arcs and sparks can occur.  The capacitor will limit voltage rate of change thus suppressing some of that electrical noise.
CharlieHanson's comment (add a flyback diode across the motor terminals) is partly related to noise suppression but mostly to suppressing high voltage excursion that occurs when you shut off motor power.  While the motor is running, the magnetic field in it stores ½ L i² joules of power.  When current stops suddenly, those joules of power convert to a high voltage spike.  A flyback diode acts as a near-short to absorb that spike.  The cathode (cross-bar) of the flyback diode attaches to the high side of the motor voltage, as shown in the circuit diagram of the project you linked to on electroschematics.com.
Re “you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!”, if the LED is wired backwards as shown in your drawing, it won't turn on – which is a good thing, because without a resistor (say 300-3000 Ω) in series with the LED, enough current may flow to damage the Uno or the LED.  Turn the LED around on the schematic (and on your wiring setup if you didn't already), and add a series resistor.

Edit: A comment says, “Don't have a diode either :S Will an LED work instead?”.  LEDs typically have rather low reverse-voltage ratings – 4 to 5 volts.  You could put two or three in series and if they don't burn up you're ok for this experiment.  But in production, don't depend on LEDs as flyback diodes except where it doesn't matter what happens.

Gerben's comment, “What is that capacitor doing there? Slow start?” refers to the 100 μF capacitor shown between transistor base and emitter.  In conjunction with the 1KΩ resistor from D4, that gives RC=0.1 second, so the transistor will take an appreciable amount of time to turn on.  This has a couple of consequences:  PWM control may be less effective (at low duty cycles, PWM depends on short, high-current pulses, to overcome stiction etc) and the transistor will run hotter.  If it's a big power transistor, ok.  If it's a small switching transistor intended for full-on or full-off, no.

Edit: A comment refers to a fan speed controlled temperature page at electroschematics.com.  That page shows a BD139 power transistor, and says the 100 μF capacitor between transistor base and emitter eliminates some motor noise.  Thus it falls into the “big power transistor, ok” category.  Well, more or less ok.  A heat sink may be needed on the transistor and the capacitor probably doesn't need to be that big; eg try 10 μF instead of 100.

An ordinary 9V battery easily supplies a dozen milliamps, but current draw larger than that quickly depletes it.  See eg 9V Alkaline tests at powerstream.com and my answer to a previous question, Using Arduino Micro With 12V Buzzer that's somewhat related.  The motor shown (TD599839) is rated at 35 mA at 5.9 V no-load, so will draw say 50 mA no-load from a 9V battery and will try to draw several times that if loaded; ie it will overstress an ordinary 9V battery.  In brief: Use a wall-wart or equivalent, or a big battery, rather than a small 9V battery when running motors.


Using Arduino as a pc remote controller I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.

My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

Since I can not commemnt due to low reputation, I'm "commenting" here.
You can search for LIRC and WinLIRC


Arduino auto power of circuit possible issue with higher voltage agains output pin? I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.

Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.

As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?

The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/

No.  It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a single external N-Channel or P-Channel device.  The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself.  This is enough to have the processor at least partially on - perhaps not enough to operate, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.

To make this work, you need two stages of switching - two fets are a possibility.

However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power.  These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application.  Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would.  I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.

Given your input voltage, another thing to consider would be using a regulator with an active-high enable input.  But realize that a linear regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.


Problem in reading data from encoder with arduino Hello guys I am trying to count the number of the steps of a stepper motor with an encoder (Avago heds).

I found an Arduino sketch to count that steps and display them on the console and I found online the scheme to connect that encoder to Arduino.

The problem is that the encoder returns as output only 0, even if I rotate manually the motor. I also tried to measure the voltage of the encoder with a voltmeter but the voltage does not change even if I rotate the motor.

That is the Arduino Sketch

Here some picture's of Arduino-encoder connections

P.S. The motor works because I tried it before

Thank you for help

In my experience (industrial encoders and PLCs) when the output don't change when the motor shaft is rotated its usually one of the following:

The set screw connecting the motor shaft to the encoder that isn't tight,
broken wire (bad connection to the encoder) or
a bad encoder.

Your picture shows what looks like a cover over the encoder coupling to the motor.  Look and make sure that the encoder is actually rotating with the motor.

Then double check your connections.  If a DMM still shows no voltage changes (use AC range if turning the motor to show that the encoder output is pulsing).

If there is still no joy, its likely that the encoder is bad.


Arduino nano stopped working After programming Arduino Nano with the DIY Headtracker code, after trying to plug the Arduino to the receiver and some time, the LED stops flashing and now it's not recognized by the computer anymore.

When I plug it, it only lights the power LED.

The worst thing is that I've already tried with another Nano and it bricked also, can't use them any more. Anyone know any fix to this?

This is the error given when trying to upload the blink sketch to the board...

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding

I suggest you visit the page Have I bricked my Arduino Uno? - whilst you have a Nano and not a Uno, it is the same processor and most of the remarks there will apply.

As the Arduino Nano page says:

  It has more or less the same functionality of the Arduino Duemilanove, but in a different package.

If you have another Uno or similar lying around you could conduct the "chip detector" test described on that page. You could also perform the loopback test.

It is possible on the FTDI chip (underneath) is damaged in which case there would be alternatives to using that.


Sending "Blink" to pin 12 is causing on-board led to blink? I recently picked up an Uno clone and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.

Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?

Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.

Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.

int ledPin = 12;
int delayPeriod = 100;

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

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(delayPeriod);
  digitalWrite(ledPin,LOW);
  delay(delayPeriod);
  delayPeriod = delayPeriod + 100;
}

See Have I bricked my Arduino Uno? Problems with uploading to board

As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:

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

See if that changes the behaviour.


Arduino Nano periodic reset under program control? Is there a way to cause a periodic reset of an Arduino Nano under program control, short of some kind of external relay that signals the RST pin?

I'd like to do a full reset triggered by a digital write.

When the power is applied to the Nano it automatically pulls all the digital output pins to LOW so it appears that simply connecting a wire from a digital output to the RST pin would cause the system to continually reset and never run the program.  This would apply equally to using the DS3231 RTC chip's alarm function.  It would require the program to run in order to use it.

I suppose a relay would do the trick.  Or maybe even just an inverter chip like the 7404 between a digital output and the RST pin.  I am trying to fit this all in a small box so more hardware gets to be a problem.

So the question:  Is there any way to do this without external hardware?

Why do you want to reset you board?  The reason affects the answer.

Do you want to reset the board because your program crashes after n hours?  If so its probably better to fix the memory leak that you have in the code.

Is it because some global variables need to resetting every now and again?  If so could you place them in a class and store a pointer to them as your only global.  When you want to 'reset' the board delete the instance of the class and recreate it.

What happens if the software crashes?  Have you got it configured to restart on a crash?  If so could you just crash the code deliberately?

Because you have size constraints then it may be worth a bit of lateral thinking to see what the code can do for you.


integer overflow in expression [-Woverflow] - TinyCircuit I have a tiny circuit Bluetooth shield and I was testing out the sample code that was provided by tinycircuit. However, when I tried uploading the sample code into the board, I kept having the following error. How can I solve this error?

this is the piece of code where there error seems to be happening.

#define  ADV_INTERVAL_MIN_MS  50
#define  ADV_INTERVAL_MAX_MS  100

void setConnectable(void)
{
  tBleStatus ret;

  const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME, 'B', 'l', 'u', 'e', 'N', 'R', 'G'};

  hci_le_set_scan_resp_data(0, NULL);
  PRINTF("General Discoverable Mode.\n");

  ret = aci_gap_set_discoverable(ADV_IND,
                                 (ADV_INTERVAL_MIN_MS * 1000) / 625, (ADV_INTERVAL_MAX_MS * 1000) / 625,
                                 STATIC_RANDOM_ADDR, NO_WHITE_LIST_USE,
                                 sizeof(local_name), local_name, 0, NULL, 0, 0);

  if (ret != BLE_STATUS_SUCCESS)
    PRINTF("%d\n", (uint8_t)ret);

}

You can specify the type of a number using suffixes such as L, LL,
UL and such. If you don't specify the type this way, all integers that
are small enough to fit in an int will be of type int. When you
write

ADV_INTERVAL_MIN_MS * 1000

it gets expanded by the preprocessor to

50 * 1000

Since both arguments are of type int, the compiler will use this type
to compute the result. However, the result is 50,000, and on 16-bit
systems the largest number that can fit in an int is 32,767, thus the
overflow.

As suggested by Majenko, the simple solution is to add the L suffix
(for long) to either operand. The compiler will then do the
arithmetics using the long data type.


Http request in interrupt esp8266 not working So i have this code that whenever i click a button a interrupt starts.
In this interrupt i want to do a get request to a webserver.

The thing is seperate the code, the interrupt code works and without an interrupt the http request also works.
But when i put this together it doesn't.

Does anybody have an idea why this doesn't work?

// Libraries
#include <ESP8266HTTPClient.h>
#include<ESP8266WiFi.h>

char ssid[] = "";
char pass[] = "";

int ledpin = 5; // D1(gpio5)
int button = 4; //D2(gpio4)
int buttonState=0;

ICACHE_RAM_ATTR void ISR() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();

  if (interrupt_time - last_interrupt_time > 200)
  {
      Serial.println("Drukknop ingedruk");
      Serial.println("Sending message to server");
       if (WiFi.status()==WL_CONNECTED)
      {
        HTTPClient http;
        String url="<httpurl>";
        http.begin(url);
        http.addHeader("Content-Type","text/plain");
        int httpCode=http.GET();
        Serial.println(httpCode);
        String payload=http.getString();
        Serial.println("While sending I received this from server : "+payload);
        http.end();
      }
      else
      {
        Serial.println("Internet Problem!");
      }
  }
  last_interrupt_time = interrupt_time;
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);

  while(WiFi.status() !=WL_CONNECTED)
  {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected...");
  delay(1000);
  if (WiFi.status() ==WL_CONNECTED)
  {
    Serial.println("Wi-Fi Connected!");
  }
  delay(5000);
  Serial.println("ok");
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), ISR, RISING);

}
void loop() {

}

Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main loop() function to perform your HTTP request.


Is it possible to connect 2 ultra sonic sensors to 1 arduino? I am currently using the Arduino Pro Micro board and I want to connect 2 ultrasonic sensors to 1 board, whilst knowing which sensor is being triggered. The sensor I am using is a HC-SR04 Ultrasonic sensor.

Please help me thank you :)

Yes, you can, as long as you serialize the send/receive pulse cycles, to avoid interferences.
basically, you attach the Trig/Echo lines to a different pair of pins, then do the reading on one sensor, then do the reading on the other.


Arduino micro lost connection after first programming I have just programmed a new micro, loaded the basic blink code in it. After that neither my laptop, nor my desktop sees it anyway with the following usb error:

Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
[Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
[Fri Apr  1 14:32:03 2016] usb 1-2: USB disconnect, device number 8
[Fri Apr  1 14:32:03 2016] usb 1-2: new full-speed USB device number 9 using ohci_hcd
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62
[Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62

If I push the reset button on it it comes back a bit then disappears again:

22620.495256] usb 1-2: New USB device found, idVendor=2341, idProduct=0037
[22620.495263] usb 1-2: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[22620.495268] usb 1-2: Product: Arduino Micro
[22620.495272] usb 1-2: Manufacturer: Arduino LLC
[22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[22627.966141] usb 1-2: USB disconnect, device number 32
[22628.432089] usb 1-2: new full-speed USB device number 33 using ohci_hcd
[22628.572111] usb 1-2: device descriptor read/64, error -62

Anybody experienced this? I have tried to reconnect it multiple times to both computers, even tried a new cable doesn't help.

The USB part of the Atmega32U4 needs quite a bit of software to operate correctly, which is either not included in the basic blinky example or you got a binary for a different Arduino model.

The syslog looks like there is a bootloader present after Reset for a couple of seconds..

[22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
     ^
[22627.966141] usb 1-2: USB disconnect, device number 32
     ^

.. which shuts down and starts blinky. This is documented on the ArduinoBoardMicro page.

Re-flashing the chip is a bit tricky in this state, as you must press the reset button at the "right" time just before the software wants to access the chip.


How to code an arduino to execute a particular code using a slide switch I’m pretty new to arduino. I need help concerning a project I’m making. I’m using a SPDT slide switch to switch between what code(method) should be executed.i.e when I shift the switch to the left, XXX method should be executed and when I move the switch to the right, YYYY method should be executed. The center pin of the switch is connected to arduino +5v while the     left and right leg of the switch are connected like how a tactile switch is interfaces with the arduino. Please can anyone help me with the code, or at least how to program the arduino? Thank you

Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.

You effectively have:

simulate this circuit – Schematic created using CircuitLab

However you are over complicating things.  A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time.  If one is pressed the other must be released.

You can completely ignore half the switch and treat the other half as a button: if the "button" is pressed then the switch is in one position. If the "button" is released then it's in the other position.

Unless it's a "center off" switch, in which case it has 3 positions, not 2, and the middle one has nothing connected.

If it is a simple 2-position SPDT switch then just disconnect the D12 wire and remove the right-and resistor in your drawing. Then read D13 to determine the position: HIGH is one position and LOW is the other.

If it's a 3-position "center off" switch then move the D12 wire 4 holes to the left so that it connects to the switch-resistor junction, not ground. Then you will need to read both D12 and D13 - which ever one is HIGH is the one that is activated, and the switch is in that position.

Then it's a simple "if / else" (2 position) or "if / elseif / else" (3 position center-off) structure to decide which code to run.


comprehensive list of common library methods that do not work in interrupt service routines Where is a comprehensive and authoritative list of commonly used library or built-in methods (functions) that do not work properly in Arduino interrupt service routines?

I am aware of the following:

do not use delay()
do not use Serial print methods

which are part of Nick Gammon's advice linked here. His TLDR summary is:

  TL;DR :

  When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be
            protected by "critical sections" (see below)
Don't try to turn interrupts off or on

however, I am looking for, as I said, a list that is more comprehensive and authoritative.

The basic rule is quite simple, but the list is practically impossible to produce.

The rule is:

You cannot use anything that relies on an interrupt to function from within an interrupt service routine.

AVR chips only have one interrupt priority. Only one interrupt routine can function at a time. If an interrupt fires whilst an ISR is currently executing that interrupt will be delayed until the ISR finishes.  If that ISR relies on a function that itself needs an ISR to fire (such as millis(), or serial transmission), then it will never get to finish.

A partial list of things to know:

You cannot transmit serial more than there is room in the TX buffer for, or it blocks.
The time generated by millis() (which delay() relies on) never changes.
Servo motors cannot be controlled and will jitter if an interrupt routine takes too long.
tone() generated sounds will also jitter since the ISR is delayed while another ISR is executing

And basically anything else that uses interrupts.


Large number into variable Probably something easy but I’ve not resolved it.

I’m extracting data from a JSON string and all the values are correct accept for two.

They are referring to two date time values and are in milliseconds.

One is the date refreshed and the other is date updated.

Problem is they are both very large and I’m having difficulty assigning them in the IDE.

One is 1588447162117 which is showing as 020-05-02 20:19:53.948  on the dashboard using the JSON.

Here is the code I have thus far to get the data from JSON:

#include <ArduinoJson.h>

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

  const char* input = "{TotalCases:3308678,TotalCasesToday:4458,TotalDeaths:234123,TotalDeathsToday:293,TotalRecovered:1042991,TotalTerritories:124,CurrentUpdatedMS:1588312648603,CurrentChangedMS:1588312648603}";

  StaticJsonDocument<512> doc;

  DeserializationError err = deserializeJson(doc, input);

  if (err) {
    Serial.print("Error: ");
    Serial.println(err.c_str());
    return;
  }

  unsigned long TotalCases = doc["TotalCases"];
  unsigned long TotalCasesToday = doc["TotalCasesToday"];
  unsigned long TotalDeaths = doc["TotalDeaths"];
  unsigned long TotalDeathsToday = doc["TotalDeathsToday"];
  unsigned long TotalRecovered = doc["TotalRecovered"];
  unsigned long TotalTerritories = doc["TotalTerritories"];
  unsigned long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
  unsigned long CurrentChangedMS = doc["CurrentChangedMS"];

  Serial.print("Total Cases: ");
  Serial.println(TotalCases);
  Serial.print("Total Cases Today: ");
  Serial.println(TotalCasesToday);
  Serial.print("Total Deaths: ");
  Serial.println(TotalDeaths);
  Serial.print("Total Deaths Today: ");
  Serial.println(TotalDeathsToday);
  Serial.print("Total Recovered: ");
  Serial.println(TotalRecovered);
  Serial.print("Total Territories: ");
  Serial.println(TotalTerritories);
  Serial.print("Update time in ms:");
  Serial.println(CurrentUpdatedMS);
  Serial.print("Change time in ms:");
  Serial.print(CurrentChangedMS);
}

void loop()
{

}

**Serial monitor output**

Total Cases: 3308678
Total Cases Today: 4458
Total Deaths: 234123
Total Deaths Today: 293
Total Recovered: 1042991
Total Territories: 124
Update time in ms:0
Change time in ms:0

Should be good to manipulate it once I can work with it in a variable.

Thanks for any input,

Shane

I didn't try myself, but just by looking at the docs I suggest you try:

Adding

#define ARDUINOJSON_USE_LONG_LONG 1

at the top of the sketch, before including ArduinoJson.h.

Declare CurrentUpdatedMS and CurrentUpdatedMS as either
unsigned long long or uint64_t.

Edit: To answer the question in the comment:

  When you said you looked at the docs where did you check?

I had to follow a (not so simple) path: Deserialization tutorial →
JsonDocument::operator[] → JsonVariant →
JsonVariant::as<T>(). This last page states that the method
as<unsigned long long>() “may require ARDUINOJSON_USE_LONG_LONG”.
Unfortunately, the macro is not linked, so I have to search for it and
found ARDUINOJSON_USE_LONG_LONG.


AT 09 BLE module not transmitting data I have recently started working with the Arduino Pro Mini 5v/16Mhz and an AT 09 BLE module for an IoT project. I am controlling the BLE module using Software Serial and am leaving the hardware serial for for my laptop. I am using an app called "Serial Bluetooth Terminal" on Android to send/receive messages. The BLE module is able to receive messages and the "AT" command is also working. But when I try to get the BLE module to send a message, I get no response in the app. Any idea why this is happening and how can I resolve it?
My connections are:

Laptop -> Arduino UNO, MB-102(USB to breadboard power adapter)
Arduino UNO(without IC) Rx -> Pro mini Tx0
Arduino UNO(without IC) Tx -> Pro mini Rx1
Arduino UNO(without IC) RESET -> Pro mini Rst
MB-102 5V -> Pro Mini Pin RAW
MB-102 GND -> Pro Mini Pin GND
Pro Mini Pin 2 -> AT 09 TXD
Pro Mini Pin 3 -> AT 09 RXD
Pro Mini Pin VCC -> AT 09 VCC
Pro Mini Pin GND -> AT 09 GND

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

SoftwareSerial ble(2, 3);

int statePin = 4;
char c;
void setup()
{
  Serial.begin(9600);
  ble.begin(9600);
  ble.print("AT\r\n");
  delay(100);
  while(!ble.available())
    Serial.print(".");
  while(ble.available())
  {
    Serial.print(char(ble.read()));
  }
}

void loop()
{
  while(ble.available() > 0)
  {
    c = char(ble.read());
    delay(10);
    Serial.print(c);
    ble.print(c);
  }
}

This is the first time I am posting here so please tell me if I missed out on any information.

So my AT 09 module is most likely faulty. I got a new HM 10 and connected it without changing any connections or code and it worked like a charm.
I do not know the exact nature of the defect but since the chip was responding to commands, I think the PCB might have been damaged.


wrong leds lit in matrix display - wrong coding? I wrote the following code for displaying a bitmap (small size) on a  LED matrix (formed using APA102 led strip):

//for 24-bit bitmaps

// the header files for the RGB data

 #include <FastLED.h>
 #include "redarray.h"
 #include "greenarray.h"   //g data header file (hex or dec)
 #include "bluearray.h"   //b data header file (hex or dec)*/

//matrix parameters

#define MatrixWidth 36 //columns
#define MatrixHeight 7 //rows
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

 void setup() {

     FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
     FastLED.clear();
  }

void loop() {

  for(uint8_t x=0 ; x<MatrixWidth ; x++)  {

      for(uint8_t y=0; y < 3; y++) {

            leds[XY (x, y)].setRGB(redarray[x][y],greenarray[x][y],bluearray[x] [y]);

           FastLED.show();

           delay(1);
         }
      }
   }

      uint16_t XY( uint8_t x, uint8_t y)
 {
   uint16_t i;

     if( MatrixSerpentineLayout == true) {
       if( y & 0x01) {
        // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
     } else {
       // Even rows run forwards
          i = (y * MatrixWidth) + x;
    }
   }

  return i;
}

The following is the data in one of the header files - its of same type for the other two colors.

const unsigned char redarray[36][3] PROGMEM  = {
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x20, 0x20, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00,
};

The matrix is in a serpentine form (evident from the XY function in code). I am using an Arduino Due. The problem is that the code compiles and runs...but the bitmap is incorrect. Although I am sure, I am somewhat along the correct path because some LEDs do light up as they should as per the bitmap. But most of them are wrongly lit.

Could you somebody plz guide where I am going wrong with the coding? I fear there is some mistake in reading the color data from array and allocating it to leds[XY(x,y)].I do not know how a 2D array is read or dealt with by Arduino.

Thanks!

Initialize your arrays like this:

int a[3][4] = {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

...you can read more about it here.

Added later...

The following explanation came from here:

Arrays that are not explicitly divided into rows:

int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

...are filled like this:

int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};

As only you understand your data you will have to verify if your data is populating the array as you expect.


Arduino Due ICSP location I am making a shield for Arduino Due. It will be a simple board with ribbon connectors for taking a variety of interfaces to external boards. It will be Open Source hardware.

I have been searching for about 3 weeks for a drawing or layout that will allow me to locate, mechanically the ICSP connector. I have downloaded about 100 drawings and none of them seem to locate it.

I downloaded KiCad and installed it on Win7 thinking that I could find the needed info there from existing KiCad shields. I can't get KiCad to "do anything" once it opens.

I downloaded free Eagle and installed it on Win7 thinking that I could find the needed info there from existing Eagle shields or the Eagle files for the Due board itself. When I try to run Eagle, it instantly crashes.

I have even visited and joined EasyEda and looked at shield projects there, but I do not find any that locate the ICSP connector.

The "Bombsightings" jpg that I got from this forum is great BUT, no ICSP location data.

Any help will be much appreciated !

The SAM3X series MCUs, not being AVR MCUs, do not have AVR ISP connections. Like most ARM MCUs, they use JTAG for programming and debugging. On the Due the JTAG lines on the MCU are connected to the 10-pin microheader near the reset button.


How does Arduino WiFi Shield connect to Blynk and How can I use ESP Module to connect to blynk? I was actually quite impressed how easily Blynk gets connected to Arduino. So I had a doubt how does Arduino WiFi Shield allow Arduino Uno to connect to blynk ? And my second doubt is how can I use the ESP boards to connect to blynk using Windows10 ( for steps ) ?
Thank You.

how does Arduino WiFi Shield allow Arduino Uno to connect to blynk

Blynk is just a web service. The WiFi shield connects your board to the internet and sends data to that web service. The Blynk app is just an interface to that web service.

  how can I use the ESP boards to connect to blynk using Windows10?

That makes no sense. You can connect an MCU to Blynk through something like an ESP8266 board (or program the ESP8266 board directly to communicate with Blynk). It is merely a network interface.

Windows 10 is not an MCU, and you already have an internet connection on it. If you want to communicate with Blynk from Windows 10 I suggest you look at the documents to see if there is an API you can use from your own programs, or a web interface you can view in your browser of choice.

Windows 10 and ESP8266 are two completely alien concepts.


Unable to send UDP packets while performing OTA update on the esp8266 I am sending specific UDP packets with my esp8266 every 5s, I have added an OTA update command, and added the update_progress callback aiming to send it back to my laptop, using a serial terminal I noticed that regular packets, as well as the progress packet, are not sent during the update, everything gets back after. Is the esp able to send and receive packets simultaneously?, is there any interference or the OTA update process causes an interruption?
Hardware: ESP8266MOD Nodemcu
Software: VS code with portable Arduino 1.8.9, espcore 2.6.3

esp8266 ArduinoOTA library has
  WiFiUDP::stopAll();
  WiFiClient::stopAll();

to ensure undisturbed OTA upload


Digital Vs. Analog Sensor Background: I'm using an Atmega1284P to add sensors to an off road racing truck onto a CANBUS network. The standard automotive sensors are thermistors, but the Dallas 1 wire temp sensors (DS18B20) with an integrated ADC caught my eye. They don't, however, come in a package that would work for my purposes so I would have to build one. I haven't been able to find one waterproofed in an NPT fitting with only a 1" probe length.

My question: how much more accurate would the 1 wire be over a thermistor?
How much of a difference would it make for processor efficiency to not have to do the math involved with thermistors and just read the value from the 1 wire? I don't mind building them, I just want to make sure they're worth it first.

To make an informed decision you first need to understand a few basic concepts and some pros and cons of each system.

Firstly there are the concepts of precision and accuracy. These are two very different properties and each is important in their own way. On the face of it they may sound the same, but they aren't.

Precision

This is how close to the real value your measurements are. This is the "±"  value that datasheets list. It's how close a match to the actual temperature the measured temperature is.  So a ±0.5° measurement could be anywhere within half a degree of the actual temperature.

Accuracy

This can also be considered as the resolution of the measurement. It is how fine a difference in temperatures the device is able to measure. For instance you may be able to detect 0.0125° differences.  This is mostly defined by the resolution of the ADC in the device.

And now the pros and cons:

Digital

Pros

These devices can be factory calibrated for a more precise reading. The accuracy is usually pretty good too, but is fixed by the design of the device. Communication is generally reliable and wire length doesn't generally affect the values reported.

Cons

Communication protocols can have some large overheads limiting the number of samples you can take per second (not just on one sensor but across the whole array of sensors). Excess EMI noise (especially from engines) can corrupt the communication signals over long connections unless extra care is taken (such as implementing a balanced line communication medium).

Analog

Pros

Very simple to connect up and samples can be read very rapidly. Accuracy is determined by the ADC you choose to use.

Cons

Wire length can have a detrimental affect on the values read unless special wiring and sensor schemes are used to cancel out the resistance of the wires. Noise induced into the wires is very hard to detect or cancel out and can give spurious results. Requires more complex mathematics to calculate a resistance.

Summary

So in short: Digital can give you more reliable communication of your sampled values over longer distances but at the cost of reduced sampling speeds.


How many PIR Motion Sensors can I connect to my Arduino-Uno R3? I am doing a school project where I intend to measure the cafeteria line with motion sensors and the send that information with a WiFi module to a server. This is my first time using Arduino and I am not sure how many motion sensors does it support.

Most PIR sensors provide a simple relay output. That means they are nothing more than a switch as far as the Arduino is concerned.

You can connect hundreds of switches to an Arduino. With judicious use of diodes and a matrix arrangement you can hundreds with not many IO pins.  For example an 8x8 matrix of switches gives you 64 PIR sensors with just 16 IO pins.  For n pins you can have (n/2)² switches with a balanced (n/2 by n/2) matrix.


Read Voltage at PWM off time, and Current at PWM on time For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read_ADC_Voltage() during the LOW time, and read_ADC_Current() during the HIGH time.

Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.

Add a pin-change-interrupt (PCI) handler (See eg PinChangeInt at arduino.cc); clear the flag and enable the interrupt whenever you want to take readings, and disable that PCI after you have the reading.  As noted in the link, PCIs are available on all signal pins (possibly not on A6 and A7 on the 328), so are available on any of the PWM pins.