Pulling the enable pin on Adafruit PowerBoost to low (It's connected to VBatt!) I am working on an Tonuino (tonuino.voss.earth), and I am using a PowerBoost-module from Adafruit (https://www.adafruit.com/product/1944) for it. The powerboost-module needs the enable pin driven to LOW(GND) to turn the output 5V off. Currently I have a rocker switch which allows me to permananently connect EN to GND.

I would like to implement a auto-off functionality for this combination, i.e. the arduino can drive the enable pin LOW and in this manner kill its own power. In addition to the auto-off, I want the user to be able to turn on the device via a button press. I come from a software background and my last connection to electronics is from a time long, long ago, which is why I am struggeling.

This shows my initial thoughts:

The user presses the button to start the Tonuino. The switch disconnects EN from GND, EN goes to UBATT(HIGH) and 5V to the arduino is enabled. By enabling the arduino, a GPIO is set to high and thus EN is maintained high
To turn off, the arduino sets the GPIO to LOW, thus setting EN to LOW, 5V are disabled and so forth...

My problem: 5V from the Arduino GPIO will always be at 5V and thus higher than the reference voltage of EN (UBATT 3V - 3.7V). I really am afraid that this will damage my lipo. For me this means, I ideally should switch UBATT for EN (safely) and am failing to come up with a solution.

Any pointers are greatly welcome

Your biggest problem is that the module defaults to on. There is a 340kΩ resistor pulling the EN pin up to VBAT all the time, so to turn it off you have to actively override that pullup.
Ideally you would modify the module by removing that resistor (R13) and adding your own resistor between the ENABLE and GND pins. You can the override that with both a button and a P-channel FET in parallel to turn the module on.
For example:

simulate this circuit – Schematic created using CircuitLab
Now normally R1 pulls ENABLE to ground turning the module off.  You press SW1 and it pulls ENABLE up to VBAT and turns it on.  5V then gets supplied to the Arduino, at which point you need to set the GPIO to output and pull it HIGH.
This causes the gate of M2 to be pulled above its threshold voltage (make sure it has a threshold voltage between 0V and 3V) and it starts to conduct pulling the gate of M1 below its threshold voltage (must be between 0V and -2V) bypassing switch SW1 keeping the system enabled.
You can now let go of SW1 and it will all stay powered on until you either set the GPIO LOW or set it to an INPUT.
Note that resetting the Arduino (for programming, for example) would cause the boost module to shut down and require re-powering with SW1 (or through the GPIO if you have the Arduino powered through USB for programming of course).
However if you don't want to or can't modify the module then things get a little nastier.
To make it default to OFF R1 in the above schematic will have to be low enough value that the voltage presented at the ENABLE pin is below 20% of the battery voltage.  R1 and the existing 340kΩ pullup resistor form a voltage divider, so you need to calculate the size of resistor that will allow it to be below 20% VBAT.
Since a voltage divider just gives you a proportion of the input voltage whose ratio is the ratio of the "top" resistance in the divider to the total resistance we don't care what the voltage is, only the ratio.  And we don't really care about the exact value, only that the result is below 20%.  So we can pick a good common value.
However we don't want a value that is too low, because the voltage divider will be draining power from the battery all the time, so the higher the resistances the less the power drain will be.
For example if we pick the common value 47kΩ we see that:
    R2           47000
 ------- = --------------- = 0.11 (11%)
 R1 + R2    340000 + 47000

Which is below the 0.2 (20%) that we want, which is good.  Calculating the current at a typical battery voltage of 3.7V we get
     V          3.7
I = --- = -------------- = 0.000010 (10µA)
     R    340000 + 47000

10µA is not much, on the scale of things, but it's good to know about it when you're working from a battery since it will form part of your power budget calculations.


Switch between timer2 and manually setting output of pin 3 I have a 62.5 kHz square wave created by timer2 on the pin 3. I would like to be able to use digitalWrite(3, HIGH) to force pin 3 high for several clock cycles, but then I would like it to return the 62.5 kHz square wave. Is there a way to reset a single output without resetting the entire program?

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT); //Output for OCR2B (Timer 2)
  //The following block allows sets the Timer2 properties for PWM
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = 255; //Sets the period to 16us (62.5kHz)
  OCR2B = 0; //Sets the duty cycle of the signal (8-bit(255) resolution)
}

void loop() {
  int pot = analogRead(A0);
  int duty = map(pot, 0, 1023, 0, 255); //scale to duty cycle resolution
  OCR2B = duty; //set duty cycle
  delay(10000); //arbitrary wait time
  digitalWrite(3, HIGH);
  delay(10000); //arbitrary wait time
  //undo the digitalWrite to continue the pulse train here
}

If you clear the clock select bits in TCCR2B, then the PWM stops and you can control the port normally. To re-start the PWM, set the CS20 bit just as you did in setup().


I2C Wire.onRequest not detected I want to know why Wire.onRequest can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)

I was able to read this part of the massage with wire.onReceive:

But I can not read this massage at all, which is requesting:

#include <Wire.h>
byte val = 170;
int sendv;

char c;

byte dataArray[16];

void setup() {
  Wire.begin(0x77);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() { }

void receiveEvent(int howMany) {
  Serial.println(howMany);

  if (howMany >= 2) {
    for (int i = 0 ; i < howMany; i++) {
      dataArray[i] =  Wire.read();
      Serial.println(dataArray[i], HEX);
    }

  } else {
    c =  Wire.read();
    Serial.println(c, HEX);
  }
}

void requestEvent() {
  Serial.println("REqEVENT");
}

I was able to solve the issue with by adding  twi_stop(); to twi.c

base on this website
enter link description here


FastLED int + float problem I'm working on a code based on PaletteCrossfade.ino example. But I found the motion speed too fast. It's stated in this:

  static uint8_t startIndex = 0;
  startIndex = startIndex + 1; /* motion speed */
  FillLEDsFromPaletteColors(startIndex);
  FastLED.show();
  FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex) {
  uint8_t brightness = 255;
  for( int i = 0; i < NUM_LEDS; i++) {
    leds[i] = ColorFromPalette( currentPalette, colorIndex + sin8(i*16), brightness);
colorIndex += 3;

Since the startIndex defined in uint8_t, it cant be lower than 1. So I used float and set it to 0.2 in my code. Which seems to work, and animation slowed down. However I'm not sure how is that float value added into the ColorFromPalette function.

Its documentations states:

  CRGB  ColorFromPalette (const CRGBPalette16 &pal, uint8_t index,
  uint8_t brightness=255, TBlendType blendType=LINEARBLEND)

To my understanding it accepts only integer, and also int based sin8 being added to float value. So, what exactly happens there? Is this method viable, or is there any better way to slow down the animation?

I'm thinking about adding a millis() based delay and only increasing the colorindex every 2-3 seconds or so.

The code you have seems to fill the lights with a colour and change every nth of a second.  You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.

sin8() might return a float or I suspect an int, but colourIndex is an uint8_t so that is a whole number.  All it is doing is picking a colour, based on some scheme.  If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1.  It does not round up.

Its not clear what you are trying to do.

If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.

If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.

Hope that helps, if not please can you try and describe what it is you are tying to achieve.


Controlling 5V PWM Fan with Potentiometer Alright so I wanted to make myself a Deskfan using Arduino and a potentiometer. The reason for using arduino is that I want to display the current temperatur and the fan speed either through rpm or with %. Currently it seems to work fine using the potentiometer to control the pwm. But either i'm just not believing that it works correctly or it really isn't. My only problem is that I think the fan is not outputting 100% of its power with the pwm signal. Maybe about a few % less. But I don't really know if there is something that I am missing or if it really is outputting 100%.  The fan in question would be a Noctua NF-A14 5V PWM (+-1500 MAX).

Edit: Is it possible  that I'm not using full 100% of the fan?
 If so what would I need to change if that were the case. I heard something about changing to 25khz pwm but yeah..

Here is my code without the lcd stuff.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(9, OUTPUT);
}

void loop() {

  int potValue = analogRead(A5);

  int newpotValue = map(potValue, 0, 1023, 0, 255);
  Serial.println(newpotValue);
  analogWrite(9, newpotValue);
}

According to Your Fan Datasheet its 1.3 W/5V Fan...
That means its nearly consume 3 A current which cant be supplied directly from arduino pins...
so you have to use PWM converter ...
it almost solve your issues...


Returning an int array from a function I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?

Here is what I want to do:

int function()
{

int array[3];

array[0] = 19;  //these are just random numbers

array[1] = 7;

array[2] = 69;

return array[]; //is this possible??

}

There are several ways to achieve what you want:

The way that does not work

Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
return array[some_index];.

The way that almost works

Remove the brackets and just return array:

int *function()
{
    int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.

Here is what happens: in C (and C++) you cannot return an array. The
identifier array “decays” to a pointer pointing at its first element.
Then return array is essentially equivalent to return &array[0]. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.

The simplest fix: make the array static

As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:

int *function()
{
    static int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The only catch is that the function is now not reentrant, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.

Have the caller manage the allocation

A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:

int *function(int array[3])
{
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.

A couple of things to note here:

The prototype is equivalent to int *function(int *array): the
function receives only a pointer. Writing array[3] instead of
*array has the sole effect of documenting that the function
expects the pointer to point to somewhere with room for 3 values. You
could document that in a comment instead.
The function could return void, since the caller presumably knows
the address it is giving you. Returning that same address is just for
convenience, as it can help you chain calls like
another_function(function(array)).

Return the array in a struct

One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
really only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:

// Struct definition.
struct Array3 {
    int array[3];
};

Array3 function()
{
    Array3 a;
    a.array[0] = 19;
    a.array[1] = 7;
    a.array[2] = 69;
    return a;
}


Serial Moniter is repeating output I do apologize for the constant posts on here.  However I ran into an issue and I cannot seem to find any solution to it.  The goal is to enter a username, through the Serial.read function, and if the username matches it simply responds "Welcome Steven", and lights a green LED, when the wrong username is submitted it responds "Access Denied" and lights a red LED.  So far the code works in response to access granted, and access denied, while also lighting the appropriate LEDs.  However the Serial Monitor does not wait until there is a user input, it automatically starts repetitively "access denied" and lights the red LED.  When the username is entered the red LED turns off, the green LED turns on, and Serial Monitor repetitively responds "Welcome Steven".  I can do this multiple times, and each time it will change state.  I have looked at many tutorials and read many posts on here concerning issues, but so far nothing has worked out. Even tried making changes NickGammon suggested in another post.  Would like to get rid of the repetitive issue, and wait for user input before access denied or granted appears.

int led1 = 9;
int led2 = 10;
String user_name;

void setup()
{
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.println("Enter Username");
}

void loop()
{
 if(Serial.available())
   user_name = Serial.readStringUntil('\n');
{

if(user_name == "Grantham1")
{
  Serial.println("Welcome Steven");
  digitalWrite(led1, HIGH);
  digitalWrite(led2, LOW);
}
else if(user_name != "Grantham1")
{
  Serial.println("Invalid Input");
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
}
else
{
  Serial.println("Waiting Pateintly");
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
}
}
}

Change

if(Serial.available())
    user_name = Serial.readStringUntil('\n');
{

to

if(Serial.available()) {
    user_name = Serial.readStringUntil('\n');

Edit: The reason why it didn't work properly was because all subsequent ifs were evaluated repeatedly regardless of whether there was anything new in the serial buffer or not. The modification fixes that problem.


Increasing ESP32 AP max connections It has already been asked how many clients can connect to an ESP32 AP, but the answer is far from clear; the best one is from a year and half ago (ESP32 AP max connections: 4 or 10?) :

  The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

As I'm trying to move a project from the ESP8266 because it does not have enough AP connections, two questions can be asked :

what is the maximum number of AP connections supported by the 4.0 ESP-IDF framework ?
can it be increased in any way ?

Thank you.

After some extensive testing with several modules (not just blindly trusting the documentation), here's what I found.

Short answer : maximum 10 AP connections for the ESP32 running ESP-IDF 4.0 (updated around 1st of march 2020), and no, it can't be increased (easily).

Details :

The maximum number of AP connections is defined somewhere in libnet80211, and can't be modified since I have no access to the source code.
when the 11th station tries to connect, libnet80211 prints I (39682043) wifi: max connection, deauth!, more or less like the ESP8266 for the 5th station
Changine the ESP_WIFI_MAX_CONN_NUM (defined in esp_wifi_types.h:258) from 10 to anything else ends up in unpredictable behavior (I'm labelling this as unpredictable since without the libnet80211 code, it can't be reliably assessed).

I'm not giving up on increasing the number of stations yet, so maybe there'll be an update to this answer.


Could you tell me what is wrong with this Arduino code? void fn( int pin, int pos)
{
    Servo temp;
    temp.attach(pin);
    temp.write(pos);
    delay(15);
    temp.detach();
}

void loop()
{
    int pos = 0 ;
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        //tmp2.write(pos);
        //delay(15);
        fn(41,pos);
        fn(2,180 - pos);
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        fn(41,pos);
        fn(2,180 - pos);
    }
}

But when I run the code in mega , the servo does not move when attached to pin 2 or 41.
The reason I am creating a function fn , is so that the servo does not stay attached. I want the servo to rotate freely when I am not giving it a pwm signal.

Arrange your code like this:

Servo servo1, servo2;

void setup() {
    servo1.attach(41);
    servo2.attach(2);
}

void loop()
{
    int pos;

    for (pos = 0; pos <= 180; pos++) {
        servo1.write(pos);
        delay(15);
        servo2.write(180 - pos);
        delay(15);
    }

    // 2nd loop here

}

It's rather inefficient to detach a servo after each write and then attach it again for the next write. Simply keep it up all the time.


Arduino IDE unable to see serial connection on OS X El Capitan For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks,
Shaun

I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case PD0 is Hardware Serial RX which is a receive pin.

Here's some relatively older code based around the same idea:

  Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239

Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.

UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.

The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.

As I mentioned in my comment, if you have another pin available to you, use that instead.


Do I need a relay to control a monitor's power with an Arduino? I'm trying to use an Arduino to switch a monitor's power on and off. I'm going to wire the Arduino to the monitor's power switch. I've tested the power switch with a multimeter, and when pressed, there is a 3.3V current running through it that triggers the power on and off. The monitor itself is takes 12VDC to power. I know that a relay is used when switching larger power sources from a low voltage source so as not to damage the lower voltage source, but since the switch in question only runs at 3.3V would it be safe to use the Arduino without a relay?

It's always better to use MOSFET as a switch (or relay) like this:

It can handle loads up to 24V, 5A. The load is powered from an external supply. It is based on a IRF520 Mosfet and cost 0.55 a piece in Aliexpress. Search "Arduino IRF520 module"

You need one Arduino pin to switch on/off the load.

It's very handy and provide posts for power input/output.

I understand that you will still power the monitor from the wall, replacing only the original switch with Arduino. Otherwise, you will need a bigger relay


I change ESP8266 baudrate and now it doesn't work I was trying some AT commands using the monitor of the Arduino Web Editor with an Arduino Uno and a ESP8266 module. It was working at 115200 bauds but then I changed it with AT+CIOBAUD=19200 and now it can't communicate.

How can I change the baudrate to 115200?

Now I see this:

Have you tried setting the web editor's baud rate to both the old and the new values? I ask because the CIOBAUD command has been obsolete for a while now so, depending on the age of your device, it may have done nothing. The command was replaced by "AT+UART_CUR" and "AT+UART_DEF" which have a different syntax.

See this answer to a similar question.

Update:

Yes, here's an example:

// Declare a serial object to talk to ESP8266
SoftwareSerial EspSerial(WIFITX_PIN, WIFIRX_PIN);  // RX, TX

void setup(void){
   // Init WiFi serial
   EspSerial.begin(9600);
   delay(10);
}

I've used 9600 baud in my example since SoftwareSerial may not work well at faster speeds.

Update 2:

  Is it possible to send AT commands from the code instead of the
  monitor?

Yes, easily. Once the above code has run (and note that I've deleted an unnecessary line since update 1), you can send strings to the ESP with EspSerial.print() and EspSerial.println(). Here's an AT command example:

// Set 9600 baud, standard 8-bit frame, and save as power-on default:
EspSerial.println("AT+UART_DEF=9600,8,1,0,0");


Running python script using Arduino I am trying to use Process.h library to run a shell command. Here is my code. I am using Arduino Uno.

#include <Process.h>
#include <Bridge.h>

void setup() {
  // Initialize Bridge
  //Bridge.begin(115200);

  // Initialize Serial
  Serial.begin(115200);

  // Wait until a Serial Monitor is connected.
  while (!Serial);

  // run various example processes
  runPythonFunction();
}

void loop() {
  // Do nothing here.
}

void runPythonFunction() {

  Process p;        // Create a process and call it "p"
  //p.begin("/usr/bin/python /home/kairos/Arduino/codes/sketch_jan26a/tweet.py");
  p.runShellCommandAsynchronously("/usr/bin/python -U /path/to/tweet.py");      // Run the process and wait for its termination
  //p.run();
  // Print command output on the SerialUSB.
  // A process output can be read with the stream methods
  while(p.available() > 0) {
     char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
  delay(300000);
}

If I do not comment the Bridge.begin() line, then in monitor display reverse question marks are displayed. And after commenting that, I am getting some garbage on the serial monitor. Also, my python script makes a new file in the same directory, which runs fine if I run it using a terminal. But if I run it using Arduino code, I am not able to see that new file being generated.

Even using p.begin() and p.run()it does not run. Nor using p.runShellCommandAsynchronously().

So how can I run that python script?

The Uno cannot run python.

The Bridge library is intended for communication either between the two MCUs of the Yun, or between an Arduino board and the MCU on a Yun shield.

It is literally a Bridge between the two systems - Arduino and the Linux system in the Yun.


A minor confusion in digitalWrite command Will the Arduino IDE interpret digitalWrite(13,x), where x>0, as digitalWrite(13,HIGH)?
And will it interpret digitalWrite(13,x), where x<=0, as digitalWrite(13,LOW)?

Every other value than 0 or LOW will result in setting the pin to HIGH. In the following I explain why:

The function digitalWrite() can be seen in the file hardware/arduino/avr/cores/arduino/wiring_digital.c. The important lines here are:

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

As you can see, it checks, if the given value (from the parameter) is equal to LOW and if so will set the corresponding pin to 0. In every other case it will set the pin to 1. The definition of LOW can be found in arduino/hardware/arduino/avr/cores/arduino/Arduino.h:

#define HIGH 0x1
#define LOW  0x0

So the code checks, if the value is equal to 0 and sets the pin also to 0. Every other value will result in a 1 (meaning HIGH). Also have a look at the definition of digitalWrite():

void digitalWrite(uint8_t pin, uint8_t val)

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.


PROGMEM on Arduino Due (ARM Cortex M3) I've been working with the PROGMEM function on my Arduino Uno and I'm thinking about changing to the bigger Arduino Due which is based on a ARM Cortex M3 processor instead of the AVR processor on the Uno.

The Arduino Reference now says:

  PROGMEM is part of the pgmspace.h library that is available in the AVR architecture only.

My question now is: Is it possible to store constants in program memory instead of flash on the Due?

If found this post on the Arduino forums, suggesting that this is done automatically. Does anyone know something about that?

EDIT: Arduino IDE doesn't give stats about RAM usage after compiling, so I can't just try.

There is no PROGMEM required on ARM. There is no memory bus separation between Flash and RAM, so it doesn't copy constants from flash to RAM which PROGMEM is used to prevent.


Software I2C - sending data I'm trying to read a voltage in from a power supply to an Arduino Micro, then send it to an oscilloscope through an I2C (MCP4725). I would use the default pins on the Micro but I want to wire three I2C and the default bus only allows two. As such, I'm trying to use the SoftI2CMaster library

I've looked through examples and documentation but I can't seem to get it to send any data. I've been successful scanning (from examples) and finding the I2C addresses, so I assume that the trouble is at the end of my code.

Any tips would be greatly appreciated!

#define SDA_PORT PORTD
#define SDA_PIN 4 // = A4
#define SCL_PORT PORTC
#define SCL_PIN 6 // = A5
#include <SoftWire.h>

#define I2C_7BITADDR 0x62 //MCP4725

SoftWire Wire = SoftWire();

int aPin;

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

void loop(void){
  aPin = analogRead(A0); //read in from power supply
  Wire.beginTransmission(I2C_7BITADDR);
  Wire.write(aPin); //send voltage to osc.
  Wire.endTransmission();
}

The main problem seems to be, that you are not adhering to the MCP's communication protocol. You just try to directly and only send the pure analog measurement to it.

Look at this image from page 18 of the MCP4725's datasheet:

It describes the operation is Fast Mode, which seems to be the correct mode for this. (Similar descriptions for the other modes can be found below that image). The first byte is done by the SoftWire library, but the following is your responsibility. The
next 2 bytes consist (in this order) of 2 bit's setting the Fast Mode, 2 bit's for the devices power down select (both zero for normal DAC operation) and then the 12 bits of the actual voltage value for the DAC.

At this point I will show another problem with your code. You read an analog voltage with the Arduinos ADC, which is a 10 bit number (of type int) and use it in

Wire.write(aPin);

But the parameter for Wire.write() is defined as uint8_t (see line92 in SoftWire.h of the Softwire library), which means, that your int value get's casted and you loose all bits above 255 (the lower byte), because uint8_t just cannot store more.

What you have to do: You should put the I2C data bytes together in your code and then send them. This may look like this:

byte byte1 = (aPin & 0x0F00) >> 8;
byte byte2 = (aPin & 0xFF);

This code uses bitwise operators. The & will do an AND operation, the >> shifts the bits to the right by the amount after the operator. The 0x denotes a value in hex representation (binary representation would be 0b). So for the first byte we are doing an AND with the value 0x0F00, which will give us a value with only the first 4 bits of the second byte of aPin. Then we shift the result 8 bits to the right, so that the remaining data is nicely aligned to the right of your byte. We don't need to include the mode bits and power down select bits here, since they are zero anyway. If you want to set them non-zero you could bitwise OR them (of course with the correct shift, so that the bits have the correct position in the resulting byte):

byte mode_bits = 0b10;
byte power_down_bits = 0b11;
byte byte1 = (mode_bits << 6) | (power_down_bits << 4) | (aPin & 0x0F00) >> 8;

Then you can send these bytes out with I2C:

Wire.beginTransmission(I2C_7BITADDR);
Wire.write(byte1);
Wire.write(byte2);
Wire.endTransmission();

That should work, though note, that I have not tested this. I just read the datasheet, which is always a must read.

What happened with your original code: The datasheet states for the command "Write DAC Register" (which uses 4 bytes including the address byte) the following:

  The device ignores any partially received data  bytes  if  the  I2C
  communication with the Master ends before completing the 4th byte.

So it just drops any I2C messages, that are not complete. Though it is not stated clearly, we can be pretty sure, that the same happens also for the other operation modes. You were sending only 1 byte, so the MCP found the message incomplete and ignored it.

That said, there is a principle to work around the limit of only 2 devices on the same bus, which I also only learned recently about. You might not wanna go this way here, but it's a great idea and a valid solution to the problem with the limit.

Every MCP has 1 address pin A0, which set's 1 bit of the address, resulting in 2 possible addresses. On an I2C bus there must not be more than 1 device with the same address. But if that doubled address is never called, the bus doesn't have a problem.

You would connect the A0 pins of each MCP to one digital output pin of the Arduino each. By setting the state of these output pins you can change the address of the MCPs (requirement is, that the MCP actually checks the A0 pin during operation, but the datasheet seems to suggest this). Now you keep every A0 pin on one level, so that all MCPs have the same address. To communicate with one, you would change the state of it's A0 pin to change it's address. Now this MCP is the only MCP with this address (all other MCPs have the other address). You can now communicate with it. When you want to communicate with another MCP, you reset the first MCPs A0 pin and then change the next MCPs A0 pin.

That way you make sure, that on one of the two addresses, there will always be 1 MCP at maximum, while you never use the other address. You can use as many MCPs, as you have digital output pins to change their addresses.


How to connect receiver in an Arduino with a motor shield? I have an Adafruit motor shield v1 stacked on an Arduino Uno. I want to add a 433Mhz receiver to the Uno so I can control it wirelessly. However as you know the motor shield completely covers the Arduino board and all its pins, except perhaps the analog ones (it appeared to me).

So can you please suggest a way to connect the receiver if possible. I desperately need it and can't afford to buy a Mega now.

Please help asap.

Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.

Here the schematic


4-wire shielded cable for I2C and power I have two PCBs with ATmega328 that will communicate through I2C protocol. The master will also provide power for the slave, which is located at a relatively short distance (30-40cm or 12-16 inches).

Is it feasible to use the same cable for power (3.3V) and communication?

Thank you.

Sure. Why wouldn't it be? Power is (pretty) static and noiseless.

Just be warned that having the clock and data in the same twisted pair (if your cable has twisted pairs) could cause issues over longer distances. I2C isn't designed for running over cables like that - it's designed for routing round short traces on a PCB.


Compiling includes with Ino I'm attempting to compile this simple bounce.ino example with the ino tool, but it's giving me the error:

Bounce2.h: No such file or directory

I've placed it in the same directory as bounce.ino. Why can't it find the header?

Edit: I'm using Ubuntu.

What OS are you using?

If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.


Interrupt volatile variable doesn't work as expected Please examine the following code.

volatile uint8_t myVar;

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), isr, FALLING);
  Serial.begin(115200);
}

void loop() {
  myVar = 0;
  while (myVar != 5) {
  }
  Serial.println("ISR called");
}

void isr() {
  myVar = 5;
}

From this code, I expect that every time the pin 2 is falling, I get one single print statement ISR called.

However, when dropping the voltage on pin 2 ONCE, the serial monitor shows ISR called TWICE.

Why is this? This is a simplified, stripped-down example of the problem I am facing with my current project.

Edit:
After reading the comments, here is a bit more info. I am using a 64-button shield that is triggering the interrupt. The process is time critical since I am measuring the time it takes for the button to be pressed (I am testing people's reflexes). I will add a print statement in the interrupt to see how many times it gets called. However, I believe the interrupt is only getting called once per buttonPressed.

Thank you for your help!

Turns out, the 64 button shield calls the interrupt TWICE. Once when the button is pressed and once when it is released.

Thank you for everyone's help!


Trying to connect FT sensor to Arduino Mega using RX TX I am trying to interface this sensor, https://www.robotous.com/forcetorquesensor (RTF60-HA01-C), with the Arduino Mega. The sensor has an input voltage of 5Vs and communicates using CAN/RS232/RS422. I am using the RS232 and have connected wires properly and have tried to establish Serial Communication using the below code.

#include<String.h>
# define BuffSize 32

byte buff[BuffSize];
unsigned char data_field[16];
byte comm[11]  = {0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA};
// SOP == 0x55, EOP == 0xAA, Checksum == summation of each data in data_field
void setup() {

  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial2.begin(115200);
  for (int i = 0; i < BuffSize; i++) {
    buff[i] = 13; //Number to initialise buffer
  }

}

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

     Serial2.write(comm, 11);
    //Serial.println(Serial2.available());
    if (Serial2.available() > 0) {
      //int read = Serial2.readBytes(buff, BuffSize);
        String output = "";
        for(int i=0;i<BuffSize;i++){
        buff[i]=Serial2.read();
        output = output + buff[i] + "|";
     }
  //Serial.println(read);
    Serial.flush();

    Serial.println(output);
    Serial.println();

    }
  }

The output I receive is just 0s and the occasional 10. Like below

0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|255|255|255|255|255|

I am new to this and hope this is not a stupid question.
Let

The Serial RX and TX pins of an Arduino are not RS-232 compatible without using some type of circuit to give you the proper voltage levels.

**RS-232 logic and voltage levels**
0 (space)   Asserted    +3 to +15 V
1 (mark)    Deasserted  −15 to −3 V

Connecting the RX/TX pins of an Arduino directly to an RS-232 device may fry your Arduino in addition to just not working for communication.  This circuit given below is an example what you'll need.  There are pre-made adapter boards available for a few dollars.


arduino will not save data after receiving from serial communication I'm new to Arduino and what I'm trying to do is change the variable by sending it from php to the Arduino.
I've added the delay as stated by other questions but it has not worked so far. The pin 13 LED so
Arduino Code
float val;
void setup() {

  Serial.begin(9600);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  val=29.1;

  Serial.println("Start!");
}

void loop() {

  if(Serial.available()){
    String temp = Serial.readStringUntil('\n'); //read string
    val = temp.toFloat(); //convert string to float
  }

  if(val==62.10){
    digitalWrite(13,HIGH);
  }else{
    digitalWrite(13,LOW);
  }

  Serial.println(val);
  delay(1000);

}

PHP Code
<?php
$port = fopen("COM3", "w");
sleep(2);
fwrite($port, "62.1");
fclose($port);
?>

Any tips would be much appreciated. Thank you for reading.

You are writing "62.1" but you are trying to read up until a \n, which you never send.
You need to ensure that you send the end-of-line character that you subsequently check for,
fwrite($port, "62.1\n");

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.
That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.
In doing so the sketch then runs fresh every time you open the serial port.
There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.
Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use SoftwareSerial and an external USB to UART adaptor instead of the Serial connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.


Pin 9 and 10 with different duty cycles I want to control the contrast and backlight of an HD44780 LCD display with two PWM signals. I would like to use PB1 and PB2 (Pin 9 and Pin 10) for this.
As far as my research goes, timer1 is responsible for the two pins.
OCR1A and OCR1B are responsible for the pulse length.

With the code below I get a frequency of 7.823 kHz and a duty cycle of 88%. But it works only on PB1. PB2 is still constant 0V. I am using the AtmelStudio, therefore I don't have access to functions like pinMode(10, Output)

How can I have different duty cycles on pin 9 and 10?

#define F_CPU 16000000UL
#include <avr/io.h>

int main(void)
{
    DDRB |= (1 << DDB1) | (1 << DDB2);
    OCR1A = 900;
    OCR1B = 400;
    TCCR1A |= (1 << COM1A1);
    TCCR1A |= (1 << WGM11) | (1 << WGM10);
    TCCR1B = (TCCR1B & 0b11111000) | (1 << CS10);

}

After trying  a lot of things i got it working.
And even the contrast is working directly on the pwm signal.

#define F_CPU 16000000UL
#include <avr/io.h>
void main(void){
    DDRB = 0x06;
    OCR1A = 200; //Duty cycle for PB1 ~80%
    OCR1B = 100; //Duty cycle for PB2 ~40%
    TCCR1A = 0; //Set TCCR1A to zero. We will configure it manually
    TCCR1A |= (1 << COM1A1) | (0 << COM1A0) | ( 0 << COM1B0) | (1 << COM1B1);
    TCCR1A |= (0 << WGM12) | (0 << WGM11) | (1 << WGM10);
    TCCR1B = 0; //Set TCCR1B to zero. We will configure it manually
    TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
    while(1){

    }
}


Does flashing ESP8266/ESP-01 firmware mean uploading a new 'sketch' and why different firmware? Hi I am new to IOT and I am now in love with this. However I'm a little confused right now with the jargon. My question is similar to this. But I do have some extra questions though.

When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?
On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?
For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?
To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.
Is the reason for using other firmware is because of how the code is compiled and the language used?

If someone could clear things up for me I would greatly appreciate it. Thanks!

When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

Yes. "Firmware" is application code running on the microcontroller.

  On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?

Yes. "Firmware" is application code running on the microcontroller.

  For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

Yes. "Firmware" is application code running on the microcontroller.

  To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.

No. The Arduino IDE is for coding in C++ with the Arduino API extensions.

  Is the reason for using other firmware is because of how the code is compiled and the language used?

The firmware is just what runs on the chip. If that firmware provides its own programming language then you can use that to execute that programming language.

If you write your own firmware in the Arduino IDE then the chip runs that firmware. If you upload the AT firmware then the chip runs the AT firmware and you can control it with AT commands. If you upload the NodeMCU Lua firmware then the chip runs the NodeMCU Lua firmware and you control it using Lua commands and scripts.


Circuit not working with 9 volt battery I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

Red wire: power
Black wire: ground
Orange wire: digital signal
And here's the code:
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}

It rotates the motor 90 degree and back when a button on a remote is clicked.
Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.
I have also observed that the servo vibrates a little bit, but doesn't move.
Is this a problem in my circuit, or is it just that my battery power is low?

A 9V battery has both low peak current and low total power (low mAh rating). It is not a good choice for any circuit that draws more than ≈100 mA. (I pulled that number out of thin air, but it's probably a decent guess)
Build a battery pack from 6 AA alkaline cells instead. That will provide enough peak current. Or for much longer run-time, use 6 D sized cells.


Can I make a USB Device with only data output This is about how USB ports/devices work

Lets say i have a USB port on my computer

If I have an arduino board or something similar, am I able to connect output to Data+ and sort of make my own USB keyboard.
What I aim to achieve is send without having to receive

1) Would I need to connect it to both D+ and D- so it forms a circuit in order for the USB port to read the data? (or would the data simply be read and then disappears so I don't have to worry about two wires?)

If Yes: 2) If I manage to forcefully push electricity through the wire onto the Data pins, would I only need one wire?

Else: 3) is this physically impossible and the whole universe would explode if I tried?

USB is a host-managed protocol. A USB device must be able to receive in order to operate, since the host notifies the device when it should send data back to the host.

The D+ and D- lines are not independent; the signaling state of the line is determined by examining both lines regardless of whether the host or the device is transmitting.

USB Made Simple


Arduino Micro tone() PWM Pins according to the tone() documentation using tone() interferes with PWM output:

  Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

On my Arduino Micro it seems to interfere with PWM on pin 5. After using tone() the PWM does not seem to work anymore. If I use pin 3,9 instead everything works fine.

So can someone explain why that is happening and if there is a way to circumvent that?

The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.

The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.

So on the Micro, just don't use pin 5 for PWM when using tone.

Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.


NodeMCU v2 with MH-Z19B CO2 sensor UART read problem I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

Some key points, which could be not that obvious from picture:
 - sensor has separate power supply of 4 AAs, providing ~5,5V
 - sensor's TX connected to GPIO15 (TX D2) of NodeMCU
 - sensor's RX connected to GPIO13 (RX D2) of NodeMCU

And here is my sketch:

const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // according to datasheet
unsigned char response[9];

void setup() {
  // according to datasheet, sensor uses 9600 baud, 8 databits and 1 stopbit
  // with parity NONE, which I believe corresponds to default config SERIAL_8N1
  Serial.begin(9600);
}

void loop() {

    //  ... check if it is time to measure

    Serial.swap(); // switch to sensor

    Serial.write(readCommand, sizeof(readCommand));

    memset(response, 0, sizeof(response));

    int attempts = 5;
    int available = Serial.available();
    while(available < sizeof(response) && attempts > 0) {
        delay(100);
        attempts--;
        available = Serial.available();
    }

    Serial.readBytes(response, sizeof(response));

    Serial.swap(); // switch back to console

    // print out the response in hex
    for (int i = 0; i < sizeof(response); i++) {
      Serial.print(String(response[i], HEX));
      Serial.print("   ");
    }

    // ...process the response according to protocol
}

The Problem

For some reason after sending command to serial I get an answer exactly the same as command is although the structure of answer expected to be different. Of course datasheet says nothing about situations like this.
Expectation

ff 86 .. .. 0 0 0 0 CRC

Reality (same bytes I sent as a command)

ff   1   86   0   0   0   0   0   79

Other notes:
 - I got exactly the same when tried to use SoftwareSerial with D1 & D2 pins
 - connecting TX to RX respectively on both sensor and MCU results in reading failure
 - I tried to pull everything while available from serial, there are only my expected 9 bytes
 - my soldering skills are far from ideal, but I'm pretty sure tx/rx on the sensor are connected properly

I'm new to all this stuff, so it is completely possible that there is ridiculously silly, but crucial mistake, so would appreciate any help on this. And I understand that sensor also has additional interfaces to obtain the value, but as I mentioned I'm a newbie and wanted to familiarize myself with UART as this is something new for me.

UPD 1:
I didn't use level conversion for sensor output as datasheet says:

Assuming this I thought that sensor provides logical level conversion itself. Did I get it wrong?

UPD 2:
I got back to proper TX - RX connection just to check out what is going on exactly to describe that "reading failure" problem with more details. It seems that Serial.available() returns 0 after I send command so this loop gets stopped after 5 attempts:

while(available < sizeof(response) && attempts > 0)

It says in your description that you have the Rx connected to Rx and the Tx connected to Tx.  That's backwards.  What one transmits the other needs to receive.  When you have a conversation with someone, do you talk into their mouth and listen to their ears?  You should have Rx-Tx and Tx-Rx.

You also need to be sure that it is OK to feed a 5V Tx into that Rx pin.  On some ESP8266 boards it is and on most it isn't.  If you don't have one of the boards that specifically has circuitry built in to handle 5V inputs then you will fry your NodeMCU


Is there an Adafruit function to invert the colors of my screen for Arduino language? I am trying to invert the color of my OLED display screen once a button is pushed. I have the button situation figured out but I can not find a function that inverts the color. I am using these two libraries to handle my screen on the Arduino IDE.

Adafruit_GFX.h, Adafruit_SSD1306.h

Any help would be much appreciated.

There is a function that invert the colors of your screen, you can pick either black on white or white on black, I have tried it and I have quite experience with your display, I think you should try this piece of code.

At the beginning of your Arduino code be sure that you declared the object using the same name.

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

To invert the display

display.invertDisplay(true);

To return the display again

display.invertDisplay(false);

As you said that you want a button to invert the display you might use this code I made

if(digitalRead(BUTTON_PIN)){
    display.invertDisplay(true);
}
else{
    display.invertDisplay(false);
}

Or you might use Interrupts for better performance depending on your code.

As you couldn't find on the internet, I am student and I learn alot from the internet, to for example search for such a function in an Arduino library, try searching it's documentation or it's page on GitHub then afterwards see the function you want through the pages, but don't just search the function directly it will sometimes won't work as they are not that popular.

As a last thing Here is the documents where I got the function with it's parameters from.

I hope I've helped you out. any edits in the answer is well appreciated, as I am a student.


RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h I use  RH_RF24.h to control Si4463, and realize some simple communication between two Si4463 . But I don't know the mean of RH_RF24_MAX_MESSAGE_LEN in this example.

RH_RF24_MAX_MESSAGE_LEN is a constant ? If so , what decides it ? And if I need to sent and receive  a long  char string , how to do it ?

RH_RF24_MAX_MESSAGE_LEN is probably defined in the header file RH_RF24.h.

It doesn't matter what size it is, you should always use RH_RF24_MAX_MESSAGE_LEN rather than the number because the value might change in the library and this will break your code if you have used the number.

If you want to send a message that is larger than RH_RF24_MAX_MESSAGE_LEN then you will need to 'fragment' the message (unless the library supports that).
I would use the first byte of the message as the type of message and define one of those types as a multi part string.  Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.


Detect button on a ground line (reverse eng) I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.

Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons.

Circuit:

Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin

Thanks in advance!

Edit: Circuit Board

It sounds like you might have a PCB with debounced switches on them. One such circuit for debouncing switches looks like this:

That circuit and more about switch debouncing can be found here.

A debouncer basically masks the problem of switch "bounce" which is what happens when the contacts get close and the circuit is quickly closed and opened in rapid succession until a firm connection is obtained. Its a natural problem  mechanical switches.

If that's not quite right, maybe you could help us help you better by posting a photo of the board in question.


Linking Arduino and Matlab My project is based on controlling a moving fan using different hand gestures. I am using image processing toolbox from matlab to detect and identify various hand movements.I want to link my matlab codes to arduino for hardware implementation. How to link these two?

This block of code can give you some idea...

% create an arduino object

a = arduino('com3', 'uno');

% start the loop to blink led for 10 seconds

for i = 1:10

    writeDigitalPin(a, 'D11', 1);

    pause(0.5);

    writeDigitalPin(a, 'D11', 0);

    pause(0.5);

end

% end communication with arduino

clear a

For more details on this code and working of it you can visit....
Here


Powering from 3V coin cell to VCC, using I/O pin as supply GND I'm thinking of creating a "small" electronic dice.
(I will solder the button a little different though xD)

But there are some concerns on my design:

Powering from a coin-cell

It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

Can I use a I/O as (input/supply) GND?

You can actually use outputs as positive voltage, and you can sink currents.
But does that mean I can connect the negative side of the coin-cell to an output, and sink it?
This way it should power my arduino's VCC pin through the "digital GND"

Using the reset button

I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

(I probably won't use it though, it's placed inconveniently for this project, but I am wondering.)

A crude drawing below:

The fun thing is, polarity of the LED's/segments doesn't matter, since I can change which side is high or low? :)
Also, I've only drawn half the LED's/segments. And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

(btw, battery GND pin should be pin 4, not pin 2)

Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for another (low power) device, but
you should power the Arduino itself from its Vcc and GND pins.

  I could use the reset button, but would it still give me "random
  enough" numbers?

You will likely see the very same sequence every time you reset it.
There are ways around this:

You can seed the random number generator (RNG) at startup with an
analogRead() from an unconnected pin, but it's not clear how much
entropy you can expect from this.
You can save the RNG's entropy into the .noinit memory section, this
way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the
dice, if only for one reason: the time when the user presses the button
(that you read with micros()) is a very good entropy source for
seeding the RNG.

For example, whenever the user presses the button you could:

srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

This way you combine the entropy from the button press with the entropy
from the analog pin (if any), with whatever entropy may already by in
the RNG.

Edit: More on entropy gathering.

As you seemingly already know, random() is a pseudo-random number
generator intended to produce a sequence of numbers that look random.
Unless you have some other source of randomness in your program, every
time you restart the Arduino you will get the very same sequence of
numbers. Getting true randomness (also called “entropy”) on an Arduino
is not so easy. Here are some ideas you may want to explore.

Read from an unconnected analog input

This trick seems to be pretty popular. It can even be found in the
Arduino documentation on
randomSeed():

  use randomSeed() to initialize the random number generator with a
  fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a
test program that prints out the output of analogRead(0) and it seems
to cycle through the same few values in an almost predictable way.
I estimate this gives around one or two bits of entropy per call. On the
plus side, each call takes just over 100 µs.

Read from an analog noise source

There is a lot of literature on building analog noise sources. Such
sources are used inside crypto-grade random number generators, but the
circuits are likely to be more complex than you would like. There seems,
however, to be a very simple alternative. In a comment to this
post, CharlieHanson wrote:

  Connecting the analogue input to the collector of a run-of-the-mill
  transistor, with the emitter grounded and base open helps to make a
  noisy input.

I have not tested this idea, but it is certainly worth exploring.

Time user input

If the user is required to press a button to throw the dice, the timing
of the button press is probably the best entropy source you can have.
With a 8 MHz clock, the micros() function has a resolution of
8 µs (64 clock cycles). Assuming the user is unable to control his
timing better than 0.1 seconds, then you have more than
13 bits of entropy per button press.

If, instead of micros(), you use timer 1 running at the full CPU
speed, then you would have 16 bits of entropy per button press. And
you would not need random() at all, as you could just output
1+TCNT1%6. That would be like throwing a dart at a carnival wheel
spinning at 80 million RPM (8 MHz / 6)!

Measure clock drift

The drift of a clock relative to another clock can be used as an
entropy
source.
The ATmega chip in your Arduino has two independent clocks: the internal
“calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator
used by the watchdog timer. Both are low-accuracy clocks subject to
somewhat unpredictable drift, which is a good thing for this
application. You can gather entropy from this by configuring the
watchdog timer as a periodic interrupt source, and using timer 1 at full
speed to time the interrupt arrival times:

#include <avr/wdt.h>
#include <util/atomic.h>

// Configure Timer 1 for counting CPU cycles and the watchdog as an
// interrupt source firing (roughly) once a second. Call once in
// setup().
void configure_timers()
{
    // Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS10);  // prescaler = 1

    // Watchdog. This is a timed sequence.
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        WDTCSR = _BV(WDCE)  // enable changing the prescaler
               | _BV(WDE);  // ditto
        WDTCSR = _BV(WDIF)  // clear interrupt flag
               | _BV(WDIE)  // enable interrupts
               | WDTO_1S;   // timeout ~ 1 second
    }
}

volatile uint16_t wdt_time;
volatile bool wdt_fired;

// Watchdog interrupt service routine.
ISR(WDT_vect)
{
    wdt_time = TCNT1;
    wdt_fired = true;
}

// Add entropy to the RNG from the timing of the last WDT interrupt.
// Call periodically in loop().
void get_wdt_entropy()
{
    if (!wdt_fired) return;  // No WDT event since last time.
    uint16_t wdt_time_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        wdt_time_copy = wdt_time;
        wdt_fired = false;
    }
    srandom(random() ^ wdt_time_copy);
}

I have tested this idea by plotting the time differences between
successive interrupts. On an Arduino Uno clocked at 16 MHz, I see
short-time fluctuations with an amplitude of about 300. That should
provide around 8 bits of entropy per second.

Save the entropy pool across reboots

Once you have spent some effort to gather entropy from the environment,
it would be a pity to lose it all at power down. It is common practice
to save the entropy pool to disk when a computer shuts down, and restore
it at boot time. This avoids the problem of the RNG always starting in
the same predictable state. On the Arduino, you have no disk, but you
can use the EEPROM instead. The problem is you cannot know in advance
when the user is going to switch the device off. Then, ideally, you
would save the entropy every time the user requests a new dice value.
The new problem is that the EEPROM is only guaranteed to work reliably
for 100,000 write/erase cycles. This may not be a serious problem
(100,000 is plenty of throws), but it can nonetheless be mitigated by
using a wear-leveling scheme, where you distribute the writes across the
whole EEPROM instead of always overwriting the same bytes.

Wear-leveling can add significant complexity to your program, but it
turns out there is, in this particular case, a wear-leveling scheme that
is trivial to implement: just write at a random location! At startup,
you do not know what was the last location written to, but you do not
need to: you read and mix the whole contents of the EEPROM:

#include <avr/eeprom.h>

// Save the entropy to EEPROM. Call this every time the user requests a
// new value.
void save_entropy()
{
    uint32_t *address = (uint32_t *)(random() & E2END & ~3);
    eeprom_write_dword(address, random());
}

// Restore the entropy from the EEPROM. Call once in setup().
void restore_entropy()
{
    uint32_t seed = 0;
    for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
        seed ^= eeprom_read_dword(address);
    srandom(seed);
}

Combine the entropy sources with the XOR operator

As you probably already noticed, the bitwise xor operator (^) is used
every time one wants to combine entropy sources. The main reason is
that, if a and b are independent random variables, then a^b is at
least as random as the most random of a and b. Which means that
XORing a “good” random variable with a “bad” one is harmless. This is
somewhat formalized as the piling-up
lemma.

As an example, doing randomSeed(analogRead(0)) at program startup is
fine, but doing it repeatedly during program execution is a terrible
idea: most of the time this will put the RNG in one of a very few
states. If instead you

srandom(random() ^ analogRead(0));

then you are combining the current randomness of the RNG with the output
of analogRead(), and putting this back into the RNG. And this is
harmless even if analogRead() is quite predictable.

A side note on randomSeed(): Arduino releases prior to 1.6.5 had a
bug that would truncate to 16 bits the entropy provided with
randomSeed(). On those releases it is better to use the avr-libc
srandom()
function.
The bug has since been
fixed.


Choosing rangefinder for obstacle-avoiding I am looking to buy a range finder module for an obstacle avoidance robot.
Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.

In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?

both need 5V
both have max range of 3-4m
Sensor angle HC- 15 degrees, parallax cant find..

Odds are pretty good they are real close. I've only used the sr04 with
  4 pins (too lazy to mod) and it was ok. cant say if the parallax is
  better or not. For 4 times the price you'd expect it to be, but so far
  in robotics, price seldom reflect performance in my experience. –
  Spiked3

I've also used the SR (with 4 pins) and it worked great. <2$ on eBay


How can I calculate approximate cycles per second from pulsed pin on Arduino MKR Zero? The relevant tech specs for a MKR Zero are:
    32.768 kHz (RTC*), 48 MHz

*Real-Time Clock

What I'm curious about is how I might do an approximate calculation of cycles per second from operations.

I'm running the following (extremely simplified) code :

int pin3 = 3;
void setup() {
  //set digital pin pin3 as output

  pinMode(pin3,OUTPUT);
}

void loop(){
  digitalWrite(pin3,HIGH);//set pin pin3 to +5V
  delay(100);//wait 100ms
  digitalWrite(pin3,LOW);//set pin pin3 to 0V
  delay(100);//wait 100ms
}

Now I'm curious how many cycles per second (approximately) that might account for.

The Equation?

What would the equation be to calculate that?

Not Processor Op Codes

Is this even possible to approximate?  I understand it will be difficult because those lines of code do not equal the actual op codes and don't exactly break down to specific cpu cycles or whatever.

Would it be something like:

48,000,000 (48MHz) / 200 (millisecond pause) = 240KHz?

Or would I use the real-time clock speed?

32768 / 200 = @163Hz

Or something completely different?
I'm trying to better understand how I might create a very simple frequency generator and I know that depending upon the chip speed the code will vary.

It is unclear exactly what you are trying to do, however the frequency generated by the code would be ~5Hz - corresponding to a period of 200mS


How to develop or edit an Arduino library? I'm not sure if I should split this question in two.
I had to edit some libraries and I plan to make some myself but didn't try yet.

Editing a library seems very laborious comared to editing a sketch.

I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.

The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.

What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.

I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?

And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.

How do you do all of this? Is there any trick that helps?

Thank you.

I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development.

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.

Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:

void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

And some test code:

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Make a library

To turn that into a library we need three steps:

Make a folder for the library. This should be placed inside the libraries folder in your sketchbook folder. This folder:

In my case: /home/nick/sketchbook/libraries. It does not go into anywhere associated with the IDE download.

  but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

No, not there.

I will call my library blinkLED. So I make that folder, which is now: /home/nick/sketchbook/libraries/blinkLED

Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:

blinkLED.h

#include <Arduino.h>

void blinkLED (const byte which, const int times);

Important: You must include <Arduino.h> as in the example, or you will get compile errors.

Put the C++ code into a .cpp file, like this:

blinkLED.cpp

#include <blinkLED.h>

void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

Important: You must include the .h file created in step 2, as in the example, or you will get compile errors.

That's it! Restart the IDE now so it notices the new folder with the library in it.

Now our test sketch can just use the new library.

#include <blinkLED.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Testing

For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).

You can make changes to the library source and save them. You do not need to restart the IDE if you do this. It will always pick up the latest version.

In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

Git

Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:

git init
git add *.cpp
git add *.h
git commit -m "Initial commit"


MIT "happy board" like shield for arduino I'm working with the robotics lab at the university to try and find a replacement for the obsolete Handy Board.

We're considering purchasing arduinos because of their ease of use but we can't seem to find shields with compactly integrated capabilities as the handy board (DC motor outputs, analog/digital inputs and a physical interface such as knobs and buttons).

We did consider purchasing expansion boards but the final product would be too bulky.

Here are the complete specs:

  Allow direct control of at least 4 DC motors
  Accept digital and analog sensor inputs
  Simple UI (LCD, buttons/knobs)
  Be as compact as possible (including the batery)

Does any one know if such a thing exists?

It sounds like you're looking for the Board of Education Shield (for Arduino)

  Key Features:

  17 row x 2 column breadboard for convenient circuit-building
  Headers for power (Vin, 5 V, 3.3 V) Ground, Digital I/O and Analog In
  are brought adjacent to the breadboard
  Onboard 5 V regulator supplies up to 1 A, great for robotics and
  animatronics applications
  Onboard 3.3 V regulator supplies up to 200 mA for project circuits and
  accessories, such as XBee modules
  4 servo ports with power selection jumper for regulated 5 V or Vin
  (Arduino's supply voltage)
  3-position power switch for power header only or power header + servo
  ports     Board reset button resets the Arduino
  Supply indicator LEDs for breadboard and servo power


Can I use a 3.3v GPIO to control an opto-isolated 5v relay board? I am working on a DIY home automation project using a Wemos D1 Mini as the controller, and I ordered some 4-channel 5v-triggered relay boards. The ESP8266 that Wemos D1 Mini's are built on has GPIO output voltage of 3.3v, ostensibly too low to trigger the relays.

I've read a Reddit post that was saying that as long as you use a separate 5v power suppy for the relay board, 3.3v should be enough to trigger the relays. Is that accurate, or do I need to use a transistor or something to provide the relay board inputs with 5v?

Yes, the Reddit post's approach is likely to work ok, as long as you correctly follow the cautions in it:  • connect the VCC pin of the relay board to a 5V source,
•  connect together the Arduino ground,  the relay ground, and the  5v-source ground.

Here is a typical relay-module circuit diagram (for one channel):

(Note, this diagram is from a home automation blog; for more discussion and similar diagrams, see eg
4-relay-shield-diagram at yourduino.com and stripboard-shield-relay-sm at startingelectronics.org.)

As you can see in the diagram, the Arduino pin that connects to JP2-2 will not be exposed to voltages.  (The base of an NPN transistor effectively is at the junction of two back-to-back diodes.)

When the Arduino or ESP pin at JP2-2 is at about 0 V (ie, when the Arduino pin is off) IBE=0; that is, no Q2 base-emitter current will flow; thus, Q2 will be off, so that both of LED1 and relay U1 will remain off.

When the Arduino or ESP pin at JP2-2 is at about 3.3 V (ie, when the Arduino pin is on) IBE is about 2.5 mA, which should be enough to reduce VCE to about 1 V, leaving 4 V across the relay coil, or enough to turn it on.

Note, the 2.5 mA figure for this circuit is calculated as follows:  IBE = (3.3-VBE)/1000 - VBE/10000 = (3.3-0.7)/1000 - 0.7/10000 = .00260 - .00007 = .00253 A = 2.53 mA.  Note that the alternate circuit diagrams linked above don't have a 10KΩ resistor like that in the diagram above, so instead of about 2.5 mA would have about 2.6 mA drive.

If for some reason you don't have quite enough base drive – in which case you might be able to hear a slight click from the relay, even if it doesn't switch – you could increase the "5 V" line into the LED and relay to say 5.5 V or 6 V.  As noted before, the  back-to-back diodes structure of the NPN transistor will isolate that voltage from your Arduino or ESP.


Reading from a KY-040 rotary encoder with Digispark I have a rotary encoder KY-040 connected to a Digispark like this:

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).

I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/

#include <DigiKeyboard.h>

 int pinA = 0;  // Connected to CLK on KY-040
 int pinB = 2;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.println("Rotated: ");
     if (bCW){
       //Serial.println ("clockwise");
       DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
     }else{
       //Serial.println("counterclockwise");
        DigiKeyboard.println("cc");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

I only changed the pin numbers in the code and the Serial.println (... to any of the following:

DigiKeyboard.write("1");
DigiKeyboard.println("1");
DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...

Any ideas?
Maybe the 10K resistors are too much?

Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents.  You may be able to adapt it to your DigiKeyboard ATtiny system.

/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins.
(Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace

  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);

with

  enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts
  enableInterrupt(PinB, pinChangeISR, CHANGE);

and add the following #include near the beginning:

#include <EnableInterrupt.h>

To install the .h file for use via the Arduino IDE, unpack an EnableInterrupt zip file (for example, enableinterrupt-0.8.2.zip from bintray.com/greygnome) in the directory ~/sketchbook/libraries.  I think the package works with ATtiny's as well as more-standard Arduinos.


Serial read in ESP8266-01 not working I am new to programming. kindly bear with me. I am trying to use ESP8266-01 device for serial read and write application. Before writing the full program for my application, i wanted to test how it functions. I programmed the ESP8266-01 device to read the data from its Rx pin and write it to Tx pin. I used a standard USB-TTL cable to send and receive data from PC using Hterm. The ESP device does not read the data available at the Rx pin. what am i missing ?. Also kindly help me in understanding the difference between serial.println and serial.write with respect to ESP8266-01 device. As per the program if i check the data from the Tx pin of the ESP8266 device, i get only "No data received". I am using arduino IDE 1.6.11. Kindly provide some guidance

regards

Sriniketh

#include <ESP8266WiFi.h>

void setup() {

Serial.begin(9600);
}

void loop()
{
  byte serin=0;
  if (Serial.available()>0)
  {
    serin=Serial.read();
    delay(100);
    Serial.println(serin);
    delay(100);
    Serial.write(serin);
  }
  else
  {
    Serial.println("No data received");
    delay(5000);
  }

}

A circuit diagram or photo would help, but I would guess you have taken the lead from the PC that is marked Rx and connected to the pin on the ESP marked Rx.  That's the wrong thing to do.  Firstly the PC will use 5V and the ESP uses 3.3V, so you need a little board called a level shifter something like this 2 channel level shifter.  This will let a 3.3v device talk to a 5V device.  Some ESP boards are 5V tolerant, but I don't know what you have so ...

Then when you "talk" over serial you need to cross the Tx and Rx between the two devices, so the can 'hear' each other

 PC - Tx  ---> Rx - ESP
 PC - Rx <---- Tx - ESP

(Lots of other level shifters are available and a lot are cheaper than the example shown, a lot cheaper!)


Can I check if a message has been sent successfully using Radiohead_ASK? I'm new to Arduino programming and I'm trying to get a simple 433 MHz transmitter and receiver module working on an Arduino Uno board. Unsurprisingly, it's not working as expected and I'm trying to debug the problem.
I'm using RadioHead and read in the documentation that the send() and waitPacketSent() methods return a boolean to indicate success. However, I disconnected the data wire and the send() method still returns true. As the module is no longer connected to the arduino I would have expected it to return false.
I understand that the messages are sent as unreliable datagrams, but I'm just trying to work out whether the transmitter has actually sent something. Is there some way I can do this?
The code I'm using is relatively short, so I've included it in full below, for what it's worth
#include <RH_ASK.h>
#include <RadioHead.h>

#ifdef RH_HAVE_HARDWARE_SPI
#include <SPI.h> // Not actually used but needed to compile
#endif

RH_ASK driver;

bool sent;

void setup()
{
#ifdef RH_HAVE_SERIAL
    Serial.begin(9600);    // Debugging only
#endif
    if (!driver.init())
#ifdef RH_HAVE_SERIAL
      Serial.println("init failed");
#else
  ;
#endif
  sent = false;
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    const char *msg = "hello";
    bool sendSuccess;
    bool waitSuccess;

    if (!sent) {
      Serial.println("sending");
      sendSuccess = driver.send((uint8_t *)msg, strlen(msg));
      if (sendSuccess) {
        Serial.println("Send completed successfully");
      } else {
        Serial.println("Send Error");
      }
      Serial.println("Waiting");

      waitSuccess = driver.waitPacketSent();
      if (waitSuccess) {
        Serial.println("Wait Sent Success");
      } else {
        Serial.println("Wait Sent Error");
      }
      Serial.println("Done Sending");
      sent = true;
      delay(1000);
    }

    if (driver.recv(buf, &buflen)) // Non-blocking
    {
      Serial.println("driver.recv");

      // Message with a good checksum received, dump it.
      driver.printBuffer("Got:", buf, buflen);
    }
}

The output on the serial monitor is as follows

22:22:30.647 -> sending
22:22:30.647 -> Send completed successfully
22:22:30.684 -> Waiting
22:22:30.753 -> Wait Sent Success
22:22:30.753 -> Done Sending

Thanks in advance!

There is no concept of "did the packet arrive", only "did it get sent" - and by "sent" I mean the data squirted out of the data pin for the attached module to send.

These 433MHz modules are dumb. Very dumb. You toggle the transmitter's pin high and low and the receiver sees that toggling, if it is in range, and toggles its output pin to mirror the signal.

The only way you can know if the packet arrived is if the receiver also has a transmitter and the transmitter also has a receiver. When a message arrives at the receiving node it sends a message back to the transmitting node to say "I got it". That takes a lot of work to get right, though. Especially since the original message may have arrived fine, but the acknowledgement didn't, and all sorts of horrible things can happen if you don't handle packet sequencing right.

Better is to pick a better module that does all these things for you, such as the nRF24L01+ with Auto-ACK turned on.


How to parse array to x,y positions? I have 16x16 LED matrix and I want to show some custom characters on it. I saw font made with array like this.

const byte zero[16] = { // Create byte array number 0
        B0111110,
        B1111111,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1111111,
        B0111110
    };

But I dont know how to parse it to x, y positions. Can someone help me? Do you know better way to store characters that is easily readable by human? Thanks

To get the value at a particular location, use this code:

boolean val = zero[y] & ((B1 << maxX) >> x);

where y is the y position from 0 to zero.length, maxX is the length of the binary constants minus one (in this case, it would be 6), and x is the x position from 0 to maxX.

For more information, see BitMask.


20x4 LCD will write but then won't update I am controlling a solar tracker, and it needs to be reset every 10 minutes or it loses its mind.  My program works fine, controlling power relays, so I have added I2C&Power to be able to see the status remotely.  For now it is set up on the workbench with fairly short cables.  I also have a RTC and the i2cscanner finds them all..

LCD init code is pretty basic:

// 20 x 4  LCD Display
#include LiquidCrystal_I2C.h
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

then

lcd.begin(20,4);
lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

My LCD (20x4) works fine at first, writing the top line with the name of the program, then the bottom line with a temperature reading, then every 10 minutes I need the second line to show when the power is off for 10 seconds.  It shows "power off" just fine, but after the delay(10000) it is supposed to overwrite that line with  "power on" but nothing changes...

Serial.println("POWER OFF");
lcd.setCursor(4,1);
lcd.print("-Power Off- ");
digitalWrite(power1,HIGH);  // DC HOUSE power off
digitalWrite(power2,HIGH);  // DC HOUSE power off
delay(10000);
Serial.println("POWER ON");
lcd.setCursor(4,1);
lcd.print("-Power On-  ");
digitalWrite(power1,LOW);  // DC HOUSE power on
digitalWrite(power2,LOW);  // DC HOUSE power on

The problem is that it continues to say "power off" and doesn't overwrite it.

I can see from the Serial Monitor that the program is running fine, but the LCD doesn't change after the first set of lcd.prints at those character positions.

I haven't heard of anybody having this problem, but perhaps someone out there know about this.   Any suggestions would be very welcome.

Question is:  How can I make the LCD update lines that have been originally written?

UPDATE:  Problem solved by simply clearing and rewriting the display when things change.  I can't debug libraries but at least it is working now.

Ah ha.   I solved it by using lcd.clear() and simply repainting the entire display with every change.  I have much simpler LCD programs that don't require doing this, but it worked in this instance.

Same code as above, but with this before each power notification:

lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

etc...

UPDATE:
  Now that I have two 20x4 LCD screens showing readings from two separate Arduinos (PV Controls and Weather station) I have discovered that it is very important to keep the screen writes to a minimum.  No time delays in between writing parts of the screen, for instance (like when I had Serial.print statements in there for debugging), doing all the readings and calculations before writing the screen, and timing the screen updates to be infrequent, like on the order of 65 seconds for weather and 10 minutes for the PV.  I2C does not have collision detection so it is important to try to prevent the two screens from being updated at the same time.  The I2C&Power arrangement is working great.  One source of power is all it takes to activate the entire network.


Input voltage from circuit drops despite Arduino turned off I'm using an Arduino Uno to emulate an old Atari disk drive as described here:
http://whizzosoftware.com/sio2arduino/

As both the Atari and the Arduino use 5V TTL serial communication, the hardware setup is pretty simple, RX and TX are crossed over, GND is connected an an additional line is used for status information.

All works fine when the Arduino is the only device connected to the Atari's serial port (called SIO). Since the SIO bus is a daisy-chain bus, I should be able to hook up serval devices after each other. However, once I connect an original floppy drive together with the Arduino, both the original floppy drive as well as the one emulated by the Arduino stop working.

What made me wonder is that the original drive couldn't be accessed even if the Arduino was turned off but the wiring left in place. Only after I removed the RX and TX pins from the connection, the original drive could be accessed.

I checked with a scope and realized that data transmission was still reaching both devices, however idle voltage was just around 2V instead of 5V. I then checked the resistance on the Arduino between the digital input pins as well as RX/TX in relation to GND and got (varying, depending on the scale I set my multimeter) values that probably have the effect of a voltage divider and thus reduced the voltage on the whole bus by about half.

I was thinking to add a resistor on the RX/TX lines coming from the SIO bus in order to maintain the voltage on the bus, but that would effectively mean that also less current reaches the Arduino RX/TX pins and might therefore render it useless if the voltage drops below the point where the Arduino can distinguish between logical high and low.

Or is there a way to circumvent these internal resitors between the digital inputs and GND? Does this have anything to do with the pull-up/pull-down resistors which I could probably only influence when the Arduino is on?

Thank you in advance for any pointers (other than adding another switch to physically remove RX/TX from the bus when the device is off ;) )!

To protect the internals of integrated circuits many contain diodes at most input and output pins to VCC.  In normal operation where the voltage at these pins are not expected to become greater than VCC, these diodes are not in forward bias.  However, should the unexpected happen and the voltage at these pins does become higher than VCC the diodes are in forward bias.
 That is to say, the diodes try to keep the voltage at the pin no higher than VCC.

When you removed the power from the Arduino you essentially lowered VCC to zero.  This will likely forward biased the diodes inside the Arduino and drive the voltage at the pin toward zero.

There is a good discussion of this in this Electrical Engineering StackExchange question & answer.


I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))) Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

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

I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails.
I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.
The code that I'm trying to upload:
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

My settings:

EDIT: Also, I want to add one more thing when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

You need to set esp 8266 to flash mode.
Please connect en PIN to Gnd pin.
Then flash again.