Timer2 does not work as it should I am currently playing with Arduino timers (on UNO currently) and I am building a library that  has a function that must be called every millisecond.

There is plenty of code samples on Internet so I went with something that seemed perfect for my needs. I have then updated it to make it a reusable C++ class.

Here is my code (simplified to just isolate the issue):

#define BIT(x) (0x01 << (x))

static volatile uint32_t milliseconds = 0;

class Timer
{
    public:
    Timer()
    {
        // Disable interrupts
        uint8_t savedStatus = SREG;
        cli();
        // Use Timer2 with 1 ms interrupts
        // OC2A & OC2B disconnected, mode 2 (CTC, Clear Timer on Compare match)
        TCCR2A = BIT(WGM21);
        // Don't force output compare (FOCA & FOCB), mode 2, Clock Select clk/128 (CS = 5)
        TCCR2B = BIT(CS22) | BIT(CS20);
        // Set timer counter compare match (when value reached, 1ms has elapsed)
        OCR2A = 125 - 1;
        // Reset Timer2 counter
        TCNT2 = 0;
        // Set Timer2 interrupt mode (Set interrupt on OCR2A compare match)
        TIMSK2 = BIT(OCIE2A);

        // Restore interrupt enabling state
        SREG = savedStatus;
    }
};

static void callEveryMillisecond(uint32_t ms)
{
    // Do something here
}

// Attach interrupt routine to the Timer Compare Interrupt
ISR(TIMER2_COMPA_vect)
{
    milliseconds++;
    callEveryMillisecond(milliseconds);
}

After checking ATmega328 datasheet (section 17) several times, I came to the conclusion that what I do in Timer class constructor above is correct, and for Arduino UNO, the values used must lead to one call of the ISR every ms:

CPU frequency = 16MHz
Prescaler = 128
-> timer frequency = 16MHz/128 = 125KHz
-> max counter value = 125

I decided to use the CTC (Clear Timer on Compare match) mode, which means that when the timer TCNT2 (which is incremented at 125KHz frequency), reaches OCR2A value, then it will trigger the ISR, and then will be reset on next tick; the additional tick to reset the counter explains why we use 125 - 1 for OCR2A and not just 125.

Now comes the weird stuff. In order to check that my code worked, I decided to blink the LED on pin 13 every 10 seconds, hence I have added the following code to my program:

static void callEveryMillisecond(uint32_t ms)
{
    if (ms % 10000 == 0)
        digitalWrite(13, digitalRead(13) ^ 1);
}

static Timer timer;

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

void loop()
{
}

Then I measured the time during which pin 13 LED is lit on (or off, both measures are the same). Measures are not very accurate (I just used my wristwatch) but good enough for my check.

I was surprised to see the measured time to be about 20 seconds instead of 10s.

Initially I thought about a mismatch in CPU frequency, but after performing a lot of small changes, here is what I found which worked perfectly:

//static Timer timer;

void setup()
{
    static Timer timer;
    pinMode(13, OUTPUT);
}

Just moving the Timer instance into setup() did the trick: my measures rightly indicated 10 seconds between 2 states of the pin 13 LED.

Now my questions are:

Why the second code sample works perfectly, whereas the first does not?
Is there, in standard Arduino included code, some code that would overwrite some of the settings I perform for Timer2 in Timer::Timer()?
Is there a way to make the first code sample work? Note that I don't like the second sample because it does not seem natural coding, also, I will need access to Timer timer instance in several locations of my future program, hence it can't be possible if it is declared in the scope of setup().

I have located the source of the problem.

In file wiring.c (arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino) which gets called before setup(), there is the following part that tries to changes the timer 2 prescaller to 64 by setting the CS22 bit.

// set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

You already set CS20 and  CS22 so this doesn't affect you. What does affect you is the following part which sets bit WGM20

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
#else
    #warning Timer 2 not finished (may not be present on this CPU)
#endif

and you have already set WGM21 so WGM21 and WGM20 set changes the timer mode to fast PWM , top=0xFF which gives almost double delay that the mode you were trying to use (CTC top=124).

How to workaround this issue?

Timer2 is used when its associated PWM pins are used with an analogWrite() call, so the Arduino setup code sets all prescalers to well-defined values just in case the timers might get used later.

I would not try to fight that code; instead, I would just make sure that my setup code runs later, e.g. by moving it to a separate setup() method in your Timer class and calling that from the global setup() routine.


ESP8266 with Arduino Uno - Problem with AT+CIPSEND The strange fact that we are facing is, the AT command is now accepting the URL and parameters provided (earlier we were coming across "Error: 400 Bad Request"), but the URL is NOT HIT even after \n being included in the command. We are clueless at the moment on how to HIT the URL as it's the API which is going to increment the counter in the database, which is not happening even after successful command execution.

AT+CIPSTART="TCP","www.mydomain.com",80

**CONNECT**
**OK**

AT+CIPSEND=115

OK

GET /api/mywebapi.php?param1=01\r\nHTTP/1.1\r\nHost:mydomain.com

**busy s...**

**Recv 115 bytes**

**SEND OK**
**CLOSED**

** Denotes output of the AT commands.

Your GET is incorrect. You have a CRLF between the GET and the HTTP. It should just be a space.

GET /blah/blah/blah HTTP/1.1\r\nHost: BlahBlah.com\r\n\r\n

Of course the \r\n shouldn't be those specific individual characters, but the ASCII codes 13 and 10 respectively, so printing each line with Serial.println() instead of inserting \r\n might be better.


Can the SPI pins of an Arduino be separated from SPI? Are the SPI pins on the ICSP header of an Arduino Uno "separable" from the correspondent I/O pins - when one chooses to the use the ICSP header can the corresponding I/O pins be used for something else?

No.  Those pins are not separate on the microcontroller itself.  If you need to use SPI and still need more pins you may use analog inputs as digital inputs or outputs.  Otherwise you'll probably have to use an expander of some sort, or use a Mega or Due for additional inputs or outputs.


Serial input values only working for very short seconds I just made a very basic circuit with a LED and a resistor. I also wrote a program that's supposed to take an input for how long to keep the LED on for. It works fine for shorter times like 10 seconds but as soon as I try to input a time like 120 seconds the LED never turns off.
My code's below. What could be wrong?

int light=9;

void setup() {
  Serial.begin(9600);
  pinMode(light, OUTPUT);
  }

void loop() {
  Serial.println("How long do you want the light on for (in seconds)?");
  while(Serial.available()==0){}
  int on_time = (Serial.parseInt() * 1000);
  digitalWrite(light, HIGH);
  delay(on_time);
  digitalWrite(light, LOW);
  Serial.print("The light was just on for ");
  Serial.print(on_time/1000);
  Serial.print(" seconds. ");
}

If you add Serial.println(on_time); right after int on_time = (Serial.parseInt() * 1000); you will see the problem. Once you enter the number 33 for example, the integer value printed is -32536. The Allowed data type for delay() is unsigned long, so the negative number is causing a problem.

Using Serial.println() judiciously can be very helpful when you are trying to debug a sketch.


Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter? This is the first time that I realized that extra SMD IC near the USB port of the Arduino UNO is actually a fully fledged microcontroller, I thought that it was just a USB to Serial converter. Further research into this chip left me with more questions than answers.

First of all, why did Arduino decide to use the Atmega16U2 as a USB to Serial converter? Couldn't they have gone with an FTDI chip instead? I came across this phrase on Quora "The best part is that you can also program and create your own applications on the 16u2 if you have an In-circuit Serial Programmer". How exactly does this work?

What about the two other set of connectors on the board? (other than the two main rows of headers) The ones labeled ICSP and JP2? Is the JP2 for the 16U2? I read that these could be used for burning the code onto the Atmega328P so that it can be modified, but not overwritten. What are any other uses for the 16U2 on the Arduino UNO?

First reason I'd guess is price:

FT232 on octopart: USD2.65 ~ 3
Atmega16U2 on octopart: USD2.12 ~ 2.2

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).

About the programming:

There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: 1, 2, 3. I've used the second one I think, and it works fine.

You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or Arduino ISP.

Use the ISP pins by the Atmega16U2:


Performance of internal vs external resistors Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like this and this. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated here.

Is there any good reason to complicate your design with an extra resistor?

If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.

There are a number of factors to consider.

If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).

If the pin is used as both input & output the pullup can reduce the voltage swing.

In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.


Will it work ? MPU6050 Gyro etc. etc. module Will this code read the values properly ?
Using MPU6050.h.

#include <MPU6050.h>
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin();
  MPU6050.initialize();
}

void loop() {
  MPU6050.getWaitForExternalSensorEnabled();
  float X = getRotationX();
  float Y = getRotationY();
  float Z = getRotationZ();
  Serial.print("X:");
  Serial.println(X);
  Serial.print("Y:");
  Serial.println(Y);
  Serial.print("Z:");
  Serial.println(Z);
}

Please be patient. I know nothing about gyroscope's working.
I'm stupid.

Code would normally look like this

#include <MPU6050.h>
#include <Wire.h>

MPU6050 mpu;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  mpu.initialize();
}

void loop() {

  //what is this doing for you?
  mpu.getWaitForExternalSensorEnabled();

  if(mpu.getIntDataReadyStatus() == 1) {
        float X = mpu.getRotationX();
        float Y = mpu.getRotationY();
        float Z = mpu.getRotationZ();
        Serial.print("X:");
        Serial.println(X);
        Serial.print("Y:");
        Serial.println(Y);
        Serial.print("Z:");
        Serial.println(Z);
  } else
  {
        Serial.println("MPU not ready");
  }

}


Arduino WiFi shield working intermittently, "WiFi Shield not present" I am trying to use the official arduino wifi shield, It works occasionally, but most of the time (when running the WiFi web server example code, or my derivitave program, it outputs WiFi shield not present on the terminal. I have tried updating the firmware several times, but it has not fixed the problem. Is the wifi shield always this unreliable? What can I do to fix it?

Be sure the shield is not shorting out on the metal USB socket on the Arduino board. I don't know if this is still an issue but I've seen many Arduino boards with black electric tape on the top of the USB socket to insulate it from shorting out the shield.


H Bridge for microcontroller power management? Is it fine to use L298 N Dual H Bridge Stepper Motor Driver Module to control power of other ICs in a multiple microcontroller setup?

I intend to reduce power consumption in by powering communication ICs through the H bridge to allow switcching them off if not needed. Does a L298 based H bridge module like shown below supply clean stable DC current to someting like the ESP8266?

Module shown below contains condensators, i assume to reduce ripple effect created by L298.

While it may be possible to bend one of those to your proposed usage, it's far from ideal, for a number of reasons:

It's far more expensive than the single P-FET that you need to get the job done
It's risky: you can easily reverse the current through your components and blow them up
It imposes a ground offset which can cause you communication problems.

All you need is a single P-channel MOSFET (assuming you are switching 5V with a 5V logic signal) and a single resistor (10kΩ would be fine, but any large value is ok).

simulate this circuit – Schematic created using CircuitLab

Pull the GPIO LOW and the power switches on. As simple as that.

If you want to switch a higher voltage then simple use an N-channel MOSFET to pull the GPIO line LOW for you - which you then switch with your GPIO signal.


Use lowpower-libary and still use serial connection and other things I managed to get the LowPower libary working on my Arduino Micro. This code works perfectly:

#include <LowPower.h>

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

However. I also tried it with a serial connection, to put out some text periodically. But I think the lowpower-libary does - in order to save power - disable this function. So now I am worried that it also disables some other things I might have to use but won't work. Like OneWire or I2C. It also would be nice to work with a functioning standby-mode while developing where serial output is vital, altough it's not neccessary, because I can simulate it with a simple delay. So my question is: How can I use the lowpower-libary AND have a serial connection. And will this libary affect OneWire or I2C? If so: Is there a way on how to keep these "services" running? Or is there maybe another libary wich also saves power in a similar way, but where you have more abilities to customize what you want to have shut down?

Yes, activating low power does disable the UART - but only while it's sleeping.

To use serial you just need to ensure that you only use it while it's not sleeping - and due to the interrupt and buffered nature of the Serial driver it's not as easy as just printing.

However, it's simple to achieve: just flush the serial before sleeping. This ensures that any pending serial data is sent out through the serial port before you go to sleep:

void loop() {
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

If that doesn't help you may need to turn serial off and on yourself either side of your powerdown:

void loop() {
  Serial.begin(115200);
  Serial.println("Turning LED on");
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                      // wait for a second
  Serial.begin(115200);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  Serial.flush();
  Serial.end();
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);                  // wait for a second
}

Update:

I just noticed you're using the Micro. That makes a big difference. The Micro and the Leonardo's Serial object is actually a USB CDC/ACM serial emulation, not UART.  You cannot sustain a USB connection while sleeping. So it will be killed.

To use communication while sleeping you will have to switch to a proper UART connection with a USB to TTL UART (e.g., FT232RL) adaptor to connect to the TX/RX pins and use Serial1 instead.


IR trouble with raw buffer I am attempting to send a RAW IR code using the IRremote.h library.  The process for capturing IR pulses is easy to find on the web, but the process for sending them again is not.  After a few days, i pieced the following code together:

#include <IRremote.h>
 IRsend irsend;

void setup() {

}

void loop() {

  int IRsignal[] = {

// ON, OFF (in 10's of microseconds)

    90, 86,

    174, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 174,

    88, 86,

    174, 88,

    86, 2340,

    88, 86,

    174, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 88,

    86, 174,

    88, 86,

    174, 88,

    86, 0};

      irsend.sendRaw(IRsignal, 10, 38);

      delay(1000);

}

When I run it, i get the following error:

  ir_test.ino: In function 'void loop()': ir_test.ino:65:38: error:
  invalid conversion from 'int*' to 'unsigned int*' [-fpermissive] In
  file included from ir_test.ino:3:0:
  /Applications/Arduino.app/Contents/Resources/Java/libraries/RobotIRremote/src/IRremote.h:143:8:
  error:   initializing argument 1 of 'void IRsend::sendRaw(unsigned
  int*, int, int)' [-fpermissive]    void sendRaw(unsigned int buf[],
  int len, int hz);
          ^ Error compiling.

I am not sure what I did wrong, or how to convert the data types.  Any tips or ideas?

Use unsigned int IRsignal[] instead.

Also, your array is 48 items long, not 10. So irsend.sendRaw(IRsignal, 48, 38);


Unable to alter SPI speed on Arduino Micro I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

unsigned int m_SPISpeed = 400000;
SPI.begin();
pinMode(m_SPISelect, OUTPUT);
m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
...
SPI.beginTransaction(m_SPISettings);
digitalWrite(m_SPISelect, LOW);
SPI.transfer(regAddr | 0x80);

Where m_SPISpeed is 400000. No matter what i set this value to it is always operating at 125000Hz.

As was pointed out in the question comments, your use of unsigned int is the problem. The prototype for SPISettings is:

SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

The comments in spi.h say:

// We find the fastest clock that is less than or equal to the
// given clock rate. The clock divider that results in clock_setting
// is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
// slowest (128 == 2 ^^ 7, so clock_div = 6).

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).


HTTP get request using Arduino Uno and ESP8266 I have an Arduino Uno and an ESP8266 and I want to send a HTTP get request to google.com and print the response.
Please help me thanks.

You can use ESP8266Wifi Arduino Library.

Here an example:

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

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://www.google.com");  //Specify request destination
    int httpCode = http.GET();     //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload

    }

    http.end();   //Close connection

  }

  delay(30000);    //Send a request every 30 seconds

}


What is the variable pot exactly for in arduino sensors boards? I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.

Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.


How to prevent breaking my Arduino by mistake? What is the best practice to make my Arduino circuit more robust against prototyping mistakes (like shorting pins)? I don't want the controller to release its blue magic smoke while experimenting with it, what precautions can I make while designing a circuit?

Not best practices, but an alternative approach:

Consider the Ruggeduino instead of a standard Arduino. At a price ($39.95) comparable with the equivalent Arduino, the Ruggeduino offers:

Resettable fuse on each GPIO pin, i.e. all GPIO pins are protected from short-circuit to ground or other pins
All GPIO pins withstand 24 Volts
Reverse voltage protection (-30 V) on Vin
Microcontroller overcurrent protection
3.3V and 5V outputs on the board are over-current and short-circuit protected

Besides the above points specific to the question, the boards are designed to survive harsh environments and various mistakes. Also, the clock is more precise than on the Arduino.


Selling a product using Arduino microcontroller or bootloader I was wondering if I am legally allowed to sell an Arduino based product.  I also want to know if it is easy for people to retrieve code from an Arduino based circuit (reverse engineer it) or upload code from Arduino microcontrollers.

If I'm posting in the wrong please, please let me know. If there is better place to redirect my question, letting me know would be helpful too.

The Arduino hardware is released under the creative commons license.

https://www.arduino.cc/en/Main/FAQ#toc3

"which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license"

It's possible for someone to retrieve the instructions from the MCU but they would be looking at assembly rather than the c code you wrote your sketch in.

This is a similar question and answer:
https://electronics.stackexchange.com/questions/67030/can-arduino-be-used-in-commercial-products


How do I call functions sequentially without using the Delay function? I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;

void loop() {
  currentMillis = millis();

  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
}

void colorWipe(uint32_t c, uint8_t wait) {
  if (currentMillis - previousMillis >= 200) {
    for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
      previousMillis = currentMillis;
    }
   Serial.println("Done");
  }
}

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

I'm assuming you want to run each colorWipe for 200 ms, one after another.

You need a state machine to timing each colorWipe, like this:

void loop()
{
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            colorWipe(strip.Color(255, 0, 0), 50); // Red
            state++;
            break;

        case 1 :
            colorWipe(strip.Color(0, 255, 0), 50); // Green
            state++;
            break;

        case 2 :
            colorWipe(strip.Color(0, 0, 255), 50); // Blue
            state++;
            break;

        case 3 :
            colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
            Serial.println("Done");
            state = 0;
        }
    }
}

void colorWipe(uint32_t c, uint8_t wait)
{
    for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        //delay(wait);
        Serial.println("Light");
    }
}

In each loop you will be waiting 200 ms before doing anything. When the times comes, you will enter the if with state==0 and you will execute the first 'colorWipe'. After that, you advance the state by adding 1 to state variable.

Then you will be entering loop and doing nothing for another 200 ms. When that time pass, you will enter the ìf with state==1. Now the second colorWipe will be executed.

When the last colorWipe is executed, you set state to zero and begin again.


Checking connection/ communication Can I ping or “hello world” an Arduino.
Background:  My son and I bought a 3-D printer kit.
(EZ-3D)

We are having some issues talking with it.  (Well we can't talk at all.)  So we thought to upload the firmware,

It’s an Arduino Mega 2560, and when we upload the Arduino times out… but it takes a minute or two.  Can I try some simpler program just to try and talk to the Arduino?

I’m almost a “virgin” Arduino user so be gentle.

Adafruit has a good set of guides to getting started with arduino:
https://learn.adafruit.com/series/learn-arduino

The "Blink" program is the equivalent of "hello world".

When testing you probably should disconnect the Arduino from the 3D printer.


Seeking help - Using CJMCU 8*8 LED matrix with arduino The CJMCU 8*8 LED board is a grid of 64 W2812 (addressable) LEDs. The board is configured as if it was one long LED strand (just a single  DIN, 5v and GND). For some flipping hair pulling reason, my code works fine on 2812 LED strands, but I get nothing on the board. Just random flickering when I jostle the 5V wire. Any ideas? Am I completely missing something here? Pretty sure the board is fine, just can't seem to take any input...

(Here's a link to the board: http://www.aliexpress.com/store/product/CJMCU-64Bit-WS2812-5050-RGB-LED-Development-Board-Built-in-RGB-Driver-White-SKU-11481/933826_32249197598.html)

I just received 2 of these from 2 different suppliers on EBAY.
None work using the pins called [GND +5V DIN]. As it turns out the DIN is actually NOT DIN. The other connector area [GND +5V DOUT] is the DIN. Ugh!

These boards are marked CJMCU-8*8 on the back side and on the front they say "WS2812B-64 RGB LEDS". Which is another issue. They are using the 6 pin WS2812, not the 4 pin WS2812B.

So if this is what your board looks like then perhaps try the pin marked DOUT for your DIN. Or try to psych out the traces to make sure first.


Op Amp Understanding + Holiday Lights Tutorial I am following Jeremy Blum's tutorial for Holiday Lights: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds

I am just trying to set up the circuit for one of the audio channels. I believe I followed the breadboard schematic. However, when I connect the Arduino the power, but without any audio input, the LED lights up. I would've thought that would not be the case.

Can someone help me correct my understanding here? Thanks.

Image of my breadboard: http://postimg.org/image/ibqfvezqp/

Per Jeremy Blum:

  If the input doesn’t have a audio input plugged in, then it’s said to be “floating” and you >can’t really count on the circuit to do what you would expect. The audio input connection >introduces a known voltage (0 when no sound is playing) connection between the positive op->amp input and GND that we then amplify. Try connecting the input to GND and you should see >the LED turn off.

Source: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds/comment-page-2/#comment-1373392


Programming stepper motor move a fixed step till it reach the target I have a stepper motor and try to program it like this but I kinda stuck since I'm new to Arduino.
1. The target is set to 2048, means motor have to move 2048 steps.
2. I program the motor to run 200 steps each time, every 200 steps will stop for a sec until it reach 2048.

I've been using AccelStepper library to program my motor, I found out it is very hard for me to program like this. I'm not asking to do my homework but I dunno where to start. Just wanted to ask what method can I use to program the motor to work like this. Thank you.

I would start with the Blocking example provided with the library. Add the delays you need, the steps/distance you want. The following is simple but crude. It is call blocking code. It can only do the following sequence, but sometimes that is good enough.

A bit better would be to have a conditional loop to get to the final target. The loop would move 200, then delay 1 second, subtract the amount moved. Loop until you use up all the required distance. But initially I suggest to keep it simple and just make it work with inline sequences.

#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup()
{
    stepper.setMaxSpeed(200.0);
    stepper.setAcceleration(100.0);
}
void loop()
{
    stepper.runToNewPosition(0);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
}


YUN. How to reset the micro controller from linux? As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?

One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.

According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.


Read amount of I/Os in code I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.

Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

It depends on the core, but most provide the macro NUM_DIGITAL_PINS which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).

So you can use:

if (pinNumber < NUM_DIGITAL_PINS) {
    digitalWrite(pinNumber, HIGH);
} else {
    Serial.println("Invalid pin number");
}

In tandem with that you also usually have NUM_ANALOG_INPUTS.


What is wrong with my code? Did you forget '()'? #include <SimbleeBLE.h>

// constants won't change. They're used here to set pin numbers:

const int ButtonPlayPause = 15;
const int ButtonNext = 12;
const int ButtonPrevious = 11;
const int OBled = 29;
       int Playp = 1;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{

  pinMode(ButtonPlayPause, INPUT);
  pinMode(ButtonNext, INPUT);
  pinMode(ButtonPrevious, INPUT);

  pinMode(OBled, INPUT);

  SimbleeBLE.deviceName = "GBAND";

  Serial.begin(115200);

  SimbleeBLE.begin();

  SimbleeBLE.txPowerLevel = +4;
}

void loop()
{
  buttonState = digitalRead(ButtonPlayPause);
  if (buttonState == HIGH)
  {
    SimbleeBLE.begin();
    SimbleeBLE.deviceName = "GBAND";
    //More code here to establish connection with android
     SimbleeBLE.sendInt = (Playp);
    digitalWrite(OBled, HIGH);
    SimbleeBLE.end();
    digitalWrite(OBled, LOW);
  } else  {
            buttonState = digitalRead(ButtonNext);
            if (buttonState == HIGH)
            {
              SimbleeBLE.begin();

              //More code here to establish connection with android

              digitalWrite(OBled, HIGH);
              SimbleeBLE.end();
              digitalWrite(OBled, LOW);
            } else  {
                      buttonState = digitalRead(ButtonPrevious);
                      if (buttonState == HIGH)
                      {
                        SimbleeBLE.begin();
                        //More code here to establish connection with android

                        digitalWrite(OBled, HIGH);
                        SimbleeBLE.end();
                        digitalWrite(OBled, LOW);
                      }
                    }
          }
    }

This is the error I keep getting:

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Simblee"

C:\Users\Lestat\Desktop\SD PROJECR PAPERWORK\Sketch programs\sketch_mar20a\sketch_mar20a.ino: In function 'void loop()':

sketch_mar20a:42: error: invalid use of member function (did you forget the '()' ?)

     SimbleeBLE.sendInt = (Playp);
                        ^
exit status 1
invalid use of member function (did you forget the '()' ?)

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

You're trying to assign a value to a function. That is almost certainly wrong.

SimbleeBLE.sendInt(Playp);


How to increase sensitivity of Capacitive Touch Switch? I am working with Capacitive Touch Sense technology.In that I am using TTP224 Touch detector IC. I am getting good sensitivity when I am using Touch pad without putting any non electric material over it and able to switch ON/OFF connected led.But when I put any non electric material like Acrylic Sheet of 2mm thickness I am not able to get any signal through pad or not able to ON/OFF connected led.

So, How can I increase sensitivity of Touch pad?

I have bought TTP224 module from here.

And what can be the alternatives for TTP224???

Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.


Use photocell as digital input I need to use multiple photocells as input, but its more than the amount of analog pins that my arduino has.

I'm wondering if theres any way to use a photocell as a digital input, with the photocell triggering at a specific set threshold of light.

It doesn't seem quite possible but I thought I'd ask.

I see two possible options for achieving what you want:
Voltage divider
This is the solution proposed by William Roy: you make a voltage divider
circuit and check whether it gives a voltage above the threshold of the
digital input. For example:
+5V ---+
       |
       R
       |
       +--- digital input
       |
      LDR
       |
GND ---+

There are a couple of issues with this approach though:

Every digital input is fitted with a Schmitt trigger which makes
it hysteretic, meaning the voltage threshold for switching from LOW
to HIGH is higher than the threshold for switching from HIGH to
LOW. If the pin voltage is between the two thresholds, it will read
either HIGH or LOW, as determined by the history of that voltage.
Depending on your application, this may not be a problem, and may
even be desirable. But if you want, as you wrote in your question, “a
specific set threshold of light”, it sure will be problematic.

You do not know what those threshold voltages are. The datasheet of
the ATmega328P (the main chip of the Uno) states that
they should “typically” be around 2.1 and 2.6 V, but it only
guarantees that the low threshold should be no less than 1.5 V
and the high threshold no more than 3 V. For any input voltage
between 1.5 and 3 V (which is a very significant range), the
chip manufacturer doesn't guarantee what the pin will read.

The first issue can be solved by using a write-before-read protocol:
first you set the pin to OUTPUT LOW, which will force the input Schmitt
trigger to the LOW state. Then you set it to INPUT and take a reading.
This way you will read HIGH if and only if the pin voltage is above
the high threshold. The low threshold becomes irrelevant. Example code:
/*
 * Read the given pin avoiding the input hysteresis.
 *
 * Returns HIGH if the pin voltage is above the upper (LOW to HIGH)
 * threshold, LOW otherwise.
 *
 * WARNING: The pin is set to OUTPUT LOW for a very short time.
 */
int anhystereticRead(uint8_t pin) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    pinMode(pin, INPUT);
    return digitalRead(pin);
}

The second point can be solved by calibrating your input using a trimpot
instead of a resistor. You would adjust the pot until the threshold is
exactly what you want. Using fixed resistors instead of a pot will make
it very difficult to achieve your “specific set threshold of light”,
unless you can live with a very rough precision.
Capacitive measurement
The second option is use the LDR as the resistor in an RC circuit, and
measure the charging time of the circuit, like this:
digital output --- LDR ---+--- digital input
                          |
                      capacitor
                          |
                         GND

Starting with a discharged capacitor, you set the output to HIGH and
measure how long it takes for the input to read HIGH. This time is
typically something like 0.73 R C, where R is the
resistance of the LDR and C the capacitance of the capacitor. The
exact numerical factor is not know, as it depends on the high threshold
voltage of the digital pin.
For details and example code, you could check the Capacitance Meter and
RC Time Constants Arduino tutorial, or search the Web for
“Arduino capacitance meter”. You will find material about how to measure
an unknown capacitance using a know resistance, but you can use the same
technique to measure an unknown resistance using a known capacitance.
And you should replace the waiting loop:
while (analogRead(input) < THRESHOLD) {}  // wait

by a similar loop using the digital input threshold:
while (digitalRead(input) == LOW) {}  // wait

The interesting thing about this technique is that you do not need a
trimpot to set the illuminance threshold: you will measure the
charging time and set the threshold in software. Also, this technique is
not affected by the input hysteresis. The main drawback is that the
measurement takes longer than the voltage divider technique.
Edit: I found a blog post describing this exact method in greater
detail: Measuring resistance or voltage with 1 digital I/O,
by Moser.


Counting the number of pulses in a second For my speedometer application, I want to count the number of pulses occurring every second and convert it to speed. So for that, I need to count the number of pulses occurring at a given input pin for one second. This count is used to convert to speed. The count should go to zero and start over after every second. But I don't get how to set a limit of one second and start over every second. So far I have come up to this:

int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
    Serial.begin(115200);
    pinMode(speedpin, INPUT);
}

void loop()
{
    currenttime = millis();
    if (currenttime - lasttime <= 1000)
    {
        if (digitalRead(speedpin == HIGH))
        {
            count = count + 1;
        }
        else
        {
            count = count;
        }
    }
    else
    {
        count = 0;
    }
    Serial.println(count);
}

As already explained in Michel Keijzers' answer, instead of counting how
many times you find the input HIGH, you should count the LOW →
HIGH transitions. This requires saving the previous input state and
counting a transition only when the input is HIGH while it was LOW
last time you saw it:

static int last_pin_state = LOW;
int pin_state = digitalRead(SPEED_PIN);
if (pin_state == HIGH && last_pin_state == LOW) {  // rising edge
    count++;
}
last_pin_state = pin_state;

For displaying the count every second, use the technique explained in
the Blink without delay Arduino tutorial:

static uint32_t last_time = 0;
if (millis() - last_time >= PERIOD) {
    Serial.println(count);
    count = 0;
    last_time += PERIOD;
}

Note that you have to reset the count every time you print it.

VE7JRO suggests using interrupts. Interrupts save you the pain of
writing the edge detection. On the other hand, they also make things
slightly more complicated, because you now have to worry about
atomicity, race conditions, volatile variables and such. There is no
need to use interrupts unless the pulses are so fast (or your loop()
is so slow) that you may miss a pulse. If your loop() gets bigger and
slower, and you risk missing pulses, then interrupts can really help.
But the proper way to use them is to count the pulses in the ISR. If you
use the ISR only to rise a flag, you loose the speed advantage of the
interrupts, which is the whole point of this approach.

The interrupt service routine would then be like this:

volatile unsigned int count;

void count_pulse()
{
    count++;
}

Then, the loop only has to print and reset the count:

void loop()
{
    // Periodically print and reset the count.
    static uint32_t last_time = 0;
    if (millis() - last_time >= PERIOD) {
        noInterrupts();
        unsigned int count_copy = count;
        count = 0;
        interrupts();
        Serial.println(count_copy);
        last_time += PERIOD;
    }
}

Note that the variable count is shared between the ISR and the main
loop. That's why it has to be declared volatile. Also, its access
within loop() has to be protected within a critical section delimited
by a noInterrupts()/interrupts() pair, otherwise you would have a
race condition. Also note that, in order to keep the critical section as
short as possible, the value of count is only copied within the
critical section, and the actual printing is deferred to after the
critical section is finished.


Connect arduino to beaglebone black I want to exchange some date between arduino and beaglebone, as far as I know, most arduinos works with 5v levels, so I need to convert 5v into 3.3v beaglebone in order to communicate with it.
Unfortunatly I have no pro mini 3.3v now, only 5v arduinos.
So I need to convert levels.
I have several questions.

I have UART TTL CP2102 converter, I am using it to programm my Arduino pro mini, can I use it directly with beagle bone without converter ? http://ecx.images-amazon.com/images/I/410n8%2BHhdNL.SY300.jpg like this.
I can buy this cable with pl2303 inside http://i01.i.aliimg.com/wsphoto/v0/32250361345/Free-postage-1pcs-PL2303-PL2303HX-USB-to-UART-TTL-Cable-module-4p-4-pin-RS232-Converter.jpg
Is it possible to power my arduino pro mini 5v with 3.3v supply and use it directly with beaglebone

Can you provide simple level converter schematic to solder it quickly

All in all I need just to communicate with beaglebone via uart from pc with USB-UART converter or from arduino it doesn't matter, just to communicate and send some data.

Please suggest what is the best way to follow.

The simplest way is just to plug the Arduino in to the BBB.

The BBB has USB.  The Arduino has USB.  Connect the two together and you have both power and data immediately available.

Depending on the Arduino and its version it will either be there as /dev/ttyAMA0 or /dev/ttyUSB0

You can even use avrdude to upload new software to the Arduino direct from the BBB.


Use an electromagnet for reading induction as well I have an electromagnet that I wish to use to pull a neodyne magnet closer.

I'm thinking of having the electromagnet sensing when the magnet is close, but when the magnet is running I'm pushing 12 volts through it and I don't want to fry my Arduino. How can I do the wiring to achieve this?

I only have to be able to use the magnet as a sensor while it's turned off.

You can use a hall sensor from an old computer fan.

If the magnet is not moving you are not going to be able to sense it with the coil of your electromagnet.
You can also decouple de input of your arduino with a cap in series with the coil, but again if the magnet is not fast enough you will have to use a bigger cap.

You can also make a voltage divider between your coil and sense from there. When the 12V are applied just add some code to offset the input signal.


Using an LM339 IC as a motor driver I have an LM339 IC from Radioshack that I am hoping to use as a motor driver.
I read many resources on how the L239D can be used as one.  I don't have enough circuit experience to truly know the difference between the two and googling shows many wiki pages I couldn't fully understand.
Can the LM339 be used as a motor driver?
I did a quick comparison of the two circuits here LM339  and L239D
But I am still unsure.  I don't want to fry my board so I am asking first.

The LM339 is a comparator, not a motor driver. The L239D is a dual H-bridge motor driver.

They are completely different things. One is used for comparing two voltages (up to 4 times, it's a "quad"), the other is used for driving motors.

The LM339 can output an absolute maximum of 20mA. That's half what the Arduino itself can output on an IO pin!

You could use the LM339 as part of the control circuitry to control a H-bridge, but it cannot itself drive a motor in any way, shape, or form.


How to stole/read data from an output serial port? (Sorry, I'm not a native English speaker)

I have a chip with Serial Input, Serial Output, and a Clock (used by both serials). I want to read the output with an Arduino or ESP-32.

The device I want to read is: https://statics.cirrus.com/pubs/proDatasheet/CS5460A_F5.pdf

How can I do this? I don't have too much expertise in serial communication.

Do I need anything else?

I would appreciate any help.

This device seems to communicate via SPI. Google for "serial peripheral interface" and learn how it works. You will then be able to know what to do with the information in chapter 4 of the datasheet.


UART communication issue on Arduino Mega I am using an MH-Z19 CO2 sensor with an Arduino Mega using UART. As per the specifications of this sensor, after we send a command, we expect the response in a particular 9 byte format (with starting bytes as 0xFF and 0x86).

byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
byte response[9];
Serial.flush();
Serial.write(cmd,9);
while (Serial.available()<9) {}
for(int n=0; n<9; n++) {
  response[n] = Serial.read();
}
if (response[0] != 0xFF) {
  //Error
  predictCo2 = 0;
} else if (response[1] != 0x86) {
  //Error
  predictCo2 = 1;
} else {
  predictCo2=((response[2]*256)+response[3]);
}

I wait till all the 9 bytes are filled in to read the values.

The problem here is that, when I turn the board ON, most of the times the response isn't in the required format (starting bytes aren't 0xFF or 0x86).
But, if I press the Arduino reset button, it starts reading values in proper format straight away.

I'm wondering why this is happening. Why is the UART response not in the proper format immediately after I turn on the Arduino, and I have to explicitly do a reset? Is the reset button clearing the serial stream? How can this be achieved through software?

I included serial.flush() before sending the command, but that didn't help either.

Serial.flush() only empties the output buffer, so that won't achieve anything. Reading exactly 9 bytes and hoping they match the input stream is not very effective, as you found. If you are out of sync with the incoming bytes, you will stay out of sync.

It would be better to keep reading (single bytes) until you get 0xFF or 0x86 and then read the rest.


IR remote unstable button numbers Question

Is there a reason for unstable button numbers of an IR remote?

Desciption

I wrote a remote class where I identify the pressed number of the remote to set states. But however I get never the same number of the pressed key.

For example I press the number '1' and on the serial interface shows this:

3588650484
2740290906
3148594742
689746115
2396927248
2934053595
4294967295
3876827360

And it should look like this:

16724175 // Button 1
4294967295
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1

Hardware

I am using an arduino UNO board and the standart remote of the starter kit. There is no name just 'SPECIAL FOR MP3'.

Some more infos

Ok, in my first project I used the code from Noreddine Kessa(Example Project) which works fine. Next I copied some code in my new class 'IRControl.cpp' ( you can see below). Then I created an object IRControl in the main.cpp and run the menu() in the loop.

h-File:

/*
 * IRControl.h
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#ifndef IRCONTROL_H_
#define IRCONTROL_H_

//Remote Defines
#define buttonON 16753245
#define buttonMode 16736925
#define buttonSoundOff 16769565
#define buttonPlayStop 16743045
#define buttonTrackBack 16712445
#define buttonTrackForward 16761405
#define buttonEQ 16769055
#define buttonMinus 16754775
#define buttonPlus 16748655
#define button0 16738455
#define buttonRepeat 16750695
#define buttonJSD 16756815
#define button1 16724175
#define button2 16718055
#define button3 16743045
#define button4 16716015
#define button5 16726215
#define button6 16734885
#define button7 16728765
#define button8 16730805

#include "IRremote.h"
#include "wiring_private.h"

enum zustaende{Motor1, Motor2, Motor3, Sleep};
extern int zustand;

class IRControl {
private:
    IRrecv *irrecv;
    decode_results remoteValue;
public:
    IRControl(int RECV_PIN);
    virtual ~IRControl();
    void menu();
};

#endif /* IRCONTROL_H_ */

cpp-File:

* IRControl.cpp
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#include "IRControl.h"

IRControl::IRControl(int RECV_PIN) {
    // TODO Auto-generated constructor stub
    irrecv = new IRrecv(RECV_PIN);
    pinMode(RECV_PIN , INPUT);
    irrecv->enableIRIn();
}

IRControl::~IRControl() {
    // TODO Auto-generated destructor stub
    delete irrecv;
}

void IRControl::menu() {
    if (irrecv->decode(&remoteValue)) {
        //lReceived = remoteValue.value ;
        Serial.println(remoteValue.value);
        /*
        switch(remoteValue.value)
                {
                case button1:
                    zustand = Motor1;
                    //digitalWrite (LED1, HIGH); // for control
                    break;

                case button2:
                    zustand = Motor2;
                    //digitalWrite (LED2, HIGH);
                    break;
                case button3:
                    zustand = Motor3;
                    //digitalWrite (LED3, HIGH);
                    break;

                case button0:
                    zustand = Sleep;
                    break;

                default: break;
                }
                */
        irrecv->resume(); // Receive the next value
      }
}

Where the problem could be

I think there could be a problem with the IRrecv *irrecv;. But i'm not sure.

Thanks for your help

Please post the code where you call the library. In particular where do you make an instance of IRControl?

I am guessing you are doing it at global scope which means you are probably running into the C++ static initialization order fiasco.

What it is: http://www.parashift.com/c++-faq/static-init-order.html

How to prevent it: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html

To prevent this, you should not be doing this in the class constructor:

irrecv = new IRrecv(RECV_PIN);
pinMode(RECV_PIN , INPUT);
irrecv->enableIRIn();

Instead, make a begin function (like most Arduino classes do) and call that from setup.


How do I connect this SPI serial display to an Arduino? I've recently purchased a screen on DX without really thinking about it, because I have no idea how to connect it to my Arduino.

It is this screen:

The description says that it uses the SPI serial protocol but I don't know how to connect that ribbon to my Arduino, is soldering cables to it the only way?

That kind of connector is most commonly directly soldered on to a PCB.  You can buy adaptor boards with the various different pitch pads on them for soldering it to.

Also there is no mention of what chip the screen uses (I am unfamiliar with "XS057" as a chip, so that is probably the model of the screen not the chip).  At that resolution it's probably an ILI9163, but without being sure all you can do is stab wildly in the dark and try different drivers.


SerialGSM for GSM shield without SoftwareSerial SerialGSM is a library for simplifying GSM shields.

This is sample code for sending SMS:

#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(2,3);
void setup(){
 Serial.begin(9600);
 cell.begin(9600);
  cell.Verbose(true);
  cell.Boot();
  cell.FwdSMS2Serial();
  cell.Rcpt("+972123456789");
  cell.Message("hello world");
  cell.SendSMS();
}

void loop(){
  if (cell.ReceiveSMS()){
    Serial.println(cell.Message());
    cell.DeleteAllSMS();
  }

}

As you can see, he uses software serial.

I intend to use this for my school thesis, but I am using a shield, so I won't be using Software Serial.

What bothers me is this line

SerialGSM cell(2,3);

In my case, do I declare it like this?:

SerialGSM cell(0,1);

Or will there be conflicts with serial?

EDIT: In other words, how do I declare the SeralGSM object using hardware serial and not software serial?

SerialGSM is designed to work with software serial, as you can see that from the class declaration in the SerialGSM.h header:

class SerialGSM : public SoftwareSerial {
...
};

Unfortunately, changing it to use hardware serial is more complicated than it looks. There are two potential ways you could go about it:

Derive from HardwareSerial instead of SoftwareSerial. This would give you flexibility, but you'd have to take care of passing all the right data to the HardwareSerial constructor, which is quite messy.
Don't derive from anything. Use the global Serial object, and manually replace all serial function calls with their Serial.xxx() equivalents. This is probably easier, but it restricts you to a specific serial port.

Both approaches involve quite a lot of coding, so they aren't trivial tasks. It's also important to note that SerialGSM currently uses the global Serial object to output debug information. You'd have to remove or modify that before converting to hardware serial, or else it could interfere.


Arduino how to get amount of elements in an array? Hello  have an array of strings that loads strings from a txt file on an sd card.
The txt file on the SD card can change from time to time(not while the Arduino is running).I want to be able to get the amount of elements in the array after the txt file has been loaded into the array. The txt file has lines of txt in it. Each line in the file is put into a string in the array. I want to be able to get the amount of elements in the array how can I do this?

numElements = (sizeof(array) / sizeof(array[0]));


Why HDOP in TinyGPS++ is less than 1? HDOP is supposed to be greater than 1: https://en.wikipedia.org/wiki/Dilution_of_precision_(navigation)
But I get HDOP about 0.7. What does it mean?

Where can I found explanation of the output parameters?

HDOP can be less than 1 according to this article.. I am no expert in this area, but according to the article, the HDOP=1 limit is based on 4 satellites; visibility and use of more than 4 satellites can reduce HDOP below this limit. When you think on it, this makes sense.

GPS specifications limit the inherent accuracy of a position solution through timing errors and vagaries in rf propagation through our atmosphere. Imagine drawing a vector from a GPS satellite to your receiver. The length of that vector represents the distance from the satellite to your receiver, but we depend on signal timing to infer distance/vector magnitude. In other words, we can only measure distance as accurately as we can measure time.

Now think about the accuracy of a position solution based on a single satellite. If we assume the receiver is confined to the surface of the earth (and the satellite is geostationary), the single vector of length L1 will intersect the surface of the earth forming a circle. Your position could be anywhere on that circle - which could be quite a large range of values!

Now imagine a 2nd satellite, a 2nd vector of length L2 tracing a second circle. Now your position is constrained to be those points where the two circles intersect - two points! With a third satellite, a 3rd vector of length L3, one of these two points will be eliminated.

Now replace those sharp lines with bands or swaths of some width D. In this case, the intersection describes a polygon instead of a point. We know our position is within the polygon, but with only three satellites that is the best we can do.

As you can see, adding more satellites will begin to "slice off" sections of the original polygon, making it progressively smaller. So: HDOP=1 represents the limit with 4 satellites; more satellites yield a smaller polygon, and smaller HDOP.

While writing this, I found a video that does a far better job than my words at describing the position solution process with multiple satellites.

This video is quite good also!


Debugging with an ATtiny? I have an ATtiny hooked up to two line scan modules. I'm sending digital signals to the line scan modules then receiving the analog output and storing it in an array. I have an if statement that will make the LED on the ATtiny programmer blink when the number are below a certain range (meaning that lens is covered).

Here is my code:

#include <SoftwareSerial.h>
const int rx=0;
const int tx=1;

SoftwareSerial mySerial(rx,tx);
int CLK = 2;
int SI = 1;
int Aout = A3;
int Aout1 = A2;

int LED = 0;

int pixelsArray[128];   //Array to hold the values of the individual pixles.
int pixelsArray1[128];

 void outputPixels()
{
  for(int j = 0; j < 128; j++)
  {
    digitalWrite(LED, LOW);

    if(pixelsArray[j] < 100)
    {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(500);
    }
  }
}

The problem that I am having is that when I test my code with one line scan module it works just fine. You will notice that in the readPixels() I have the statement pixelsArray1[i]=analogRead(Aout1); commented out. However, when I try to use it with two the LED start blinking regardless of how much light is hitting the line scanner.

The strange thing is that EVEN when I comment out the digitalWrite(LED, HIGH); statement in the outputPixels() method...THE LED STILL BLINKS!!!

Since the ATtiny does not support URT and can't use the console in Arduino I have no idea how to debug this. Does anyone here have any clue what is wrong?

Here is the datasheets

ATtiny: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

ATtiny Programmer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/?_ga=1.59946280.467360091.1464906372

Since you do not have enough RAM for your arrays, something has to
give. A few options:

Do you really need the 10-bit precision of the ADC? If you can live
with 8 bits, then use 8-bit arrays (type uint8_t) and store only
the 8 most significant bits of each reading
(pixelsArray[i]=analogRead(Aout)>>2). This will make the arrays
half as big.
If you really need 10-bit precision, maybe you do not need 128-pixel
resolution? Then you could store only every other pixel. This will
also halve the array sizes.
If you do need both the full precision and the full resolution, then
you will have to pack the bits tight. You can pack up to 4 readings
in 5 bytes. But this will increase the complexity of your program.

Addendum: To declare the arrays as being made of 8-bit integers,
just replace

int pixelsArray[128];
int pixelsArray1[128];

by

uint8_t pixelsArray[128];
uint8_t pixelsArray1[128];

Here “uint8_t” means “unsigned 8-bit integer”, whereas “int” is a
regular integer, i.e. signed and, on the AVRs, 16-bits long.


HC-SR04 Echo Pin Fails To Go Low After Trigger Pulse I have implemented an HC-SR04 distance sensor using an Arduino.  After power up, the sensor operates well when objects are within range of the sensor.  However, if the distance to be measured exceeds the maximum (about 15 feet) distance, the sensor times out (which is what I expect).  However, after a time-out and with the distance between the object and the sensor in range, the Echo pin fails to be set low after a trigger pulse is generated.  The only way to fix this condition is to power down the sensor and power it back up again.  (I have verified the state of the Echo pin by using an oscilloscope.)

After many hours of research, I discovered that the problem is related to the fact that there is (apparently) a well-known bug in the HC-SR04 which is a Chinese clone of a Devantech SRF04.  I replaced the HC-SR04 with an SRF04 and the problem was solved.  Now, the ECHO pin always goes low after a trigger and after a time-out (i.e. the object is beyond the maximum measurement distance).


What data type are the analog pin labels (A0, A1, etc)? Arduino Mega

I would like to have an array containing analog pin labels something like...

int analog_pins[] = {A0, A1, A2, A3};
int num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

Is this possible? It has compiled without any warnings or errors but I'm dont have my board with me (yes beginners mistake) so cant really check if it works.

As you can see in Arduino.h, the analogRead() has uint8_t as parameter. You can define them as byte or uint8_t and you don't have to use the sizeof().

The type of A0 is defined in the file pins_arduino.h:

#define PIN_A0 (14)
static const uint8_t A0 = PIN_A0;

Nevertheless, what you have with integers is 100% okay as well.

When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at Tinkercad.

As @DataFiddler writes below this answer, using a 'const' keyword is preferred:

const uint8_t analog_pins[] = {A0, A1, A2, A3};


9 volt battery not being able to power motor driver Currently I am using a 9 Volt Duracell A one like this:

I am using it to power a motor driver which contains 2 motors within. I  can see where the main problem is coming and that is to do with that the voltage is not big enough. But I don't understand why this is. I see in the manual for the robot that I am building it is using a smaller voltage battery than what I am using. I tried using another set of batteries but the motors did not move at all then. The 9V Duracell battery that I am currently using has only been used for about a week (so it probably hasn't ran out), its practically brand new.

It is likely not a question of the voltage being "big enough". You do need to feed the correct voltage to your robot, but max current and capacity are also very important.
Those "9V transistor batteries" have very low peak current and very low total power capacity (measured in milliamp-hours, or mAh.) They are not up to the job of powering motors. You could easily drain a 9V battery like that in 15 minutes, much less a week.
You should connect 6 D cells in series, and use that instead. That would give you enough peak current and total capacity for your robot.


LED not blinking when using a transistor I want to control an led using a transistor. The led gets it‘s power from an external 5v dc power supply.

For the transistor I use an 1kΩ base resistor. The transistor is a BC547C (npn). The datashet is available here.
The led is red (3mm), draws 20mA of current and needs 2V.

I‘ve got a very simple Arduino sketch and wiring setup:

Code:

#define ledPin 6

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

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

Wiring diagram:

Problem:

The led is not blinking but shining at full power constantly.
Disconnecting ledPin 6 from the Arduino (to mimic digitalWrite(ledPin, LOW)) still lets the led shine, just not as bright. The LED should be off in that case, not just dimmed to 50% brightness.

What I tried so far:

I tried using different base resistors. I tried 2kΩ, 3kΩ, 2.5kΩ, 470Ω, 1.5kΩ. The behavior did not change.
I tried using different leds. Same behavior. LEDs are shining constantly, not blinking, and are dimmed when disconnecting pin 6.
I used another BC547C to see if the first one was broken. It wasn’t. I still got the same behavior.
Connecting the led directly to the Arduino without the transistor and external power supply let’s the led blink exactly how it was defined in code.

Any ideas?
I several-times-checked the wiring in my setup. It should not be the problem.

Without a common reference (ground) between the Arduino power supply and the external power-supply, again, you have a floating base, as you can't know what the Arduino's 5v output (or local ground) looks like to the external circuit.

Connect the two grounds. That should correct the LED brightness with respect to the Arduino output pin level. Then, if you need the external circuit to behave in a specific way when the base is disconnected from the Arduino, add a 10K resistor from the transistor base to the external +5 if you want the LED to be on, or to ground, if you want it to be off. Again, I'm guessing at both the pullup/pulldown value (but 10K should be in the ballpark) and the switching sense ('On' or 'Off' for base at +5), but from the expectation state in your point (2.), I think I have it right.

Update: But see @EdgarBonet's comment to me about BJT's. I'd still avoid leaving an input floating as a matter of practice, but it seems not relevant in your circuit.


Looking for light-weight Arduino OLED library that supports text and bitmaps I'm trying to incorporate a screen into my Arduino code which is quite large already. The Adafruit SSD1306 library is overly large and has a lot of unnecessary things in it. I've found the SSD1306Ascii library which is great because it takes up barely any space, but I really would like to be able to display a bitmap logo on the screen. Does anyone know of a library that is light weight but still supports bitmaps?

Thanks.

This is supposed to be a small implementation. https://github.com/nicoud/Oled

I have not used it, but it does look interesting. You can pick the bits that you need.

https://www.didel.com/OledLib.pdf


Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call? I've found posts explaining how to get client IP by modifying the W5100 Ethernet library and the Adafruit CC3000 library but not the Ethernet2 lib for W5500 chip, which is different enough that the W5100 mod won't work. I suspect the TCP Socket struct will contain it, but haven't been able to find its declaration anywhere to confirm this so I can modify the library to make it accessible.

Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, it is not Ethernet2 library. The new Ethernet library supports W5500 and has client.remoteIP().

example

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());

  New features in version 2.0.0
  Auto-detection of W5100, W5200, and W5500 Ethernet hardware.


Using two software serial - two UART I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).

I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.

How can I do that?

I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.

All baud rates are 9600.

You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).

I describe the process here.

The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.

Example code:

// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

The other Arduino (which receives the debugging information) simply echoes it to Serial:

char buf [1000];
volatile int inpoint, outpoint;

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

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

I made a library out of the relevant code. The library is available from:

http://gammon.com.au/Arduino/SPI_Debugging.zip

Example using the library:

// make true to debug, false to not
#define DEBUG true

#include <SPI.h>
#include <SPI_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

There is a similar library for I2C debugging:

http://gammon.com.au/Arduino/I2C_Debugging.zip

Example of doing I2C debugging:

// make true to debug, false to not
#define DEBUG true
const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

#include <Wire.h>
#include <I2C_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

All of the examples illustrate using a #define to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.


Serial monitor window opens frozen My serial monitor window opens frozen, without any output or possibility to input, or even activate the window.
Sketch is very simple, but behavior is same even with empty sketch, so I assume problem is not in sketch. I also checked if sketch is uploaded correctly by uploading simple sketch with blinking diode, which worked.
Same behavior with Arduino Nano and Uno.
I tried to reinstall IDE, uninstalled, removed and reinstalled serial driver (ch340) with no success.
I can see Serial monitor window only on windows taskbar, it won't activate after click.
Until now I haven't had any significant problems with IDE or serial monitor for years.

Try updating the java. Also check whether the device manager shows the USB serial port without any yellow warning sign on it.
If there is a current short in the usb port that specific port will be off for safety, restarting the computer should resolve that problem.


Arduino RGB component identification Can someone help me identify this component?

Thanks in advance.

It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.


Is it possible to disable functions/methods? I recently started using the TimeAction library (which allows for proto-threading) and I noticed it has a really useful function for enabling/disabling threads. I want to use the same idea but apply it to a general function, though I haven't been able to find a possible solution to doing such a task on the internet. Here is a potential way for how I would like to implement it:

#include <TimedAction.h>

boolean disableCheck = false;
boolean checking = false;
boolean state = false;
const int motionPin = 5;
void checkMotion();
void motion();
void DisableCheckMotion();

TimedAction checkable = TimedAction(6000, DisableCheckMotion);

void setup() {
   pinMode(motionPin, INPUT);
   Serial.begin(9600);
}

void loop() {
  checkMotion(); //this will be the function I wish to enable and disable

  if(checking == true)
  {
    motion();
  }
  if(disableCheck == true)
  {
    checkable.check();
  }

}
void checkMotion()
{
   checking = true;
}
void motion()
{
   if(digitalRead(motionPin) == HIGH)
{
   Serial.println("motion");
   checking = false;
   checkable.check();
}
}
void DisableCheckMotion()
{
  state ? state = true : state = false;
  if(state == false)
{
  checkMotion.disable(); //this is where I would like to disable the function
  disableCheck = true;
}

  if(state == true)
{
  checkMotion.enable(); //this is where I would like to enable the function
  disableCheck = false;
}
}

The purpose of this task is to output one value for whenever a PIR scanner (set at pin 5) picks up motion. Without any form of delaying it will flood the output with values (which is undesirable). A thread is used to offer this delay, I cannot put the code for checking for motion within the thread as I could risk the chance of a reading being missed.

The ideal setup would be for the Arduino board to receive the input and then delay the input from being received again for a period of time while not delaying the entire program. What would be the best way to implement this?

If you don't want a function to run you can just return at the start of that function:

void myFunction() {
    if (!myFunctionShouldRun) return;
    ... rest of function ...
}

If myFunctionShouldRun is false the if will be true (due to the !) and the function will return.  If it's true the rest of the function will execute.


Problem with nodemcu esp-01 can't connect to wifi i've been working on a project that im using an esp8266 nodemcu-01 as described in the title, and i've been having some headache with this module, first because after searching i figured out that the commands LOW and HIGH are inversed as in LOW outputs 3.3v e HIGH outputs low tension, so i began to grow worried about the possibility that other programming resources may follow the same situation. But with that problem a part, i've been trying a few different codes including the one found in the sketchbook examples and still couldn't connect.

Also another weird problem, is that i was working working with the baudrate set on the arduino IDE settings on 115200, and so is the Serial.begin, that is also set to 115200, however i can only read properly the continuous dot that is contained in the while loop "........." when i set it to 74880, which another thing that i was trying to understand. I also forgot to mention that it keeps spamming dots but does not connect at all.

And to conclude, my problem resumes in not being able to connect to any wifi i've tried, i tried my friend's home and also 4g, both did not work, here's the code, which we tried first:

#include <ESP8266WiFi.h>

char* ssid = "Net Wi-fi";
char* password = "testingtest";
//
void setup() {
  WiFi.begin(ssid, password);
  Serial.begin(115200);
  while(WiFi.status()!=WL_CONNECTED)
  {
    Serial.print("Conecting");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP:");
  Serial.print(WiFi.localIP());
}

void loop(){

This was the original try, using the arduino sketch example:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Net6271";
const char* password = "megaman";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

Board setting: Generic ESP8266 Module.
Crystal Frequency: 40MHz.
Flash Frequency: 80Mhz.
Upload Speed: 115200.
Flash Mode: DIO.
Flash Size: 512k no SPIFFS.

pls help.

ESP-01 modules use 26 MHz crystal. Set the Crystal frequency in IDE to 26 MHz.

Both io pins (0 and 2) on esp-01 have pull-up circuit. That is why you think you measured 'inverted' logic.


Help with Arduino Micro Keypress Algorithm Greeting, first time Arduino user here.

So I am using the Arduino Micro as an HID keyboard device. It accepts arbitrary input from a Node-JavaScript program I am running (so I have full freedom in in the data transferred to the micro).

The goal is for the data transmitted to the micro to include information about a keypress: whether it was pressed or released and which key it is. The serial connections are all fine and dandy - I just have questions regarding the key pressing logic.

As far as the JavaScript program goes, a key down is detected based on the keyCode, not the character code so when tapping “a”, character code  97, the Arduino micro is receiving “A”, character code 65 since the JavaScript detected keyCode is 65. So that all sounds like problems with JavaScript (which it is), but remember that I have freedom in portraying the information sent to the micro.

That being said, instead of detecting by keyCodes and character codes in JavaScript, I could just transmit the letter e.g. “a” with some identifier for press/release such as “+a” for release and “-a” for press. My problem here is how would I handle modifier keys using the Keyboard library.

Should I handle character keys and modifiers keys separately i.e. Keyboard.write for characters and Keyboard.press/release for modifiers or are there cases where it would make sense to press and hold “a” (which would also be different than pressing and holding “A”)?

Below is my original code using keyCodes and “u/d” identifiers to denote up or down (which I am thinking now that “u/d” could be easily confused as a letter if I decide to transmit characters as characters:

/*
  Receives from the hardware serial, sends to software serial.
  Receives from software serial, sends to hardware serial.

  The circuit:
   RX is digital pin 10 (connect to TX of other device)
   TX is digital pin 11 (connect to RX of other device)

  Not all pins on the Leonardo and Micro support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
*/

#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial rpiSerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  // Set the data rate for the SoftwareSerial port
  rpiSerial.begin(115200);
  // initialize control over the keyboard:
  Keyboard.begin();
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Keyboard Serial Connection Established");
}

String keyCode = "";
char state;

void loop() {
  while (rpiSerial.available() > 0) {
    // "Type" via keyCodes (recommended for modifiers)
    // https://www.arduino.cc/en/Reference/KeyboardWrite not behaving as expected

    int data = rpiSerial.read();
    if (isDigit(data)) {
      keyCode += (char)data;
    }

    if (isAlpha(data)) {
      state = (char)data;
    }

    if (data == '\n') {
      Serial.print(state);
      Serial.println(keyCode.toInt());

      if (state == 'd') {
        Keyboard.press(keyCode.toInt());
      }

      if (state == 'u') {
        Keyboard.release(keyCode.toInt());
      }

      keyCode = "";
      char state;
    }
  }
}

I have also noticed that the data from the serial connection parsed by the micro is sometimes incorrect i.e. a keyCode will be misidentified. For instance, by repeatedly pressing “a” through my JavaScript program, the JavaScript program will consistently identify keyCode 65 yet Arduino will identify the received data as keyCode 65 most of the time and then randomly keyCode 64. This happens with other keys as well and the keyCode doesn’t always happen to be just one less nor does it always occur after “n” presses.

Modifier keys are treated no different to normal keys.

The Arduino Keyboard library contains code to map different keys from the internal list of macros to specific keypresses:

If the key value is >= 138 it's a non-printing special key (subtract 138)
If the key value is >= 128 it is a modifier key (1 << (k - 128))
Otherwise look the code up in a mapping table.

That means you can use:

Keyboard.press(KEY_LEFT_SHIFT);

or

Keyboard.release(KEY_RIGHT_GUI);

The full list of modifier keys is:

#define KEY_LEFT_CTRL   0x80
#define KEY_LEFT_SHIFT    0x81
#define KEY_LEFT_ALT    0x82
#define KEY_LEFT_GUI    0x83
#define KEY_RIGHT_CTRL    0x84
#define KEY_RIGHT_SHIFT   0x85
#define KEY_RIGHT_ALT   0x86
#define KEY_RIGHT_GUI   0x87

So to do a capital A you can use:

Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('a');
Keyboard.release('a');
Keyboard.release(KEY_LEFT_SHIFT);

There is also a shortcut, and that is:

Keyboard.press('A');
Keyboard.release('A');

The character 'A' is the same in the lookup table as character 'a' except the high bit of the result is set, which triggers a "Press or release the shift key" addition in the mapping code.

A USB keyboard report consists of 8 bytes:

Up to 8 modifier keys (bitmap)
One reserved byte
6 bytes to indicate pressed keys

This means that you can have up to 6 keys pressed at once, plus modifier keys. Never any more than that. So you don't need to handle any more than that in your code.

The current list of pressed keys is maintained by the keyboard and is sent in every report. There's no concept as such of "pressed" or "released" - only the list of what is currently pressed. If a key is released it's just removed from that list of pressed keys.

So what you need is some way of transferring that data in such a way that the Arduino can interpret it properly.

Since the data is not high throughput you can afford to be quite wasteful in your protocol.  I would suggest using a fairly verbose ASCII based protocol.

All the protocol data is using ASCII characters between 32 and 127 inclusive
This frees up control characters (<32) for controlling the protocol.

The simplest thing is to use a single control character (such as \n) to act as a line ending to break your data up into packets.  Each packet can then contain a list of instructions.

For example, you might choose to have a protocol that looks like:

P,129\n
P,97\n
R,97\n
R,129\n

By treating each line as a complete entity you know that you want to Press key 129 (#define KEY_LEFT_SHIFT    0x81), press key 97 ('a'), release 97, then release 129.

There's no confusion, since commands are all a single upper-case character, and keys are all a decimal number.

For your application, though, a "raw" access interface would be of more use, since you don't really want the Arduino interpreting things for you. However, the API doesn't provide that kind of thing.  So you just have to make the best of what you have and work around it.


MAX31865 and PT100 problem I have a strange problem with the MAX31865 and the PT100. Every time when I start the system it shows that the temperature is -242 and the RTD value is 0 and so on.
But When the system is in the loop() and when I unplug the power cable of the MAX31865 and put it back on, it shows the right temperature. The same happens when I start the serial monitor.

Connected a 330nF capacitor between one pin of the PT100 to -DC, and one 330nF between -DC and ground.


formatting of IPAddress via printf(...) family similar to Serial Object I am trying to use an sprintf with an IPAddress and I am not sure why Serial.print() is able to convert IPAddress to a reasonable human readable representation. I mean, presumably it uses an overloaded function that detects what type the parameter is. I want to somehow leverage that functionality ina printf or sprintf.

What I know:

IPAddress ip = WiFi.localIP();
Serial.println(ip);

works great and outputs "192.168.4.1".

char *buf = malloc(128);
sprintf(buf,"%s",String(ip).c_str());

generates buf as "17082560" which isn't wrong, but its not the usual format for an IP address.

I could write a function to output it the way I want, but I figured there must be some relatively simple way to utilize the functionality that Serial.print() provides but somehow channel it to an sprintf() call. Or any other simple way to provide a formatted IP output would be appreciated.

Whereas KIIV's answer solves your problem, it does not address some very
interesting parts of your original question:

  I am not sure why Serial.print() is able to convert IPAddress to a
  reasonable human readable representation

This works thanks to a couple of abstract classes in the Arduino library
called Print and Printable. A Print object is anything that can
output text, like a serial port, a network connection or an LCD. A
Printable object is anything that can be converted to a text
representation and sent through a Print object.

From Print.h:

class Print
{
    // ...
    virtual size_t write(uint8_t) = 0;
    // ...
    size_t print(const String &);
    size_t print(const char[]);
    size_t print(unsigned int, int = DEC);
    size_t print(const Printable&);
    // ...
    size_t println(const String &s);
    // ...
};

In other words, in order to create a Print, you only have to implement
write(uint8_t), which should output a single character. Then you get
all the print() and println() methods.

From Printable.h:

class Printable
{
  public:
    virtual size_t printTo(Print& p) const = 0;
};

This means you can make any object Printable by implementing
printTo(Print&).

From IPAddress.h:

class IPAddress : public Printable {
    // ...
};

This means IPAddress objects are Printable: they know how to print
themselves into any Print. You can find the implementation of
IPAddress::printTo(Print&) at the end of
IPAddress.cpp.

Thus, to answer your question, Serial.print() does not really know how
to create a textual representation of the IPAddress, but IPAddress knows
how to send itself through Serial, or any other Print object.

  I want to somehow leverage that functionality [...] there must be some
  relatively simple way to utilize the functionality that Serial.print()
  provides but somehow channel it to an sprintf() call.

The functionality is not provided by Serial.print(): it's the fact
that the IPAddress is Printable. In order to leverage that, you have to
create a Print object. You cannot use sprintf() for that, but you can
create a Print object which behaves like sprintf() and writes into a C
string:

// Write into a C string (a char array), a la sprintf().
// Warning: there is no check for buffer overflow.
class StringPrinter : public Print
{
public:
    StringPrinter(char *buffer) : buf(buffer), pos(0) {}
    virtual size_t write(uint8_t c)
    {
        buf[pos++] = c;  // add the character to the string
        buf[pos] = 0;    // null perminator
        return 1;        // one character written
    }
private:
    char *buf;
    size_t pos;
};

which could be used like this:

char buf[16];
StringPrinter(buf).print(ip);

For the sake of simplicity, I would generally prefer the straight
sprintf() solution. However, if you are short on flash, the code above
is likely to be smaller, as sprintf() is large and you are very likely
to be already using Print in your program.


Analog read negative voltage inbuilt protection I'm trying to read a -10 to +10V analog signal on my Arduino Mega (2560). I've been using a voltage divider to obtain a -5V to +5V signal (with two 10kOhm resistors), which used to work just fine.
I'm wondering if this -5V signal can damage the Analog Input pins of the Mega ?

Thank you in advance for your time !

All the IO pins contain a pair of clamping diodes to protect against over-voltage and negative-voltage situations:

As long as the current flowing through one of those diodes doesn't exceed its maximum forward current all will be well and the Arduino won't be damaged. If too much current flows then you will damage the pin.

Since you have 10KΩ resistors, at -5V the maximum current that could flow (assuming a 0.7V drop on the diode) would be (-5 + 0.7) / (10,000 / 2) = -860µA (negative because it's flowing backwards out of the pin from ground to your negative voltage source, not into the pin to ground).

Unfortunately the datasheet doesn't provide a current limit specification for those diodes, but I would expect such a small amount of current to be safe enough.


How to convert char[] to int with fail\success control? this is more like C question, but i failed to google this.

i expect a command parameter in char[], but there may be no argument passed at all, so i need to try to parse this char[] to int and if there is garbage instead of a number, notify user.

i also need to be able to parse negative (with -sign char) numbers from char[].

how can i do this? thanks.

It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it did or did not parse, but not necessarily whether it is valid in some respect.

If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.


Win10 PCs won't see ATtiny boards I bought some ATtiny boards on ebay but I can't get my computers to see them.  When I plug them in I get the USB connected sound then a couple of seconds later it gives the USB unplugged sound.

The power light stays on and the LED blinks, I assume it has the blink sketch already loaded.

I have added the drivers to the IDE but I reckon the problem is before that, something to do with the Win10 PC even seeing it.  I have two versions of the board, one with a USB socket and one with a USB plug, neither work.  [UPDATE] Should have mentioned that the board doesn't show up as being connected to a port

I've looked around for solutions with no joy, I have tried everything I can think of.

Does anyone have a suggestion on where to start troubleshooting this?

There were a couple of comments that both led to the solution.

For me the most important was Nick's that the board pretends to have a USB interface for a couple of seconds, and then runs the sketch.  It stopped me tearing my hair out over why the board didn't show up as a port.

Ignacio suggested using Micronucleus.  I did this having installed the Digistump drivers and selecting them.

After compiling I was prompted to plug in the board, voila, it uploaded.

Thanks Stack Exchange!


Arduino IDE display DEBUG PORT Serial1 output How can I display / capture Arduino IDE's Serial1 output?
Can I display it using Arduino IDE or using a script in Python?

This python script (courtesy of Chad G) works for the Serial:

#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,9600,timeout=5)

while True:
    try:
    stringMe = str(ser.readline().strip())
    if len(stringMe)>3:
        print(stringMe)

    except:
    print(sys.exc_info())
    ser.close()
    exit()

called as (for USB0):

python3 Arduino/tools/multiMonitor/monitorUsb1.py 0

or, if I want to save to a log file:

python3 Arduino/tools/multiMonitor/monitorUsb1.py 0 >> Arduino/tools/multiMonitor/log/usb00.txt

Serial1 (on most Arduino boards that have Serial1) is connected to a pair of pins on the GPIO headers and nowhere else.

To get it to your computer you will have to feed those TX and RX pins through a USB to TTL UART (FT232, CP2102, etc) adaptor.

From there on in it's exactly the same as using Serial but of course with a different device name.


On the Uno, why does VIN require 7-12 volts and the USB only 5 volts? I'm just wondering why the VIN would require 7-12 volts when the USB port itself only requires 5 volts? What happens if you power an Uno on VIN with 5 volts?

USB's Vcc pin is assumed to be a stable, 5v supply, and is directly connected to the 5v bus on the Arduino board with no further regulation. Vin is assumed to be an unknown and unregulated voltage in the range of 7-12 volts.

The 7v minimum is a requirement of the design of the on-board voltage regulator which needs the 2v "head room" to maintain its output at 5v. A 5v power supply could be designed with a larger input range, even including voltages less than 5v, but the simple design used on the board covers a range of sources at a lower cost than a higher-performance power supply.