Trying to use Nano Every as a sort of USB logic analyzer, but can't isolate it from "device under observation" Here's the scenario: I have a radio that displays information on a 1602A LCD. The 1602A is plugged into a header so I can easily pull it out and instead plug in logic analyzer leads. The logic analyzer decodes the HD44780 protocol and shows me the data that would have gone to the 1602A. The logic analyzer, not surprisingly, doesn't have any noticeable effect on the radio.
Now I want to replace the logic analyzer with a Nano Every. I wired it up so that the signals to be observed are connected to digital input pins on the Every. The Every is powered through USB and doesn't intentionally draw any power from the radio. Everything runs as expected and the Every shuffles readings to the PC via serial. HOWEVER, in this combination, the radio draws at least twice as much current from the power supply and the radio's voltage regulators begin to heat up substantially!
I would have thought that the digital input pins of the Every are high enough impedance that it would have no significant effect on the radio, just like the logic analyzer didn't. I can only assume that "significant" current is flowing from the radio's LCD header into the Nano Self's input pins, since they are the only connection between the radio and the Nano.
So, I guess my question is this: How can I make the Nano Self work more like a logic analyzer? Do I need additional circuitry between the signals being tested and the Self's input pins, perhaps logic buffers? Or might something else be going on here?

@jsotola was correct and the software defined pin directions incorrectly. Looks like I fried one of the pins in the process (multimeter shows continuity between the pin and ground), but when I rewired to a new pin on Port D and ran the corrected software, everything seems to work as expected!


EEPROM library throwing errors I've included  in my sketch and am trying to run a simple sketch that just does EEPROM.write(0,4); followed by a println of EEPROM.read(0);  However, it won't compile.  It keeps telling me there is an error, and that I'm making a "request for member 'write' in something that is not a structure or a union".  I'm using the Mega ADK.  What am I doing wrong?  I've also tried to go to sketch->include libraries and include the EEPROM library directly, still no joy.  This is Arduino 1.6.13 on Windows 8, if it matters.

The problem had to do with data types.  I was using an unsigned int as follows:

unsigned int addr = 0;
EEPROM.write(addr,5);

However, EEPROM.write requires an int, not an unsigned int, and this caused a compiler error.


Connecting Load combinator to HX711 then to Arduino i'm currently a student and my project is to create a weighing scale using 50kg load sensors (x4) with HX711 amplifiers, load combinator and Arduino UNO. I've connected the load combinator and HX711 based on the picture below:

I'm wondering after this connection, how do i connect it to the pins of Arduino UNO and does anyone know the codes to make the load sensors work? Because currently i keep getting 0kg as the final value as well as the offset value.

To be able to wire load sensors up you first need to understand how they work and what the wires on them actually mean. There are no standards as regards colour coding of the wires.

So step one is to find out the colour coding of your load cells. Assuming they are "normal" cheap 3-wire ones, internally they look like:

simulate this circuit – Schematic created using CircuitLab

You need to identify those wires on your cells.  We'll call them +, C and - (in that order) from now on.

The idea is that you provide power between + and - and a varying voltage comes out of C depending on the load applied. More load means a lower voltage, since R1 and R2 form a simple potential divider.

However that's not enough to get good results - the voltage differences are too small. So they are usually used as part of a Wheatstone Bridge. This allows a much smaller voltage variance to be detected.

The Wheatstone Bridge is created by the combinator board. It does it by combining the individual parts of separate cells together to form just two load cells along with the static resistances.  This is the form the Wheatstone Bridge create takes:

simulate this circuit

I have boxed in each load cell so you can see how two "variable" legs combine into a single variable resistance, and two "static" legs combine into a single static resistance.

Now you can see how you could test the combinator to make sure it's giving proper results. Apply a voltage between E+ and E- (say 5V) and measure the voltage between A+ and A-. Apply pressure to the load cells (all of them at once) and observe a change in the voltage between A+ and A-.

Assuming that is showing good results (the voltage change will be quite small, so set your DMM to its most sensitive setting), your next point of call is the connection to the Arduino itself.

The HX711 uses a digital serial protocol. Sparkfun has software that bit-bangs that protocol over any pair of IO pins you choose. There is nothing special about which pins are chosen - any two can be used. So as long as you have +5V, GND and the two data pins connected up to the Arduino there's not much that can go wrong.

So that then leaves the software.  The biggest mistake people often make is to not tell the software which pins are being used for the serial communication. Or telling it the wrong pins - getting the clock and data pins mixed up, for instance.  This would be the first port of call for checking the software. Make sure you have the right pins specified.  Quite how you do that without seeing your software I can't say, but Sparkfun have some example software (scroll down to the bottom of the page) which just uses a pair of #define macros to specify the pins.


Is there a way to traverse a filesystem and read files with an arduino? I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.

Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?

Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)

Any help/ideas are appreciated!

The Arduino has no access to the file system on a PC.  All it has is a serial connection with which it can communicate with some program running on the PC. The code that is handling the PC's file system would have to run on the PC itself.


Sending 4 analog values from one arduino to another with I2C I have modded a cheap drone controller to output its joystick values to an Arduino Nano.
I made it to output its 4 pot values using I2C to another Arduino don't ask why. So my problem is that I need to send 4 values but I can send only 1. Help me please.
I don't have a time limit or something so I don't need this quick or now!
I am also using a 16x2 LCD without I2C to show the live values and sometime I want to make a menu there or stuff like that.
I would like if you wrote the code for me but its ok if you cant. Also I'm kind of a noob at arduino programming.
Master(a.k.a the nano in the controller):
int pot1 = A0;
int pot2 = A1;
int pot3 = A2;
int pot4 = A3;

int potValue1 = 0;
int potValue2 = 0;
int potValue3 = 0;
int potValue4 = 0;

int led = 10;
int button = 8;

int lastButtonState;    // the previous state of button
int currentButtonState; // the current state of button

int output1 = A4;
int output2 = A5;
int output3 = A6;
int output4 = A7;

#include <Wire.h>
#include <LiquidCrystal.h> // includes the LiquidCrystal Library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)

#define SLAVE_ADDR 9

void setup() {
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP);

  // Open serial communications and wait for port to open:
  Wire.begin();

  lcd.begin(16, 2);
  lcd.print("   ArduinoTX");
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  digitalWrite(led, LOW);
  delay(600);
  digitalWrite(led, HIGH);
  delay(600);
  delay(3000);
  lcd.clear();
}

void loop() {
  currentButtonState = digitalRead(button);
  potValue1 = analogRead(pot1);
  potValue2 = analogRead(pot2);
  potValue3 = analogRead(pot3);
  potValue4 = analogRead(pot4);

  int sendValue = map(potValue4, 1, 1023, 1, 255);  //converting to values 255 max
  int sendValue2 = map(potValue3, 1, 1023, 1, 255);
  int sendValue3 = map(potValue2, 1, 1023, 1, 255);
  int sendValue4 = map(potValue1, 1, 1023, 1, 255);

  Wire.beginTransmission(SLAVE_ADDR); //sending only one pot value
  Wire.write(sendValue);
  Wire.endTransmission();

  lastButtonState  = currentButtonState;      // save the last state
  currentButtonState = digitalRead(button); // read new state

  if (lastButtonState == LOW && currentButtonState == LOW) { //dont worry about this
    lcd.print(potValue4);
    lcd.print("        ");
    lcd.print(potValue2);
    delay(delayTime);
    lcd.clear();
    lcd.setCursor(0, 2);
    lcd.print(potValue3);
    lcd.print("        ");
    lcd.print(potValue1);
    delay(delayTime);
    lcd.clear();
  }
}

Slave(or an uno who receives the values):
int rd;
int br;

#include <Wire.h>

#define SLAVE_ADDR 9

void setup() {
  // put your setup code here, to run once:
  Wire.begin(SLAVE_ADDR);

  // Function to run when data received from master
  Wire.onReceive(receiveEvent);

  // Setup Serial Monitor
  Serial.begin(9600);
}

void receiveEvent() {
  // read one character from the I2C
  rd = Wire.read();
  Serial.println(rd);
}

void loop() {
  delay(50);
}

Thanks!

Why are you limited to sending one value? You can have multiple Wire.write() calls in one transmission.
The slave side just needs to know to expect multiple values in order to accommodate. The best way to do this would be to read in values as long as the master is sending them (check out https://www.arduino.cc/en/Reference/WireRead).
Then your master changes from
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.endTransmission();

to
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.write(sendValue2);
Wire.write(sendValue3);
Wire.write(sendValue4);
Wire.endTransmission();

And the slave receiveEvent() becomes
int receiveValue;
int receiveValue2;
int receiveValue3;
int receiveValue4;
int index = 0;
while(Wire.available()){
    if(index == 0){ receiveValue = Wire.read(); }
    else if(index == 1) {receiveValue2 = Wire.read(); }
    else if(index == 2) {receiveValue3 = Wire.read(); }
    else if(index == 3) {receiveValue4 = Wire.read(); }
    index++;
}

I would also consider using arrays as a way to clean up some of your variables, but making the above changes should accomplish what you want if not as cleanly.


Easy bipolar motor control? Is here some easy way to control bipolar motor
 without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise  and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.

You need a motor driver (or at least some transistors and diodes etc) to control the motor.


Best practise when dynamically updating sketch I am currently working on a project that uses an Arduino Mega 2560 board along with the Arduino GSM shield to connect to the internet and send/receive SMS messages.

As part of my project, I want to be able to update the software that I am running dynamically. At a high level, I want to connect to my server, check if there is an update, if there is, download it and then overwrite the current sketch to run the new downloaded binary if the checksum of the downloaded binary is as expected (to avoid corruption).

Now, I am new to Arduino programming, so I figured I would ask a community of people with experience to determine the best method.

My current ideas are as follows:

Writing a custom bootloader - The sketch will have an update routine that downloads the new binary to a known location, and then performs a system reset. The bootloader will then overwrite the current sketch with the downloaded binary and then run the sketch.
Overwriting the sketch whilst running - I'm not sure of the viability of this method, but the overall method would be to write an update routine to the end of flash memory, and in this code simply overwrite all of the non-bootloader code with the new sketch.

Are these methods both viable, if so, is there one that would be preferable to another? If not, are there any known solutions to this problem?

You won't be able to download the whole binary and test its checksum before flashing because RAM is so much smaller than flash. To do that, you'd need an external storage device to hold the new binary, and a custom bootloader to install it from the device.

Otherwise you'll have to load-and-flash, testing the checksum on the fly, and retry if you need to until you get a good reload. Can your device and its environment tolerate stopping for however long a couple of retry cycles might take? You can't recover if the process is interrupted once you start flashing; you can only move forward. Can it tolerate a conceivably long outage if communication goes down once the reload process has started?


Arduino (weird) ADC problem I'm trying to read to voltage output of module ACS712. Here is my problem: The module outputs a voltage around 2.5V, however, arduino sends the value "1023" to the PC. (Gives a reading of 5V).

Arduino's analogRead function works, however, is slow so I used atmega registers to solve the issue. Which worked... Except only for the module. Here is the relevant part of my code:

Setup:

void setup() {
  ADMUX = 0xC0;
  ADCSRA = 0x8E;           // prescaler = 64
  ADCSRB = 0x40;
  sei();
  bitWrite(ADCSRA, 6, 1);    //This starts single converion.
  Serial.begin(250000);
}

Relevant ISR function:

ISR(ADC_vect) {
  sensorValue = ADCL;        // read adcl first. locks adc bytes.
  sensorValue += ADCH << 8;
  Serial.println((int)sensorValue);
  bitWrite(ADCSRA, 6, 1); // Set high so another conversion starts.
}

Now, this code runs as expected for another adc pin which is located at "A3", or in code:

ADMUX = 0xC3;

However, does not work for:

ADMUX = 0xC0;

Yes, I tried replacing the wires A0 and A3. This time "0xC0" works but "0xC3" doesn't. So my arduino somehow is resistant on reading the module output!

Also, this works on same hardware:

sensorValue = analogRead(A0);
Serial.println((int)sensorValue);

Arduino's analogRead runs as expected on same hardware.

So basically, the hardware seems okay, but there seems to be a problem with my code. I just can't read the modules output voltage and I'm all out of ideas. Can anyone help?

However, does not work for:
 ADMUX = 0xC0;

See the datasheet:

An ADMUX of 0xC0 will be using a voltage reference of "Internal 1.1V Voltage Reference with external capacitor at AREF pin". Since you are supplying 2.5V that exceeds 1.1V and thus you get a reading of 1023.

  Serial.println((int)sensorValue);

Also, don't do serial prints inside an ISR.


Atmega168 interrupt error handling I'm using an Atmega168 in a project that involve using the ISRs from multiple sources. I have an ISR hooked up to an external button and a timer, to use it as a reset button after a predetermined hold time.

I'm also using an ISR hooked upto UART. The UART is connected to an external Linux based SoC. Upon receiving specific commands from the linux machine, the atmel will perform certain functions.

In very rare occasions, the linux hangs up during tranmission and is always sending out the UART commands. This saturates the ISR and it also prevents the reset button ISR to function.

Although this happens rarely, I would like to take measures for this. As far as I know, there are no way to set priority in avr ISRs. So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

EDIT:
I think the problem arises when the linux machine sends an empty string to the atmel.
the UART_receive() on the atmel gets stuck at: while ( !(UCSR0A & (1<<RXC0)) );

Any way I can avoid this?

unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.

Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

  So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".


Why can't I upload a sketch while other components/devices are connected to my Uno? I wanted to make a fairly simple circuit which would flash a series of LEDs in sequence, using my Arduino Uno (more specifically, a SainSmart clone). I wrote my sketch and it compiled fine. After that, I connected 8 LEDS+resistors to pins 0 through 7, and then connected the Uno to my computer via USB.

I've uploaded sketches successfully in the past, so I'm sure my settings and drivers etc. are correct. However, when I tried to upload my sketch this time, it didn't work.

I tried removing everything I'd connected to the Arduino's pins, and suddenly the upload worked again.

Why does this happen? Does it mean I have to disconnect everything from the board every time I upload a sketch?

The problem is specifically pins 0 and 1. Although they can be used as regular digital IO pins, they also serve as the RX and TX pins for the Uno's serial port. The USB connection (for uploading sketches etc.) is routed to the same pins internally. Unfortunately that means anything connected on pins 0 and 1 can interfere with the serial connection, preventing communication via USB.

In short, it's not necessary to disconnect everything when uploading a sketch. It should only be necessary to disconnect anything from pins 0 and 1. Rather than going through that hassle every time a sketch is uploaded though, it may be best just to avoid using those pins unless necessary (e.g. you run out of other pins, or your project needs a serial connection to another device).


How to get data from 9DOF razor IMU directly to arduino mega My final project goal is to make Brushless gimbal for drones using only Arduino MEGA 2560 and 9DOF IMU for control. On Instructables I found two excellent tutorials. Both are different than mine in selected components.
I use the following components:
Arduino MEGA2560
Motors - Quanum 2208 Precision Brushless Gimbal Motor ( httpx://goo.gl/RDBvJL)
Motor Driver - H bridge L298n (httpx://goo.gl/A4ZQi5)
9DOF Razor IMU (httpx://goo.gl/myg9oj )
I'm stuck with 9DOF Razor IMU. Surfing on the internet I found a great tutorial and  github repository (httpx://goo.gl/jh2pfU). This tutorial is excellent and AHRS works great with the FTDI Basic Breakout 3.3V. They gave me a good starting point, but my goal is use only Arduino MEGA2560 and sensors.
I want to connect the Arduino and 9DOF IMU directly and use the accelerometer data (Yaw, Pitch, Roll) for directly control the engines. On the website of the manufacturer Sparkfun (httpx://goo.gl/myg9oj ) I can’t find any datasheet exclusively for 9DOF IMU that could help me to connect Arduino and IMU. There are only datasheet of sensors that are on IMU ( ITG-3200 (MEMS triple-axis gyro), ADXL345 (triple-axis accelerometer), and HMC5883L (triple-axis magnetometer)  which are useless for me.
That's why I decided to use code from this site ( httpx://goo.gl/zOnYjN ) and he works great. I connected everything as is in tutorial and  Arduino SerialMonitor show me the desired values YPR. Values load very quickly directly from IMU and printed on SerialMonitor.
Values on SerialMonitor looks like this:
YPR=72.13,1.74,-16.38
YPR=72.14,1.72,-16.39
YPR=72.12,1.71,-16.39
YPR=72.13,1.71,-16.37
YPR=72.13,1.70,-16.40 …
HELP ME
This is my first solo Arduino project and I have a lot of questions about it.
How could I parse the data that appears on SerialMonitor to get new variables eg. Yaw = 72.12, Pitch = 1.74, Roll = -16.39?
Is it possible to do that?
Does anyone have any experience with 9DOF razor IMU and maybe know  better way to collect information from the accelerometer 9DOF razor IMU?
I want to achieve three separate variables which i will use to control the brushless motor. I think this should be an easier method as it is just comma separated numbers but then again i am new to arduino serial communication so i would appreciate any help with this. Even if it's only how to parse and extract the values.

sscanf should be enough. There is also other options, String class for example with substring method.

Take a look at the example:

#include <stdio.h>

char myString[] = "#YPR=72.13,1.74,-16.38";

void setup() {
  // put your setup code here, to run once:
  float yaw = 0;
  float pitch = 0;
  float roll = 0;

  sscanf(myString, "#YPR=%f,%f,%f", &yaw, &pitch, &roll);
  Serial.println(yaw);
  Serial.println(pitch);
  Serial.println(roll);
}

void loop() {

}


Is it possible to increase the Arduino's input and output pins? I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.

I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.

In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?

I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

I am good at coding however when it comes to hardware sometimes I'll need some push.

Thanks a lot.

You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.

Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf

As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.


PWM delay without blocking the code I want my LED to turn on gradually without using the delay() function and blocking the code.

Here's the code i came up with:

int led_pin = 6;
unsigned long millisTimer = 0;
int PWMdelay = 5000;
int condition = 0;
int i = 0;
void setup() {
    pinMode(led_pin, OUTPUT);
}
void loop() {
    if(condition == 1){
    if ((millis() - millisTimer) > PWMdelay){
        if(i<255){
            i++;
            millisTimer = millis();
        }

    }
        analogWrite(led_pin, i);
    }
}

Is this the "right way" of slowing the PMW duration from 0 to 255 or there are alternative/better/easier ways?

Here is my take at this - I've followed the example code mentioned by other members and here is "FadeWithoutDelay"

const int ledPin = 11;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 100;               // fade interval (milliseconds)
int brightness = 0;                      // how bright the LED is
int fadeAmount = 5;                      // how many points to fade the LED by

void setup()
{
  pinMode(ledPin, OUTPUT);  // set the digital pin as output:
}
void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;         // save the last state
    analogWrite(ledPin, brightness);        // Set the brightness
    brightness = brightness + fadeAmount;   // change the brightness for next time through the loop
    // reverse the direction of the fading at the ends of the fade:
    if (brightness <= 0 || brightness >= 255)
    {
      fadeAmount = -fadeAmount;
    }
  }
}


Confusion about String handling I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.

I can println a string directly, but if I have it in a variable, it will disappear :I

I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?

I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..

Code:

Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time {0}";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time {0}");
Serial.println(message.substring(3,6));

Response:

- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time {0}
(nothing)

Update

This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:

Code:

Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time here is a number 0";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time here is a number 0");
Serial.println(message.substring(3,6));

Response:

- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time here is a number 0
(nothing)

The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.

I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).

Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.

Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:

Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.

To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:

Serial.print(F("Test time: ");
Serial.println(test_time);


ArduinoJson buffer gets overwritten I have not that much experience with native languages like c/c++ and I'm facing a strange issue, which drives me crazy. So I'm using an Wemos D1 mini (ESP8266) which uses a class calles ConfigManager to read a configuration file from eeprom. The config file is formatted as json, so I'm using ArduinoJson to parse the content. I have declared a StaticJsonBuffer and pointer to a JsonObject in the header, like you can see in the code example:

//FILE: ConfigManager.h
#ifndef ConfigManager_H
#define ConfigManager_H

#include <Arduino.h>
#include <ArduinoJson.h>
#include <FS.h>
#include "Logger.h"

class ConfigManager {
public:

    Settings *settings;

    ConfigManager();

    void read_from_eeprom();

private:

    File configFile;
    JsonObject *json;
    StaticJsonBuffer<200> jsonBuffer;

    void open_file(const char *permission);

    void read_json();

    void recreate_file();

    void create_json();

    void check_success();

    void populate_settings();

    void clean_up();
};

#endif

When the function read_from_eeprom is invoked, it opens the file and invokes the functionread_json:

void ConfigManager::read_json() {
    size_t size = configFile.size();
    Log.verbose("[ConfigManager] Config file size: %d", size);

    std::unique_ptr<char[]> buf(new char[size]);
    configFile.readBytes(buf.get(), size);
    Log.verbose("[ConfigManager] File content: %s", buf.get());

    Log.verbose("[ConfigManager] Parsing json");
    json = &jsonBuffer.parseObject(buf.get());

    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();
}

Which is followed by a call to check_success()

void ConfigManager::check_success() {
    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();

    bool should_recreate = true;
    if (json->success()) {
        Log.notice("[ConfigManager] Parsed json successfully");

        auto version = json->get<const char*>("version");
        if (version) {
            if (strcmp(version, Settings::current_version) == 0) {
                Log.notice("[ConfigManager] Config version is up2date");
                should_recreate = false;
            } else {
                Log.warning("[ConfigManager] Config version outdated");
            }
        } else {
            Log.warning("[ConfigManager] Invalid config file");
        }
    } else {
        Log.warning("[ConfigManager] Config file is not valid json");
    }

    if (should_recreate) {
        Log.notice("[ConfigManager] Recreating config file");
        recreate_file();
        create_json();
    }

    Log.notice("JSON IS: ");
    json->prettyPrintTo(Serial);

    Log.notice("[ConfigManager] Sucessfully read json");
}

So what I noticed is that the file content is fine. E.g. {"version":"0.2","led_count":"64"}.

Then the json is parsed, which succeeds and logs the json object, which is again {"version":"0.2","led_count":"64"}.

Afterwards the function returns, and calls check_success, which again prints the content of the json object to the log, but this time it seems that something has overwritten the JsonBuffer, which causes the json object to be corrupted. This time the logged content is {"v␂":"0.2","led_count":"64"} (with some strange unicorn characters that change as the source code changes). I'm trying to figure out whats going on for many hours now, but I'm stuck. Can someone please point me in the right direction to solve this problem? Thank you!

the ArduinoJson library doesn't copy the strings, it only stores pointers and writes terminating zeros into input buffer. And your buffer buf is disposed by std::unique_ptr at the end of read_json() function


Atmega328P - SCK pin I am using Atmega328p with arduino bootloader in a project. There happens to be an LED connected on SCK pin. During Start (or restarts), the LED appears to flicker a couple of times (3 times to be exact). I don't want this to happen. I can change the connections but I would prefer a software solution because hardware change means a PCB modification.

I probed the SCK pin and I got some expected waveforms. There were two different cases:

1) When I powered the arduino using USB to serial programmer i.e. Tx Rx connected to a PC:

2) When I powered the arduino with an external power source (the case with my project):

This is what I think:

1) As mentioned in this thread, the bootloader has a piece of code which makes it act that way.
The bootloader code has a pin definition file which declares SCK pin as a LED and blinks it a couple of times to indicate that it has entered the bootloader. I found the code here:

#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
/* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duemilanove */
#define LED_DDR     DDRB
#define LED_PORT    PORTB
#define LED_PIN     PINB
#define LED         PINB5

Other relevant piece of code is here.

In this case, changing the LED definition to PINB4 and burning the bootloader and program again should take care of the issue. However this didn't work out for me. This is what I did exactly:

a) Opened the file D:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot\pin_defs.h

b) Modified the PINB5 to PINB4 on line 6.

c) Saved the file, burnt the bootloader and then program.

d) Powered up the chip and tested whether I am getting those 3 pulses. I got those 3 pulses.

(Even though it didn't work, I am still going to try it a few more times just in case I might have made an error.) :(

2) This brings me to second thought that since atmega328 accepts code through SPI by default, it checks for incoming data by clocking the SCK pins 3 times during startup. In this case, a software fix won't do anything.

What do you guys suggest? Should I go for the PCB modification or is there still some hope left?

Ignacio pointed out that I can disable bootloader to get rid of the issue. I want to program the chip using arduino IDE (preferably via UART) but I can consider SPI as well in case everything else fails.

Note: I am not sure whether this post is more suited for EE or Arduino. In case you guys(mods) think I'd get better suggestions there, feel free to move my post to Arduino.

There is nothing in the default megaAVR initialization that causes SCK to behave in this manner; it is all caused by the bootloader.

Fortunately all you have to do to solve this is disable the bootloader. Unprogramming the BOOTRST fuse (ext:0) will cause execution to start at address 0 instead of the beginning of the bootloader on reset.


Can you use a RF remote with nRF24L01 and Arduino? I recently bought a 10 pack of RF transceivers (nRF24L01). I wanted to know if its possible to pair one with an RC drone controller. I can't seem to find any ways to do this through google.

If this helps:

My drone and its controller is called "Sky Viper v2400" and a link to where you buy it is: https://www.amazon.com/Sky-Viper-01601-Streaming-Video/dp/B01D1HRXSK.

Thanks

The nRF24 operates in the 2.4GHz frequency and implements a proprietary protocol so, even if I don't have much information on your particular drone/controller, I strongly doubt there's a chance you can use the nRF24 module to talk to your drone.


DB:NO RESP Using inet.httpPOST on loop() I'm using SIM900 module + arduino uno + gsmlib.org library.

I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using inet.httpPOST function in setup(), but... in loop(), when I call that function again, it doesn't work. On serial monitor I get:

ATT: ERROR
RIC:
ERROR
DB:STARTING NEW CONNECTION
ATT: SHUT OK
RIC:
SHUT OK
DB:SHUTTED OK
ATT: OK
RIC:
OK
DB:APN OK
ATT: OK
RIC:
OK
DB:CONNECTION OK
ATT: ERROR
RIC:
xxx.xxx.xxx.xxx

DB:ASSIGNED AN IP
status=ATTACHED

http://api.com.br/mystring

ATT: OK
RIC:
OK
DB:RECVD CMD
ATT: CONNECT OK
RIC:
OK
ATT: OK
RIC:
CONNECT OK
DB:OK TCP
ATT: >
RIC:
>
DB:>
ATT: SEND OK
RIC:
SEND OK

DB:SENT

http://api.com.br/mystring

ATT: OK
RIC:
xxx.xxx.xxx.xxx
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN

How can I send data to my API continuously on loop() Could someone help me?

Following is my code (SOLVED):

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(11, 10);

/**
    setup
*/
void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.println(F("Starting App Arduino"));

  // Turn on GPRS
  powerUpGprs();

  // Start configuration of shield SIM900 with baudrate and  connect to internet.
  if (gsm.begin(9600)) {
    Serial.println(F("\nstatus=READY"));

  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);

  // Mensure and show memory usage
  Serial.println(F("\nMemory usage"));
  Serial.print(freeRam());
}

/**
   loop
*/
 void loop() {
  serialGps.listen();
  while (serialGps.available() > 0)  {
    if (gps.encode(serialGps.read())) {
      // Get GPS position and send To API
      gsm.listen();
      // if sim900 started, connect to internet
      Serial.print(F("\r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));

      // GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.com.br", "zap", "zap"))
        Serial.println("status=ATTACHED");
      else Serial.println("status=ERROR");
      delay(1000);
      // Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");

      Serial.print(F("\r\n\r\n"));
      Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
      // get geolocation
      String geo;
      geo.concat("lat=" + String(gps.location.lat(), 6));
      geo.concat("&lng=" + String(gps.location.lng(), 6));
      geo.concat("&spd=" + String(gps.speed.kmph()));
      geo.concat("&gps.uuid=1");
      // send2Api
      Serial.println(geo.c_str());
      Serial.print(F("\n"));
      gsm.SimpleWriteln("AT+CIFSR");
      inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
    }
  }
}

/**
   mensure memory usage
*/
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/**
   Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

Thank You!!!

Like I told you before, you have 2 instances of SoftwareSerial active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling listen() on each instance; any data arriving at any port while its not the active port will be discarded. inet.httpPOST() worked in setup() because you called the function before begin()ing serialGps. Calling serialGps.begin() immediately made serialGps the active port, severing communication with the modem.

Add this line to SIM900.h in the library, under the public methods:

void listen();

Add this method to SIM900.cpp:

void SIMCOM900::listen(){
   _cell.listen();
}

Save the files and add gsm.listen() right before gsm.SimpleWriteln("AT+CIFSR"); in loop().
Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().
Make serialGps.listen() the last  statement in loop() immediately after the inet.httpPOST() call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.


Just sanity-checking a concept... poor man's self-monitored alarm system If I wanted to throw together a simple burglar-alarm system that had wireless sensors talking to an Arduino (which would then send me an SMS message via cellular shield as a silent alarm telling me which alarm sensor had changed state_)... what technology would you recommend for the sensor-to-arduino signalling?

It needs to be something that draws little or no power until the alarm is triggered, resistant to radio interference, and as always cheap is a huge plus.... but I haven't gotten much beyond that.

(Of course if anyone's already implemented something like this and there are descriptions/sketches I can adopt and adapt, feel free to point me in the right direction.)

EDIT: To provide more info,this is a wood-framed house, 2 storey plus basement, brick chimney possibly in the way. No straight-line distances greater than 60 feet. Wifi, wireless phone, usual electronics and a wood shop I'm still putting together. Shouldn't be difficult, I just want a robust solution in case a friend asks me to replicate it... and for purely aesthetic reasons.

NRF24L01+ for communication. Extreme low power if not sending. Detects packet loss, and automatically resend the packet.

You would however need a small arduino board at the sensor, to read the sensor, and signal to NRF24L01 to send a message.

You'll have to put the arduino in to low power sleep mode to get some good battery life. Either have the sensor wake the arduino up with an interrupt, of poll the sensor like every half second, and immediately go back to sleep.


Difference between Ultrasonic sensor and Distance Sensor? What is the difference between an Ultrasonic Sensor and a Distance Sensor?

An ultrasonic sensor can usually develop and receive high frequency sound waves.  They can be used to measure distance by measuring the time of flight of the sound wave.

distance(meters)  = [speed_of_sound(meters/second)][1] x time_of_flight(seconds)
distance(meters) = 343(meters/second) x time_of_flight(seconds)

For example, say the time of flight was 0.01 seconds.

distance(meters) = 343(meters/second) x 0.01(seconds)
distance = 3.43 meters

This is just one way distance can be measured by a processor.  Other ways use different types of radiation such as electromagnetic radio and light radiation.  Some of these use time of flight. Others use more exotic phase techniques.  These types of detectors can be very accurate over long distances.  But are usually very costly.  They are commonly used for automated car driving.

A completely different approach uses triangulation or parallax of a light beam and a focused linear array light sensor.

These types of detectors normally operate over short distances and are cheap to make.  They are commonly used in places like copier machine to detect objects and paper.  Or in automated vacuums cleaners to detect floor edges such as stair drop offs.


HC-SR04 calibration conditions As is known, the speed of sound depends of temperature and Relative Humidity. I'm trying to calibrate HC-SR04 sensor taking account these factors.

In SparkFun page there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found a paper with some calibration, but again it is no mention of original conditions.

I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.

Anyone know the environmental conditions of HC-SR04 calibration?

The HC-SR04 is not calibrated, nor does it take any measurements.

All it does is allow software on a connected microcontroller or system like an Arduino to measure the sum of the round trip time delay and some small internal offset delay, and from this calculate distance.

As the timing and calculation are entirely in your program, calibration is entirely up to you.

Under known conditions you could measure both a short and a long distance.  This would give you a slope and intercept - the slope from the speed of sound (which should not depend on the device at all, only on the conditions and your timing reference), and the intercept or offset, having to do with latencies in the system.

You could then cross-check at other distances, but under fixed conditions behavior should be linear.

As there is some initial ringing of the sender which can couple to the receiver and be mistaken for an echo, there will be a minimum distance below which you cannot reliably take a reading - as a guess, this is more than 5 cm, but you'll have to see, and it may even vary a little from unit to unit.

To a degree, it's a little bit amazing that these even work.  They use an RS232 level shifter to generate transmit pulses, and it's been alleged that the receive circuit is horribly mistuned, not really matching the emitted frequency at all... but despite that they do seem to work fairly well.


HC-05 connecting to Arduino I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.

Setup:
Arduino Nano 168
HC-05 VERSION:3.0-20170601

I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.

After many attempts with no results, I attempted the following:

#include <SoftwareSerial.h>

int light=8;
int Received=0;
int light_state =0;

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup(){

  Serial.begin(38400);
  pinMode(light,OUTPUT);
  BTSerial.begin(38400);

}

void loop(){
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
 }

 if(BTSerial.available()>0) {
    Received = BTSerial.read();
 }

if (light_state == 0 && Received == '1') {
    digitalWrite(light,HIGH);
    light_state=1;
    Received=0;
  }
if (light_state ==1 && Received == '1') {
    digitalWrite(light,LOW);
    light_state=0;
    Received=0;
  }
}

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes.  Before I connect, the status LED flashes fast.  After I connect, it flashes slow.

I have the serial monitor open on my laptop monitoring the Nano.  The HC-05 connects via pins 10 & 11.  When the phone connects to the HC-05, the data printed on the serial monitor is garbage.

⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮

That is what I get.

The app is set to transmit a "1" via BT to the Nano.  When I press the button to send the 1, no data comes across.  But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.

Thank you in advance for your help.

This issue has been resolved.  There was an issue with the parity and stop bits.

When setting up for arduino comms, remember, baud rate, 1 stop bit, 0 parity bits.


Can I use IR Transmitter/Receiver for heart beat detecting? Specifically, I want to know if the KY-022 module and KY-005 module can be used for heart beat detecting according to this tutorial?

KY-005:

KY-022:

If so, can you please explain to me how can I achieve such thing with respect to the following:
1- Is there any kind of synchronization between transmitter/receiver?
2- How to get a stable analog value from the receiver?
3- The Correlation between Heart beat rate and the obtained values?

providing circuit sketch will be very helpful but not necessary.
Thanks in advance.

No, you cannot.  The sensor you link to has a circuit which attempts to detect IR light modulated at a specific frequency, and produces a digital output.   For a heartbeat sensor you need an analog output to feed into far more sophisticated signal processing - effectively the built-in processing gets in the way and means you cannot use it for this purpose.

Additionally, sensors of this type typically have an automatic gain control which means that they desensitize when subjected to continuous signal - they are designed for sources like remote controls where the modulation is itself pulsed on an off in small fractions of a second, so they interpret constant modulated light as noise and soon turn off their output.


How to detect the direction of a rotary encoder? I'm trying to detect the direction of rotation for an incremental rotary encoder. I'm supposed to get +1 for clockwise and  -1  for counter-clockwise. However, I receive random values. Any help appreciated.

Following is the code.

const int encoderPinA = 7;
const int encoderPinB = 12;
int val;
int encoderPos = 0;
boolean encoderALast = LOW; // remember the previous pin state

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

void loop() {
  analogWrite(3,250); //powering motor
  val = encoder_direction();
  // receive the direction for clockwise 1 and for counter clock wise  -1
  Serial.println(val); // print it in serial monitor
}

int encoder_direction() {
  boolean encoderA = digitalRead(encoderPinA);
  if ((encoderALast == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB)) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    return  encoderPos;
    // return the value either 1 or -1
  }
  encoderALast = encoderA;
}

// using digitalread() code  for four encoders
const int ENCODERS = 4; // the number of encoders
const int encoderPinA[ENCODERS] = { 7, 8, A1 , 2 };
// encoderA pins on 2 and 4
const int encoderPinB[ENCODERS] = { 12, 5, 4 , A2 };
// encoderB pins on 3 and 5
int encoderPos[ ENCODERS] = { 0, 0, 0, 0 };
// initialize the positions to 0
boolean encoderALast[ENCODERS] = { LOW, LOW, LOW, LOW };
// holds last state of encoderA pin

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

int updatePosition(int encoderIndex) {
  boolean encoderA = digitalRead(encoderPinA[encoderIndex]);
  if ((encoderALast[encoderIndex] == HIGH) && (encoderA == LOW)) {
    if (digitalRead(encoderPinB[encoderIndex]) == LOW) {
      //encoderPos[encoderIndex]--;
      encoderPos[encoderIndex] = -1;
    } else {
      //encoderPos[encoderIndex]++;
      encoderPos[encoderIndex] = 1;
    }
    Serial.print("Encoder ");
    Serial.print(encoderIndex+1,DEC);
    Serial.print("=");
    Serial.println (encoderPos[encoderIndex]);
  }
  encoderALast[encoderIndex] = encoderA;
}

void loop() {
  updatePosition(0);
  updatePosition(1);
  updatePosition(2);
  updatePosition(3);
}

// using direct access to digitalread code in order to process faster
int val[4];
int encoderPos = 0;
boolean encoderALast[4] ={LOW, LOW, LOW, LOW};
// remember the previous pin state

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

void loop() {
  for (int ii=0; ii<4;ii++) {
    encoder_direction(ii);
  }
}
int encoder_direction(int m) {
  boolean encoderA;
  boolean encoderB;
  if(m == 0) {
    encoderA = (PIND & _BV (7)) == 0;
    //   digitalRead(7) encoderPinA
    encoderB = (PINB & _BV (4)) == 0;
    // digitalRead(12) encoderPinB
  }
  if (m == 1) {
    encoderA = (PINB & _BV (0)) == 0;
    // digitalRead(8) encoderPinA
    encoderB = (PIND & _BV (5)) == 0;
    // digitalRead(5) encoderPinB
  }
  if (m == 2) {
    encoderA = (PINC & _BV (1)) == 0;
    // digitalRead(A1) encoderPinA
    encoderB = (PIND & _BV (4)) == 0;
    // digitalRead(4)  encoderPinB
  }
  if (m == 3) {
    encoderA = (PIND & _BV (2)) == 0;
    // digitalRead(2) encoderPinA
    encoderB = (PINC & _BV (2)) == 0;
    // digitalRead(A2)  encoderPinB
  }
  if ((encoderALast[m] == HIGH) && (encoderA == LOW)) {
    if (encoderB == LOW) {
      //encoderPos --;
      encoderPos = -1;
    } else {
      //encoderPos ++;
      encoderPos = 1;
    }
    Serial.print(" Encoder ");
    Serial.print(m+1);
    Serial.print(" = ");
    Serial.println(encoderPos);
  }
  encoderALast[m] = encoderA;
}

I have a page about rotary encoders - in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:

// Wiring: Connect common pin of encoder to ground.
// Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
// Connect pin B (the other outer one) to another free pin (eg. D5)

volatile bool fired;
volatile bool up;

const byte encoderPinA = 2;
const byte encoderPinB = 5;

// Interrupt Service Routine for a change to encoder pin A
void isr ()
{
  if (digitalRead (encoderPinA))
    up = digitalRead (encoderPinB);
  else
    up = !digitalRead (encoderPinB);
  fired = true;
}  // end of isr

void setup ()
{
  pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
  pinMode (encoderPinB, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

  Serial.begin (115200);
}  // end of setup

void loop ()
{
static long rotaryCount = 0;

  if (fired)
    {
    if (up)
      rotaryCount++;
    else
      rotaryCount--;
    fired = false;

    Serial.print ("Count = ");
    Serial.println (rotaryCount);
    }  // end if fired

}  // end of loop

In the main loop you just need to test the boolean fired to see if the encoder changed, and up to see if it went up (otherwise it went down).

  I receive random of these values ...

I think with your code you need to detect a change - that is, if the encoder pin is now HIGH but was previously LOW.

Solution for 4 encoders

  The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.

// Wiring: Connect common pin of encoder to ground.

volatile bool fired;

const byte ENCODERS = 4;

typedef struct
  {
  int aPin;     // which Arduino pin for the "A" side
  int bPin;     // which Arduino pin for the "B" side

  // values below are calculated at run-time
  volatile byte * aPort;  // which processor port the A side is plugged into
  volatile byte * bPort;  // which processor port the B side is plugged into
  byte aBitMask;   // which bit in the A port
  byte bBitMask;   // which bit in the B port
  byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
  byte oldValue;   // old value of A port (to see if it changed)
  int count;       // current encoder counter
  } encoder;

 volatile encoder encoders [ENCODERS] =
  {

 // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

  { 4,  8 },
  { 5,  9 },
  { 6, 10 },
  { 7, 11 },

  };  // end of encoders

void checkForPinChange (const byte which)
  {
  for (byte i = 0; i < ENCODERS; i++)
    {
    if (encoders [i].whichInterrupt == which)
      {
      byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
      if (newValue != encoders [i].oldValue)
        {
        bool up;
        byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
        if (newValue)
          up = bPort;
        else
          up = !bPort;
        fired = true;
        if (up)
          encoders [i].count++;
        else
          encoders [i].count--;
        encoders [i].oldValue = newValue;
        }  // end of if value has changed
      }   // end of if this is the right interrupt number
    }     // end of for each encoder
  } // end of checkForPinChange

// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
 {
 checkForPinChange (PCIE0);
 }  // end of PCINT0_vect

// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
 {
 checkForPinChange (PCIE1);
 }  // end of PCINT1_vect

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {
 checkForPinChange (PCIE2);
 }  // end of PCINT2_vect

void setup ()
{
 Serial.begin (115200);
 Serial.println ("Starting ...");

 PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

 for (byte i = 0; i < ENCODERS; i++)
    {
    pinMode (encoders [i].aPin, INPUT_PULLUP);
    pinMode (encoders [i].bPin, INPUT_PULLUP);
    // convert pin number to port, mask, etc. for efficiency

    // Input port
    encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
    encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

    // Which bit in the port to test
    encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
    encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

    // Which interrupt number (0, 1, 2)
    encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

    // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
    volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
    *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

    // enable this pin-change interrupt
    PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

    } // end of for each encoder

}  // end of setup

void loop ()
{
  if (fired)
    {
    for (byte i = 0; i < ENCODERS; i++)
      {
      char buf [10];
      sprintf (buf, "%5d", encoders [i].count);
      Serial.print (buf);
      }
    Serial.println ();
    fired = false;
    }  // end if fired

}  // end of loop

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).

The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.

I am getting results like this (with 2 encoders connected):

   16  -19    1    1
   17  -19    1    1
   18  -19    1    1
   19  -19    1    1
   20  -19    1    1
   21  -19    1    1
   22  -19    1    1
   23  -19    1    1
   23  -20    1    1
   23  -21    1    1
   23  -22    1    1
   23  -23    1    1
   23  -24    1    1
   23  -25    1    1

The other two are showing as "1" (that is, not turned yet).


Arduino Ethernet Shield 2 stuck on EthernetServer::begin() I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.

This is my test code:

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {
  0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D
};
byte subnet[] = { 255,0,0,0 };
byte gateway[] = { 2,0,0,1 };
IPAddress ip(2, 0, 0, 1);

EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.println("Ethernet started");
  server.begin();
  Serial.println("Server started");
}

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

The output I get from the serial console is:

Etrted
Ethernet started

So I think the program gets stuck inside the EthernetServer::begin() function.
I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.

Also I don't understand, why it outputs the first line.

Thanks for your hints!

You must use these libraries:

#include <Ethernet.h>  -->  #include <Ethernet2.h>
#include <EthernetUdp.h>  -->  #include <EthernetUdp2.h>

More info at this link Arduino Ethernet Shield2


How do I compile the Marlin firmware? I have a folder of mostly .h and .cpp files for the Marlin firmware (3D Printing) from here.

How do I compile that so I can upload it to my Arduino Mega with Ramps?

You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.

http://solidutopia.com/marlin-firmware-user-guide-basic/ - heres a guide for Marlin.

the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.


Arduino program wont work properly for some reason I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.

int forward =12 ; //assign to correlating pin attached to TP06
int backward = 11; //assign to correlating pin attached to TP07
int left = 10; //assign to correlating pin attached to (left steer)
int right = 9; //assign to correlating pin attached to (right steer)

// TP09 & TP02 (don't remember which is left and right)

void setup() {
pinMode(forward, OUTPUT);
pinMode(backward, OUTPUT);
pinMode(left, OUTPUT);
pinMode(right, OUTPUT);
}

void move_Forward() {
digitalWrite(forward, HIGH);
digitalWrite(backward, LOW);
}

void move_Backward() {
digitalWrite(backward, HIGH);
digitalWrite(forward, LOW);
}

void turn_Left() {
digitalWrite(left, HIGH);
digitalWrite(right, LOW);
}

void turn_Right() {
digitalWrite(right, HIGH);
digitalWrite(left, LOW);
}

void stop_Completely() {
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
digitalWrite(right, LOW);
digitalWrite(left, LOW);
}

// loop will keep going while arduino has power
void loop() {
move_Forward();
turn_Left();
}

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.

On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.

Here's a useful pinout: http://t.co/MKtmCILSdj

Here's a Nano pinout:

Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.

If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)


SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.

Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.

I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.

Can anyone help me?

P.S. ATMEGA328P ic MCU

Thank you,
Matija

#include <SoftwareSerial.h>
#include <avr/sleep.h>

SoftwareSerial SIM800(8, 7);

String buffer1;
unsigned int current_millis = 0;
String phone;

void setup() {
     buffer1.reserve(200);
     phone.reserve(20);

     Serial.begin(19200); //
     SIM800.begin(9600);
     delay(1000);
     SIM800.write("AT\r");  // because of SIM800L autobounding mode
     delay(1000);
     SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
     and  other, and with autobauding but still got same problem
     delay(1000);
     SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
     delay(1000);
     SIM800.write("AT+CNMI=2,2,0,0,0\r");
     delay(1000);
     Serial.print(SIM800.readString());
     SIM800.write("AT+CLIP=1\r\n");
     delay(1000);
     SIM800.write("AT+SGPIO=0,7,1,0\r");
     delay(1000);
     SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
     delay(1000);
     current_millis = millis();
}

void loop() {
   // put your main code here, to run repeatedly:
   if (SIM800.available() > 0) {
      buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
           caller number from it
      Serial.println(buffer1);
      parse();
      current_millis = millis();
      }

    if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
       sleepNow();
       delay(1000);// tried many delays
       current_millis = millis();
     }

 }

void parse() {
    if (buffer1.indexOf("CLIP:") > 0) {
        phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
        buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
        Serial.println(phone);
        SIM800.write("ATH\r"); //hang out phone call
        delay(500);
        SIM800.write("ATH\r");
        delay(500);
  }

}

void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                   LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                          sleep bit in the mcucr register
    sleep_mode();            // here the device is actually put to sleep!!
                         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable
                                sleep...
    }

Give AltSoftSerial a try, it's hands down superior.

Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from example#2:

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}


ESP8266, Arduino IDE vs Lua? I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.

Do you need a custom firmware to use the Arduino IDE instead of Lua?

The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.

In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably not worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?


Communication between three NodeMCUs such that one in in AP mode, second one in AP+STA mode and the third NodeMCU in STA mode I am able to establish a connection between first and second NodeMCU, but unable to do so for the third nodeMCU. I used the IP  address to establish connection.
Should I assign a different IP to each nodeMCU so that communication can take place?
In the code that I had written, i have taken the same IP for all three NodeMCUs, so   communication was possible between 1st nodemcu(in AP mode) and 2nd nodemcu(in STA+AP mode).
For the 3rd node mcu the IP taken was different. Can any one suggest what to do next.

The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top esp8266 has SoftAP with 192.168.4.x, set for the SoftAP of the middle esp8266 IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to connect a TCP socket or send an UDP message.


Is crystal mandatory on attiny84? I am trying to make a mini project with attiny84 and I searched the web so I can make an arduino on breadboard. What I saw on the internet is that they didnt use crystal. Is it mandatory if I want to use 1 pwm pin and the SPI interface on the attiny84?

Only if you need crystal accuracy. If the internal RC oscillator is accurate enough then feel free to use it instead.


Migrating from ATMega2560 to ARM based -- Teensy vs Due? I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.

Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.

I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.

So my QUESTION is:
Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.

Any other considerations/suggestions/advice will be appreciated.

Thank you.

If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.

That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.

There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.


Arduino Sainsmart uno communication problem I'm trying to communicate with my arduino uno but it seems to have troubles to understand characters. For example, printing things with Serial display weird things, changes characters, removes some.

For exemple printing "test !" every two seconds results in that :

Every characters have been removed except "!"...

Is my arduino broken ?  Thanks in advance

You are doing 2 things wrong in your program:

First is using serial.write(), which writes bytes rather than ASCII.

Second is you are declaring a string literal as a char instead, you must declare a string using  double quotation marks (which is ") so that your program should read:

Serial.print("Test!");

When you declare 'Test !'  you are doing it wrong, and it will only take the last char in the string, which is '!' - using single quote marks is for a single char declaration, like '!' or 'T', and you can make an array of chars into a string if you wanted, like this:

char array[] = {'T', 'E', 'S', 'T', '!' };
Serial.write(array, 5);

but why would you when the earlier one works better?


Watchdog Timer for atmega 128 I am using atmega 128 for a smart vehicle tracker. I am trying to use watchdog timer for this controller.But problem is that I have found the maximum watchdog reset time is 2 seconds. I need watchdog reset time 8 seconds. Now what can I do ?

There is no way you can make the Watchdog timer longer on Atmega 128. It is max 1.8 sec if you set all 3 bits of Timer Prescaler.

For Atmega 328 the max watchdog time is 8 sec and longer time can be achieved using  watchdog interrupt and count up (or down) until you want a reset and then force the reset by setting the shortest watchdog timer.

Atmega 128 doesn't support watchdog interrupt, so the trick with interrupt can't be used.


How to remove Adafruit Pro Trinket bootloader flashing startup sequence From what I understand, the Pro Trinket has "Optiboot" which allows it to detect which boot loader you are trying to use, one for USB and one for FTDI. When it's in this "bootloader state" the red LED on pin 13 buses for 10 seconds before it starts to run the program I've programmed.

Can I remove this Optiboot functionality? Would that entail permanently choosing a single boot loader/interface?

One problem I have with this is that along with the LED on 13, it causes the LED strip I have attached to pins 9, 10, 11 to blink. I would also really like to not have to wait 10 seconds to start running code.

Here's the page on Adafruit's site that talks about the bootloader[s] on the Pro Trinket.

Thanks!

You could take the Pro Trinket bootloader source code and tweak it to your needs, burn it, and make sure you have patience and debugging skills.

From the author's (Frank Zhao) source code, it seems that this is the 10 seconds loop you are referring to, located in main.c, line #456:

if ( ((usbHasRxed != 0) && (timeout > USBBOOTLOADER_TIMEOUT)

The USBBOOTLOADER_TIMEOUT variable which is defined to 10 at the top of that file, line #70:

#define USBBOOTLOADER_TIMEOUT 10

and is progressed after 'roughly' 1 second, at line #496:

// roughly 1 second
#if (F_CPU == 12000000)
    if (t1ovf > 183) {
    #elif (F_CPU == 16000000)
    if (t1ovf > 244) {
    #endif
        t1ovf = 0;
        timeout++;
    }


request for a member "X" in something not a structure or a union i was programming a Self Balancing    Robot, I am writing the code in vscode using platformio extension.

when i put the code i need to get the angle out of the gyro in another file (named angle.c) and including it in the main program, the ide throws with error, in every line I use the Wire library in the angle.c, however same code copy and paste it in the main program and it works.

P.S. the angle.c is just a file of functions and doesnot have any class.

A .c file is compiled with C compiler. If you include Wire.h which contains a class definition, the C compiler doesn't understand it and generates errors.

If your angle.c file doesn't have C code not compatible with C++, then change the extension of the file to .cpp and it will be compiled with C++ compiler.


What are safe memory usage limits? The Arduino IDE used to warn you when your sketch used too much memory. This warning now seems to have been removed. I compiled a sketch, and was surprised to see it use 175% of data memory...but not give me any explicit warning that this would be unstable, much less be physically unable to load onto the Arduino.

What are program and data memory usage levels that you should be concerned about? I seem to remember the best practice was to keep data memory under 80%. Is this still true? Is there any general rule for program memory?

The compiler can only report the amount of statically allocated (RAM) memory. Depending on what you are doing in your sketch the value may be important, or it may be completely meaningless.

Suffice it to say, the total of heap + stack + static must not exceed the memory of your MCU.

When it comes to the Flash memory you can go right up to 100%.


How come my transistor doesn't work? I have a TIP 120 to 229 NON 60V 5A transistor

I'm trying to use it to switch an electro magnet. Using the blink example to test it out:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
}

pin 13 is connected to the base and I'm trying to powering the magnet with a 12V DC adapter. I'm not sure if the transistor is before or after the magnet, but I'm not sure how that would make a difference.

I'm not great with diagrams but something like this (the power source might be the other way around:

simulate this circuit – Schematic created using CircuitLab

I've tried switching between the collector and the emitter. In one instance the magnet is always active and in one instance it's always passive. What could be wrong?

The cords running of the table in the bottom is just a bit of extra wiring.

Is there the only wire from Arduino to the Base of Transistor?

Basically you need something like this:

If you reverse the transistor (E and C), builtin protection diode will be in forward direction, so electro magnet is on.

If you have only one wire to the base, it cannot work as you need current to the base.

If you don't have R1 into the base (about 500R-1K), it'll burn your output eventually. (not if you don't have common ground)

If you have electro magnet between ground and Emitter, you'll have negative current feedback and about 4.2V on L1 tops as there must be some current into the base.


eclipse photon with cdt-arduino plugin can't upload sketches i've recently decided to give eclipse-photon-cdt a shot. i use it with the built in arduino plugin, downloaded my feather m0 board config and tried to upload an empty sketch. failed, the console shows it tries to connect but fails. of course arudino ide 1.8.5 succeeds wonderfully.
point is if i copy paste the command line activating bossac i get the same result. i also know why. when using scripts i need to use a python scripts that uses serial signaling to reset the feather into bootloader mode. arduino ide does it on his own probably using java. eclipse doesn't do that which sounds like a huge bug to me.

am i missing something ? or did they actually assumed i'll press twice on the reset button on the board each and every time i want to upload a sketch ?

It sounds to me like Eclipse doesn't know how to reboot the board into the bootloader.

Traditional Arduinos automatically boot into the bootloader when the board is reset, and the board resets every time you open the serial port thanks to the USB chip having DTR connected (through a capacitor) to the reset pin of the man MCU.

Chips with a direct USB connection can't do that (boards like the M0 Feather, the Leonardo, etc).  Instead they have to be rebooted by opening the serial port at 1200 baud and then closing it again.

With the "traditional" boards the IDE neither knows, nor cares, about rebooting the board - it just happens. However with direct USB boards the IDE has to have specific code to perform the reboot at the right time. The Arduino IDE has that code. However I would guess that the Eclipse plugin either doesn't implement that, or doesn't have the ability to implement it.

So you will have to manually reset the board for programming.


Uno - measure the voltage, NOT connecting GND I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).

The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.

Is there any way to measure the Voltage over the resistor without using GND?

If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .


Has anyone used an Arduino to transfer software to an Apple IIe? Yes, you read that right.  An Apple IIe.

I have many retro computers and I was thinking that since the Apple II line of computers (especially the IIe) have pretty speedy serial ports that it should be somewhat simple to use an Arduino to send data to/from the Apple.

My issue is that all of my every-day computers are USB based with no RS232 serial.  I guess I could boot up an old Linux laptop that has a serial port but that seems too cumbersome given my limited desk space.  :-)

Anyway, I've Googled but I'm not finding anything.

Since most Apple IIe disk images are pretty small (<144k or so) they should fit pretty easily into, say, an Arduino DUE that I have.  Or better yet, using the DUE to mount as a USB device that could send over to the IIe would be great.

So, my question is, does anyone know of any site that explains how this could be done?

Thanks!

EDIT

OK, turns out it WAS pretty easy getting the Arduino DUE to send to the Apple IIe.  I simply connected 3 wires from TX1/TR1/GND to the Apple IIe serial port (SSC).

Now, when I launch ADT Pro and start sending, the IIe is receiving garbage.  Bunch of "9d9d9d9d" all over the place.

Here's my code:

// ADT.ino

int incomingByte = 0;

void setup() {

    Serial.begin(9600);
    Serial1.begin(9600);

}

void loop() {

    if(Serial.available() > 0) {

        while(Serial.available() > 0) {

            incomingByte = Serial.read();

        }

        Serial1.write(incomingByte);
        delay(100);
    }

}

The ADT Pro software is set to send the data over the USB port and it's obviously sending data to the IIe.  I'm just wondering if the formatting is wrong or something.

You need to adapt the levels. Arduino Due operates on 0 - 3.3 V. Apple IIe is either on 0 - 5 V or +/- 12 V (depends which port you are using). There are standard ICs to do the level adaptation.


What do I need to make fluffy toys move and talk? My kids got many fluffy toys, and I would like to make them move and talk. Something like a small platform with wheels and a speaker and some sensors that I would be able to mount any of the toys on.

I'd like to build something like 2 platforms with motors and sensors that move around, and when encountering obstacles "bark" at them through the speakers, wait random number of seconds, and move in different directions. Then the kids would mount their favorite fluffy dogs/cats/bears/rabbits on top of these platforms and unleash them on each other.

I am very new to DIY; what do I need to buy for such a project?

You will need a processor board, motor driver, sensors, and audio amplifier.

Since you are asking on the Arduino forum, it would be natural to consider one of the Arduino boards or derivates - but beware they tend to be rather antiquated compared to alternatives now available.  The plus side of the classic ATmega boards is the wide variety of read-to-go example code available right within the IDE, and the wide supply voltage range (of the bare chips if not the boards) which is more compatible with AA-cell battery packs than competing device's narrower voltage range tends to be.  The one part of the functionality you describe that is a bit of an issue is the audio output - you can get it from an ATmega but it will be poor in quality and you will need to add storage for the "bark" data.  You might almost consider a separate module with an ATtiny and a small SD card for that (ironically the ATtiny while generally less capable has fast PWM better suited to audio).

For motor drivers, especially when using batteries steer clear of the older bipolar L293/L298 type of solutions, as these have very high internal loss which basically means that one cell in your battery pack exists just to generate heat in the driver IC.  A modern FET based driver (the TB6612FNG is quite popular) will be better.

For sensors you probably want one or more of microswitches extended with "whiskers", ultrasonic rangefinders, or short range IR reflectance.

Some dual wheel drive (or "tank steering") RC toys can be worth considering as platforms, but their gearing may be too fast for your purposes, particularly those designed to spin and tumble.  Continuous rotation servos are sometimes mentioned, but it can be hard to get them tuned to not rotate when commanded to stop, and mounting wheels can be tricky.  The small plastic gearboxes work well if you can get matching wheels but are hard themselves to mount.  Access to a 3d printer can be quite useful for creating missing physical components, though a block of wood and a router can make a nice chassis, too.  You can also buy ready made Arduino robot base kits with chassis, gearboxes, and wheels.

For audio output, you can accomplish something with an NPN transistor and base resistor driving a speaker, but best results would be with a small class D driver board as are now widely sold for a few dollars.  They tend to be stereo, but you can feed both sides with the same signal.  If you only wanted "robot beeps" you can drive a piezo disk directly from a processor pin with reasonable loudness at higher frequencies, but the low frequency response is quite poor.


PID control for Motor Speed control I was trying to apply PI controller to a motor using Arduino. I have somewhat achieved the task but the problem is that it oscillates too much. Also i couldn't figure out what to do when pwm signal are calculated as negative

  int counter = 0;
  double end_time=0;
  double ini_time=0;
  double rpm=0;
  double my_time=0;
  double temp = 0;
  int pid_speed=0;
  float kp=2.25;
  float ki=.01;
  float kd=0.005;
  int prev_error=0;
  double pwm_sig=0;
  int integrator  = 0;
  int motor_sig_pin= 5;
  int error=0;
  int absolute = 0;
  float desired_rpm=1000; //my desired RPM value
  double zero_time=0;
  double i_time=0;
  double f_time=0;
  int rpm_tacho=0;
  int previous_error=0;
  int derivative=0;

  void setup() {
    pinMode(2,INPUT);
    digitalWrite(2,HIGH);
    pinMode(motor_sig_pin,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(10,OUTPUT);
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW );
    attachInterrupt (0,Count,RISING);
    ini_time = micros();
    i_time=micros();
    Serial.begin(115200);
  }

   void Count(){ //calculating time for one round using encoder

      counter++;
      if (counter>=100){
        end_time=micros()-ini_time;

        ini_time=micros();
        counter=0;
      }
   }
  void loop() {
      rpm = ((1000000*60)/(end_time));
      rpm = abs(rpm);
      rpm_tacho = ((1000000*60)/(zero_time));
      if (rpm <10 || rpm>5000){
        rpm=0;
      }
      error=desired_rpm-rpm;

      integrator += error;
      pid_speed = kp*error; + ki*integrator;

      pid_speed=(int)pid_speed;

      Serial.print(pid_speed);
      Serial.print("       ");

      if (pid_speed> 0){
        if (pid_speed>255)
          analogWrite(motor_sig_pin,255);
        else
          analogWrite(motor_sig_pin,pid_speed);
      }
      if(pid_speed<0){
        if(pid_speed<-255)
        {
            analogWrite(motor_sig_pin,0);
        }
        else
       {
          pid_speed=abs(pid_speed);
          analogWrite(motor_sig_pin,255-pid_speed);
       }
      }
      Serial.print ("      ");
      Serial.println(rpm);
  }

Instead of thinking of the PID output as pid_speed, think of it as motor_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.

You are probably getting oscillation because of integral windup.  If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust.   For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec  If the integrator is faster than the system, it can easily cause overshoot.  You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmErrorseconds/100, rpmErrorseconds/10, or rpmError*seconds into output power.

To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.


Measuring voltage from -12 to +12 VDC I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).

I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.

And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).

I will make additional PCB for this application, so size and number of components isn't important at all.

Measuring voltage

Use the following interfacing circuit for measuring voltage:

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC  (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.

The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.

This is the resulting input to output voltage translation curve:

Measuring current

For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

simulate this circuit – Schematic created using CircuitLab

Follow this link to an article in EE Times to learn more about the main options available for current measurements using a shunt.


Controlling TFT LCD with Arduino I bought this LCD module. How many pins does this LCD module uses? They have written in the product description that this LCD module uses 8 bit communication, but the LCD module has 16 bit pinout (DB0-DB15). What is the right pin number?

Is there any Arduino LCD library that supports this LCD module, which uses the OTM4001A LCD driver? Usually for LCD the UTFT library works, but it does not support the OTM4001A LCD driver.

Thanks for your help!

Trust what is on the board, not what the eBay seller says. They invariably can't tell the difference between a TFT screen and a doll, and they sell everything in between. They just regurgitate Chinglish nonsense. If the board says DB0-DB15 then DB0-DB15 is what you need to use.

Plus it says in the description:

  Support 16 bit RGB565 format , can connect any 16 bit data bus.

At least this one has told you what the driver chip is (OTM4001A) - many times they can't even do that and don't even understand what you are asking when you request that information.

Mind, it's a driver chip I have never come across before, so maybe I should get one on order to support it in DisplayCore...


: Failed to open /dev/ttyACM0 (port busy) I am trying to work with the (new) sparkfun razor IMU 9dof, I wrote a silple sktetch to calibrate the magnetometer:

#include <SparkFunMPU9250-DMP.h> // Include SparkFun MPU-9250-DMP library
#include <Wire.h> // Depending on your Arduino version, you may need to include Wire.h
MPU9250_DMP imu; // Create an instance of the MPU9250_DMP clas
void setup() {
  Serial.begin(115200);

  Serial.println(F("Adafruit 10 DOF Board AHRS Calibration Example")); Serial.println("");

  if (imu.begin() != INV_SUCCESS){
    while (1) {
    Serial.println("Failed to initialize MPU-9250, loop forever");
   }

  }

 imu.setGyroFSR(2000); // Set gyro to 2000 dps

 imu.setAccelFSR(2); // Set accel to +/-2g

 imu.setLPF(5); // Set LPF corner frequency to 5Hz

 imu.setSampleRate(100); // Set sample rate to 10Hz

imu.setCompassSampleRate(100); // Set mag rate to 10Hz
}

void loop(void){
  imu.update();

  // Print the sensor data
  Serial.print("Raw:");
  Serial.print(imu.ax);
  Serial.print(',');
  Serial.print(imu.ay);
  Serial.print(',');
  Serial.print(imu.az);
  Serial.print(',');
  Serial.print(imu.gx);
  Serial.print(',');
  Serial.print(imu.gy);
  Serial.print(',');
  Serial.print(imu.gz);
  Serial.print(',');
  Serial.print(imu.mx);
  Serial.print(',');
  Serial.print(imu.my);
  Serial.print(',');
  Serial.print(imu.mz);
  Serial.println();

  delay(50);
}

To be sure the Arduino IDE can access to dev/ttcACM0, I did   sudo chmod 666 /dev/ttyACM0

I can dowload successfully but when I want to open the terminal I got the following error:

Erreur d'ouverture du port série « /dev/ttyACM0 ». (Port busy) (see attached screenshot)

More over when I entered dmesg on the console, I can see the following messages:

[   94.133923] usb 3-2: USB disconnect, device number 2
[   94.133978] cdc_acm 3-2:1.1: urb 12 failed submission with -19
[   94.135862] cdc_acm 3-2:1.1: urb 13 failed submission with -19
[   94.136059] cdc_acm 3-2:1.1: urb 14 failed submission with -19
[   94.136257] cdc_acm 3-2:1.1: urb 15 failed submission with -19
[   94.136457] cdc_acm 3-2:1.1: urb 2 failed submission with -19
[   94.136656] cdc_acm 3-2:1.1: urb 3 failed submission with -19
[   94.136852] cdc_acm 3-2:1.1: urb 5 failed submission with -19
[   94.137048] cdc_acm 3-2:1.1: urb 6 failed submission with -19
[   94.138841] xhci_hcd 0000:03:00.0: WARN Cannot submit Set TR Deq Ptr
[   94.138843] xhci_hcd 0000:03:00.0: A Set TR Deq Ptr command is pending.
[   94.931853] usb 3-2: new full-speed USB device number 3 using xhci_hcd
[   95.316578] usb 3-2: New USB device found, idVendor=1b4f, idProduct=9d0f
[   95.316581] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[   95.316582] usb 3-2: Product: SFE 9DOF-D21
[   95.316584] usb 3-2: Manufacturer: SparkFun
[   95.320306] cdc_acm 3-2:1.0: ttyACM0: USB ACM device
[  858.774849] usb 3-2: USB disconnect, device number 3
[  904.529058] TCP: wlp1s0: Driver has suspect GRO implementation, TCP performance may be compromised.

Does anyone outhere experienced such issue?

Thank you for your help

Fabrice

sudo apt-get purge modemmanager
It helps me for linux user and for many other peoples.
Now I am playing with stm32f103 and opening port was painfull.
That  was problem only for stm32 chip. Arduino nano was working without problems.
Before I need reopened few times port to initiate communication.
That was painfull. After finding that solution now Arduino ID is working without problems.
 I am not sure if deleting modemmanager will have impact for my system.


How to sense mobile signal coming to a room using arduino uno How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

You can't.

Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".

And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".

What you could do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.


Making an H-bridge with transistors I am trying to make an H-bridge with two NPN and two PNP transistors to drive a motor which works fine on the 5 V Arduino. I have a schematic in the picture. When I use a simple code to have pin 9 HIGH and pin 8 LOW, the motor doesn't do anything. The transistor which I circled green is getting very hot. Is there something wrong with the schematic or code? Or is it my wiring?

I know people use diodes as well, but in my case the motor doesn't work, so the diodes aren't the problem.

This is my code:

     void setup()
    {

    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    }

There is a few possible scenarios to create a H-bridge:

with NPN transistors only or PNP
mix of PNP and NPN

You have to be careful to not mix the types and inputs. See pictures below:


HC-06 Bluethoot communication During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.

No.

What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1* HC-05 and 1* HC-06.


Do motors need to have capacitor even if being used with motor shield I'm using a 12V DC geared motor with an Adafruit motor shield which is connected to Arduino.

So, I want to know inspite of using the motor shield, do I need to add capacitors to the motor?

If the motors have a lot of "brush noise" you need to add capacitors to the motor. It is written in the FAQ.

The noise must be suppressed at the source or the motor leads will act like antennae and broadcast it to the rest of the system link.