analogRead seems to freeze some seconds the program I have the following code that reads a RFID reader, it was working perfect without any dealy and then I try to an analog read from a potentiometer using analogRead.

The analog read works fine but then when I hover the card over the RFID it takes about 7 seconds or so to go into the line where I turn on a LED.

Im sure Im doing something wrong with analogReader because this is the first time I use it.

  I really appreciate any help

    #include <MicroView.h>

    MicroViewWidget *widget;        // create widget pointer

    #define MAX_BITS 100                 // max number of bits
    #define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

    unsigned char databits[MAX_BITS];    // stores all of the data bits
    unsigned char bitCount;              // number of bits currently captured
    unsigned char flagDone;              // goes low when data is currently being captured
    unsigned int weigand_counter;        // countdown until we assume there are no more bits

    unsigned long facilityCode=0;        // decoded facility code
    unsigned long cardCode=0;            // decoded card code

    int sensorPin = A1;    // select the input pin for the potentiometer
    int sensorValue = 0;  // variable to store the value coming from the sensor

    // interrupt that happens when INTO goes low (0 bit)
    void ISR_INT0()
    {

      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;

    }

    // interrupt that happens when INT1 goes low (1 bit)
    void ISR_INT1()
    {

      databits[bitCount] = 1;
      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void setup()
    {

      pinMode(2, INPUT_PULLUP);     // DATA0 (INT0)
      pinMode(3, INPUT_PULLUP);     // DATA1 (INT1)
      pinMode(5, OUTPUT);           // LED

      Serial.begin(9600);

      // binds the ISR functions to the falling edge of INTO and INT1
      attachInterrupt(0, ISR_INT0, FALLING);
      attachInterrupt(1, ISR_INT1, FALLING);

      digitalWrite(sensorPin, HIGH);      // Internal Pull-up
      pinMode(sensorPin, INPUT);          // make pin as INPUT

      uView.begin();                      // start MicroView
      uView.clear(PAGE);                  // clear page
       uView.setCursor(5,0);
      uView.print("TEST");
       uView.setCursor(0,20);
       uView.print("RFID READ");
      widget = new MicroViewSlider(0, 35, 0, 1024);    // make widget as Slider
      //widget2 = new MicroViewSlider(0, 20, 0, 1024, WIDGETSTYLE1);    // make widget as Silder STYLE1
      uView.display();                    // display the content in the screen buffer

      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void loop()
    {

      // This waits to make sure that there have been no more data pulses before processing data
      if (!flagDone) {
        if (--weigand_counter == 0)
          flagDone = 1;
      }

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//
      sensorValue = analogRead(sensorPin);    // read sensorPin
      widget->setValue(sensorValue);          // set value of sensorPin to widget
      //widget2->setValue(sensorValue);         // set value of sensorPin to widget
      uView.display();

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//

      // if we have bits and we the weigand counter went out
      if (bitCount > 0 && flagDone) {
        unsigned char i;

        Serial.print("Read ");
        Serial.print(bitCount);
        Serial.print(" bits. ");

        if (bitCount == 32){

          // **** AFTER 7 SECONDS I GET INTO THIS CODE ****///

          uView.clear(PAGE);      // clear the page buffer
          uView.setCursor(0,0);

          digitalWrite(5, HIGH);

        }

         // cleanup and get ready for the next card
         bitCount = 0;
         facilityCode = 0;
         cardCode = 0;
         for (i=0; i<MAX_BITS; i++)
         {
           databits[i] = 0;
         }
      }
    }

analogRead() is fine, it takes only about 110 µs, but there are
several other issues with your code that you should fix:

Any variable that is shared between interrupt code and normal code
should be declared volatile in order to prevent the compiler to do
some unsafe optimizations.
Any such variable that is more than one byte in size should be
accessed from the main program with interrupts disabled.
You should take care of not writing into databits[] past the end of
the array.
Counting loop iterations is a very bad way of measuring elapsed time,
as the counting speed will change whenever you change your loop code.
Use micros() instead.

There is also an issue with how you use flagDone. You set it to 1,
then you call analogRead(), MicroViewSlider::setValue() and
uView.display(), then you read it back. What if your ISR has set it
back to 0 in the meantime? I suspect this is the main cause of the
problem you see.

I suggest you use flagDone to inhibit the ISRs: the main loop sets it
to true to tell the ISRs “Let's say we are done with this card. Please
do not touch anything while I process the already received information.”
And later it sets it to false meaning “You can proceed reading bits
now.”

Given the above considerations, I would try something along these lines:

volatile bool flagDone;     // if we are done, pause the reading
volatile uint8_t bitCount;  // number of bits received so far
volatile uint32_t rxTime;   // last time we got a bit

// Interrupt that happens when INTO goes low (0 bit).
void ISR_INT0()
{
    if (!flagDone && bitCount < MAX_BITS) {
        rxTime = micros();
        databits[bitCount++] = 0;
    }
}

// Same thing, but writes 1 instead of 0 into databits[].
void ISR_INT0() { ... }

void loop()
{
    // Safely read rxTime.
    noInterrupts();
    uint32_t rxTimeCopy = rxTime;
    interrupts();

    if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
        // Assume we are done reading this card.
        flagDone = true;

        // Do whatever with databits[].
        // ...

        // Get ready for the next card.
        bitCount = 0;
        flagDone = false;  // do this last: it re-enables the ISR
    }
}


How to make 4 digits 7 segments common cathode thermometer I'm new to Arduino and I have this problem: The common cathode 4 digits 7-segments keep on blinking even the code and my connection is correct (in my opition). I have used an LM35 IC to read the temperature
 I've just followed this pattern:
and I used this code:

const int digitPins[4] = {5,4,3,2}; //4 common CATHODE pins of the display (inverted the pins order)
const int clockPin = 7;    //74HC595 Pin 11
const int latchPin = 8;    //74HC595 Pin 12
const int dataPin = 12;     //74HC595 Pin 14
const int tempPin = A0;     //temperature sensor pin
const byte digit[10] =      //seven segment digits in bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111  //9
};
int digitBuffer[4] = {0};
int digitScan = 0;
float tempC; //Deleted kelvin and farenheit

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(tempPin, INPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(tempPin, INPUT);
  //Serial.begin(9600);
}

//writes the temperature on display
void updateDisp(){

  for(byte j=0; j<4; j++) {digitalWrite(digitPins[j], HIGH);} // Turns the display off. Changed to HIGH
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
  digitalWrite(latchPin, HIGH);

  delayMicroseconds(2);

  digitalWrite(digitPins[digitScan], LOW); //Changed to LOW for turning the leds on.

  digitalWrite(latchPin, LOW);
  if(digitScan==2)
    shiftOut(dataPin, clockPin, MSBFIRST, (digit[digitBuffer[digitScan]] | B10000000)); //print the decimal point on the 3rd digit
  else
    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);

  digitalWrite(latchPin, HIGH);

  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop(){
  tempC = analogRead(tempPin)*0.00488;  //multiplied for this conversion constant
  tempC = tempC*10000;
  digitBuffer[3] = int(tempC)/1000;
  digitBuffer[2] = (int(tempC)%1000)/100;
  digitBuffer[1] = (int(tempC)%100)/10;
  digitBuffer[0] = (int(tempC)%100)%10;

  if (digitBuffer[0]>=5) {
    digitBuffer[0] = 5;
  }
  else {
    digitBuffer[0] = 0;
  }

  delay(5);
  updateDisp();
}

First thing to check is that you have the IC and the 7-segment display module connected the correct way around. As a reference, the green wire is attached to Pin 14 of the 74HC595 IC, so pin 1 would be the top right pin. The 7-segment display should have the the dot points towards the bottom.

Check that you have a common cathode display. You can do this by applying a voltage, through a 220 ohm resistor, verifying that it lights up when positive is on pins A-G and Gnd connected to the common cathode pin.

Check the code by removing the temperature section of the code and just writing '0's to all 4 digits. In fact it would be worth testing the digits one by one. The below code should do just that (unverified):

const int clockPin = 7;    //74HC595 Pin 11
const int latchPin = 8;    //74HC595 Pin 12
const int dataPin = 12;    //74HC595 Pin 14
const int digitPins[4] = {5,4,3,2};

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
    digitalWrite(digitPins[i], HIGH);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  for(int i=0;i<4;i++)
  {
    //select the digit by enabling the common cathode (sink)
    digitalWrite(digitPins[i], LOW);

    // write '0'
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 63);
    digitalWrite(latchPin, HIGH);
    delay(1000);
  }
}

This code will display a '0' one digit at a time, each for 1 second.  If this code works then I suspect the problem lies in the updateDisp() function.

NB: In your code, tempPin is setup twice as an input.


Arduino HC-SR04 water experiment I am working on an experiment with the HC-SR04 sound sensor, and i am using it to record the speed of sound. I successfully measured the speed of sound in air, but when measuring it in water, I encountered a small problem. The sound waves emitted by the sensor are both absorbed and reflected off the water. Obviously, the reflected sound waves are the first ones to reach the sensor, and therefore are the ones used for calculating the speed of sound. Is there a way to code the Arduino program in order to ignore the first set of waves and only record the set of waves that were absorbed by the water? I was thinking of increasing the delay time for the pulse, but I'm not sure that would work.

Thanks.

All you need to do is ignore any reading within the first  milliseconds.  Off the top of my head there is a delay statement before reading from this sensor, just alter that.  You can work out how long it needs to be by working out how fast sound waves travel through the air and measuring the distance between the sensor and the source of the reflection.  I think you might know how to do that :)


How to setup Arduino Wifi Shield with Red Bear Lab BLE Shield? I'm new to Arduino shields.

I'm trying to stack these two shields on an arduino uno for a home automation project.

1 - Arduino Wifi Shield:

2 - Red Bear Lab BLE shield: http://redbearlab.com/bleshield/

I have pin contention, between the two shields:
The WiFi shield uses pins: 4, 7, 10, 11, 12, 13.
The BLE shield uses pins: 10, 11, 12, 13.

Is there a hardware or software way to allow the two shields to work together?

I saw in a similar thread, someone reccomended a go-between shield: https://www.sparkfun.com/products/11002, would this be something that I could use in this case?

If it's not possible, are there other shields that will work together?

Thanks

The way the Arduino talks to each of the shields is by first telling the device that it wants to communicate with it, and then by exchanging information with that device. The Arduino uses 3 pins, 11, 12, and 13, to communicate to both the shields, and a 4th pin which it uses to select which of the devices it wants to use. This way the Arduino can use connect to two shields at once, by just selecting one at a time

I did some research, and found that the selection pin on the WiFi shield (which I believe is the same as yours: https://www.arduino.cc/en/Main/ArduinoWiFiShield) are pins 10 and 4; pin 4 for the SD card selection, and pin 10 for the WiFi selection. Now since pin 10 is used as a selection pin for both the WiFi shield and the BLE shield, you run into some problems: both the boards will be selected at the same time when pin 10 is used. In this case, you can use the Sparkfun go-between board you linked.

I've never used it myself, but it appears to be able to change what pin is attached where on the shield it's attached to. In this case, you want to put the WiFi shield on the bottom, then the Sparkfun go-between shield, then the BLE on the top. You want to set up the go-between shield to change pin numver 10 to another pin that's not being used (any pin but 11, 12, 13, 7, 4, or 10).

In the Arduino code you will at some point declare which pin is being used to select which board. In this case, set the WiFi selection to 10 (default), the SD card selection to 4 (default), and the BLE selection to whatever pin you changed pin 10 from with the go-between shield. This way, when you select the shield on pin 10, it will only select one shield, rather than two.


Extracting bits from hex encoded binary I've been using an Adafruit Huzzah ESP8266 Breakout to read data from an OpenTherm Gateway connected to my central heating unit, and publish that to MQTT. I'm programming the ESP8266 using the Arduino IDE.

The gateway publishes messages to the ESP8266 via serial. These messages look like this: T901812F3 or B501812F3

The first letter indicates whether the message comes from the thermostat or the boiler, while the remaining characters represent four bytes, hexadecimally encoded.

These four bytes are structured as follows:

I'm trying to extract the MSG-TYPE, DATA-ID, and DATA-VALUE from the four bytes, but I'm getting weird (to me) results. I'm new to Arduino and C in general.

I'm familiar with PHP, and extracting the data using that is easy:

$decimal = hexdec(substr("B501812F3", 1));      // 1343754995
$messageType = (($decimal & 0x70000000) >> 28); // 5
$dataId = (($decimal & 0x00FF0000) >> 16);      // 24
$dataValue = ($decimal & 0x0000FFFF);           // 4851

However when I try something similar in the Arduino IDE, and upload it an Arduino, I get a different result:

void setup() {
    Serial.begin(9600);
    delay(500);

    parseLine("B501812F3");
}

parseLine(char* message) {
    // Extract data
    char messageType;
    unsigned long data;
    int numberExtracted = sscanf(message, "%c%08x", &messageType, &data);

    // Decompose a single message
    int flag = (int) ((data & 0x70000000) >> 28);
    unsigned char openThermId = (unsigned char)((data & 0x00FF0000) >> 16);
    unsigned short openThermPayload = (unsigned short)(data & 0x0000FFFF);

    Serial.println(data);             // 4851
    Serial.println(flag);             // 0
    Serial.println(openThermId);      // 0
    Serial.println(openThermPayload); // 4851
}

I (perhaps incorrectly) assume that the effect will be the same when I upload the code to an ESP8266.

What am I missing here? I suspect it has something to do with the different max integer value on the Arduino, but I'm not really sure how to proceed.

You're best off using strtoul():

messageType = message[0];
uint32_t data = strtoul(message + 1, NULL, 16);

The trick here is that message is just an array, so you can get the first letter with message[0]. Also, since C arrays are themselves just pointers to blocks of memory, message + 1 actually points to the location in memory of message[1], so you start processing the numbers from the second character in the string, thus omitting the first letter.

strtoul() takes a third parameter which is the base to decode from - 16 in this case for hexadecimal.

From there you can then use your bit shifting and masking to slice up your 32-bit value into your required sub values.


need help hooking up an oled display recently i bought this oled display .

http://www.wvshare.com/product/0.96inch-OLED-A.htm

how can i connect it with arduino . Driver Chip is SSD1306 . Supported Interface are 3-wire SPI, 4-wire SPI, I2C . it's can display two colors Yellow and Blue.

i need some guidance on how to hook it up with arduino lets say using i2c protocol . and is there any existing library ?

Note : on the wvshare website there's only code sample for STM32 Microcontrollers .

it's working with u8glib.  but i am using  4-wire SPI.

constructor for U8GLIB

U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9,8);

Pin configuration was

Arduino -   Oled Display
13 -    CLK
11 -    DIN (SI)
10 -    CS
9 - D/C (A0)
8 - RES

the reset pin is required. i used 3.3v  arduino pin for vcc .


Serial.read(); and state machine for AT commands I have a strange type of issue: the index of the array doesn't increment and when I print the value from the serialdata[pointingfinger] it just gives me an empty space.
This is a state machine (I guess) that should check what is the current char that's being written into the array and its position to avoid searching it later. When we have a finished line it changes the bigger state machine to another mode (that checks if four chars further is the command) when the processing is done it should get back getting the next line.

This is Arduino Leonardo and Serial is the USB and Serial1 is where I send and receive AT commands.

const long interval = 1000;
static long currentMillis;

char plussignpoint = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; //Array to store the chars before parsing

int rdpos = 0;

int pointingfinger = 0;

char timeen = 0;
byte stat0 = 0;
char futstat0 = 0;
char searchcharpos = 0;

char enabled = 0;

char searchchartype = 0;

char smsvalid = 0;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write("ATE0\r");
}

void loop() {
    if (millis() - currentMillis >= interval)
    {
      Serial1.print("AT+CCLK?\r"); //ask for the time

      enabled = 1;

      currentMillis = millis();
    }

    if (enabled == 1) {
      if (stat0 == 0) {
        if (Serial1.available () > 0) {
          pointingfinger++;
          serialdata[pointingfinger] = Serial1.read();
          if (serialdata[pointingfinger] == '+') {

            searchcharpos = pointingfinger;
            searchchartype = 1;
            futstat0 = 1;
          }
          else if (serialdata[pointingfinger] == '$') {
            if (smsvalid = 1) {
              searchcharpos = pointingfinger;
              searchchartype = 2;
              futstat0 = 2;
            }
            if (smsvalid = 0) {
              stat0 = futstat0;
              pointingfinger = 0;
            }
          }
          else if (serialdata[pointingfinger] == '\n') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else if (serialdata[pointingfinger] == '\r') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else {
            stat0 = 0;
            pointingfinger = 0;
          }
        }

        if (pointingfinger == 255) {
          pointingfinger = 0;
          enabled = 0;
        }

      }
    }
}

EDIT: I forgot to include what AT commands it should parse:

Arduino: AT+CCLK?

SIM800H: +CCLK: "04/01/01,01:35:31+00"

         OK

When checking value of smsvalid you use assignment operator = instead of comparison operator ==.

            else if (serialdata[pointingfinger] == '$') {
                if (smsvalid == 1) {
                    searchcharpos = pointingfinger;
                    searchchartype = 2;
                    futstat0 = 2;
                }
                if (smsvalid == 0) {
                    stat0 = futstat0;
                    pointingfinger = 0;
                }
            }

And also you increment pointingfinget prior writing to serialdata buffer. This means that the first character will be written at index 1. So the first character serialdata will be zero, which means empty string.

      pointingfinger++;
      serialdata[pointingfinger] = Serial1.read();

There are many issues with your code, I pasted your code to online gdb c++ compiler, so you can play with it and see what is going on.

Those AT state machines aren't easy to finetune on Arduino. I spent a lot of time debugging similar code and found out that the best way is to unit test all possible situations in visual studio or xcode. Arduino is just C++ and if you copy/paste some portions of your code to C++ IDE, after implementing few functions or classes it should work. For example, to make your code working in XCode, I had to implement some dummy Serial1 class and simplify the loop code:

class _Serial1
{
    std::string buffer{"OK\r\n"};
public:
    int available()
    {
        return (int)buffer.size();
    }

    char read()
    {
        char c = buffer[0];
        buffer.erase(0, 1);
        return c;
    }
} Serial1;

void loop() {
    if (enabled == 1) {
        if (stat0 == 0) {
            if (Serial1.available () > 0) {
                pointingfinger++;
                serialdata[pointingfinger] = Serial1.read();
                if (serialdata[pointingfinger] == '+') {

                    searchcharpos = pointingfinger;
                    searchchartype = 1;
                    futstat0 = 1;
                }
                else if (serialdata[pointingfinger] == '$') {
                    if (smsvalid == 1) {  // ==
                        searchcharpos = pointingfinger;
                        searchchartype = 2;
                        futstat0 = 2;
                    }
                    if (smsvalid == 0) { // ==
                        stat0 = futstat0;
                        pointingfinger = 0;
                    }
                }
                else if (serialdata[pointingfinger] == '\n') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else if (serialdata[pointingfinger] == '\r') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else {
                    stat0 = 0;
                    pointingfinger = 0;
                }
            }

            if (pointingfinger == 255) {
                pointingfinger = 0;
                enabled = 0;
            }

        }
    }
}

And the compiler immediatelly pointed me at the incorrect assignments and also I was able to debug the code step by step and see what is happening inside.

In my situation I was interfacing SIMCOM900 gprs module and I made a state machine that allows me to write code like this:

virtual void Program()
{
    switch (Pc())
    {
        case 0: _ASSERT(strlen(mApn)>0);
                Stream() << "AT+CSTT=\"" << mApn << "\",\"\",\"\"\r\n";
                break;
        case 1: Expect("OK\r\n");
                if (Expect("+CME ERROR")) { Error("CME Error when attaching apn"); Return(false);}
                if (Timeout(25000)) Return(false);
            break;
        case 2: Stream() << "AT+CIICR\r\n"; break;
        case 3: Expect("OK\r\n");
                if (Timeout(15000)) Next(); break;
        case 4: Stream() << "AT+CIFSR\r\n"; break;
        case 5: if (ReadIpAddress()) Next();
                if (Timeout(2000)) Return(false); break; // longer?
        default: Return(true);
    }
}

Here is a bit older version of it:
https://gist.github.com/gabonator/88b80d9c6b16d699d6f4234ebc3a2587


BLE SPI Module with ATtiny85 Adafruit carries a number of Bluetooth LE 4.0 modules in their store, notably the SPI (https://www.adafruit.com/products/2633) and UART (https://www.adafruit.com/product/2479) version. I have used the NRF24L01 module with ATtiny85 via SPI to transmit data in the past, and this uses 3 pins. I used the following setup to do so: https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2.

My previous system consisted of ATtiny85s communicating with a receiver (Bluefruit Feather) via NRF24L01 radios. As the receiver got data, it sent it to an iPhone app that I wrote. Now, I would like to cut out this receiver and BLE straight to the iPhone, which supports multiple peripheral connections.

However, unlike the RF24 library, the Adafruit BLE SPI library needs the actual SPI library to compile correctly, which for some reason the RF24 library (this version: http://tmrh20.github.io/RF24/) doesn't. I don't quite get how the RF24 library can compile fine without the SPI library when targeting the ATtiny85 - Is there some way to get this to work similar to the RF24 library?

Alternatively, I think there is a way to do software UART on ATtiny85, which I know nothing about, so if there truly is no way to do SPI is UART possible?

I realize that this is a question best asked to Adafruit, which I have done, but I thought I'd post it here and see if anyone can help.

Thanks,
Alex

I find the ATTiny85 working well with software serial port. Serial UART (or in fact any of the protocols like I2C or SPI) are just bit banging - and you can do that pretty well in software. Of course, having a hardware support makes things easier and faster, but there is nothing badly wrong with a software uart either. Except that you have to continuously check if there is some data arrives.

I was using software serial on Adafruit Trinket (ATTiny85) in various projects to talk to a Bluetooth 2.1 module, and it worked pretty well.

Here
http://arduining.com/category/trinket-projects/ they use the same approach to talk to an ESP8266.

You may wish to look for the SoftwareSerial lib for Trinket, or in certain cases you may want to go for the SendOnlySoftwareSerial lib (send only, but smaller code footprint).

Also a hardware based serial lib is available:
https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/


Diode lights generate false interruptions I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.

I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.

So, I have a board that looks like this:

You can see two reed switches (close circuit in the presence of a magnet) which leads the INT0 (pin 2) and INT1 (pin 3) on arduino to trigger an interruption on their RISING behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly.

The original version of this circuit had lights in positions D5-D10 and D19-D24 (between the reed switches and the connections to the interruptor pins). The lights are these:

The part of the circuit with the red light (connected to INT1) worked flawlessly, while the circuit with the green light (connected to INT0) every once in a while triggered a false interruption in INT1. The lights, however were always blinking correctly.

I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.

Thanks!

PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.

Aaaaah, ok, now I see...

You put

  +5V - Reed - LED - input pin - 1k resistor - ground

right?

If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6*Vcc, so for a 5V supply this value is 3V.

Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.

Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.

To solve the problem, you have three solutions:

1) use a (low brightness) red led also for the green path
2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command)
3) change the path to

  +5V - Reed - input pin - LED - 1k resistor - ground

(i.e. take the voltage BEFORE the led, not after)

I think it'll work then :)

EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.

And... You won't "fry" your pins with the 5V you are prividing to the circuit....


Is SRAM erased when putting Arduino into sleep_mode_pwr_down? Question
In the interest of reducing power consumption, I am putting the Arduino into sleep mode between taking sensor readings. However, the data from readings are stored in arrays, and must not be erased when the device enters sleep mode.
For clarity, I am using sleep_mode_pwr_down, and triggering an interrupt using the Watchdog Timer on the ATMega328 chip. See this post for a description of the different sleep modes: What are (or how do I use) the power saving options of the Arduino to extend battery life?
It would be possible to address this issue by writing data to the EEPROM, however, I am unsure whether this is necessary. The question is whether putting the device into sleep_mode_pwr_down erases the dynamic memory?

Specs / Context:
Arduino Uno (ATMega328 chip)

Generally, Atmega sleep modes do not erase RAM. Their memory is static and as long as voltage (above 2.7V I believe) is applied, data is held.

However, this also depends on how you plan to wake up the device.
If it receives a RESET, RAM is cleared and program execution starts from the beginning.

  If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from sleep.

Check out the AVR's sleep modes to see which fits your application best and how to safely wake it up again


Arduino SoftwareSerial library basic example doesn't work I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.

The basic code example:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
void setup() {
  mySerial.begin(4800);
}
void loop() {
    mySerial.println("HELLO");
    delay(100);
}

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.

If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call Serial.begin(..) and Serial.println(..), instead of mySerial....

SoftwareSerial is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.


Timer0 overflow interrupt not working I try to use the Timer0 of an Arduino Leonardo (ATmega32u) to trigger an interrupt at regular intervals, using plain avr-gcc (not the arduino library). I try to blink the built-in LED as test, but it does not light up.

If I place a PINC=0x80; in the main function, the LED turns up, but not if I do it from the interrupt.
What am I doing wrong?

EDIT : The LED turns on with TCCR0B = (1 << CS00);, (no prescaler) or TCCR0B = (1 << CS01) (prescaler /8), but it does not with TCCR0B = (1 << CS00) | (1 << CS02); (prescaler /1024, what I want). At 16MHz CPU frequency the resulting frequency should be more than 15kHz, so I should see it instantly.

Here is my code:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect)
{
    PINC = 0x80;
}

int main()
{
    DDRC = 0b10000000;

    //Start Timer 0 @ 15625 Hz
    TCCR0A = 0;
    TCCR0B = (0b101 << CS00);
    TIMSK0 = (1 << TOIE0);
    sei();

    while(true); // Avoid return from main
}

I just found the answer here : https://www.avrfreaks.net/forum/atmega32u4-arduino-leonardo-strange-timer-behavior

It seems that the USB connection generates higher-priority interrupts. I still don't know why the interrupts do work at higher frequency.

Solutions include powering the board from a USB charger or other power source rather than through the computer USB or adding the following code before the interrupt enable :

// Clear usb interrupt flags
USBINT = 0;
UDINT  = 0;
for (uint8_t i = 0; i < 6; i++)
{ // For each USB endpoint
    UENUM = i; // select the _i-th endpoint
    UEINTX = UEIENX = 0; // Clear interrupt flags for that endpoint
}

Thanks to those who helped me !


ESP8266-12 is showing garbage when RST is given I use ESP8266-12 with an Arduino Uno as a USB-serial adapter.

When I upload any sketch to the ESP8266 it works fine until I reset the ESP8266.

uint32_t realSize = ESP.getFlashChipRealSize();
uint32_t ideSize = ESP.getFlashChipSize();
FlashMode_t ideMode = ESP.getFlashChipMode();

Serial.printf("Flash real id:   %08X\n", ESP.getFlashChipId());
Serial.printf("Flash real size: %u\n\n", realSize);

Serial.printf("Flash ide  size: %u\n", ideSize);
Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

if(ideSize != realSize) {
    Serial.println("Flash Chip configuration wrong!\n");
} else {
    Serial.println("Flash Chip configuration ok.\n");
}

delay(5000);

If I ground reset button, garbage values are being shown.

Connections details:

EN  - 3.3V of Uno
VCC - 3.3V of Uno
RST - GND Of Uno(If needed)
TX - TX of Uno
RX - RX of Uno
GPO15 - GND of Uno
GPO01 - GND of Uno
GND - GND of Uno

Espressif says it can not be disabled.

Ref.: https://github.com/esp8266/Arduino/issues/3047


Decreasing large DC motor power usage by coasting I'm working on a class project - an electric bike competition. Part of the requirements for the final grade is having a "race advantage system" on your bike. Basically, just something unique that will give you an edge in a final competition where the winner is the bike that goes the furthest on motor power in half an hour. Speed doesn't matter. I was thinking of using an Arduino is some way to do this.

We're using 2 12 volt, 7 amp hour batteries which could be powered in series or parallel. The motors are pretty large, I didn't get any specifics on them though.

My idea was to let the motor coast when it reaches a certain speed, and to turn it on again once it goes under it. I would have to do this with a relay because of the high amounts of electricity we're working with (unless someone knows of a transistor that could handle that while being powered by an Arduino, but I couldn't find one).

My question is: Would repeatedly coasting and starting the motor based on the bike speed increase the "lifetime" of the motor on limited battery power?

The only concern I have is starting the motor again. I'm afraid that could be the point where the most power is consumed, and would make this idea useless. I've searched for similar things online, but I haven't found anything about it. I hope this fits in Arduino, I wasn't sure whether to post it here or electronics.

I suggest you also consider the load going up in inclines. if you turn off the engine going uphill based on speed, you're most likely to turn it on again soon because of the load. You might be able to get a hint of load from the current drawn by the motor. Combining speed and load might also optimize your bike going downhill.


Burning the Arduino bootloader without an extra Arduino board Is there any way to burn the Arduino bootloader on a standalone Atmega328 (internal clock 8MHz) from the Arduino official website without using an extra Arduino board to burn the bootloader?

I mean, is it possible to burn the bootloader on the Arduino and then remove the ATmega chip from the Arduino board and use it in a breadboard?

Thanks.

If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:


Lighting LED with Arduino Uno from PC keyboard I tried to turn on a LED with my PC keyboard and an Arduino Uno with the letter A.
I get the message

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

My code:

int led1 = 10;

void setup()
{

pinMode(led1, OUTPUT);
}
void loop()
{

 if(keypressed == 'a'){
               digitalWrite(led1, HIGH);
               delay(500);
}
}

What is the problem?

Firstly, you can't just make up the term "keypressed" because the programming language is unable to understand it (unless you assign it as a variable but it's purpose then would just be to store and retrieve values). Secondly the arduino itself is unable to detect keystrokes from the computer by itself. It needs a program on the computer to be able to detect keystrokes from the keyboard then send it to the arduino.

So how would one do this?

Assuming you use Windows, learn Python (A not-so-hard programming language on the computer), then look up the msvcrt library and from there learn how to get key strokes (this only works if you are currently selecting the running program). Then in arduino and python, learn how to use serial. For Python, you need to download this library and learn how to use it. For Arduino it's already in there you just have to learn how to use it. Then you can do the rest and make it turn on your LED.

I hope this helps.


How many sensors can be supported by a single Arduino unit? I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.

I want to buy an Arduino Uno for measure room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module.

After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.

Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?

As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

An Uno has more than enough pins for the devices you described.

A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
An MQ-7 Carbon Monoxide sensor needs one analog pin.
An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
A Piezo buzzer needs one PWM pin.
The LCD with a Hitachi interface needs four digital pins.
The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.


Read car high temperature exhaust pressure sensor Is it possible to read the exhaust gas pressure of a turbo car with an Arduino, and then control an electric motor based on the pressure?

Yes, I don't see why it wouldn't be possible.

You would need a sturdy barometer, preferably a digital I2C one because they are typically more accurate. I recently bought this one to measure altitude: BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready.

Be careful about the temperature that the sensor will have to deal with, its maximum temperature is 85°C (185°F).

The motor, I'm assuming, would be fairly large so you would need a beefy motor driver that uses a 5 volt logic level, maybe like this one: L298 Dual H-Bridge Motor Driver.

This is a fairly difficult project, I'd say mostly because of the difficulty you would have mounting the barometer and motor. Never the less, it still is possible.


High errors in transmission (completely eliminated by adding delay): What's the issue? I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.

        delay(2000);

        // Calcuate weather parameters for serial and web
        calcWeather(); // Go calc all the various sensors

        // send weather out to serial port
        if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
        {
            Serial.write(0);
            Serial.write(templm34_1);
            Serial.write(templm34_1 ^ 0);
        }

        // send weather out to serial port
        if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
        {
            Serial.write(1);
            Serial.write(templm34_2);
            Serial.write(templm34_2 ^ 1);
        }

        // send weather out to serial port
        if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
        {
            Serial.write(2);
            Serial.write(templm34_3);
            Serial.write(templm34_3 ^ 2);
        }
        delay(2000);

The code for parsing received data is:

int readData ()
{
// There must be at least three available bytes to satisfy the protocol
// Otherwise, wait until three bytes have arrived to read anything
if (Serial.available() >= 3) {

      // Read the next three byte in the serial buffer
      incomingByteOne = Serial.read();
      Serial.write("Byte One: ");
      Serial.write(incomingByteOne);
      Serial.println();
      incomingByteTwo = Serial.read();
      Serial.write("Byte Two: ");
      Serial.write(incomingByteTwo);
      Serial.println();
      incomingByteThree = Serial.read();
      Serial.write("Byte Three: ");
      Serial.write(incomingByteThree);
      Serial.println();

      // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
      byte xorValue = incomingByteOne ^ incomingByteTwo;
      Serial.write("XOR VALUE: ");
      Serial.write(xorValue);
      Serial.println("Number of Errors: ");
      Serial.println(numberOfErrors);
      Serial.println();
      Serial.println();
      if(xorValue != incomingByteThree) {
        numberOfErrors++; // Add one to the total count of number of errors in transmission
      }
      else {
        // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
        byte maskForSensorNumber = 0x1f;

        // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
        int unitNumber = incomingByteOne >> 5;

        // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
        int sensorNumber = incomingByteOne & maskForSensorNumber;

        // Store the data for the correct sensor on the correct unit
        data[unitNumber][sensorNumber] = incomingByteTwo*1;
     }
}
}

What could be causing the transmissions to work fine with delay, but not otherwise?

You are probably just transmitting too fast.

Your receiver is writing at least 80 bytes of debugging information (if
I counted it right) for every 3 bytes of incoming data. Since both input
and debug output happen at the same baud rate, this means the receiver
can only cope with an input data rate equal to 3/80 = 3.75% of
the nominal baud rate.

I would expect no errors at the very beginning of the program run,
because the debugging info is written to a RAM buffer. Only when that
buffer fills up the receiver is slowed down by every Serial.write()
and Serial.println() it performs.


What is the maximum SPI speed for a slave Uno/clone? I have a Rapsberry Pi master sending SPI requests to an Uno Chinese clone slave : I send 16 characters to the Arduino, which answers 16 others characters. What I send is not important, it's the Arduino answer that matters.

When I set the speed on the Raspberry Pi at 1 Mbit/s with my C program, the received answer coming from the Arduino is mostly garbage (random characters), but this issue disappears with lower speeds.

So that leads me to this question : what is the maximum SPI speed for a slave Uno/clone, in order to have no errors ?

Edit : the Arduino code :

#include <SPI.h>

char receivingBuffer[5];
char sendingBuffer[5] = {'T', 'e', 's', 't', '!'};

volatile char bytes_received = 0;

void setup()
{

  SPCR |= bit(SPE);

  pinMode(MISO, OUTPUT);

  SPI.attachInterrupt();

  SPDR = sendingBuffer[bytes_received];

}

ISR(SPI_STC_vect)
{

  if (++bytes_received == 5)
  {

    bytes_received = 0;

  }

  SPDR = sendingBuffer[bytes_received];

}

void loop()
{

  //

}

Also, the C code on the RPi :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wiringPiSPI.h>

#define SPI_CHANNEL 0
#define SPI_SPEED   1000000 // Hz.

int main(void)
{

   wiringPiSPISetup(SPI_CHANNEL, SPI_SPEED);

   while (1)
   {

      char buf[5] = {'T', 'e', 's', 't', '?'};

      printf("Sending   : %s\n", buf);

      wiringPiSPIDataRW(SPI_CHANNEL, buf, 5);

      printf("Receiving : %s\n\n", buf);

      sleep(1);

   }

   return 1;

}

The maximum speed for Arduino as a slave is F_CPU/4, so it's 4Mbps.
When the Arduino is the master it can work at F_CPU/2, so it's 8Mbps


Small Baseball Scoreboard using 2 to 3 breadboards I'm helping my son start an Arduino small baseball scoreboard (roughly 2 or 3 breadboards in size). Im thinking to use qty 2, 2 digit 7 segment LED's (score of each team), an LCD 1602 module (inning tracker), using a serial monitor. Last is 3 individual LED's (controlled with a switch or remote).

My question is: can one arduino drive all of this? What would be a recommended configuration?
Thank you,Dave

Actually, you can very easily verify this yourself:

Per item (1602LCD, 7 segment LCD and LEDs check how many pins you need and what type, like e.g. I2C or SPI for the 1602 LCD). The 7 segment displays can have many or less pins, depending on the 'controller', See the reaction of CrossRoads below.
Count them together. If it fits on the Arduino you want to use OK. The Uno is cheapest, so if it fits on it, you use that, otherwise you can go to the Mega.
As alternative, and you need 'generic pins, called GPIOs' (not SPI/I2C) for some, you can use multiplexers like 74HC595 to reduce the number of GPIOs needed, at the cost of some speed (not critical for your project), and some more programming work.
In some cases you can use a MAX7219 driver IC, see (again) the remark of Crossroads below.


Methods to prevent Accelerometer values changing from current spikes I've connected an Arduino Uno to a MAX7219 IC, which is connected to only one standard 8x8 LED matrix, and an ADXL355 3-axis accelerometer. I use the matrix initially, and turn on all LEDs, while taking the "rest" values for the accelerometer to base all other calculations on. However, what happens is the current spike the LEDs create messes up the values - they become closer to 300, instead of the 230 they settle on when the spike is over. I've tried preventing this by adding up to a 5-second delay between the LEDs turning on and the rest values being measured. However, the problem still persists, though to a somewhat lesser extent.

Are there any methods to prevent this more effectively?

Adding a distinct power supply for the MAX7219, as suggested by @jfpoilpret, solved the issue.


.toFloat() giving incorrect anwsers I am broadcasting a fixed value float over a HC-12 radio which is then received by another HC-12 radio. I am then trying to convert that String to a Float which requires 6 decimal places. However, when I print the String value out and then the Float value out, I get two different answers.
Code:
    String lat=getValue(_msg, '|', 6); // Function to get lat value from incoming message
    Serial.println(lat);
    Serial.println(lat.toFloat(), 6);

This then results in the following values being displayed to the user:
51.507401
51.507396

The value 51.507401 is the correct value, so I would ideally like the float value to be the same.

It seems the toFloat() method is being a bit sloppy in its conversion.
The float closest to 51.507401 is 51.5074005126953125, which is only
0.13 ulps off. The number you got is the float right before it,
namely 51.507396697998046875, which is 1.13 ulps off. Alas, the
avr-libc functions atof() and strtod() make the same error.
I would suggest first considering whether the error is really
significant for your application: it is only about 48 cm on the
surface of the Earth. If this level of accuracy is relevant for you,
then follow Majenko's suggestion and use an integer count of
microdegrees.


Possible to store variables directly in EEPROM? Is it possible to store a variable directly in EEPROM and retrieve it without needing to use a library?

I'm building a project that can change the colour of an RGB LED and I want to store the colour in a non-volatile memory space, but I was wondering if I could avoid using one of the EEPROM libraries and have a global variable stored in nonvolatile memory, but still accessed directly, without needing to call a function.

Writing and reading EEPROM is possible to do without a library. Take a look at the datasheet of the ATmega328P to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.

Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.

However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.


Arduino OTA port not updating in Arduino IDE The OTA (from the ArduinoOTA library) on my ESP8266 does not show up in the programming ports on the Arduino IDE unless I restart the IDE.   Even when I plug in a usb cable and the ports list updates to show that device, it does not show the network port without a restart.   Does anyone know why this would happen or how to solve it?

I downloaded the newest version of the IDE and this is still the case.

I found an workaround for Windows:

disable IPv6 from Network Configuration
disable/enable network interface
restart Arduino IDE

You should see your OTA device in port list, in Arduino IDE.


ESP-01 won't start correctly I'm trying to connect my Arduino Uno to an ESP-01 module, but I can't get it to start correctly. All I can get out from the ESP-01 is an "invalid" message when it is enabled. Can anyone please help? Additional information can be found below.

Here's my configuration:

Arduino connected to a computer via USB cable (serial connection working)
ESP-01 connected to the same UART connection, TX from Arduino is lowered to 3,3V with resistors
ESP-01 powered with external battery + capacitor to ensure sufficient current
I've tried all different configurations with GPIO0 and GPIO2 connecting them to ground and 3,3V, with and without resistors.
I've tried 3 different ESP modules

Here's how things work:

Arduino sends back every received UART transmission so that I can monitor the whole thing.
I can send messages to Arduino from a terminal on the PC and Arduino responds.
I can send messages from Arduino by pressing a button and the messages can be seen on the terminal.
When I send AT\r\n from Arduino I can read it on the terminal but nothing happens on the ESP-01.
When I send exactly the same message from the terminal, the blue light on ESP flashes but there is no response from the ESP. Arduino sends that message back to terminal of course.
When I connect CH_PD to 3,3V the ESP gives a message: Ai-Thinker Technology Co. Ltd.
invalid
The baud rate is correct (115200) since I can only read that invalid message on this rate

Sharing the hardware UART between the terminal and the ESP generally does not work well. You'll be much better off to add a SoftwareSerial port on another pair of pins to talk the the ESP.


Amforth on Arduino UNO I'm having trouble with flashing amforth on my Arduino UNO.
I'm using an Arduino as ISP to write amforth.

Here's what I do:

Upload the code on the Arduino programmer and set Baudrate to 19200
Wire the Arduinos this way -> Wiring
Run avrdude -P /dev/ttyUSB* -c avrisp -b 19200 -p m328p -e -U flash:w:uno.hex:i -U eeprom:w:uno.eep.hex:i -U efuse:w:0x05:m -U hfuse:w:0xD9:m -U lfuse:w:0xFF:m

Sometimes it fails to set efuse,  but if I give the command just for it, even if it says "efuse changed, it was 5, not is 0xfd, do you want to change it back?" and I say no, I get the message with the correct fuses.

I log onto the amforth Arduino with the python shell, but my stack is constantly ??? -13 and different numbers. I found out -13 is error code for not found, but... not found what?

What does it mean? What am I missing?

I have to say that I'm new at this things, I recently studied Forth and discovered that I can use it on my Arduino, and I wanted to try.

By the way, the Arduino is not original.
 The chip is ATmega 328p

EDIT:
I downloaded amforth from here
Initially I followed [first guide] (different wiring but I've read around it's the same) and then "clarified my doubts" with another one from sparkfun.
(no link used because maximum for me is 2 links per post at the moment, I'll write it in the comments)

I tried with versions 6.1 and 6.0, then I decided to try with 5.9 (the one from the first guide) and now I'm running that (at least it allows me to pop elements from the stack).


Zeroing a Vernier force probe For a class assignment I have been tasked with zeroing a Vernier force probe by typing a command into the serial monitor. I am having trouble writing the code for this algorithim. I was hoping to give the monitor the command and have it save the analogread as a variable which I can later subtract from future reads. Does anyone know if I can save the analogread value without it being updated in a loop? If, so how?

Not sure if this is what you mean, but:

const int FP = 0;  // force probe analog pin
const int OFFSET = 10; // your deadband depending on your sensors consistency too
int init_read = 0;  // initial read
int curr_read = 0;  // this will be constantly updated till zeroing is done

void setup(){
  Serial.begin(9600);
  //the rest of your setup()
}

void loop(){
  if (Serial.available() && (Serial.read() == 'z')){  // if you sent anything with the monitor and if 'z' is present
    init_read = analogRead(FP); // initial read from sensor before 'zeroing' begins
    while (abs(curr_read - init_read) < OFFSET){ // here you indicate the condition that would mean the probe has been zeroed
      // make your adjustments or whatever
      curr_read = analogRead(FP);  // take a new reading and check in the next iteration
    }
    Serial.print("Zeroing is done.");
  }
}

z is the command you send from the serial monitor to begin zeroing.


Why are there 3 crystals on the Mega2560 schematic? I am a software engineer who is new(er) to electronics, I only started a couple of months ago. I've built a bunch of custom circuits, then some arduino nodes that are around my apartment that communicate with a C# server. So I've at least got the breadboarding part down.

So now I am working on a controller board that connects to my home automation system and determines the color on the LED light strips I installed into my bookshelf. So I want to transfer from working with pre-built Arduinos to building my own full node, there are some things I think I'm missing.

I've noticed that there are duplicate parts on the schematic for the Arduino Mega2560 schematic (such as there being 2 voltage regulators - one is replacement if the other is not available). I couldn't find any such description however for why there are 3 crystals located on the board. I see 3 different circuits for crystals (all of which are 16MHz).

Specifically, I am referencing the following

One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.

The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal.

Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires.

As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.


Why doesn't analogWrite() work Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.

    class Pwm
{
  unsigned long previousMillis = 0;
  unsigned long currentMillis;
  int LED;
  int DELAY;
  int up;
  int down;
  int x;

  public:
  Pwm(int led, int Delay) {

    int LED = led;
    pinMode(LED, OUTPUT);

    DELAY = Delay;
    up = 1;
    down = 0;
    x = 0;

  }

  void Update() {
    currentMillis = millis();
    if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 0) {
      up = 1;
      down = 0;
    }
   }
  }

};

// create Flasher Objects
Flasher red(12, 1000, 250);
//Flasher yellow(11, 500, 500);
//Flasher green(10, 250, 1000);
//Flasher blue(8, 250, 500);

// create PWM Objects
Pwm pin9(9,8);

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

void loop()
{
  red.Update();
  //yellow.Update();
  //green.Update();
  //blue.Update();
  pin9.Update();
}

if I load this code everything works fine. I only have issues with the OOP method.

int LED = 9;
int DELAY = 8;
int up = 1;
int down = 0;
int x;
unsigned long currentMillis;
unsigned long previousMillis = 0;

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

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    if (x == 0) {
      up = 1;
      down = 0;
    }
  }
}

The constructor in your Pwm class declares a local variable LED which it sets equal to the parameter led. You use the member variable LED in other methods, so you probably meant to set the member variable of the same name, not create a local.

Remove the int from before LED = led in the constructor.


send mixed data over serial I want to launch a communication between two Arduinos, in which case the first Arduino (S) sends data to the second one (R). The type of the data is mixed, consisting of integers, longs, floats and maybe some text. For example:

{125, 1250, 12500, 125000, 1.25, 12.5, 125.0, "some text"}

I thought about converting each one value to string, adding up all strings to a big one, and send the final string with  Serial.print(Big_string).  In that case I reckon that it would be difficult for the Receiver to extract the string to the exact substrings and convert them to real values.
A second thought was to convert all values to bytes and create a byte (or char) array, but each value would be limited to 0-255 (let alone floats and text)
A third thought was to convert them to word type (let alone the text), but I think that Serial.print( ) sends only bytes, not words.

In any case, which is the best way to send mixed data over serial?

Any thoughts would be appreciated.

I think the easiest way to solve your problem is using a separator and transmit the array values one after the other. That means having a for loop and in every iteration sending one value of the array with

Serial.println(array[i]).

The function will

convert numbers into Strings so you will get "125", "1250", ...
append a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n')

On the receiver side you can simply wait for Serial.read() to equal the number 13 and (immediately afterwards) 10 and split the messages there. That works unless your transmitted strings contain new lines.

The disadvantage is, that numbers are of course transmitted in an unefficient way. If you want to transmit them as real numbers instead of strings you have to write your own protocol. This video "Wireless Module Multiple Receivers" goes into that direction, it's using a fixed packet length but it gives an idea of how such a thing works.


Sine wave using arduino uno I am an adruino hobbyist, i want to make sine wave using arduino uno,
for that i using timer0 as interrupt, OCR0A set to 17 for 3.6khz interrupt(16000000/(100hz*36 interval)/256-1),
If i am using only one pwm pin i am getting correct frequency but when i enable two pwm pin i am getting only half if the frequency, kindly advise what is wrong and how to correct it.
.................................
This code i am getting correct frequency at PWM pin 9.

//

ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
//OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

//
............................
This code i am getting only half of the previous frequency at PWM pin 9,10

//

ISR(TIMER0_COMPA_vect)
{
OCR1A=(256+((((sin(num*3.14/180))*256))))/2;
OCR1B=(256+((((sin(num*3.14/180))*256))))/2;
     num=num+10;
    if(num >= 360)
{
       num = 0;
    }
}

//

You are doing complex calculations inside an Interrupt Service Routine. This is not a good idea. Computing sines takes a large amount of time as this consists of multiple, complex floating point operations. Interrupt Service Routines should be short and as simple as possible.

This is probably the reason you can't have two PWM signals active at the same time at the same frequency. The ISRs simply take too long.

The solution would be to pre-calculate the desired waveforms or greatly simplify the waveform calculations (preferably without floating point). If you decide to pre-calculate, take care to stay within the limited amount of memory you have available on your Arduino. You can minimize the memory used by calculating and storing just 1/4 of a complete waveform and constructing the remaining 3/4 from these values.

This leaves the conversion of your PWM output to a real sine wave. How are you planning to do that?


Generated frequency is not as expected This code sets a pin HIGH for 1 microsecond and then LOW for 1 microsecond. The expected frequency should be about 500 kHz. When measuring the output the frequency is about 96.4khz. Why ?

int del = 1;

void setup() {
   // put your setup code here, to run once:
pinMode(3, OUTPUT);
}

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

digitalWrite(3, HIGH);
delayMicroseconds(del);
digitalWrite(3, LOW);
delayMicroseconds(del);

}

Welcome to SE.

digitalWrite() takes a few microseconds to execute as well. There is also some overhead around the delayMicroseconds() function.

I you need exactly 500 kHz, you would want to consider using a timer.
You can read up on how to set one up in the microcontrollers datasheet.

Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.

// 500 kHz frequency

void setup() {
  cli();                 //Disable interrupt during setup
  TCCR2A = 0;
  TCCR2B = 0;

  TCCR2B |= (1 << CS20); //Enable timer without prescaler
  OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
  TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

  DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
  sei();                 //Enable interrupts again
}

ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
  TCNT2 = 0;
  PIND |= (1 << PORTD3); //Toggle Digital Pin 3
}

void loop() {
  //your looping code here
}

Explanation:
TIMER2 is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.

Normally, it counts up at the Arduino's clock frequency, like 16 MHz.

When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your outpin pin, resulting in a 500 kHz square wave on that pin.

We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.

16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz

The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.


How long does my digital pulse need to be for it to be read? I have the following really simple code. On every iteration it'll read the first pin, and if it's high - do some serial IO. Then do the same with the second pin. Nice and simple, works during my tests.

My concern is that (in production), the digital pulse I'm receiving (and trying to mimic during testing) would be too quick for the arduino to read. So, for example, the race condition could be:

First pin is low Read first pin - result is low.
First pin is now high Read second pin - result is low.
Fist pin now low again Read first pin - result is low again (missed the 'high')

How much of an 'edge case' is this? Am I worrying about something that's likely to be a non-issue here? In production, each single pulse would represent a significant amount of product (I multiply it elsewhere) - so even skipping one could throw my data off.

boolean count1High = false;
boolean count2High = false;
int count1 = 7;
int count2 = 8;
int a = 1;
void setup() {
  pinMode(count1, INPUT);
  pinMode(count2, INPUT);
  Serial.begin(9600);
}

void loop()
{
  if (digitalRead(count1) == HIGH)
  {
    if (!count1High)
    {
      count1High = true;
      a++;
      Serial.println(a);
    }
  }
  else
  {
    count1High = false;
  }

  if (digitalRead(count2) == HIGH)
  {
    if (!count2High)
    {
      count2High = true;
      a++;
      Serial.println(a);
    }
  }
  else
  {
    count2High = false;
  }
}

EDIT:

I know best approach here might be to attach an interrupt but I've been advised to avoid serial IO from within interrupts, I don't see an alternative here.

As explained by Majenko's answer, you should detect the pulses from an
interrupt and print the result from the regular code. However, instead
of just setting a flag in the interrupt handler, I suggest you instead
count the pulses within the handler. This will make the handler a tiny
bit slower, which is often something you want to avoid. However, the
extra overhead is really tiny, and you gain the ability to count
not only pulses that are short but also pulses that are closely spaced.

There is, however, something to be aware of when sharing a variable
between interrupt code and regular code. If the variable cannot be read
in a single CPU instruction (which is the case of an int on an
AVR-based board), there is some risk that the value gets changed in the
middle of you reading it. To void this problem, you have to disable
interrupts when reading the variable from regular code.

Here is an implementation of this strategy highlighting this point:

const uint8_t intPin1 = 2;
const uint8_t intPin2 = 3;

// This is volatile because it is shared between interrupt context
// and regular code.
volatile unsigned int sharedCount = 0;

// Interrupt handler.
void countPulse() { sharedCount++; }

// A variable shared with interrupt context should be accessed from
// regular code with interrupts disabled, in order to avoid race
// conditions.
unsigned int getCount() {
    noInterrupts();
    unsigned int countCopy = sharedCount;
    interrupts();
    return countCopy;
}

void setup() {
    pinMode(intPin1, INPUT);
    pinMode(intPin2, INPUT);
    attachInterrupt(digitalPinToInterrupt(intPin1), countPulse, RISING);
    attachInterrupt(digitalPinToInterrupt(intPin2), countPulse, RISING);
    Serial.begin(9600);
}

void loop() {
    static unsigned int previousCount = 0;
    unsigned int count = getCount();
    if (count != previousCount) {
        Serial.println(count);
        previousCount = count;
    }
}

Note that if the pulses come very fast, you may miss printing the
value, but you will not miss counting it (up to some limit, of
course). Thus you may see non-consecutive numbers being printed.


How to convert char[12] to byte[6] I am trying to convert a char[12] array that contains a Mac Address into a byte[6] in order to use within the Ethernet.begin method. I have tried various methods from online, but had little success to date. The char array currently contains "A4BDC334688C" and i would like a byte array containing { A4, BD, C3, etc }.

The following is extremely close to working, with the output of the following
"File Opened.
A4BDC334688C
A4
9D
C3
34
68
6C" With BD incorecctly converting to 9D, and 8C becomming 68.

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

byte ByteMacAddress[6]; // RESERVED MAC ADDRESS
StaticJsonDocument<200> doc;

int ShotCount = 0;
byte buf[40];

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

  //Initialise SD Card for Config
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
  }

  // open the file for reading:
  File ConfigFile = SD.open("Config.txt");
  if (ConfigFile) {
    Serial.println("File Opened.");
  } else {
    Serial.println("error opening Config.txt");
  }

  //Deserialize Json Config in File
  delay(5);
  DeserializationError error = deserializeJson(doc, ConfigFile);
  ConfigFile.close();
  // Test if parsing succeeds.
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }

  char* SDMacAddress = doc["MacAddress"];
  Serial.println(SDMacAddress);

  char arr[12];
  strcpy(arr, SDMacAddress);

  auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
  byte *ptr = ByteMacAddress;

  for(char *idx = arr ; *idx ; ++idx, ++ptr ){
    *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
  }

  //Check converted byte values.
  for( byte b : ByteMacAddress )
    Serial.println( b, HEX );
}

void loop(){
  //Maintain DHCP Lease
  //Ethernet.maintain();

  //GetShotCount();
  delay(500);
}

Please see the comments in the code:

// SDMacAdress is zero terminated
// (it should be because you use strcp not strncp)
// char arr[12]; you need one extra byte for the zero
char arr[13];
strcpy(arr, SDMacAddress);

auto getNum = [](char c)
{
  // you forgot upercase HEX letters (A-F)
  // don't use sophisticated code
  // the best programmers produce understandable code IMHO at least ;-)
  // perhaps you copied it from the internet
  // return c > '9' ? c - 'a' + 10 : c - '0';

  if ( c >= '0' && c <= '9' ) return c - '0';
  if ( c >= 'a' && c <= 'f' ) return 10 + c - 'a';
  if ( c >= 'A' && c <= 'F' ) return 10 + c - 'A';

  return 0;
};

byte *ptr = ByteMacAddress;

for(char *idx = arr ; *idx ; ++idx, ++ptr )
{
  *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
}


What's the difference between ICSP vs ISP? I'm not sure if these terms are interchangeable or not. What's the difference between ICSP and ISP? Is it simply the reset? I've shown two configurations in this question I just asked. Are they both ICSP?

The difference between ISP and ICSP is a hyphen.

ISP stands for In-circuit Serial Programming, and ICSP stands for In Circuit Serial Programming.

Any arrangement that allows you to program a microcontroller while it is in a circuit using a serial protocol can be called ISP or ICSP.


prgramming arduino led on then off i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:

int led=13;
void setup() {
  pinMode(led,OUTPUT);
}
void loop() {
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us  delay (5000)  then it should turn off with  digitalWrite (led,LOW).
but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.


How to convert a String number Into a int value? I want to convert a string into a int value. in my real code, I receive a string "Slider 255" the number after slider changes from 0 to 255, so I want a int value to be equal to that number. This is a small example of the code:

#include <Servo.h>
Servo myServo;

int val = 0;
String s = "";
void setup() {

  Serial.begin(9600);
  myServo.attach(9);
}

void loop() {
  while(BT.available() >0){
  s =  Serial.read(); // which wiil be a number between 0 and 255
  // So I want val to be = to ehatever the string is. So far I have try this but it doesn´t work.
  // first attempt # 1
  val = s:
  myServo.write(val);

  // Second attempt # 2
  Serial.println(s)
  val = Serial.read();
   myServo.write(val);
  }
}

The easiest way is to use the parseInt method available to Serial like this

int val = Serial.parseInt()

But, you will have to be sure that the non-number part of the message ("Slider") has already been dealt with.

You could also put the data into an arduino String Object and use it's toInt method, or put it in a C style string and use the atoi method.


how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6 I have to switch 2 MOSFET IRF640 at a duty ratio of .6 and the frequency of  switching is  50khz how can I generate it with a single aurdino

This could be achieved either with software (with a timer interrupt or
by polling micros()) or with hardware. The software methods, however,
are prone to a high level of jitter. If you want to have a steady
signal, you should use a hardware solution.

The most straightforward hardware option is to use a timer in PWM mode.
I would avoid fiddling with timer 0, as it is used by the Arduino
timekeeping functions. You are left with either timer 1 or timer 2. The
following program configures timer 2 to output the desired signal:

period = 20 µs = 5 × 64 CPU cycles
signal HIGH for 12 µs = 3 × 64 CPU cycles.

The output goes to pin 3, which is one of the two PWM pins controlled by
timer 2.

void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 = digital 3 as output
    OCR2A  = 5 - 1;       // period = 5 * 64 CPU cycles
    OCR2B  = 3 - 1;       // HIGH for 3 * 64 CPU cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22)   // ...ditto
           | _BV(CS22);   // clock at F_CPU / 64
}

void loop(){}

For some in depth information on how timers work, see
Nick Gammon's tutorial on timers.


Which sensor is best for obstacle detecting with retroreflector? Distance is about 3m. IR or visible light - does not matter.

It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.

Maybe for this task better to use specific retroreflector?

UPDATE:

there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.

The scheme of this sensor should be this:

But the use will be this:

I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:

I'd say an infrared LED, and an infrared detector.

Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.

However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).


Proto Threading 2 functions I would like to proto thread two functions to run pseudo-simultaneously. One function takes the input of a force sensor and moves a servo accordingly, and the other takes the input of a gyroscope (MPU650) and moves a different sensor accordingly. Below is my code where I attempt to use timers to handle this.

#include <Wire.h>
#include <Servo.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

int FSR_Pin = A0;
bool isClosed = false;
unsigned long lastMillis = 0;
unsigned long lastMillis2 = 0;

MPU6050 mpu;

int16_t ax, ay, az;
int16_t gx, gy, gz;

Servo handServo;

Servo wristServo;

int pos = 0;
int val;
int prevVal;

void setup(){
  Serial.begin(9600);
  handServo.attach(9);

  Wire.begin();
  Serial.begin(38400);

  Serial.println("Initialize MPU");
  mpu.initialize();
  Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
  wristServo.attach(8);
}

void handleFingers () {
  int FSRReading = analogRead(FSR_Pin);
  Serial.println(FSRReading);

if (FSRReading > 9) {
 if (pos < 90) {
     handServo.write(pos);
      pos ++;
 }
  isClosed = true;

} else if (isClosed == true && FSRReading < 10) {
  pos = 0;
  handServo.write(pos);
  isClosed = false;
}
}

void handleWrist() {
  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);
    if (val != prevVal)
    {
        wristServo.write(val);
        prevVal = val;
    }

}

void loop(){
  if (millis() - lastMillis > 1000) {
    handleFingers ();
  }
   lastMillis = millis();

 if (millis() - lastMillis2 > 1000) {
    handleWrist();
  }
   lastMillis2 = millis();

}

When I run the code above, the servos move a few degrees each and then do nothing at all. It appears that none of the servos are responsive to the sensor feedback. Something is wrong with my timing or my method of proto threading. I would really appreciate your help, thanks.

Jot provided the answer in a comment: you are updating lastMillis in
the wrong place. The correct way is:

if (millis() - lastMillis >= 1000) {
    handleFingers();
    lastMillis = millis();
}

Optionally, you can use lastMillis += 1000 instead of
lastMillis = millis() if you want to precisely control the average
(rather than minimum) update period.

Just to elaborate a bit, the idiom I like for doing this kind of stuff
is as follows:

const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

void loop() {
    unsigned long now = millis();

    // Handle the fingers.
    static unsigned long last_finger_update;
    if (now - last_finger_update >= FINGER_UPDATE_PERIOD) {
        last_finger_update = now;
        handleFingers();
    }

    // Handle the wrist.
    static unsigned long last_wrist_update;
    if (now - last_wrist_update >= WRIST_UPDATE_PERIOD) {
        last_wrist_update = now;
        handleWrist();
    }
}

Note that:

The update periods are constants defined at the top of the
program.
millis() only needs to be called once per loop iteration: if the
loop takes many milliseconds to run you would be doing something
wrong anyway.
last_finger_update and last_wrist_update stand for lastMillis
and lastMillis2, which are very poor naming choices.
These two variables are local to loop(), as they are not needed
anywhere else.
These variables are also declared static, which means they are
implicitly initialized to 0 and they preserve their values from call
to call.
I update the timing variables before doing the actual work. This
helps keeping all the timing code together, which makes the code
clearer, especially if the actual work takes many lines of code (e.g.
you do the work inline instead of having it in separate functions).

Some people prefer using libraries for this kind of proto-threading. If
you use the ArduinoThread library, the same could be written as:

const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

Thread updateFingers(handleFingers, FINGER_UPDATE_PERIOD);
Thread updateWrist(handleWrist, WRIST_UPDATE_PERIOD);
StaticThreadController<2> scheduler(&updateFingers, &updateWrist);

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


Unable to power an Arduino Pro Mini through the RAW pin I've recently bought an Arduino Pro Mini, the 3.3V and 8MHz version. The first time I powered it, using the VCC pin, all worked. But, as soon as I attempt using the RAW pin instead, nothing lights up... Is my regulator broken ? Or is this a typical issue ?

I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".

I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.


Arduino and industrial stepper driver For a project I need to use an industrial stepper driver with an arduino. There it is: http://www.omc-stepperonline.com/bipolar-stepper-motor-driver-max-4a-current-40vdc-input-16-subdivision-st6600-p-246.html

The motor: https://prototypes.haydonkerk.com/ecatalog/hybrid-linear-actuators/en/linear-actuator-57F42-3.25-099#

I'm not familiar with this driver, so can I use it with the Arduino Stepper Library?

I didn't see a lot of tutorial for this driver compared to many other popular driver.

Thanks!

Absolutely you can. Looking at the picture, this is set up for bipolar and a unipolar motor. There you have to wire according to the wire diagram.


Do the I/O pins on Arduino read current or voltage? So I've recently started Arduino and I just had a question about the digitalRead() function.
Does the IO Pins read Voltage or Current?
The reason I'm asking is because of the attached circuit.
So IO pin 7 is HIGH when the button is not pressed because the resistor is connected to 5V through the resistor. When the button is pressed the button is shorted to ground and is LOW. Why does it read LOW? Surely it would still read 5v because it is still connected to 5V through the resistor?

They read voltage.  When you close the pushbutton switch the input should have a 0V or digital "0" on it.  When you open the pushbutton the resistor should pull the input to 5V or digital "1".
Yes, it is still connected to +5V via the resistor but the nearly 0 Ohm switch pulls the line all the way (or very close) to 0V.


How to capture good sound with Arduino? Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

As I found, maximal sample rate, achievable with built-in ADC is 9kHz, which is to low.

So, I require to use some external hardware. But wave shields I saw are to expensive (comparable by price with Arduino itself), probably, because of excess functions (including not only ADC but also DAC and so on).

Simultaneously, there are ICs, providing ADC functionality and even MP3 encoding functionality for relatively low price. But here a schematic design required.

So, how to find appropriate solution here?

Yes but you want something much faster then the Arduino, normally it is in the 96k~48k bps range.  Try this link, they make a lot of great parts and the bulk of what you have to do is control software.  You can let the chip do the grunt work (analog) and transfer thee data to where ever you want.  Some of the chips will record for 300 seconds plus.

http://www.aplusinc.com.tw/exec/product.php?lg=E&mod=show&cid=43&pid=aPR33A3

I have used there parts they work great.

Have fun,
Gil


Infrared receiver gives only zeroes for results I bought a 37 in 1 sensor kit from Aliexpress.

Now am trying to use the infrared receiver with a TV commander.

My problem is that it returns as result only zeroes. The wiring is right. The code is from an example and includes not much.

I did a serial print to see if the receiver is working. It gives zeroes back so it is working.

I thought maybe a different library will help and downloaded irlib2 library and set the folders into the library folder.

But it can not find it the library so i must use IRremote library.

#include <IRremote.h>

const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup(){
Serial.begin(9600);
irrecv.enableIRIn();
irrecv.blink13(true);
}

void loop(){
Serial.println(results.decode_type);

Serial.println(results.value, HEX);
if (irrecv.decode(&results)){

    Serial.println(results.value, HEX);
    irrecv.resume();
}
}

What can i do to find what causes the zeroes?

I GUESS that it might be because of the following:

You declare results (it will be initialised to zeros)
In loop, you print the results.decodeType (which will be zero)
You then print results.value, which is still zero.
You then call irrecv.decode() which fails for some reason.
The code loops and starts printing lots of zeros.

You need to find out IF irrecv.decode() is failing and if so why. So add an else clause to catch it in the act.


How do I update the serial monitor without printing a new line each time? I'm testing out an accelerometer and I want to know if there's a way to make it so that the serial monitor will update the values without printing a new line. Ideally the serial monitor would say something like:

Accelerometer X: $xval
Accelerometer y: $yval

and then instead of printing two new lines each time, it just updates the values. Is there anyway to do that in Arduino? Thanks.

The ultra-basic "serial monitor" in the Arduino IDE cannot do what you want.

Instead you need to either write a special client program, or use a more standard serial terminal program, such as Tera Term (Windows), Minicom (Linux), etc.

These standard serial terminal programs use a special sequence of characters called ANSI escape codes which manipulate the display, doing such things as setting colours, moving the cursor around, etc.

More information on ANSI escape codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code


How to skip the first line and output the second? My question is related to my previous question.
These encoder programs outputs two line per pule/tick.

Here is the part of the code I want to use:

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }
//
  if (EncVariation != 0) {

        encoder0Pos = encoder0Pos + EncVariation;

        int degs = (encoder0Pos * 6) % 360 ;

        if(degs<0){ degs = 360 + degs; }

        Serial.println (degs);
   }
}

For three inputs/ticks this outputs like:

6

12

18

24

30

36

But I only need the second ones like:

12

24

36

How can I do that?
(I need it to send the relevant data do a PC.)

I spend so long time on it couldnt find any solution.

IF and only IF you want exactly what you have asked for which is alternate lines not to be output then this is a very crude and quick solution.

Outside of loop() add this declaration:

bool skipNextLine = true;  // true skips the odd lines, false skips even lines

And change the end of your code like this:

  if (EncVariation != 0) {
    encoder0Pos = encoder0Pos + EncVariation;
    int degrees = (encoder0Pos * 6) % 360 ;
    if(degrees<0){ deg = 360 + degs; }
    if (!skipNextLine)
    {  // This will skip alternate lines
        Serial.println (deg);
        skipNextLine = true;
    }
    else
    {
        skipNextLine = false;
    }
  }


Power suply for MicroSD card breakout board I'm developing a project and I need to connect to my Arduino Mini with a SD card breakout board. The problem is that I can't plug it directly to the Arduino since it is already powering some sensors and a BITalino, and I was told that it would, for some reason, be better to connect an external battery to the SD board.

My question is if i can supply this  MICROSD CARD BREAKOUT BOARD+ with a 3.7V battery, instead of a 5V.

Thank you!

Description:

Onboard 5V->3V regulator provides 150mA for power-hungry cards
3V level shifting means you can use this with ease on either 3V or 5V systems

Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.

Take reference from here Schematic of MICROSD CARD BREAKOUT BOARD


I2C libraries for ATTiny85? I want to transmit I2C data, using a Digispark ATTiny85 board:

http://digistump.com/products/1
http://digistump.com/wiki/digispark/tutorials/connecting

I've found the following I2C libraries. Which one is more lightweight, stable, bug-free, efficient, powerful, and easy to use?

Adafruit's TinyWireM has not been updated in 2 years.
felias-fogg's SoftI2CMaster has been updated within days of this post.
lucullusTheOnly's TinyWire represents some years of improvements, "based on the TinyWireM and TinyWireS libraries". This version is recommended by BroHogan, co-creator of TinyWireM:
https://playground.arduino.cc/Code/USIi2c

Wire seems under-featured:

  "the default Arduino Wire() library does not support changes in bus
  speed or feature proper clock stretching support. This makes the
  default library only marginally functional"
  https://www.maxbotix.com/articles/095.htm

What other I2C libs are available for ATTiny? In the IDE i see Digispark SoftSerial, OneWire, and VirtualWire.

How do they all compare?

Note, these other answers do not seem relevant to my question:

What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible?
Alternatives to Wire library for I2C

I want to transmit I2C data...

A little vague.

Transmit to what device? How fast is your data rate (100kHz, 400kHz)? Your only transmitting and not reading anything back? What is the idling voltage of your I2C bus (to then ask if you have chosen correct pull-up resistor values for your intended bus speed)?

You mention that the Wire library doesn't support core clock speed changes without some hacking, but don't talk about the speed you intend to run the microcontroller or how fast you intend to use the I2C. I can guess 400kHz, since you brought up speed, but that's not a great way to answer a question.

I have using the Wire library on an Arduino UNO at I2C bus rate of 100kHz and it's worked fine for my needs. I got bytes in and out.

At this point, the best suggestion I'd have is that if one of the above libraries you listed does not support a feature you'd like, fork it, and add support for your feature yourself. If you're only transmitting to one slave device, then you shouldn't need to worry about bus arbitration, like the TinyWire does. Adafruit is okay for the most part, but they seem (to me) slow to fix bugs and maintain code. But don't let the code's age get to you. I2C was created back in 1982, and you're still using it... :-P

Here's how I would approach choosing a library:

Define features you need
Look for a library which has most of those features
Add any new features you need
Possibly share your added features with the community with a Pull Request


wiring a arduino led project I am moving a project from breadboard and jumper cables.
It light a bunch of LEDs with different sets running of many almost every pin.
I need a few meters of cables.
I will a resistor on each led.
I have no idea what kinda cable/wire to use and googling cable gets me nowhere.
What kinda wire do people use?

When choosing wire for your project the main consideration is the amount of current. Second would be the distance.

For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or Amazon of course.

FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.

You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire_Size.htm


Get board.vid and board.pid value in code I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid

From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.

But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.

The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"

this line in "platform.txt" grabs them and makes build flags for them:

build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

the -D* option in the build is equivalent to the following lines being in the code

#define USB_VID /*value of build.vid*/
#define USB_PID /*value of build.pid*/
#define USB_MANUFACTURER /*value of build.usb_manufacturer*/
#define USB_PRODUCT /*value of build.usb_product*/

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.


Programming Arduino With Python Im a beginner working with arduino.
Im little familliar with java syn and its not hard for me to do the work with ide ;but i know python better....is there any Lib that let you program Arduino with Python?

Here is a page on interfacing Arduino with Python.

Interface Arduino with Python