Why is my code only reading the change of the encoder's pin A? I am writing code for reading in a quadrature encoder. I used attachInterrupt on pin 2 and 3, but by using the same ISR.

    int encAPin= 2;
    int encBPin= 3;
    volatile int encAValue= 0;
    volatile int encBValue= 0;
    volatile int encCount= 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(encAPin, INPUT);
      pinMode(encBPin, INPUT);
      attachInterrupt(digitalPinToInterrupt(encAPin),encUpdate, CHANGE);
      attachInterrupt(digitalPinToInterrupt(encBPin),encUpdate, CHANGE);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(encCount);
    }

    void encUpdate() {
      if(digitalRead(encAPin)==RISING){
        if(digitalRead(encBPin)==LOW){
          encCount++;
        }else if(digitalRead(encBPin)==HIGH){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==HIGH){
        if(digitalRead(encBPin)==RISING){
          encCount++;
        }else if(digitalRead(encBPin)==FALLING){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==FALLING){
        if(digitalRead(encBPin)==HIGH){
          encCount++;
        }else if(digitalRead(encBPin)==LOW){
          encCount--;
        }
      }
      if(digitalRead(encAPin)==LOW){
        if(digitalRead(encBPin)==FALLING){
          encCount++;
        }else if(digitalRead(encBPin)==RISING){
          encCount--;
        }
      }
    }

When I tried Serial.print to check whether or not the pin A's and B's inputs were changing, I noticed that only pin A's (pin 2) input was changing. I made sure that the circuit and the wiring were all correct. Is there something about my code that is not reading pin B's input properly?

You're confusing interrupt events and pin states here.

A pin can be either HIGH or LOW. Never anything else.

An interrupt can trigger on one of four events:

The pin transitions from HIGH to LOW (FALLING)
The pin transitions from LOW to HIGH (RISING)
The pin transitions from one state to another (CHANGE)
The pin remains low (LOW)

Your code should be (as you have done) attaching the interrupt to the pins using CHANGE so you can see any change in the state of the pins.

Your interrupt code should then examine the two pins to see their current state.

But there is one bit missing from your code, and that is what was the state before this interrupt triggered? - i.e., from what did the pins change from to get to this state?

The simplest way of coding this kind of thing is to think of each pin as a bit in a 2-bit binary number. Join the two pins together to form a number between 0 and 3:

uint8_t pinVal = (digitalRead(encBPin) << 1) | digitalRead(encAPin);

The truth table for that would be:

B | A | B<<1 | pinVal
0 | 0 |  00  |   00 (0)
0 | 1 |  00  |   01 (1)
1 | 0 |  10  |   10 (2)
1 | 1 |  10  |   11 (3)

There you have 4 states. And if you remember that state from one interrupt call to the next, you can compare the current value to the previous value. And that is where you get your 8 states from.  Encoders use Gray Code so the sequence of numbers you would get as you rotate the encoder would be:

0, 1, 3, 2, 0, 1, 3, 2 ...

Or the other way:

2, 3, 1, 0, 2, 3, 1, 0 ...

And it's the transition between those values that tells you what the encoder is doing:

0 <-> 1 <-> 3 <-> 2 <-> 0 ...

Each of those transitions can go two ways, and if you count the arrows (< and >) there are 8 of them there, which are the 8 states you were thinking of before.

So if the previous value is stored in oldVal from the last time the interrupt triggered, and the new value is in newVal, your 8 states are:

oldVal == 0 && newVal == 1
oldVal == 1 && newVal == 3
oldVal == 3 && newVal == 2
oldVal == 2 && newVal == 0
oldVal == 0 && newVal == 2
oldVal == 2 && newVal == 3
oldVal == 3 && newVal == 1
oldVal == 1 && newVal == 0

The first four are progressing in one direction, the last four in the other - one set is clockwise, one is anti-clockwise.

So you could have an (untested) interrupt handler that looks something like this:

void encUpdate() {
    static uint8_t oldVal = 0; // Static variable to remember the last state
    uint8_t newVal = (digitalRead(encBPin)) << 1 | digitalRead(encAPin);

    if (
        (oldVal == 0 && newVal == 1) ||
        (oldVal == 1 && newVal == 3) ||
        (oldVal == 3 && newVal == 2) ||
        (oldVal == 2 && newVal == 0)) {
            encCount++;
    } else {
        encCount--;
    }
    oldVal = newVal;
}

You notice I've only implemented the comparison for the first four states and not the last four. Since there are only 8 states, and those states cause one of only two things to happen, if it's not one of the first four states, which would increase your count, it must then be one of the last four states which decrease your count. No point in checking for them since it can't be anything else.  If you turned it clockwise then increase the value. Otherwise you must have turned it anti-clockwise since there is no other direction you can possibly turn it in, so decrease the count.

This is precisely why Gray Code is used - only one pin ever changes at a time, so there is no ambiguity in what has happened - either you turned it one code-point in one direction or you turned it one code-point in the other. Even if there is lots of bounce it will just bounce between two neighbouring code-points and settle on the final new code point (as long as the interrupt can react fast enough to catch all the bounces).


Controlling I2C slave on Arduino with Python Typically, when I connect my Arduino to a slave device through I2C or SPI, I'll control the slave using instructions coded in the firmware. The output data will be then printed to the Serial port and I'll use Python or MATLAB to read from the serial port and process the data later on.

PC <- Arduino <--> Slave

Now say I want to control the I2C slave from my computer, i.e. write instructions to the I2C slave. How do I go about it? I thought of writing to the Arduino Serial port, making Arduino read it and hence configuring it but this doesn't seem efficient and I have been racking my head over this for a while.

Since you are using an arduino as a partial bridge to a PC, it appears that you already have a solution in hand.

There is a project on Git that is intended to perform this function that you could use for reference.  (Disclaimer -- I have not tested this code.)

The cheapest stand alone device that I found was a $15 breakout board from Adafruit.


Funduino Uno with 5V 1A power supply? Can I use a "Funduino Uno" arduino with power from a power bank with DC 5V 1A output?

Yes. As long as it connects the the arduino clone via USB and can maintain a stable power output then it's suitable.


i2c of Atmega 328 on arduino uno not working I am using Arduino uno board with Atmega 328 for i2c.
The ic is not showing any clock signal on its SCL line on oscilloscope, The same code when used with different new atmega 328, and same code. It is showing a good clock signal on oscilloscope.

The ic whose i2c is not working can be still programmed and can be used for other purposes like serial communication , adc etc.

So, is there any way by which i can confirm and surely say that i2c of my atmega 328 is fried up. And what can be the possible methods by which it can be fried up.

I2C (SDA-SCL) line needs to be pull up (place resistor on both to 5v input from master- the uno), it works with the arduino code for master-slave I2C (uno on master-severino on slave) using the code from arduino website (just be sure you set the address for the slave on the slave sketch (any number 1-126), it works for me that way, my pull up resistor is 10kohm, the same goes for my breadboard, if this is not doing the trick, maybe there's something wrong (I wouldn't know the answer to, just tried the i2c yesterday) update : on august5th (today) I just finished reading i2c's on atmel site, it is a complex one, there are several factors on why something is doing something on your twi comm, post your code, and maybe I have an answer


how to get an unofficial WiFi Shield to work? I just bought these two WiFi Shields -> http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

As they arrived I put one of them onto my Arduino Uno R3 and tried if my LED test sketch still works. It did.

After that I tried this WiFi tutorial (https://www.arduino.cc/en/Tutorial/ConnectWithWPA) to play around with the WiFi API a little bit. Sadly it prints to the serial monitor "WiFi shield not present" which tells me I missed something when setting up the shield.

I just thought the WiFi shield will be already usable without wiring anything. Surely that might be naive somehow, but hey I'm still a noob ;)

Can you guys tell me or simply point out a tutorial where it tells me what wiring I have to do to at least get pass this "WiFi shield not present" check?

Then I just realized that I do not have the "real" Arduino WiFi Shield and therefore the origin WiFi lib won't work for me according to this thread: http://forum.arduino.cc/index.php?topic=371362.0

Sadly I did not received any documenation on how to get this thing to work now. I found A LOT of threads about the "WiFi shield not present" error but none of them solved my specific problem with the shields I bought.

Somewhere it should say this: It is really really difficult to implement enough of the TCP/IP stack on an Uno to handle talking over the Ethernet.  In other words, the shield is doing almost all the work.  As such, if you don't have any documentation, using this Ethernet shield will be difficult.  That said, it looks like this shield is using an ESP8266 which IS widely documented. And if you search around, can even find people creating Arduino / ESP8266 software.


How to fix memory-leak code in ESP8266/NodeMCU caused by string concenation? I have following code in loop() in NodeMCU.

This part is before setup():

String serial_data_read = "";   // for incoming serial string data
String serial_data = "";   // for incoming serial string data

This part is in loop():

if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   serial_data_read = "";
   Serial.print("P");
   while(Serial.available()) {
      character = Serial.read();
      serial_data_read.concat(character);
   }
   serial_data = serial_data_read;
}

I don't understand C programming that much, but I think it has something to do with memory leaking and eventually running out of memory. It runs for around 20 minutes and then just stops. When I manually restart NodeMCU it runs again fine.

I would be very grateful for any help, how to rewrite my code so it doesn't leak memory. Thank you very much.

To write code that will not cause memory leak, you need to understand of where and what caused the memory leak first. The memory leak in this particular case is caused by the line
serial_data_read.concat(character);

When you instantiate a String object with String serial_data_read = "", Arduino String class create a memory allocation using dynamic memory allocation in the heap, and since your initialised it with "", it therefore create a minimum size of allocation. This is all good if you know how to the dynamic memory is created and how it going to be used.
The problem started when you start doing String concatenation with the line serial_data_read.concat(character), the original allocation for your global variable serial_data_read is no longer have enough space for the concatenated variable, so it create a temporary variable in the heap and do the concatenation, and then eventually put the result back to this newly allocated memory for serial_data_read on the heap, leaving a hole at the heap for the original serial_data_read variable (and the temp variable).
What make this worst is that this is happening for each iteration every 16 iterations(see Edgar Bonet's comment below) of the while loop. Theoretically the old serial_data_read prior the concatenation should be free-up at some point (e.g. if your while loop is within a function, the part of the heap might be free-up at the exit of the function), it however does not necessary be the case because your newly created serial_data_read stay on top of piles of to-be-free-up memory that blocking the free up(think of a piece of cheese with a lot of holes on it), so the heap memory get less and less at each iteration.
Short term fix - do not do String concatenation in a loop
String class is not always evil if you know what's going on and how to use it. One of the quick fix for your problem is simply do not do String concatenation within a loop. And if you are using it within a function, keep it local. This will minimise the heap fragmentation.
if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   if (Serial.available() > 0) {
      String serial_data_read = Serial.readStringUntil('\n');
   }
}

BTW, you can add ESP.getFreeHeap() in your loop() to check if there is still memory leak.
Long term fix - Don't use String class
For a better fix, and especially for some one new to the programming or C/C++, do not use String class and learn how to use c string and array. Here is the version without using String class.
length = 80;
char buffer[length] = {0};
if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   while(Serial.available()) {
      Serial.readBytesUntil('\n', buffer, length);
   }
}

Other resources to learn about
https://www.cplusplus.com/reference/cstring/ all the functions for c string and array manipulation to replace Arduino String class.
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


Reading multiple pins via registers on the Arduino Due I would like to read multiple pins at once in Arduino Due via registers just like PINB, PINC, PIND of the arduino uno. I know that the pins will be scattered to multiple registers, but i deduce it would still be faster this way since there for sure there will be multiple pins on a single register rather than call digitalRead 40 times.

Arduino shared the documentation for what digital/analog pins corressponds to the what ports to the actual sam chip, i just need that snippet of code that reads via registers.

So if any can give me the equivalents to these, It would be greatly appreciated:

DDRx - The Port C Data Direction Register - read/write
PORTx - The Port C Data Register - read/write
PINx - The Port C Input Pins Register - read only

You will find a good introduction on using port registers here. It also mentions some cons and pros of using port manipulation.


How to show one thing in the serial monitor? I am trying to make a device which has two push buttons and one analog input. At first the serial monitor will show INITIALIZING, then it will show ready to begin if the measured pin is pressed. Then only it will start to measure if again pressed, then it will show ****************************** and if the reset pin is pressed, it will show reset. If again pressed then ------------------------
but the problem is, it is showing

*************

(analog value) at the same time.

This is my code.

int sensor = A0;
int A = 0;
int resetPin = 3;
int measurePin = 2;
int resetstatus = 0;
int measurestatus = 0;
boolean flag1 = true;
boolean flag2 = true;
long current = 0;

void setup() {
    Serial.begin (9600);
    pinMode (sensor, INPUT);
    pinMode (resetPin, INPUT_PULLUP);
    pinMode (measurePin, INPUT_PULLUP);
    current = millis ();
}

void loop() {
    while (current < 3000) {
        Serial.println ("INITIALIZING");
        current = millis ();
        delay (200);
    }
    Serial.println ("Ready to begin");
    delay (200);
    resetstatus = digitalRead (resetPin);
    measurestatus = digitalRead (measurePin);
    if (resetstatus == LOW) {
        flag1 = !flag1;
        delay (50);
    }
    if (flag1 == HIGH)  {
        delay (50);
        reset ();
    }
    if (flag1 == LOW) {
        Serial.println ("------------------------------------");
    }
    delay (100);
    if (measurestatus == LOW) {
        flag2 = !flag2;
        delay (50);
    }
    if (flag2 == HIGH) {
        delay (50);
        measure ();
    }
    if (flag2 == LOW) {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }
    delay (100);
}

void measure() {
    A = analogRead (sensor);
    Serial.println (A);
    digitalWrite (13, HIGH);
}

void reset() {
    Serial.println ("reset");
}

You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW.  Bools are either true or false.  However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.

When you have this bit of code:

if (flag2 == HIGH)
{
    delay (50);
    measure ();
}
if (flag2 == LOW)
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}

You could use an else statement instead, i.e.

if (flag2 == true) // Corrected to true
{
    delay (50);
    measure ();
}
else
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}


Which thermometer for home brewing Hello,

I have an Arduino Yun and I brew beer.

I would like to log the temperature of the beer at all time during the fermentation process (final stage).  This means the thermometer would have to remain in the beer during this time (10 days).  The temperature would be < 40 degrees Celsius (probably around the 20 degree mark).

Question: What temperature sensor would be best suited to this task?

It must be:

Food grade
Can be used in alcohol for extended periods
Can be hooked up to Arduino (i.e. add a library and ready to go)

Thanks, Dan.

You are looking for a thermocouple.

They need some specific chip to be read, so you'll probably want to spend a bit more and get a chip with a digital interface, there are some witch has arduino library, like MAX6675 (output at 1Hz, 0.25° precision).

As this chip read "C type" thermocouple, you just have to find the right probe for your needing, with probably can be found in many specialized store.

You may even buy a normal k probe, and then wrap it up in some protective case. Obviously that case should be designed to let the heat flow easily, but without short circuiting the probe; a food plastic bag;

or just spend a little more money and buy a stainless steel probe


Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega I am trying to follow Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?

Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and  I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;

void analogWrite25k(int value)
{
    OCR4A = value;
    OCR4B = value;
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4A1)
           | _BV(COM4B1)
           | _BV(COM4C1)
           | _BV(WGM11);
    TCCR4B = _BV(WGM13)
           | _BV(CS10);
    TCCR4C = _BV(WGM13)
           | _BV(CS10);
    ICR4   = 320;

    // Set the PWM pins as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

edit2:

Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;

TCCR4A = 0;
TCCR4B = 0;
TCNT4  = 0;
TCCR4A = _BV(COM4C1)
      | _BV(WGM41);
TCCR4B = _BV(WGM43)
     | _BV(CS40);
ICR4   = 320;         // TOP = 320

easy.

find a copy of the datasheet for your mcu;
go to the section about your timer;
figure out a prescaler setting that yields the maximum roll-over count;
pick the timer mode that supports the roll-over count;
write your own analogWrite() function;
[optional] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.
done.

edit: i decided to give it a try.

the following code:

void setup() {
  // put your setup code here, to run once:
  pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);       //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  analogWrite(9, 20);                           //dc = 20/80=25%
  analogWrite(10, 40);                          //dc = 40/80=50%
}

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

produced the following output on an ATMega328p's TIMER1.

i'm reasonably sure that the output is indeed 25Khz.

the code itself however is capable of generating pwm at other frequencies.

edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

code used for that is as follows:

  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  //DC on Pin 6 = 20/80 = 25,
  //DC on Pin 7 = 40/80 = 50,
  //DC on Pin 8 = 60/80 = 75,
  pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.


Reducing Clock Speed increases sketch size? I just lowered the clock speed of my arduino promini 3.3v - 328p from 8Mhz to 1Mhz on the external clock disabling the brounout detection and when I compiled I my old sketch it wouldn't upload any more because suddenly the size has increased from 31KB to 35KB.

Does anyone know why this could happen. I didn't make any changes in the code and it still loads into the 8Mhz Arduino without any problems.

I used these low power config files: https://github.com/joe-speedboat/Arduino-LowPower

Does your code have delays in it? If you changed the clock speed, then the compiled assembly for the delays may require more NOP instructions or something similar to achieve the same real-time delay. As a result, the size of the compiled sketch could increase.


Alternative to Tone( ) Is there any way to make sounds using an Arduino without using the tone function?
It must be possible via this new method to control frequency of sound.

I've used a somewhat more complex method with some success, which uses 2 timers to play 8kHz sampled audio. The idea is that one of the timers runs at 8kHz to determine the PWM duty cycle of the other, which runs at as fast a frequency as possible.

While the original code uses a short stored sample (On an Arduino, you could store maybe 3 seconds of audio that way), my usages involved computing the audio on the fly by overlapping several sine waves or using table lookups with varying strides. As long as computation is kept simple, this just barely works.


Arduino Nano IoT 33 Char Array size constraints I would like to save data that I am receiving from API calls in a char array. The problem is the data is around 80KB however my Arduino IoT 33 has 32KB of memory. It will save data in a char array that 25000 bytes however when I go to 30000 or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, however, when receiving data over API in chunks of 10KB it won't save the entire 80KB. Is there a way to go around this? A response will be appreciated.

You can use the flash memory of the SAMD21 MCU used on Nano 33 IoT, if you don't write to often. Flash memories have limited count of write-erase cycles. It is guarantied for 10000 writes.

For Arduino SAMD boards like the nano 33 IoT you can use the FlashStorage library. The library is in Library Manager.


Using software Serial for Adafruit Thermal library and more general cpp question I'm working on a proof of concept for using the Adafruit_Thermal printer library with an ATTiny85.

The ATTiny85 does not come with hardware serial capability, so I started looking into using SoftwareSerial to create the serial port necessary. I started down this path and ran into an error in the thermal library's constructor:

// thermal-printer.ino example file

#include "SoftwareSerial.h"
#define TX_PIN 3
#define RX_PIN 4

SoftwareSerial mySerial(RX_PIN, TX_PIN);

#include "Adafruit_Thermal.h"

Adafruit_Thermal printer(&mySerial); // Pass addr to printer constructor

// Adafruit_Thermal.h

class Adafruit_Thermal : public Print
{

public:
    // IMPORTANT: constructor syntax has changed from prior versions
    // of this library.  Please see notes in the example code!

    Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

  Documents/Arduino/libraries/Adafruit_Thermal_Printer_Library/Adafruit_Thermal.h:125:33: error: 'Serial' was not declared in this scope
     Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

If I understand correctly, the verification process is failing because the compiler is looking for a global Serial value in the Adafruit_Thermal.hfile that doesn't exist because the ATTiny85 does not have HardwareSerial.

But, going by the Adafruit_Thermal class' constructor signature the reference passing of Serial is just a default value (right?) so I should be able to remove it and pass in my software serial reference. The SoftwareSerial class inherits from Stream, so it should still be a valid reference pass:

// this:
Adafruit_Thermal(Stream *s = &Serial, uint8_t dtr = 255);

// changes to this:
Adafruit_Thermal(Stream *s, uint8_t dtr = 255);

But when I do that, I start getting verification errors that make it look like the thermal instance wasn't constructed, like:

  undefined reference to `Adafruit_Thermal::begin(unsigned char)'

and

  undefined reference to `Adafruit_Thermal::Adafruit_Thermal(Stream*, unsigned char)'

Does this mean the class isn't getting constructed?

I looked at the underlying constructor definition to see if something was blowing up in there, but there doesn't seem to be anything fancy at the constructor level:

// Constructor
Adafruit_Thermal::Adafruit_Thermal(Stream *s, uint8_t dtr) :
  stream(s), dtrPin(dtr) {
  dtrEnabled = false;
}

This should still work with the software serial reference pass, right?

I'm a bit lost on how to debug this now. Any ideas?

Update

After a reply from Majenko I pulled up the cpp file and looked at the header reference:

So this means the cpp file was still referring to the include path header file instead of the lib version?

I updated my cpp file to use:

#include "lib/Adafruit_Thermal.h"

and I still get undefined reference errors, so it may still be something else, but I wanted to share this additional info.

:'( it's a bitter sweet solution.

After @majenko's last comment:

  Ah. So is there something you have to do in that IDE to say "Include the files in lib in the compilation`?

I remembered that this issue has bitten me before. Specifically, the issue of including subfolders into a sketch.

Normally in programming languages (at least all of the ones I work in normally), you can use relative paths or namespaces to include files from subfolders, but for some reason with Arduino if you want to include files from subfolders you have to put the files in a directory named src.

And it specifically needs to be src. You can't use lib or libs or source or whatevernameyouwant, it needs to be src.

I can't find a spot in the arduino reference docs or the IDE's github repository that explains that you need to use src for the subfolder name, but you can find various mentions in the forums. E.g.

https://arduino.stackexchange.com/a/54655/35534

So yeah, the solution to my problem was three parts.

Adopting the Adafruit_Thermal library into my codebase so that I could edit the source code without worrying about those changes polluting the orginal.
Removing the &Serial reference pass in the constructor declaration of Adafruit_Thermal.h
using the src directory name to include things from a subfolder.

After doing this, the sketch passes verification.

But here's the bittersweet part. After getting past all of this and seeing the compiler get past the sketch verification the bombshell dropped; the sketch is too big for the attiny:

I guess it was not meant to be :'(

Well, at least I know what was causing the linker/compiler errors and I'll be able to sleep at night :P

Thanks for your help Majenko :bows:.


invalid conversion from 'char' to 'const char*' My intention was to overload a function to handle optional parameters. My code looks like

void functionA(const char *errorMsg) {
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg) {
    ...
}

The line functionA('0',... generates the error

invalid conversion from 'char' to 'const char*'

How do I fix that?

What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of functionA() and is trying to cast '0' to a 'const char *` and that isn't going to work…

If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.


Is it possible to insert your own routine into the Reset procedure I'm working with  ATmega328 NANO boards, and I would like to know if it is possible to INSERT my own routine, to be included in the things done during reset, BEFORE any pre-C initialization is done, or any upload of new code occurs. If this is possible, I'd like to know how. I'd want to be able to "install" this routine during setup(). I also would not expect it to work after a power loss. I'm talking about a reset caused by pressing the reset button, uploading code, opening a serial port, or any reset that was NOT caused by a loss of power.

I'm including a simple example sketch illustrating what I would LIKE to do, but it obviously won't do what I want as written, because I do not know the "magic" answer I'm seeking,

I've defined and initialized a global static byte outside of any functions. The setup() simply reads a byte from EEPROM and displays it with Serial.print(), and then stores its value in that global 'number'.  Now notice I created a void(void) function called magic(). It simply increments the global number and stores it in EEPROM. I call it "magic() because what I need to do to call it is unknown. I want some way to "install" magic() during setup(), so that it runs only as part of the reset process, before anything within code or data space is affected. By install, I don't mean just call the function. It should not actually be called unless RESET occurs.   Whatever "magic" has to be added to make this happen, the proof of the pudding will be that after loading the sketch. every time you press RESET, or even upload the sketch again, the printed number will be different, because it was incremented and saved when reset was pushed. NOTE: (I just edited some stupid errors here)

#include <EEPROM.h>

static uint8_t number =0;

void setup()
{
  uint8_t n = EEPROM.read(0);
  Serial.begin(57600);
  Serial.print(n);
  number = n;

  // somehow, install "magic" routine here

}

void loop() { }

void magic(void)
{
 ++number;
 EEPROM.write(0, &number);
}

Yes, it is possible. See the documentation on memory
sections, from the avr-libc manual. For example:

// Run this after initializing the stack pointer and zero_reg, but
// before initializing the RAM.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    // Whatever...
}

Note that this runs after both a warm reset and a cold boot. See
Gerben's answer if you want to tell the difference between these two
reset conditions.

Note also that, if you just want some data to be preserved through a
reset, you can put it in the .noinit section, no need to use the EEPROM.

Edit 1: In response to the OP's comment, here is a small program
demonstrating the technique. It just quickly blinks the LED three times
early in the program initialization, then three more times, more slowly,
during setup():

#include <util/delay.h>

// Blink the LED three times, fast, early in the initialization.
void __attribute__((naked, used, section(".init3"))) magic(void)
{
    DDRB |= _BV(PB5);      // pin PB5 = digital 13 as output
    for (int i= 0; i < 6; i++) {
        PINB |= _BV(PB5);  // toggle PB5
        _delay_ms(100);
    }
}

// Blink the LED three times, slowly.
void setup()
{
    pinMode(13, OUTPUT);
    for (int i = 0; i < 6; i++) {
        delay(300);
        digitalWrite(13, !(i & 1));
    }
}

void loop(){}

I tested it on an Uno, and it works.

Note that magic() runs before the Arduino core library has been
initialized. At this point, many core function, like delay(), do not
work. Any job that is done here should be done low-level, using only
direct port access and avr-libc calls.

Edit 2: In the previous version of this answer I forgot the used
attribute. It worked with the old Arduino setup I tested with, but not
with the newest IDE. Adding the used attribute fixes this.


Arduino pin 13 as PWM output, not possible? I have noted on more than one occasion the comments in sketches "reserving pin 13 for future PWM backlight dimming of the LCD" while using Uno and Nano boards.
Am I missing something ?  I always considered it NOT possible as PWM output is only available on pins 3,5,6,9,10 and 11 on most boards.

Arduino pin 13 is SCK/BP5 on the ATmega8 MPU, there's no hardware PWM capability on that pin, so any PWM would be software driven.


Do I need resistors or capacitors on this relay? I'm using my Arduino to control a relay switch, which has an extension cord attached to it (see photo).

The relay is connected to the Arduino via pin 9, which is set to pinMode(9, OUTPUT);

Do I need any resistors or capacitors or diodes attached to this? Almost feels too simple, given I'm running AC power through the relay. But maybe no?

It definitely works, but I want to make sure I'm not going to burn something out (or down).

Yes, that is too simple.

The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.

Google for "Arduino Relay" and you will find hundreds of thousands of examples.

In short, the circuit you need to create is this:


cannot get low power with Adafruit Trinket I want to get as low power use during sleep as possible with an Adafruit Trinket. Based on results presented on various places in the internet (blogs etc), I expect to be able to go down to 50 - 100 micro amps on the ATTiny85 of the Trinket. I am aware of the fact that using a board such as Trinket may add a bit of consumption, and I physically removed the power LED and the power regulator. I am feeding 5V directly on the 5V pin.

I am using the simplest sketch I can think about for low power, with nothing connected to any pin:

#include <avr/sleep.h>          // library for sleep

#define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC (before power-off)

void setup() {
  // put your setup code here, to run once:
  delay(10000);

  // power_all_disable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  adc_disable();
  sleep_enable();
  sleep_mode();

}

void loop() {

}

But I cannot get less than around 1.3 milli amps consumption during sleep. Do you know what may be the cause of using ~1mA instead of ~100 microA? Any idea how I can decrease this further?

Edit 1: it should be even much less than ~50 - 100 micro Amps: ATtiny85: Power consumption vs clock speed ; even though this the libraries are maybe primary intended for the ATMega328P, it looks like it should work also with ATTiny85 as well: http://www.technoblogy.com/show?KX0

Edit 2: I had an ATMega328P-based Adafruit Metro Mini lying around. I took away the ON LED, and then using exactly this sketch, feeding power directly on the 5V pin of the Metro Mini, leads to a power consumption of around 150 micro Amps during sleep, which is more like what I expect. Strange it is 10 times more with the ATtiny while it should have been less (?). Am I missing something or is it maybe just broken library on ATtiny? This is a bit ironic, as I went for the lesser ATtiny85 based board for saving current compared with the ATMega328P...

Please have a look at the schematics:
https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit_products_trinket5.png?1378223478
The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5[V] - 3.6[V])/1500[ohm] = 0.0009333... ~= 0.001 [A].
Even though I'm not completely sure without making some tests, that seams plausible to me.
EDIT
(Answer to the OPs comment below.)
The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits  the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us  by Ohms Law that the current through the  resistor is:
I = U / R
I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.


Life span of arduino We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light  project selected in Smart India Hackathon 2017 under ministry of steel. For this project  We are using Arduino nano to control street lights in industries. Now we are requiring some general following  information about arduino nano.

What is the life span of Arduino nano?
We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include  serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?

Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051.
What you want to focus on might be the enclosure, seal it against the outside.

Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/


How to use 503 Thermistors for temperature? I have a black Thermistor with the number 503 on it.

I know that I would need a 50k resistor as a voltage divider.

I don't get to convert the number I am getting. I get the number 340 when my house is at 64*F.
I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17*C I get 30k ohms.

This is how it is wired:

[Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                              |
                         Analog Pin 0

First of, 503 means 50 x 10^3, ie 50K Ohm: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.

I think what could work well is just simple calibration by establishing a mapping between
the value returned by analogRead() and the temperature measured by a real, good precision, thermometer.

Establighing the mapping for 2 extreme temperatures would provide a first approximation on computing any temperature from the read value.

However, such an approximation would not be very accurate because thermistors are not linear, ie their resitance don't vary linearly with temperature.

What you can try to do then, is to increase the number of mapped value<->temperature with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.

The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...


Get value from a website using Yún and a RPi I have a project that requires opening a door remotely. I'm using an arduino Yún and a raspberry pi.
 I have a switch connected to the RPI and i'm sending it's value to a web server. How can I get the value from the website to the arduino, so that it can process it and see if an order to open the door is issued?

Thanks for any help :)

You need to use the Process library that comes with the IDE.

That allows you to execute commands on the Linux portion of the Yun from within your Arduino code, and get data back from it.

You use that class to execute the curl command in Linux to fetch the content of a web page and return that content to the AVR code where you can deal with it.

If the content of the web page is complex it may be worth passing the output of curl through some other Linux based commands first (such as grep and cut or awk) to clean it up and reduce the amount of text you have to deal with at the AVR end.


Arduino Uno as keyboard I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using this link also and programmed it like this.

uint8_t buf[8] = {
 0
};

int inpin1 = 7;
int inpin2 = 8;
int val1 = 0;
int val2 = 0;

void setup() {
  Serial.begin(9600);
  delay(200);
  pinMode(inpin1, INPUT);
  pinMode(inpin2, INPUT);
}

void loop() {
  val1 = digitalRead(inpin1);
  if(val1 != HIGH) {
   buf[2] = 80; // Left Arrow
   Serial.write(buf, 8);
   releaseKey();
  }
  val2 = digitalRead(inpin2);
  if(val2 != HIGH) {
    buf[2] = 79; // Right Arrow
    Serial.write(buf, 8);
    releaseKey();
  }
}

void releaseKey() {
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8);
}

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?

You should just not call the releaseKey function, until the button is released.

int oldVal1 = 0;
int oldVal2 = 0;

void loop()
{
    val1 = digitalRead(inpin1);
    if( val1!=oldVal1 )
    {
        oldVal1 = val1;
        if(val1 != HIGH)
        {
            buf[2] = 80; // Left Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

    val2 = digitalRead(inpin2);
    if( val2!=oldVal2 )
    {
        oldVal2 = val2;
        if(val2 != HIGH)
        {
            buf[2] = 79; // Right Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

}


WaveHC Library Trouble I posted this on the main Arduino forum, but no one has responded in 24 hours.

I'm trying to use the WaveHC library from Adafruit with a custom PCB. I am having trouble getting the SPI com to work for some reason, I modified the ArduinoPins.h, SS_PIN, from pin 10 to 8.

Using the Arduino SD library, I can see all the files no problem.

In the WaveHC library, all of the examples freeze after card.init(), I traced it to the spiSend(uint8_t b) in SdReader.cpp. It seems to get stuck in while(!(SPSR & (1 << SPIF)). This looks like the SPDR register (the SPI data register) is never loaded properly.

Does anyone know what is going on?

Adafruit library : https://github.com/adafruit/WaveHC

Edit :
This is the output from the SDReadTest example (Arduino SD Library)

Initializing SD card...Wiring is correct and a card is present.

Card type: SD2

Volume type is FAT32

Volume size (bytes): 1973350400
Volume size (Kbytes): 1927100
Volume size (Mbytes): 1881

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2016-11-07 14:11:06
  INDEXE~1      2016-11-07 14:11:06 76
0.WAV         2016-11-07 11:44:14 22124
1.WAV         2016-11-07 11:44:14 18604
2.WAV         2016-11-07 11:44:14 19244
3.WAV         2016-11-07 11:44:14 19884
4.WAV         2016-11-07 11:44:14 21164
5.WAV         2016-11-07 11:44:14 23084
6.WAV         2016-11-07 11:44:14 21484
7.WAV         2016-11-07 11:44:14 29484
8.WAV         2016-11-07 11:44:14 20844
9.WAV         2016-11-07 11:44:14 25004
P.WAV         2016-11-07 11:44:14 21804

Notes :

I am using an Atmega328P @ 8MHz with the pro mini bootloader (this may be the issue)
SPI_DEFAULT_HALF_SPEED is set to true
SPI_INIT_SLOW is set to 1

So the problem was that I did not read this comment carefully

/** SPI slave select pin. Warning: SS may be redefined as another pin
but the hardware SS_PIN must be set to output mode before any calls to
WaveHC functions. The SS_PIN can then be used as a general output pin */

"SS_PIN must be set to output mode before any calls to
WaveHC functions"

I read this and thought that meant whatever pin was being used as the SS pin needed to be an output, but it meant literally that pin 10 (the hardware SS pin) had to be set as an output regardless of whether it was being used or not.

So the solution is to add

pinMode(10, OUTPUT);

to anywhere in the code

Edit : also thanks @per1234 for pointing out the correct answer, I just didn't read your comment properly.


Interfacing Hex keypad with arduino I was trying to interface my hex keypad with Arduino. I declared rows as input and columns as output. When I initialize three of the four columns as HIGH and one as LOW, and detect the button pressed as LOW in the corresponding row, it works fine. That is, it detects the button when its corresponding row and column is LOW. But, when I reverse the condition, i.e. when I try to detect the button pressed when its corresponding row and column is high while others are low, it does not work as expected.

I really want to know why is this happening?

The code that works:-

int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],HIGH);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],HIGH);
      digitalWrite(row[1],HIGH);
      digitalWrite(row[2],HIGH);
      digitalWrite(row[3],HIGH);
      digitalWrite(row[i],LOW);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==LOW)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

the code that doesn't work:-

int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],LOW);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],LOW);
      digitalWrite(row[1],LOW);
      digitalWrite(row[2],LOW);
      digitalWrite(row[3],LOW);
      digitalWrite(row[i],HIGH);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==HIGH)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

To use unipolar switches as inputs, you need pulling resistors to give the input pin a defined value when the switch is open.

The ATmega has software configurable internal pullups.  Even if these are not configured, implementation detail may (or may not) yield a very weak unreliable pullup effect.

There is no configurable pulldown on the ATmega.  To operate in that direction (with a switch to high) you would need external pulldown resistors.

A few matrix keyboards include diodes, to combat some of the confusion which results when multiple keys are pressed in a simple matrix.

Also, you should add a tiny delay between driving and reading, in order to allow for capacitive delay.


Replying with a html page in HTTP Web Server using esp01 and ArduinoIDE Now there are many ways to reply with a webpage content to a user who is accessing the web server,
But Keeping in mind to use as less space as possible,
I was trying something new, Since i didnt got compilation error, I am a little confused as to what might be the error,

in void data() I am storing the html page and saving it in ROM,

void data()
{
  if(SPIFFS.exists("/login.html"))
  {
    Serial.println();
  }
  else{
    SPIFFS.begin();
    File f=SPIFFS.open("/login.html","w");
    String s="<title>AP</title>
Welcome to AP page
\n";
    s+="<form name=\"/myform\" action=\"/login\" method=\"POST\">\n";
    s+="<input type=\"text\" name=\"username\" placeholder=\"username\">
\n";
    s+="<input type=\"password\" name=\"password\" placeholder=\"password\">
\n";
    s+="<input type=\"submit\" value=\"login\"></form>";
    f.println(s);
    f.close();
  }

}

Please correct the above lines if I wrote it wrong,
After that,
I wrote some lines in void setup()

WiFi.mode(WIFI_AP_STA);//Only Access point
  WiFi.softAP(ssid, password);  //Start HOTspot removing password will disable security

  IPAddress myIP = WiFi.softAPIP(); //Get IP address
  Serial.print("HotSpt IP:");
  Serial.println(myIP);

  server.on("/", HTTP_GET, handleRoot);      //Which routine to handle at root location
  server.on("/",HTTP_POST,handlelogin);
  server.onNotFound(handleerror);

  server.begin();

Now  I am calling void handleRoot()
I want to send the page that I wrote and saved in the /login.html file.

so for that,

void handleRoot()
  {
    SPIFFS.begin();
    File f=SPIFFS.open("/login.html","r");
    server.send(200, "text/html",f.readStringUntil('EOF'));
  }

Now once I do this and execute and load the program in ESP01, it shows me nothing,
I have also tried sending (String)f, anything else I write is giving me an error,
This is compiling fine, but when I connect to the AP and open 192.168.4.1 in the browser i am not seeing anything,
But when I wrote server.send(200,"text/html",(String)f)
I was getting 0, Any idea on what mistake I am making.

Small update, I used the same code for ESP8266 NodeMCU.

Sorry If I am posting this with wrong device number. But I tried that same code and uploaded it to ESP8266, it worked, and I am getting the AP webpage, that I am storing and sending the file. I will post it as an answer as I need to post an image.

The is the page that I get when using the HTML that I wrote:

So, this happened. I am confused as to why it didn't work with ESP01, plus I have to load the code every time I plug in the ESP01.


Millis () funtion fails to perform for extended period of time I'm using millis () function to control the timer of my LED. It is a very basic code that I used from the example libraries. The code worked well for 6 hours (On for 6 h, Off for the following 6 h and continues), however, when I set it up for 12 hours, the light failed to turn off when I checked on it. The designed time should have fit into the 2^32 bits for unsigned long which I have defined beforehand.
Can someone please help on this issue? Thank you!

/*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  7;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
unsigned long interval = 12*60*60*1000UL;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

In C++, the multiplication operator is “left-associative”. This means
that the expression

12*60*60*1000UL

is interpreted as

((12*60)*60)*1000UL

The left factor, namely (12*60)*60, is computed using the int data
type, but the result overflows that format, resulting in the problem you
see.

The simple solution is to make one of the factors of the first product
be an unsigned long. For example

1000UL*60*60*12

Then, 1000UL*60 is computed with the unsigned long data type. Since
the result is itself an unsigned long, the next multiplication is also
done as unsigned long, and likewise for the last one.

If you find this technique somewhat obscure, you can also add the UL
suffix to every single factor. This would avoid implicit conversions by
the compiler, making all the types explicit.


No Data Received on Serial Port & Unable to DFU Reset. Advice? Having a problem running my original code that I tested last week, which worked on multiple days last week.

I tried to do a DFU reset and update the BootLoader, but it didn't work. I checked the baudrate and board selections in the Tools tab, but those were fine.

I didn't change anything in the code, I checked the wires on the hardware setup (nothing looks loose).

Thought it could be an error with the USB cable, changed the USB cable to a different one, still same error.

Also - using a Mac. But the same issue arose on the Windows PC. Did not try to reset using the Windows computer, but reset issue has more to do with the other hardware?

Checked the serial port - and it's selected to right one.

Step Zero - check that the port selected works.

Step Next -  if you still get the error, try the DFU reset options and follow the steps outlined in the link below.

https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/using-the-bootloader


Will unnecessary Serial.print() statements slow down my program? I have lots of Serial.print() and Serial.println() statements throughout my (rather large) program for debugging when things fail. I've commented out the Serial.begin() statement so I don't slow down execution by running a serial port. However, I'd like to leave the Serial.print() calls so I only have to uncomment Serial.begin() later on.

If there is no Serial port active on the device, are the Serial.print() lines still executed at runtime, or does the compiler ignore them? Is there any performance advantage to explicitly commenting out those lines?

No, there is no USART wasn't enabled so skip all prints. Everything must be done anyways (calls, conversions to strings, writes to UDR - USART Data Register). It is just not sent outside by USART and it doesn't have to wait for UDRE (USART Data Register Empty flag) so it might be slightly faster.

You can use similar technique as Loggers - log level variable and ifs (this can be changed runtime).

Or you can use macros:

// comment out this line, if you want to show logs:
#define NDEBUG

#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__)
  #define LOGLN(...) Serial.println(__VA_ARGS__)
#endif

And later:

LOG(F("Something: 0x"));
LOGLN(variable, HEX);

And how it looks after macro substitution? For code:

if (...) LOG(F("something")); else LOG(F("something else"));

With NDEBUG defined it's expanded to:

if (...) ; else ;

And without NDEBUG defined it's expanded to:

if (...) Serial.print(F("something")); else Serial.print(F("something else"));


How might the SD library be reading phantom files? I have the Sparkfun CAN Bus shield with integrated SD card writer attached to an Arduino Mega 2560. I can delete a logged file from the SD card using Windows, log more data using the SD library, then look at the logged data in, say, Excel. The new log file will include the logged data from the old, deleted file.

The card is formatted in Windows in FAT32 and the logged file has the same name as the original. It seems like the SD card reader/SD library is able to 'recover' the deleted file by name, open it for writing having read its uncorrupted contents, and continue logging to it, despite it having been 'deleted' in Windows. I know a deleted file doesn't get rid of the data unless it is overwritten, but there seems to be some bug/oversight in how the SD library in card reader or how it interrogates the SD card or FAT32 volume for the existence of the file.

Has anyone come across this before? Is it a bug or am I doing something wrong?

How large is the file when it is deleted in Windows? I can imagine what you describe happening if there's a bug in the Arduino File System (see below) - but that requires relatively small files (less than 4K or so).
I assume that the SD card has zero or more "static" files, that don't change; and then the log file, that grows. That is, when the log file is deleted, the newly-freed blocks get re-used again for the new log file?
I also assume that you're using Windows' "Safe Removal" mechanism - giving it a chance to tidy up the SD Card before you yank it out.

To delete a file in FAT, the file system needs to do two steps:

Unlink the used blocks from the File Allocation Table (the eponymous F.A.T.).
These should be set back to zero - making it hard to accidentally re-use them again unless they're the same blocks again (which, for SD Cards, is unlikely due to wear levelling!)
Mark the directory entry as available again.
This is done by merely overwriting the first character of the directory entry with 0xE5. When FAT needs a new directory entry, it will use entries with either 0x00 or 0xE5. If the deleted file is being "resurrected", then a bug could be that it re-uses the directory entry but doesn't zero the existing contents, allowing the existing block number and length to be appended to.

Rather than deleting the file in Windows, try renaming it to something else entirely. That way the Arduino will create a new file, and you shouldn't have the problem. If you still do (worse: if the renamed file gets corrupted) then it's a caching problem. If you don't, then it's a bug in the file system.


Alternatives to Nextion display I am wanting to have a display where I can design the GUI on a program and then somehow transfer it to the display. For the graphics I want to make, it would be really hard to manually write the code. I heard that the Nextion displays do this but they are quite costly. Is there some cheaper alternative? If not, can you make a normal display do all of that?

We work with Proculus displays, and we are a distributor of this display here in Brazil (Victor Vision). The display is great, very professional. Used in medical equipments, and cheaper than Nextion.
They are starting now in the web and selling in Alibaba.


Wrong data from DS18B20 temperature sensor after long power off I have my Arduino Uno connected to the PC via USB when prototyping.  I am developing a thermometer with memory, using DS18B20 sensors.

When PC is shut down, there is no power on the USB and the Arduino is off. Sometimes, when my PC is turned off for several hours and then, when I turn it on, the Arduino is started, but it behaves "strange" - the program is showing buggy values on the display, looking like if there is some bug in the sketch. However, when I upload the sketch again, it works fine.

The buggy values are the averages for the run, computed simply by summing a float and dividing by int. What I see is e.g. instead of seeing something around 23.5 I see 85.1. The current values read from the sensor look OK (show 23.5 as expected), but I cannot tell for sure if perhaps some value read early might be wrong.

It is not easy to reproduce, I see it only sometimes, always when powering Arduino on after several hours without power.

My first idea is either the sketch got corrupted during the long power down, or variables are initialized wrong, and the sample sum / sample count is not zero.

However I though the sketches are uploaded into the Flash RAM, which should be non-volatile according to the docs. Is there something obvious I am missing, some explanation why is the sketch working differently after long power down?

I researched this once when I was getting consistent, exactly 85 degC readings from my sensors. The Maxim DS18b20 data sheet (rev 042208, page 4, in a footnote to Table 1) says:

  "The power-on reset value of the temperature register is +85°C.

Double check that the Arduino code is follows the sensor communication protocol correctly.


WS2812B only works while I measure the voltage I'm going crazy, there is clearly something I'm missing here.
I have a NodeMCU V3.0 and a 5V LED strip WS2812B with 10 diodes.
I tested this first with a 5V 0.3A power supply, only powering 3 diodes, this worked fine.

Than I changed the power supply to a 5V 2A (Measured to 5.2V) and now the colours are way off, they even change everytime its updating, even though nothing is changed. I put my voltmeter across "D3" and "GND" and suddently the LEDs were perfect and stable.

If I remove it again, the LEDs change to random colours again, I tried pulling "D3" to ground with a 10 kOhm resistor, but this doesn't change anything.

What is going on here, why isn't it working, and why does it work with the voltmeter?

Code:

#include <ESP8266WiFi.h>
#include <FastLED.h>

#define LED_PIN     3
#define NUM_LEDS    10

CRGB leds[NUM_LEDS];
int R = 255;
int G = 90;
int B = 10;

//Set up MQTT and WiFi clients
WiFiClient client;

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

  //Connect to WiFi
  Serial.print("\n\nConnecting Wifi... ");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
  }
  Serial.println("OK!");
  pinMode(D4, OUTPUT);
  digitalWrite(D4, HIGH);
}

void loop()
{
    leds[0] = CRGB(255, 0, 0);
    leds[1] = CRGB(0, 255, 0);
    leds[2] = CRGB(0, 0, 255);
    FastLED.show();
    delay(5000);
}

WS2812B LEDs are 5V devices. The NodeMCU is 3V.  Your first 5V supply will probably have been somewhat under 5V once the NodeMCU had taken a big chunk of the current (see Voltage Droop). This would mean that the Logic High Threshold would be within the bounds of the 3.3V output by the NodeMCU.

However, with your new high powered power supply that voltage droop will be less prevalent (added to the fact that it's measuring 5.2V), and so the logic high threshold will be higher. At, or very close to, the 3.3V that is output by the NodeMCU. That makes it rather unstable at communicating, since the logic HIGH may not always be above that required HIGH threshold.

Adding your voltmeter obviously changes that logic signal so that it stabilizes above the required threshold (the volt meter input has capacitance. That will help hold the line higher for longer).

To drive 5V devices from a 3.3V MCU you really need to add a logic level shifter, or ensure that the power supply isn't too high.

The WS2812B has a logic HIGH of 0.7 × Vdd. At 5V that's (0.7*5=) 3.5V. That's close, but not quite there. Your original power supply was probably putting out more like 4.75V under load. That would be 3.325V for a logic high - just about manageable by a NodeMCU.

However at 5.2V the logic HIGH will be 3.675V, which is way above the 3.3V that the NodeMCU outputs.

So you either need to:

Add a 3.3V to 5V logic level shifter, or
Reduce your LED power input voltage to below 4.75V.

The latter can be done by adding a single series diode with a suitable current handling capacity to the VDD connection. That will (depending on the diode) drop around 0.7V taking you to about 4.5V (the actual drop usually depends on the current to a certain extent).  The WS2812B will happily run from 3.5V to 5.3V.


How to add a pedestrian button code to a traffic light with ultrasonic sensor? So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.

I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:

// Variables for Station 1 Traffic Light Components
const int Red1LED = 9;
const int Yellow1LED = 2;
const int Green1LED = 3;
const int GreenArrow = 4;
#define trigPin 12
#define echoPin 13
// Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 5;
const int Yellow2LED = 6;
const int Green2LED = 7;
const int GreenArrow2 = 8;

void setup() {

  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(GreenArrow, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(GreenArrow2, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
 Serial.begin(9600);
  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  //delayMicroseconds(10); // Added this line
  //digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.println(distance);
  if (distance < 20) {  // This is where the LED On/Off happens
     delay(1000);  //  1 Seconds of Red
  digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Yellow1LED, HIGH);
  delay(1000);  // 1 Seconds of Green
  digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Red1LED, HIGH);
  delay(1000);  // 1 Seconds of Yellow
   // Station 2 Timing
  delay(1000);  //  1 Second of Red
  digitalWrite(Red2LED, LOW);
  digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
  delay(1000);  // 1 Second of Green
  digitalWrite(GreenArrow2, LOW);
  digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
  delay(1000);  // 1 Second of Yellow
  digitalWrite(Green2LED, LOW);
  digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
  delay(1000);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Red2LED, HIGH);

   digitalWrite(Red1LED, LOW);
  digitalWrite(GreenArrow, HIGH);
  delay(1000);
  digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite( Green1LED, HIGH);
}
  else {
   digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
  digitalWrite(Red2LED, HIGH);
  digitalWrite(GreenArrow, LOW);
  digitalWrite(Green1LED, HIGH);
  digitalWrite(Yellow1LED, LOW);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Green2LED, LOW);
  digitalWrite(GreenArrow2, LOW);

  }
}

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.

Thank you for making it clear that this is course work.
You are asking for help to do the extension, but by your own words you don't understand how the core code works.  I have to be honest I can't be bothered to read the code, it looks horrible.  If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding.  "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty!  (If you teacher can't be bothered to read it, you aren't going to get 100%!)

Comments - commenting out code is not the best use for // explaining why you are doing what you are doing is.
Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures.  (These might be more advanced than where you are at the moment, sorry if that's the case).
Breaking you code down into bite sized pieces make it more readable.  That start of your loop contains some code that could be in a function called getDistance()
Turning the lights on and off in the way you are doing it is open to errors.  You could turn the red light on and the green light on.  If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted.  You wouldn't need to store the state.

Example code (not tested or compiled)

class Lights
{
  public:
    enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
    Lights(int[] pins)
    {
      for (int l = 0; l < eMaxLight; ++l)
        pinMode (pins[l], OUTPUT);
    }
    ~Lights()
    {}
    void setLight (eLight newLight)
    {
       for (int l = 0; l < eMaxLight; ++l)
         digitalWrite(m_Light[l], LOW);
       digitalWrite(m_Light[newLight], HIGH);
    }
}

You probably want to look at a state machine.  List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed.  This should give you a working system with a pedestrian button that hopefully you understand.


Problem with microSD SPI mode in AVR I'm trying to read a microSD block. But I don't know why it doesn't work.

I do:

CS_UP;
for(uint8_t i = 0; i <14; i++){ /* Send 74+ clocks */
    spi_tranceiver(0xff);
}
_delay_ms(1); /* Wait 1 ms */

//CS_UP;

/* Initizalize microSD */
put_string("Go to idle state\n");
while (Reset_Card() != 0x01) // Go to idle state
    ;

put_string("Send IF COND\n");
while (Send_CMD8() != 0x01) // SEND IF COND
    ;

put_string("Send ACMD41 and CMD55\n");
for (int i = 0; i<100; i++)
    while (Send_CMD55() && Send_ACMD41())
        ;

setBlockLen(); // Set block read in 512 bytes
CS_DOWN;
put_string("\nConfigure finished correctly\n");

And then I just call:

readSingleBlock(0x00, &buf)

readSingleBlock is defined as follows:

uint8_t readSingleBlock(uint32_t block_address, unsigned char *buf)
{
    int i;

    block_address = block_address << 9;

    CS_UP;
    while (0x00 != sdsc_command(READ_SINGLE_BLOCK, block_address))
        ;

    while (0xfe != spi_rx ())
        ;

    for (i = 0; i < 512; i ++ ){
        //buf [ i ] = spi_rx();
        put_int(spi_rx());
        put_string("\n");
    }
    spi_rx();
    spi_rx();
    CS_DOWN;

    //for (i = 0; i<512; i++) put_int(buf[i]);

The problem is that the printout is:

0 0 0 ..(zeros).. 128 255 255 255 12 255 255 255 0 8 0 0 0 72 59 ..(zeros).. 85 170

Did somebody encounter this problem?

Do you have some suggestions?

I formated the SD card, and then work correctly

Thanks!


Why is my arduino acting like a radio? And is there a way to abuse this? I am playing around with an arduino and a cheap SDR dongle and I just noticed something strange!

When I play a tune on pin 13 with just a random piece of wire connected to the pin (Using the Melody example from the arduino page: http://www.arduino.cc/en/Tutorial/Melody)
I can pick it up as AM sound on my SDR on exactly 64Mhz even as far as 15meters away through walls with a little gain!!!

What magic is going on here and secondly and maybe most importantly would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

(Just for educational purposes of course, I know that there is better options depending on what I need to send)

I would like any qualified guess as to what is going on, I am genuinely puzzled...

I did something like that a while ago. Hardware:

Code:

const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

If you hold the Arduino near an AM radio tuned to around 800 KHz you should hear a hissing toggling on and off (like Morse code) as the carrier is turned on and off for 0.5 / 0.3 second intervals.

  would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

I think you might find making a receiver a bit harder than a transmitter.


What is importance of the reflow profile? I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the Reflow Soldering Definition

As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.

Why is important?

How do you read this values?(or when you use this data)

Reflow soldering is an assembly process for printed circuit boards (PCBs) in which surface-mount parts are placed on a PCB prepared with solder paste.  The solder is melted by heating in a temperature-controlled oven, which then electrically connects component leads to pads on the PCB.  ICs can be damaged by high temperatures/rapid changes in temperatures, so the thermal profile defines the acceptable limits on the temperature of the reflow to avoid damaging the component.


FTDI Adjustable 3v3/5v only outputs 5v I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.

http://www.ebay.co.uk/itm/301597777458?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

Now on the eBay description it says:

  This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.

You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.


amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support getting the following error when trying to upload Amblone code to my Arduino One board:

Arduino: 1.6.12 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\pha\Desktop\amblone\amblone.pde: In function 'void setup()':

amblone:85: error: 'TCCR3B' was not declared in this scope

   TCCR3B = TCCR0B & 0b11111000 | 0x2;

   ^

amblone:86: error: 'TCCR4B' was not declared in this scope

   TCCR4B = TCCR0B & 0b11111000 | 0x2;

   ^

exit status 1
'TCCR3B' was not declared in this scope

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe1
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Code:

void setup()   {
  // initialize the serial communication
  Serial.begin(256000); // opens serial port, sets data rate to 256000 bps

  TCCR0B = TCCR0B & 0b11111000 | 0x2;
  TCCR1B = TCCR0B & 0b11111000 | 0x2;
  TCCR2B = TCCR0B & 0b11111000 | 0x2;
  TCCR3B = TCCR0B & 0b11111000 | 0x2;
  TCCR4B = TCCR0B & 0b11111000 | 0x2;

  State = S_WAIT_FOR_SF;
}

Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.


How to make BLE data accessible to a particular app? I used the BLE example from here.

But any device can read and write to the advertised characteristic. Is there a way to make the data inaccessible to other devices except for my app somehow. What I would really like to do is something like SDP and then connect and exchange data over RFCOMM but it seems impossible to do so in esp32. I have done it using bluez library on Linux but in case of esp32 I found only one library btstack that is impossible to use with esp-idf because of lack of CMakeLists.txt. Is there some way I can achieve what I want?

In general terms, you could simply require a client to authenticate first. This would require a bit of a deviation from the example you linked to (which actually only handles reading of the characteristic) to handle multiple connections and their state, but it should be pretty straightforward.

The Arduino BLE library seems to lack sending quite a bit of information via the callbacks, so you just know there's a connect or disconnect or a write to a characteristic, and not which devices did. This means you won't be able to handle multiple connections at the same time, but making sure you reset your authentication state whenever you receive a connect or disconnect should be enough to prevent anyone but your own client from "talking" to your device.


OLED display crashes when connecting USB I got an 16x2 OLED Display (DEP 16201-Y , compatible to the HD44780 controller) for my Arduino Uno and I got it to work in 4-bit Mode, but just if the USB isn't connected and it is powered by a 9V power supply.

So my routine is:

Connect USB and power supply
Upload Code
--> Doesn't work
Disconnect USB and power supply
Just connect power supply
--> Works
Connect USB
--> Display crashes

So basically: If the arduino is connected via USB to my PC, with or without an additional power supply, the display won't work properly, it will crash or the Arduino even restarts itself. (some kind of memory error?)

I have no possible explanation for this..

Thanks for your help.

EDIT: I'm running Ubuntu Mate Kernel 4.4.0-43-generic 64bit

If I plug in the cabel without power, display works fine.
If I plug in the cabel with 5V, but the PC is shut down, the display works fine.
For the display to crash, the pc has to be running.

Test code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

void setup()
{
    //lcd.clear();
    lcd.begin(16, 2);
    lcd.clear();
    lcd.setCursor(0,1);
    lcd.print("Hello there");
    delay(1000);
}

void loop()
{
    lcd.setCursor(0,1);
    lcd.print("Hello World");

    lcd.setCursor(0,0);
    lcd.print("ABCDEFGHIJKLM");

    delay(1800);

    lcd.clear();

}

When your computer boots, or when you plug the board in with it booted, most likely the serial port that gets created (/dev/ttyACM0) is opened by the process modem-manager. That will cause the Arduino to reset giving you the same results you see when you reset the board in other ways.

I have had no end of trouble in the same manner with a green version of the same screen. The best results I have had is to control the power to the display and power it up at every boot.  You can do it with a simple P-channel logic level MOSFET or PNP transistor:

simulate this circuit – Schematic created using CircuitLab

If you chose, say, D3 (as an example) as your control GPIO you would go:

void setup() {
    pinMode(3, OUTPUT);
    digitalWrite(3, LOW);
    delay(1000); // Give it time to settle after powering up
    ... rest of setup code ...
}

You can also then use it to save power (if you want to) by turning the display off - simply set the pin back to INPUT and it will be turned off by R1.


Is it correct to use a 9V 1A transformer to power my project? I have a quick question:

I have a small alarm project running on an ArduinoNanoV3 (a chinese clon). Counting sensors, actuators and the arduino itself the consumed current (theoretically speaking, calculated by the data provided by the datasheets) doesn't approach to a max of 300mA. Now, the way I plan to feed the project is using a 110V (AC) transformer that gives me 9V output with 1A maximum output. My fear is the output of this transformer (that says 1A) when in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

My question is: if my project is not going to consume more than 300mA, is there any danger/trouble when connecting the 9V ~ 1A transformer for energize my Arduino based project?

in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

Nowhere says that.  They say you should not draw more than 500mA when you supply with 9V.

The heat generated by the 5V voltage regulator is proportional to the current multiplied by the voltage.  The more current you draw the hotter the regulator will get. The higher the input voltage, the more voltage it has to drop, and thus the hotter it gets.

So the higher the input voltage the lower the current drawn by your project can be before the regulator gets too hot.

Since you are only around 300mA that's below the recommended maximum for a 9V input.


SoftSerial freezes on comparing getInt to int I have a robot application on my Arduino which basically takes values from a SoftSerial instance on my 0/1 pins (connected to a Bluetooth board).

From the 'driver station' I send speed values to the Arduino through the aforementioned Bluetooth controller. The freezing happens when I compare the data (an integer) to a local integer (i.e 500). If I send the reverse command, I'm actually sending the int 500. If I compare my SoftSerial data like so:

if(softSerial.parseInt() == 500)
{
 //Reverse
}else{
 //Forward
}

it freezes. It only happens when I'm using my SoftSerial stack over Bluetooth, over USB it doesn't freeze. What are my options?

There is no point in using SoftwareSerial on pins 0 and 1, as you have HardwareSerial for that. Whatever the sketch does once it starts will not affect whether or not it uploads. If you have something connected to pins 0 and 1, during the upload, that may well stop the upload working, but what the sketch does afterwards does not.

It is hard to tell from your snippet, but if you also have activated HardwareSerial - eg. Serial.begin(9600); - then the hardware takes over those two pins and SoftwareSerial won't work anyway.


Multiple Buttons to control the same led for different on off times I am just learning the Arduino, it is a learning curve that's for sure.

Using the onboard Led I want to use two buttons to make the Led blink for different times.

I am not sure what is missing from the code, as pressing BUTTON2 gives the same time as BUTTON.

Any help would be greatly appreciated.

 const byte BUTTON = 2;
const byte BUTTON2 = 3;
const byte LED = 13;

unsigned long buttonPushedMillis;
unsigned long ledTurnedOnAt;
unsigned long turnOnDelay = 500;
unsigned long turnOffDelay = 500;
unsigned long turnOnDelay2 = 1000;
unsigned long turnOffDelay2 = 1000;
bool ledReady = false;
bool ledState = false;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTTON2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  unsigned long currentMillis = millis();
  if (digitalRead(BUTTON) == LOW) {
    delay(50);
    buttonPushedMillis = currentMillis;
    ledReady = true;
  }
  if (ledReady) {
    if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
      digitalWrite(LED, HIGH);
      ledState = true;
      ledTurnedOnAt = currentMillis;
      ledReady = false;
    }
  }
  if (ledState) {
    if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
      ledState = false;
      digitalWrite(LED, LOW);
    }
  }
  {
    unsigned long currentMillis = millis();
    if (digitalRead(BUTTON2) == LOW) {
      delay(50);
      buttonPushedMillis = currentMillis;
      ledReady = true;
    }
    if (ledReady) {
      if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay2) {
        digitalWrite(LED, HIGH);
        ledState = true;
        ledTurnedOnAt = currentMillis;
        ledReady = false;
      }
    }
    if (ledState) {
      if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay2) {
        ledState = false;
        digitalWrite(LED, LOW);
      }
    }
  }
}

\\

You're making your program too complex for its own good.

Instead of changing your blink code depending on which button is pressed, just make the button change the blink code's parameters, and stick to just one blink code.

That means having just one set of blink variables which your blink code uses, and your button code then just changes what values those variables contain.


Specified folder/zip file does not contain a valid library I am trying to use this library.
But when I try to import the .zip file (of the directory) downloaded from GitHub, Arduino IDE says "Specified folder/zip file does not contain a valid library"

That's because it contains two libraries, and the IDE doesn't know how to handle that.

Because of this repository structure, you will need to do a manual installation.

Extract the zip file manually and copy the libraries folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.


ESP-12 + FTDi + platformio I have 2 questions.

Why we have to put our functions before void loop and void setup into VScode+platformio?
I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

I have this Warning: src\main.cpp:46:24: warning: large integer implicitly truncated to unsigned type [-Woverflow]
 const byte menuColor = 0XF206;

[EDIT]The problem comes from these lines:

attachInterrupt(digitalPinToInterrupt(enA), enAin, RISING);
attachInterrupt(digitalPinToInterrupt(enB), enBin, RISING);
attachInterrupt(digitalPinToInterrupt(enBtn), enBtnIn, FALLING);

Why we have to put our functions before void loop and void setup into VScode+platformio?

Because that is how C works. The Arduino IDE hides it from you by adding function prototypes at the start of your code.

  I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

const byte menuColor = 0XF206;

That can never work. The value 0x06 will be assigned to menuColor since a byte is only 8 bits.  You need to learn to use data types that are suitable for the values you are trying to store in them.


Converting char array to int I'm trying to use nRF24L01 module to send a messages between 2 arduinos

Transmiter code:

  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);

Reciver code:

char text[32] = {0};
radio.read(&text, sizeof(text));

Serial.println(text);

How I can put into char array an int value?
I tried doing it in this way

For example:
      int a = 60;
      const char text[] = String(a);
      radio.write(&text, sizeof(text));

  delay(1000);

Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.

I recommend using sprintf

sprintf(char * str, char * format, args)

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:

char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result);   //sends "My number is 24"


Problems Sending Signals to the Arduino-Uno via Keyboard I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.
I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

int SKEY = 8;

class KbdRptParser : public KeyboardReportParser
{
    void PrintKey(uint8_t mod, uint8_t key);

  protected:

    void OnKeyDown  (uint8_t mod, uint8_t key);
    void OnKeyUp    (uint8_t mod, uint8_t key);
    void OnKeyPressed            (uint8_t key);
};

void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
  MODIFIERKEYS mod;
  *((uint8_t*)&mod) = m;
  Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
  Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
  Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");

  Serial.print(" >");
  PrintHex<uint8_t>(key, 0x80);
  Serial.print("< ");

  Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
  Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
  Serial.println((mod.bmRightGUI  == 1) ? "G" : " ");
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
  Serial.print("DN ");
  PrintKey(mod, key);
  uint8_t c = OemToAscii(mod, key);

}

void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
  Serial.print("UP ");
  PrintKey(mod, key);
}

void KbdRptParser::OnKeyPressed(uint8_t key)
{
  Serial.print("ASCII: ");
  Serial.println((char)key);
};

USB Usb;
HIDBoot<USB_HID_PROTOCOL_KEYBOARD>    HidKeyboard(&Usb);

KbdRptParser Prs;

void setup() {

 Serial.begin(9600);
#if !defined(__MIPSEL__)
  while (!Serial);
  Serial.println("Start");

  if (Usb.Init() == -1)
    Serial.println("OSC did not start.");

  delay( 1 );

  HidKeyboard.SetReportParser(0, &Prs);

}

void loop() {
 Usb.Task();
}

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?
Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!

Keyboards cannot be used quite like you wish - the keyboard will send a key (scan) code when a key is pressed and then repeat that code if the button continues to be pressed. There is a different code sent when the same key is released.

The scancode for key release is obtained from it by setting the high
order bit (adding 0x80 = 128). Thus, Esc press produces scancode 01,
Esc release scancode 81 (hex).  For sequences things are similar:
Keypad-/ gives e0 35 when pressed, e0 b5 when released. Most keyboards
will repeat the make code (key down code) when the key repeats.

From: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html