Unable to send data from Processing to Arduino through ports I'm just beginning to use Processing along side with Arduino and need help linking the two. Just to get started, I just wanted to send a single character (eventually strings) to the Arduino and have the Arduino light up a matrix if the Arduino receives the data.

Here's my code for the Arduino (I'm using an Arduino Uno):

#include <Adafruit_GFX.h>   // Core graphics library
#include <RGBmatrixPanel.h> // Hardware-specific library

// Set up the matrix
#define CLK 8
#define LAT A3
#define OE  9
#define A   A0
#define B   A1
#define C   A2
RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

int incomingByte = 0;   // for incoming serial data

void setup() {

  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  matrix.begin();
}

void loop() {
    if(Serial.available() > 0) {
    incomingByte = Serial.read();

    // Print a white "Done!" to the matrix
    matrix.setCursor(1, 0);
    matrix.setTextSize(0);
    matrix.setTextColor(matrix.Color333(7, 7, 7));
    matrix.print("Done!");

  }
}

And here's the code for Processing:

// Example by Tom Igoe

import processing.serial.*;

// The serial port:
Serial myPort;

// List all the available serial ports:
println(Serial.list());

// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[1], 9600);

// Send a capital "A" out the serial port
myPort.write(65);

I run the processing sketch and then upload the code to the Arduino, but get nothing. The Arduino is using COM3 and I believe the Processing sketch is too, but that may be where I'm messing up.

If I open up the serial monitor and send some data to the Arduino that way, then the LED lights up fine, but only when I do it through that.

Any help would be appreciated. Thanks!

When you open a serial connection to Arduino Uno the atmega328 microcontroller is usually reset(this depends if the OS is configured to toggle the DTR serial control signal on/off when a port is opened). Just after a reset the bootloader (optiboot) runs to see if you are trying to upload a new sketch. If the bootloader doesn't receive any meaningful communication it will start your sketch after ~1 sec. All communication sent to the serial port while the bootloader is running is lost.

When you use the serial monitor you are too slow to notice the 1 second where the board won't respond to your commands. But the processing sketch is another story.

The easiest fix will be to insert a delay after you open the serial port and before you send any data.

// Wait 1.2 sec
int start = millis();
while (millis() - start < 1200);

If you would rather use a hardware fix you can connect a 10uF capacitor between RESET and GND pins that will prevent the board from being reset by the usb to serial converter.


Stop Arduino Timer after some seconds I'm building a basic program that when a button is pressed, a buzzer comes on.

I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).

Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.

// Setting The Pin Numbers
const int touchsensor = 2;     // the number of the touchsensor pin
const int buzzer =  4;         // the number of the LED pin

// variables:
int touchsensorState = 0;      // variable for reading the touchsensor status

void setup() {
  // initialize the buzzer as an output:
  pinMode(buzzer, OUTPUT);
  // initialize the touchsensor as an input:
  pinMode(touchsensor, INPUT);
}

void loop() {
  // read state of the pushbutton value:
  touchsensorState = digitalRead(touchsensor);

  // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
  if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
  } else {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
  }
}

You set a timestamp = millis() when the button is pushed and then you disable the buzzer only when millis() - timestamp > timeout

if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
    timestamp = millis();
}
if(millis() - timestamp > timeout) {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
}


Joining several PIR sensors I wish to use some PIR (HC-SR501) sensors and give some response if at least one of them detects human movements.
For simplicity I wish to use only one input pin in an Arduino UNO. My idea is to connect all the output wires into a single Arduino digital input. Should it work?
I am in doubt because the following two reasons:

The sensors must be far away from each other (about 5 sensors partially covering an area of about 200 m^2). That implies that wires are long and I do not know if this can have some adverse effect.
I do not know if it is bad to supply the 3.5V of some sensor that is currently detecting movement to the output of the sensors that are not detecting anything.

Thanks in advance

The BISS0001 that your unit uses provides an "active high" output. To connect multiple devices together you just need to "OR" the signals.
There's many ways of doing that.
The simplest method is the "wired OR" circuit, which just involves one pulldown resistor plus one diode per device:

simulate this circuit – Schematic created using CircuitLab
You could also use a multiple-input OR gate chip. You can get these in 2- (74HC32), 3- (74HC4075), 4- (74HC4072) input versions.


Locking ATmega328 from reading back the hex file I want to completely block the access to an ATmega328. How do I do this?

I have Atmel ICE, AVR studio 7 and Arduino.

Bootloader - optiboot_atmega328
Fuses(without lock) - 0x05, 0xDE, 0xFF

Steps I am executing:

Program fresh ATmega328 with bootloader using Atmel Studio.
Burn the fuses as mentioned above.
Go to Arduino and program the code.
Come back to Atmel Studio >> lock bits >> enable no further programming and verification.>> Fuse bits>> disable reset.

Is the above way OK? Or should I add something to the above?

I have programmed the fuse bit with "Further programming and verification disabled". I read out the hex file and it does not match even I programmed the same hex into a different micro and it didn't work. This seems to be fine. But will high Voltage programmer brick this wall?

Note: When I program the above fuse bit. I am unable to disable the RESET or SPI. It says one or more register differ

I want avoid a readback via high voltage programmer too.

I have too many people to steal my code I want to avoid it. Kindly help

Siddharth

Locking out programming prevents writing, and locking out verification prevents reading, via all programming methods.

Note that there is no way to prevent erasing the chip, which will clear both the lock bits and the flash.


Garbled high bits on serial output I'm trying to send the byte 0x5A (0b01011010) on the serial output of an Arduino Due. My program is based on this example project, but I've stripped out all the unrelated parts:

#![feature(lang_items)]
#![no_std]
#![no_main]

extern crate sam3x;

pub mod rust_base;
use sam3x::*;
use sam3x::hal::peripherals::{Peripheral};
use sam3x::drivers::led::{Led};
use sam3x::hal::rtt::{init_timer, wait_ms};
use sam3x::hal::pmc;
use sam3x::hal::uart;

#[link_section=".vectors"]
pub static VECTOR_TABLE: VectorTable =
    VectorTable {
        reset_handler : start,
        exceptions    : [0; 14],
    };

fn start() -> ! {
    init_timer();
    pmc::enable_peripheral_clock_0(Peripheral::PioC);

    let led = Led::connect(Peripheral::PioB, 27).expect("Wrong pin for led.");
    let tx = uart::Tx::init(uart::BR_9600);

    let mut led_on = true;
    led.on();
    loop {
        tx.write_byte(0b01011010);

        wait_ms(250);
        if led_on {
            led.off()
        } else {
            led.on()
        }
        led_on = !led_on;
    }
}

As you can see, all I do is send out the byte 0x5A four times a second, with some LED blinking just to show the program is running.

My problem is that if I connect a serial terminal program with 9600-8N1 settings, I am not getting 0x5A; instead, I am getting mostly 0xBA, and sometimes a 0x9A slips through.

Writing out the bits:

0101 1010    5A
1011 1010    BA
1001 1010    9A

Note that the lower nybble is always correct, which is why I don't think it's a serial communication setting issue; also, it's pretty clear from uart::Tx::init's implementation that it defaults to no parity bits.

It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

  It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of 0x5A on my PC receiving at 9600).


Playing MP3 Shield tracks I have an MP3 shield on a Arduino Uno. When using "File Player" I can get the tracks to play by keyboard entry with three digits (001-009).

The problem is that I want to use (SFEMP3Shield > examples > MP3ButtonPlayer2) that is looking for files 1-9. Any file numbers other than 1,2,3,4,5,6,7,8,9 doesn’t work. Any suggestions?

The playTrack function used in MP3ButtonPlayer2 example plays file with name created with printf format "track%03d.mp3". %03d creates a number prefixed with zeros to lenght 3. For example track005.mp3 or track042.mp3 or track999.mp3.

implementation of the playTrack function:

uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

  //a storage place for track names
  char trackName[] = "track001.mp3";
  uint8_t trackNumber = 1;

  //tack the number onto the rest of the filename
  sprintf(trackName, "track%03d.mp3", trackNo);

  //play the file
  return playMP3(trackName);
}

change it to:

uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

  //a storage place for track names
  char trackName[13];
  int trackNumber = trackNo;

  //tack the number onto the rest of the filename
  sprintf(trackName, "track%03d.mp3", trackNumber);

  //play the file
  return playMP3(trackName);
}


Error when trying to write analog and digital signals from different pins (Arduino UNO) I'm using the Arduino UNO and started noticing some funny behavior when I was trying a few basic projects. Specifically when trying to write an analog signal through one of the PWM pins, then a digital signal through another.

Using some LED's connected to a few different permutations of pins 8-13, I found that when I have an analog output set for one of the pins (in this case 9, 10, or 11 as they're the only one's of the set capable of PWM) and then try to output a digital signal from a different pin to another LED the digital signal seems much weaker. That is, the LED shines very very dim.

The pins 2-7 work fine.
Does the behavior described above indicate anything wrong with the arduino? are those pins potentially damaged, or is there something I'm not understanding here?

My code:

void setup()
{}

void loop()
{
   analogWrite(9, 255);
   delay(1000);
   analogWrite(9, 0);
   delay(2000);
   digitalWrite(8, HIGH);
   delay(1000);
   digitalWrite(8, LOW);
   delay(2000);
}

I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.

analogWrite does this for you automatically in the library, however digitalWrite does not. This is because sending a digital pin HIGH when it is INPUT turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to setup:

 pinMode (8, OUTPUT);

(And preferably pin 9 as well, just in case you decide to change to digital writes later).


What does "+=" mean? I'm working with an esp8266 and want to have it default to an access point when it cannot connect to a wifi network.  I'm using chriscook8's example from github here.

chriscook8 uses "+=" in several places and I can't find an explanation of what that means.

Here is an example from setup():

void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
  {
    esid += char(EEPROM.read(i));  //<- here
  }

What does += do?

It adds the value or variable on the right to the variable on the left and assigns the result to the variable on the left.

A += B

is the same as:

A = A + B

It's short-hand.

In the case of a String it concatenates the right hand item on to the end of the left hand item.


ESP8266 and Interrupts - not possible? I'm planning to use an ESP8266 (Wemos D1 Mini) to use as a software SPI monitor to send over WiFi.
As a test, I've done a cut-down sketch that just counts the interrupts, a simple frequency counter. I've made it as simple as possible but it won't stay connected to WiFi and crashes after about 10 seconds.
The input signal to CLKPin is 6667Hz.
Here's the sketch:
#include <ESP8266WiFi.h>

const char* ssid     = "SSID";
const char* password = "PASSWORD";

long nextPrint = 1000; // when to print the next message to serial

const int CLKPin = 5; // Pin connected to CLK
volatile long ClkCount = 0; // number of times clock interrupt has fired

void CLK_ISR() {
  ClkCount++;
}

void setup() {
  Serial.begin(115200);
  long startTime = millis();

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to wifi");

  attachInterrupt(CLKPin, CLK_ISR, RISING);

  //Set the CLK-pin to input
  pinMode(CLKPin, INPUT);
}

void loop() {
  if (millis() > nextPrint) {
    Serial.print("Freq is: ");
    Serial.println(ClkCount);
    ClkCount = 0;
    nextPrint += 1000;
  }
  yield();
}

It always gets in a reboot/crash loop (no idea why the first few counts are wrong - I guess the ESP isn't ready yet):
Connecting to SSID ...
.Connected to wifi
Freq is: 1
Freq is: 1
Freq is: 0
Freq is: 0
Freq is: 1
Freq is: 0
Freq is: 2313
Freq is: 6667
Freq is: 6666
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667
Freq is: 6667

Exception (0):
epc1=0x40202034 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: sys
sp: 3ffffc40 end: 3fffffb0 offset: 01a0

>>>stack>>>
3ffffde0:  401067da 00000026 00000000 00000001
3ffffdf0:  c0017025 3ffe8d04 3ffee188 00000001
3ffffe00:  00000003 00000008 3ffee99c 00000022
3ffffe10:  3fffc200 401067a0 3fffc258 4000050c
3ffffe20:  40004384 00000030 00000012 ffffffff
3ffffe30:  60000200 00000006 30043003 80000000
3ffffe40:  20000000 3fff0c38 80000000 203fc120
3ffffe50:  00000000 3fffc6fc 00000001 3fff0c3c
3ffffe60:  00000154 003fc120 60000600 00000030
3ffffe70:  40106845 00000080 00000022 3fffc200
3ffffe80:  c0017025 3fffc258 4000050c 00000022
3ffffe90:  3fffc200 401067a0 3fffc258 00000022
3ffffea0:  3fffc200 401067a0 3fffc258 4000050c
3ffffeb0:  40202b20 00000030 00000012 ffffffff
3ffffec0:  40000f49 3ffee9e8 00000000 3fffd9d0
3ffffed0:  00000000 00000000 00000000 fffffffe
3ffffee0:  ffffffff 3fffc6fc 00000001 3fffdab0
3ffffef0:  00000000 3fffdad0 3ffee9e8 00000030
3fffff00:  3ffee99c 0000000a 3ffe8bc8 402094cc
3fffff10:  00000000 400042db 3ffeff84 40104580
3fffff20:  40004b31 3fff0b84 000001f4 003fc080
3fffff30:  40105aac 000001f4 3ffed190 401004f4
3fffff40:  40106e4d 3fff0b84 00000000 00f8676f
3fffff50:  3ffe8bc8 3ffe8d04 3ffed190 40224d02
3fffff60:  40223d49 40223d52 3ffed004 3ffee1b0
3fffff70:  40228445 3ffed004 3ffee1b0 00f857fe
3fffff80:  4022848a 3fffdab0 00000000 3fffdcb0
3fffff90:  3ffee1c8 3fffdad0 3ffee9e8 40202b43
3fffffa0:  40000f49 40000f49 3fffdab0 40000f49
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

What am I doing wrong, or is it just not possible to stay connected to WiFi while using interrupts on an ESP8266?

Yes possible, but the ESP8266 only has one core and one set of peripherals. WiFi uses time, interrupts, and even the ADC peripheral, and maybe more.
This is why anything timing-critical, or time-intensive, is a pain to get to work properly on an ESP8266. It depends one what you are trying to do, of course, and also on if you can unload what you want to a peripheral the WiFi doesn't use, or if switching off WiFi is an option during parts of your code.
Generally, for applications such as yours, I would get an ESP32 or an Arduino Nano 33 IoT or any other solution that has a core for handling WiFi, and a core for you to use without restrictions. It makes development a more pleasant experience.
If, for some reason, you are bound to using an ESP8266, you would have to be more specific about what your eventual goal is; maybe a workaround can be found.


Serial communication between PC and Arduino using C I'm trying to send some data to my arduino mega 2560 using serial communication.

I'm using the exemple that I found here without success.

Every site I read say that I can send data to the arduino board like writing to any file on ubuntu.

But I alway get Segmentation fault

Here is my code

#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};

  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

Your program works flawlessly on my Ubuntu 18.04. I would guess that you
have a problem with your setup (flaky USB port, permission problems...)
rather than the program itself. Still, I would recommend you add some
error checking: right after the fopen() call,

if (!usb_port) {
    perror(arduinoPort);
    return 1;
}

I would expect you see something like

/dev/ttyACM0: No such file or directory

or

/dev/ttyACM0: Permission denied

that could help you pin down the real problem.


WiFi Password Safety Are there any best practices regarding password safety?  The following is taken from a wifi tutorial sketch.

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "yourNetwork";      // your network SSID (name)
char pass[] = "secretPassword";   // your network password
int keyIndex = 0;                 // your network key Index number (needed only for WEP)

While I accept that the tutorial is there for learning how to use the shield, I would assume hard coding the password into the sketch leaves this open to attackers.  Is this actually the case?  If so, are there any strategies to harden the sketch, for example with encrypted storage?

I am a relative newbie with physical computing and Arduino, so sorry if I am overlooking something obvious.

You're actually entering into a very tricky and difficult area.

Yes, having a plain text password in your sketch is a risk. It is stored in flash as plain text. If an attacker can gain access to the contents of the flash through some means (whatever they may be) then they could obtain that WiFi password.

You would think that encrypting the password would be the answer, but that's not the case. The problem with an encrypted password like this is it has to be decrypted to use it. That means that both the encrypted password and the encryption key are both stored together in flash. If you can get one you can get the other, and thus the encryption is null and void.  Encryption security relies on keeping the encrypted data and the key used to encrypt/decrypt it completely separate. After all, you don't leave the key to your house in the front door lock when you go out, do you? It's exactly the same.

So what do you do?

Well, there's lots of different ways of looking at security. In this case there is one specific viewpoint that works best:

Security Through Obscurity

Your system is (pretty much) unique. Nobody but you knows just what it does and how it does it, or how you interact with it. It's not obvious to the casual observer just what it is or what could be done with it. That means that they won't know how to break in to it.

The majority of use of vulnerabilities in systems rely on those systems being ubiquitous - that is, all over the place; easy to obtain. In short, easy to find out what they are, how they work, and even reverse engineer them to a certain extent. Attackers aren't going to be able to do that with your system, since you are the only person in the world with it.

However, it's far from perfect, and you shouldn't rely only on Security Through Obscurity.

Simple obfuscation of the password (not actual encryption, but just storing it in a way that isn't obvious) can help, since it isn't then easy to see where in a memory dump the password would be. Splitting it up and scattering it around the place, too, can be useful.

Basically there is no simple answer, other than make it as hard for an attacker to find sensitive things as possible and don't tell anyone what you have done to hide it ;)


CH340G Uploading problem I've tried to copy CH340G from other schematics and existing Arduino Uno Clones...
Searched online & StackExchange but no good :/ My problem is almost the same as this one

Here is my schematic

I can read & send data from the serial monitor

OS: Win 10 64 Bit
USB Driver: 3.5.2019.1

Upload Options:

Arduino IDE version: 1.8.12
Board: Arduino Uno (also tired nano & nano old bootloader options)

What I've tried:

With & without the driver
Rebooted the computer
Tried different ports
Different cables
In case of IC not working, I've desoldered IC from working UNO
Changed RX, TX vice versa
Without R1 & R2
Different capacitors on C6 and C3
Buuut results are always the same as below

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf3

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I appreciate any help, idea, suggestion
Regards

The schematic is totally working. My mistake was after burning bootloader, I was uploading code via ISP. If you upload code via ISP, you're removing bootloader.

Thank you everyone who helped me to I wasn't mistaken at schematic and else...


Is it possible to setup a system based on Arduino Due running QNX? I would like to create some QNX applications and test them in a hardware different than my virtual machine. Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

What would be the challenges to make it work?

Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

Please see the BSP list.

Cheers!


Analog output low voltage issue, how to troubleshoot I have connected my arduino according to the schematics in the image, with a few additions.

The setup

A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.
A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)
A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)
A Potentiometer connected to A1, 3,3V and GND.

Code description:
Using the Timer and the LiquidCrystal_I2C library,
Once every other second the LCD is refreshed
Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.

The issue.

It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.

I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)

What have I already tried

I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)

Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?

Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...

If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.

analogWrite is PWM on digital ports and doesn't work on analog ports
analogWrite reference

use digitalWrite


How to connect a 240x320 37-pin TFT to an Arduino Nano? I have an old TFT display (extracted from an MP5 player) and I can't figure out how to connect it with an arduino nano, pls help.
here's the datasheet of the TFT:
http://read.pudn.com/downloads137/sourcecode/embed/586271/Varitronix-2.8-lcd/vl-ps-cog-t280mbqi-041.pdf
Thank you.

The Nano isn't a good choice for driving that screen. You need almost all the pins of the Nano to connect to the screen alone, and there's not enough to include the touch-screen as well. And that's when you're not using the serial port of the Arduino (TX/RX pins) for communication with the PC.

You need to connect:

16 data pins
/CS pin
/RS pin
/WR pin
Optionally RD pin, or tie it to 3.3V
/RESET pin

And all those need to be level shifted to 3.3V.

You need to provide 3.3V to VCC1/2 and VCI.  The LED A connects to 5V (since it has more current capacity than the 3.3V) and each LED Kx pin through a suitable resistor (220Ω maybe) to ground.

The touchscreen needs the X- and Y- pins connecting to a digital IO pin, and the X+ and Y+ pins to analog IO pins that can also double as digital IO pins (so not A6/A7 on boards that have them).

And then you need to obtain or write the software to drive the ILI9320 through the 16-bit interface.

Driving the interface is simple enough:

Initially:

Set /CS HIGH
Set /WR HIGH
Set /RD HIGH (if not tied to 3.3V)
Set /RESET HIGH
Short delay
Set /RESET LOW
Short delay
Set /RESET HIGH

Then to transfer a group of 16-bit words:

Set /CS LOW
Set the value to write on the 16 data pins
Pulse /WR LOW then HIGH
Repeat from 2 for each word
Set /CS HIGH

Refer to the ILI9320 datasheet for how to control the chip, or use existing library code (does uTFT or u8glib support it?).

For the touch screen it's a case of setting Y- LOW and Y+ HIGH, and X- and X+ to INPUT, then reading the analog value from X+.  Repeat with X- set LOW and X+ set HIGH, and both Y set to INPUT, and read the analog value from Y+.

You can also get better results by reading multiple inverted settings:

Y- = LOW, Y+ = HIGH, X- = INPUT, Read X+.
Y- = HIGH, Y- = LOW, X- = INPUT, Read X+.
Subtract the second reading from 1023
Add the first and (modified) second reading
Divide by two.
Repeat for X-/X+ reading from Y+.

You can also take multiple readings and average them out to reduce noise and stabilise the output somewhat.

And of course on top of all that you need to find a way to connect to a 0.5mm pitch connector. Normally a 0.5mm pitch FPC socket is used, which means a PCB with one on.  You may be able to find 37 pin adaptor for it, but 37 pins isn't a common format.  Normally 50 pin is more common to accommodate a more general purpose interface including the M0-M2 pins that allow you to select the interface type, as well as an 18-bit data bus to allow full RGB6/6/6 interfacing, and even buffer-less clocking of raw display data for very high speed display updates by MCUs that support such an interface.


Reproducing a Fiber Optic Shape Sensor with Arduino? I want to be able to track the curvature of a human arm as it straightens out and retracts (ex: like live tracking a bicep curl). I don't want to use resistive flex sensors.

I've been trying to find suppliers for this technology demoed here: https://www.youtube.com/watch?v=iAeXp-TpFLU&t=38s

But I cant seem to find anyone who sells directly to consumers. I was thinking about creating a hobbyist level version my own using fiber optic wire, a led, and a light wavelength sensor, using a more powerful Arduino such as the Intel Edison. I have a basic understanding of how this technology works, but I want to learn by attempting to create it.

Is this practical or possible with an Arduino?

if so:

Are these the correct materials I would need?

if not:

Why not?
What kind of equipment would I need to achieve this?
Is there anywhere to buy this sensor directly?
Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I think nobody here can really give you an answer, if this is possible with an Arduino, since we don't know enough about the technology and the nitty gritty things, that make this a difficult task. So making a hobbyist version won't be easy and maybe really expensive.

In the fiber each bragg grating reflects a bit of the light back. The wave length of this reflected light is dependend on the angle between light and grating. So you get a specific wave length back from each grating, that corresponds to the bending at that particular part of the cable. The task is to measure the many wave lengths, that are being reflected in the fiber, and match them to a particular part of the cable. Since they don't say, how they are solving this, I will mention some ideas here:

Spectral Measurement (Wave length):

From the video I guess, that they use white light to shine into the cable. The gratings will only reflect the wave lengths from this spectrum, that satisfy Bragg's law due to bending angle. You have to measure the wave length directly with a spectrometer. Mostly this is another grating, that will seperate the wave lengths spatially, so that you can measure the spectral structure by using a spatial sensor, for example a camera or a line sensor. You would have to correct for different wave length sensitivities of the camera.
Maybe they are only using a laser with 1 wave length. Then the bending would result in a change in intensity reflected from that grating. If you can seperate the signals from the different gratings good enough, you would be able to measure just the change in intensity, which would be easier, since you basically need just a photo transistor or similar for that wave length. (In this case you would need to calibrate the sensor each time as a straight cable and ensure, that the measurement is fast enough for the expected movement).

Matching of signals to each part of the cable: Here I guess, that they use a time-of-flight sensor, because I cannot think of anything else without further information. This is a really difficult problem, because most available sensors are not sensible enough for measuring quarter inches without being cheap in the first place. You will likely spend a lot of money for a sensor like this. And you building an own time-of-flight sensor with the wanted sensitivity may be as difficult as building the whole device in the first place.
Needed Parts: Also you will need the fiber itself, which is - as stated - not a normal glas fiber, which you can by everywhere. It is most likely a custom build and you will pay a lot of money, to get one of these. The light source is dependend on the spectral measurement above. For a white light it is important, that all wavelength should have as equal intensity as possible. You would also have to account for the spectral absorption and the overall absorption in the fiber, which restricts the sensitivity and possible lengths.

  Is there anywhere to buy this sensor directly?

Most likely not. In the videos it seems like a device, that was developed by the NASA for a specific application. The video is a proposal for other companies to learn from the NASAs development, so the device is not consumer ready. But you might be able to get a paper about this device by searching the internet for it or by asking the NASA directly. This paper would contain way more information about the device as the videos.

All in all this would be an extremely difficult task. Since you came here (a simple Q&A site) with this difficult question, I think, that you are not really ready for this big of a task. Most likely even the developers at the NASA needed long and much money for this.

  Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I would propose to build a string of bending strips, which change their resistance according to the bending angle. You can use multiple strips for getting multiple readings for different parts of the human arm. With each strip you build a voltage divider and do an analog measurement. With a bit of calibration you should be able to measure the curls.


Open Parent Class as Child Class (SD Fat Library) I'm currently using the SDFat library and am passing a global FatFile

I if have a function that requires an SdFile type and I know that a given instance of FatFile is a valid SdFile what is the best way to reopen FatFile F as SdFile J?

Right now I'm doing:

SdFile ActiveFile;  //Global Active File
...
void SDRun (FatFile &RunFat)
{
  SdFile RunRoot;
  RunRoot.open("/", O_READ);
  ActiveFile.close();
  ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
  ....

However, this only works when RunFat is in the root directory.

If RunFat is an instance of SdFile you can just cast it:

SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

RunRoot and RunFat are now the exact same file in the exact same state (no need to open it or anything) but seen as an SdFile not a FatFile.


HC-SR04 distance measuring without delay? I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.

  long duration;
  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that delayMicroseconds() pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.

class distSensor{
   int trigPin;
   int echoPin;
   int distance;

   //Will be used in timer
   unsigned long previousMillis;

   public:
   distSensor(int tPin,int ePin){
   trigPin = tPin;
   echoPin = ePin;

   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   previousMillis = 0;
 }

 int calculateDistance(){

  //records time since program start
  unsigned long currentMillis = millis();

  long duration;
  digitalWrite(trigPin, LOW);

  //check if the previous time the method was called is greater than the interval of 2
  if(currentMillis - previousMillis > 2){
    digitalWrite(trigPin, HIGH);
    previousMillis = currentMillis;
  }

  //check if distance between current time and previous time it was called is greater than interval of 10.
  if(currentMillis - previousMillis > 10){
      digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  }
  return distance;
 }
};

In the calculateDistance() method I am trying to do the same thing as the first code but without delay() and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

delay() causes the processor to do nothing but wait.  You need to switch to millis().

In your code, you need to "grab" the current time using millis() and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what millis() returns.  When your stored value and millis() match, it is time to execute the code that would normally come after the delay() call.

Here, Arduino Playground - How and Why to avoid delay(), delay() and millis() are discussed in detail.

So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.


Running ADC triggered by TIMER1_COMPB I'm trying to run ADC on channel 0 triggered by TIMER1_COMPB.
Everything seem to work ok but basic arithmetics is not working and variables inside ISR and even main loop don't get updated (x == 2 all the time)

Can somebody explain me why is it so? Even volatile variable was not changing...
Arduino UNO,
IDE v 1.8.6

#define SAMPLES_SIZE  205

const int adc_channel = 0;
const uint16_t t1_load = 0;

// 250 corresponds to 8kHz
const uint16_t t1_comp = 25000;

uint16_t samples[SAMPLES_SIZE];
volatile uint8_t samplePos = 0;

static int x = 0;

void initADC() {
  // Init ADC free-run mode; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void initTimer() {
  // Reset Timer1 Control Reg A
  TCCR1A = 0;

// Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

// Set prescaler to 8
  TCCR1B &= ~(1 << CS12);
  TCCR1B |= (1 << CS11);
  TCCR1B &= ~(1 << CS10);

// Reset Timer 1 and set compare value
  TCNT1 = t1_load;
  OCR1B = t1_comp;

// Enable Timer 1 compare interrupt
  TIMSK1 = (1 << OCIE1B);
}

void setup() {
  cli();
  initADC();
  initTimer();
  sei();

  Serial.begin(115200);
}

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish
  cli();
  x = x + 2;
  Serial.print(samples[0]);
  Serial.print("\t");
  Serial.println(x);
//  for (int i = 0; i < SAMPLES_SIZE; i++) {
//    Serial.println(samples);
//  }
//  samplePos = 0;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
  sei();
}

ISR(ADC_vect) {
  int16_t sample = ADC;

  samples[0] = sample;
//  samplePos++;
  ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off

  if(samplePos >= SAMPLES_SIZE) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

//ISR(TIMER1_COMPB_vect) {
//}

Thanks in advance

I've found the solution, it's strange since I enabled CTC mode, but it started to work normally as soon as I reset Timer 1:

ISR(TIMER1_COMPB_vect) {
  TCNT1 = 0;
}


How to connect to MQTT broker with TLS? I have ESP8266 which is connecting to MQTT broker and it is working ok using user+pass with following code:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "WIFINAME";
const char* password = "WIFI_PASS";

const char* mqtt_server = "SERVER_IP";
const char* mqttUser = "user";
const char* mqttPassword = "pass";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, 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)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str(), mqttUser, mqttPassword)) {
      Serial.println("connected");
      client.subscribe("CoreElectronics/test");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

As this is insecure usage I have setup TLS on MQTT broker and I can connect over command line:

mosquitto_sub --cafile ca.crt -h server_ip  -t "#" -p 8883 -d --cert client.crt --key client.key

Problem is that I cannot find any working (for me) sample with using TLS connection on ESP8266 client.

I have tried generating self-signed certs by manually script and over LetsEncrypt.

Thank you

You could make the following changes to your code by making use of WifiClientSecure (which is already part of the ESP8266 Wifi library).

The tricky part is finding out the SHA1 fingerprint for your own MQTT server and hard coding it into the *fingerprint PROGMEM = "..."  part (for example by examining the certificate via a PC browser and copying the SHA1 fingerprint).

Alternatively, you could set the connection to setInsecure. This means that the connection will be encrypted but it will accept any server certificate without checking.

...
const char* mqttPassword = "pass";

WiFiClientSecure espClient;     // <-- Change #1: Secure connection to MQTT Server
PubSubClient client(espClient);

// Change #2: Set the SHA1 fingerprint for the connection -->
static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";
...
...
void setup() {
    ...
    setup_wifi();

    espClient.setFingerprint(fingerprint);   // <-- Change #3: Set the SHA1 fingerprint
    // Alternative: espClient.setInsecure;

    client.setServer(mqtt_server, 8883);  // <-- Change #4: Set the port number to 8883
    client.setCallback(callback);
 ...

Good luck!


Why does using ESP8266 in deep sleep mode still drain the battery quickly? I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to this post it should last at least a year.

I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.

#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid     = "xxxx";
const char* password = "xxxx";

const char* host = "xxxx";

void setup() {
  Serial.begin(115200);
  dht.begin();
  delay(10);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  readSensorsAndPost();
  ESP.deepSleep(18e8); //30 minutes
}

void readSensorsAndPost() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  char charVal[10];
  dtostrf(t, 5, 2, charVal);
  makeAnHttpRequest(charVal);
}

bool makeAnHttpRequest(String msg) {
  //send the value
}

void loop() {

}

The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).

I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.

Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?


Working with multiplexers for constant voltage output I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of LED rope on and off at a time using an Arduino and a multiplexer.

With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.

What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.

Below is my current Arduino sketch:

//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

}

void loop(){

  //Loop through and read all 16 values
  //Reports back Value at channel 6 is: 346
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer

Happy to start offer a bounty to a helpful answer.

Thank you

Even I am new to this and I also find it a bit challenging with the available setup and desired output. Though it seems tough, I want you to just try out this code (it is a little modification to the one posted by you) and check whether it matches the expected result.

    //Mux control pins
#define s0 8;
#define s1 9;
#define s2 10;
#define s3 11;

//Mux in "SIG" pin
#define SIG_pin 3;

#define testValue 255;  //maximum value for analogWrite() function

void setup()
{
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop()
{
  //Loop through and read all 16 values
  for(int i = 0; i < 16 ; i ++)
  {
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel)
{
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]=
  {
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++)
  {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  for(int i_testValue = 0; i_testValue < testValue; i_testValue++)
  {
    analogWrite(i_testValue, SIG_pin);      //incresing intensity slowly with delay of 100ms
    delay(100);
  }

  //return the value
  return 0;
}


What exactly does the return type do in a function? something I've never understood and still don't is, what does the return type do specifically? Everyone in tutorials just say that void returns nothing and int returns int, etc. But what does that mean? Where is it returning to?  I can't seem to understand what everyone's talking about when they discuss functions.

It returns it to whatever the function is being assigned to.
Take the function:
int plus(int a, int b) {
    return a + b;
}

That function takes two integers, adds them together, and "returns" them as an integer.
You can then do:
int c = plus(3, 4);

and c will be handed the value 7 by the function.
Equally you can do:
Serial.println(plus(3, 4));

And the Serial.println() function will be handed the value 7 for printing.
The type of the return defines the kind of data that can be returned.
Oh, and void doesn't mean "returns nothing", but means "doesn't return anything" - which means you can't assign it to anything since there's nothing returned to assign.


New Microcontroller - programmer is not responding - I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.

I get the following:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.

Did I buyed a bad/wrong MC, or I need to make something else?
Both have the same name :

ATMEGA328P-PU

The new micro controller has already a boot loader installed.

I managed to fix the problem by downloading the latest version of the Arduino IDE from their website and works fine now.

I use Linux mint 18 and installed Arduino via apt and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.


Ultrasonic sensor showing weird reading When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below

#include <NewPing.h>
#include <AFMotor.h> //import your motor shield library

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
AF_DCMotor motor2(2, MOTOR12_8KHZ);

int distance;

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

void loop() {
  delay(50);
  distance = sonar.ping_cm(); // start the scan
  delay(20);
  if (distance < 2) {
   Serial.println("Close Obstacle detected!" );
   Serial.println("Obstacle Details:");
   Serial.print("Distance From Robot is " );
   Serial.print(distance);
   Serial.print( " CM!");// print out the distance in centimeters.
   delay(10);
   Serial.println (" The obstacle is declared a threat due to close distance. ");
   Serial.println (" Turning !");
   motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
   motor2.run(BACKWARD);

}
  else {
   Serial.println("No obstacle detected. going forward");
   delay(15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
   motor2.run(FORWARD);
  }
}

Test code for sensor which worked:-

#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Tell me whats wrong here

Motor Shield used below
Wiring of sensor is connected to Arduino below the shield

Try with

unsigned int distance;

Instead of

int distance;

It could also be the motor shield that is using the same pins as your ultrasonic sensor.


Arduino Due not executing code after power on My Arduino Due does not execute its code when powered on after being powered off for ten seconds or longer. I have to press the reset button for the code to execute.

I've read some older threads about a firmware issue and saw people doing solder jobs on their boards to fix it.

My question is, does this issue happen with all/any Arduino Due boards? Are just some clones (like mine) affected and the original works fine?

What's the best way to fix this problem? In this state the board serves no purpose anymore and I've downgraded to the Uno for now.

EDIT: Adding picture and link to the board used.
https://www.amazon.de/gp/product/B016D5KYF6/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

After some more research I found out that

a) the issue applies to some Due boards only, not all

b) newer boards seem to have fixed the issue

c) there's a software (firmware update) and hardware (10k resistor) solution

I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/

I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

addendum:

The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.

The fix is simple: you just solder a 10K resistor across the top of this mosfet:

resistor about to be soldered on

resistor designated as R99


ESP8266 deep sleep and MQTT I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor.  When it wakes from deep sleep I would like to send a message to my MQTT broker.  The wiring works, the interrupt works, however, the code does not.

When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working.  However, my MQTT broker does not show any messages.  But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.

Any suggestions would be greatly appreciated

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*";
const char* ss_pswd = "*";
const char* mqtt_server = "*";
WiFiClient EspClient;
PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("belmont/sensor/pir/hallway", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}
void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  sendMQTTMessage();
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {
//  sendMQTTMessage();
//  delay(5000);
}

The answer for this actually goes to Juraj.  It was the fact that I was missing a delay.  In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent.  I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.


Wireless Bluetooth USB HUB using Arduino nano I have the following problem/idea:

I have a electronics workbench and a separate PC desk. Now I have a USB HUB on the workbench, but it doesn't properly work, because the USB-cable to the pc is too long. My setup doesnt really allow me to put the PC somewhere else and the USB-hub is already mounted in the closest usable location.

A few days ago I remembered that I have a arduino nano with a hc-05 bluetooth module attached to its hardware serial port. And as both bluetooth and USB are serial connections I was wondering if I couldn't use the arduino sort of as a middle man and connect the arduino via bluetooth to the pc. Then have a software on the pc that registers the arduino as a USB hub with one port and run some code on the arduino that basically makes the arduino act as a USB host (I know that this is possible with the arduino nano) and have it just move data between the USB connection and the bluetooth module.

Im quite sure that all this should be possible. The atmega should even be capable of doing so at or close to maximum USB 2.0 data rates as that is only 12 Mbit/s and it can run at 16 MHz when powered with 5V. Im not quite sure about the maximum data rate for the bluetooth module though, but I can work with a little lower speeds...

The software for the pc could also be relatively straight forward. Something like a virtual USB-port and the software just shifting data from the com-port that is the bluetooth to this virtual USB-port.

So thats the idea. I have some experience in both programming microcontrollers and software for pc.

So what I need is a bit of help with this, as I am not quite sure how to accomplish this.

The parts that I will need the most help with are going to be the programming of the USB host on the arduino and the virtual USB-port on the pc.

The rest should be relatively easy as its basically just shifting data from one register into another.

I agree with Majenko. The best way for you is to buy an active USB extension cable, so that you can handle the distance easily (the signal gets refreshed in the cable by active electronics, so that you can use USB over longer distances).

You consider this to be easy, because you haven't dug into the depth of these topics yet. Here are some important information on that:

Bluetooth and USB are fundamentally different. The term "serial" outside of the Arduino world is just a term for one bit after another. It doesn't describe any protocol or working principle. Interfaces as SPI and I2C are also serial interfaces, but that doesn't mean, that they work similarly, not even in their topology and also not in their protocol behavior. A bridge between these different interfaces is better described as a translator. And translation is always difficult.
Serial in the Arduino world means the UART interface. No similarity to USB or bluetooth.
The Bluetooth spec is rather big. There are many types of connection interfaces, that can be build with it. Examples are the UART (Arduino Serial), HID (like a mouse or keyboard on a PC) or audio (like headphones) interfaces. Each connection has it's specific function. The USB spec is even bigger, way bigger to be precise. You would need to understand how bluetooth and USB work at their core for implementing something like that.
The HC-05 is a chip for getting an UART interface over bluetooth. To change that, you would need to reprogram it with a new firmware. I doubt, that any firmware, that you can find in the web, would be sufficient for your case. Not generic enough. Also the chips hardware is limited, so you can only get limited resources out of it. Most likely you have the HC-05 on an adaptor board, which has a voltage regulator on it (since the HC-05 is a 3.3V device). You would need to ditch that board and solder the chip itself.
The Nano is a bad choice for everything involving USB. The Atmega328p on it, that you program when programming the Arduino, does not have an USB interface. For that the Nano has a second chip, the Atmega32u4, which acts as USB to UART adaptor. You would need to hack it to do anything different than that. Doing it is possible, but you would need to ask yourself, why you are trying to do something so complex with such an incapable board. Also the Nano cannot be an USB host, nor a hub. There is an USB Host shield for the Uno, but that also is limited.
Getting anything even remotely near to 12Mbit/s is illusionary. You won't be able to process nearly one bit every clock edge. You already need several clock edges to do very primitive processing (going into an ISR and then moving the data into a different register, as you put it). And the translation between the protocols will not be that easy. You will need much processing power and also quite some RAM and flash (you will certainly need to buffer some data and the program itself will also be very big to implement something like USB). "A little lower speeds" don't cut it there. Even if possible, that would be painstakingly slow in comparison to a real USB hub.
Most of the software, that you would need for such a project, is non-existent. Doing something that complex with such crappy hardware is an edge case. So you would need to write your own USB stack software. As mentioned, the USB interface is very complex and if you need to ask this question, you are currently not capable of doing this (and neither am I).

I don't say it is absolutely impossible to implement a bit USB functionality with the Nano. But you won't get a satisfying result, that you really can use, even if you were an absolute expert on microcontrollers and the USB and bluetooth stacks (which you really would need to be for it). That is at maximum a project, that an expert would do just for the grind, not for real results.

You have a real life problem, that you want to solve. Choose the easiest way and buy an active USB extension cable.


Proper error logging using Arduino Coming from a C# background where I do logs for every application, and given that I will be using the Mega for most projects and therefore have the memory available to do so, I want to incorporate error logging in my projects.

What is the best way to do so? Writing to an SD card? Writing via Wi-Fi or Ethernet to a networked storage or PC? Writing to a USB thumb drive?

The current project I am working on uses the Adafruit Music Maker shield so has the SD card reader incorporated into it, so the easy choice there would be to use that but I like creating solutions that are portable to multiple projects so writing via Wi-Fi or Ethernet seems to be the preferred method?

Since I am not fully up to speed with C++, and I see there are various ways to write to text files in C++, are there any preferred ways to do so depending on which storage route I take?

Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling Serial.begin() in the setup() and Serial.println() in the loop(), it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.

If you don't like the Serial Monitor feature of Arduino IDE, you can install one of the many terminal programs which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.

If you're good with command line, creating a log file is as simple as

cat /dev/ttyUSB0 > log.txt

in Linux or

type COM1 > log.txt

in Windows.


Why is my Analog Input channel adding voltage to my signal? EDIT: Here are the links to the sensor spec sheet (http://www.omega.com/temperature/pdf/HX71.pdf) and manual (http://www.omega.com/Manuals/manualpdf/M4543.pdf) for your reference.

I'm using a relative humidity (RH) sensor with an Arduino Mega. The RH sensor runs off of +/- 24V  (which is being sourced by a power supply), and outputs a signal from 0-5VDC. Naturally, I am plugging this output signal into my A0 channel. There is a bare Earth Ground wire that is wired to the power supply's earth ground (possible error?) Arduino's GND is connected to the power supply's EARTH GND, fyi.

I compared the voltage reading in my Arduino Serial Monitor to a reliable Fluke multimeter, and the analog input channel is adding ~.2 Volts!

From some research, I have read about "high impedance" "source impedance" "internal wiring of Arduino" etc, but unfortunately I am failing to grasp the reason why this is happening. I'd like to know so then I could figure out a solution on my own.

Below is a schematic of what I'm dealing with so that it may better illustrate my issue (also my code). Thank you for your time, and I appreciate your help!

)

void setup()
{

Serial.begin(9600);

}

void loop()
 {

  float hs1 = ((( analogRead(A0) * ( 5.0 / 1024.0) ) )* 20.0 );

  Serial.print("RH%");
  Serial.print(":");
  Serial.print(hs1);
  Serial.print(";");
  Serial.println();
  delay(1000);

}

Wow, you guys are gonna get a KICK out of this!

The analog input channel was not adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).

I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.

Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.

Thank you everyone for your help!


Arduino yun is not creating it's wifi? I have installed Arduino software into my PC and copied the bin files into the memory card that has to be fixed into Arduino yun.

After switching on the yun board it is not creating any Arduino yun wifi connection.

Can you help me to overcome this problem?
Thanks.

If there is no code that enables the WiFi, it won't be enabled.

Here's the link:
https://www.arduino.cc/en/Guide/ArduinoYun#toc14


How can I maintain PWM output while still performing other tasks? I want to generate a PWM signal that I can turn on and off with a button press without using interrupts.  Is there a way to keep the PWM output going while running other processes?

PWM just runs once started. It's all managed by a completely separate bit of silicon inside the chip.

Once you have done analogWrite(...) the PWM will just keep going until you tell it otherwise.


Equivalent for PORTB in Arduino Mega 2560 Like I said in the subject, I would like to know the equivalent for the instruction:

PORTB |= 0x01;
PORTB &= ~0x01;

More precisely I was using it to trigger a fast pulse conversion on my shield-ADC on an Arduino Uno. Now I am using an Arduino Mega 2560.

Can you write the exact same instruction for ATMega2560?

This code sends a pulse on pin PB0, which on the Uno is equivalent to
digital 8. On the Mega, digital 8 is PH5, thus you would write

PORTH |= _BV(PH5);
PORTH &= ~_BV(PH5);

The equivalence between the Arduino pins and the AVR pins is provided in
the official
documentation, but
there are nicer versions at pighixxx.com:

Uno pinout
Mega pinout


Xbee for Arduino Uno I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. (XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))

Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?

What you have there is an XBee module. It is designed to plug into an XBee shield which then plugs into the Arduino.

So you need to buy more.

That's the bad news.  The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.

Numerous people make the shields, such as:

Sparkfun
Seeed
DFRobot

Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going.  If you want to talk to your computer there is a device called the XBee Explorer which plugs into the PC to allow you to communicate with an XBee module.


Difference between data type int and long on Arduino I was learning to program for a void obstacle robot but when I looked at the code I saw two data types long and int.

Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.

Int and long are like same but I came up with the code where two types of datatype is used as seen below:

int trigPin = 2;
int echoPin = 4;
long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.

On the Arduino (AVR models) an int is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.

That is different from long which is 32 bits.


Creating public instance of class in another class's initialization I'm using several TM1637 displays to create timers, so I decided to make a Timer class. Every time I initialize an instance of the Timer class, I want it to create an instance of the TM1637Display class. So I started out with this, but the display object can't be accessed from within updateDisplay.

class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO) {
        TM1637Display display(CLK, DIO);
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }
}

And if I do this I get the compile time error In constructor 'Timer::Timer(uint8_t, uint8_t)': src\main.cpp:16:37: error: no matching function for call to 'TM1637Display::TM1637Display()'

    TM1637Display display;
    Timer(uint8_t CLK, uint8_t DIO) {
        display(CLK, DIO);
        ...
    }

What should I try? Maybe make an empty pointer before the display instance is created with a public scope, assign the pointer to the display instance, then hand the updateDisplay function the pointer? That seems really convoluted.

As it's now in the first example, it's local variable in Timer constructor.

In the second one you have to use member initializer list in constructor as there is no default constructor in your display class.

class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO)
    : display(CLK, DIO) // constructor's initializer list
    {
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }

    // member variable:
    TM1637Display display;
}


Creating a queue in Arduino? Does anyone know if there is a way to create a queue of some sort for arduino?

My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.

However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.

Greatly appreciated if someone can help me by pointing to the right direction.

I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
Queue

I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.

2 methods are implemented to interact with the queue, push() & pull().
I'll probably add a peek() later on if needed.

I also noticed this other FIFO only queue lib in the library manager when I commited mine: MD_CirQueue

Hope this can help!


Arduino Nano and a 3.3v Ethernet shield I plan on purchasing a Nano clone, an Ethernet shield (ENC28J60), an LCD and a DHT22 humidity + temperature sensor. This will be used in a wine cellar to monitor relative humidity and temperature.

The DHT sensor, LCD and Nano all operate on 5V logic. The Ethernet shield does not operate at 5V, but rather at 3.3V.

Does the Nano have a way to connect the two, will they work anyway (probably not), or should I use a CD4050 that is recommended on adafruit?

Any guidance is appreciated; I'm still amazed in what $10 in parts can do.

Also, in regards to the DHT22 sensor, what do I need in terms of a resistor? I've seen some people say you absolutely need a 4.7K resistor on the data pin for "pull up", and  others who say it's unnecessary. Can someone give a definite answer, either way?

Edit, wrong link on my nano clone.

Just get one with a 3.3v regulator on it. PS logic levels are allowed to be 5v.

DHT22 and LCD will also work fine on 3.3v so, alternatively, you could also get a 3.3v Nano.

The resistor value for the DHT22 depends on the length of wire between the DHT and Nano. Just buy them to be sure, or get a breakout board that already has them on the board (along with a capacitor, which is nice).


How to work with analog readings using RPi and Firmata? For context: I'm working on a project where I need to use sensors to figure out the current state of the environment. This process is done using an Arduino UNO and a RPi. The easiest way that I found to perform communication between both boards is by uploading Standard Firmata and reading the code from RPi using Serial communication. I'm using pyfirmata to write the code in Python on the RPI side. Also, the Arduino is powered by the RPi using the USB port.
My problem was: The ADC component in the Arduino uses as the analog reference the 5V provided by the USB. When I tested the integration, I was using my laptop. So, the computer was providing 5V to the Arduino. So far so good. When I integrated the Arduino board to the RPi, I got some problems related to the precision of the sensor. I figured out that the RPi was only giving 4.75 V to the Arduino Board. This was messing with my readings since the ADC was using 4.75V while my code had 5V to compute things. After adjusting the code, everything proceeded as planned. Both 4.75 V and 5 V were hardcoded in my code.
So, these are my questions:

Is there a way to read the Vcc using pyfirmata to figure out the correct voltage without having this hardcoded?
Is there a way to modify the analog reference to use the INTERNAL reference of 1.1V?

About the analog reference, I found this: https://github.com/firmata/arduino/issues/39 . So, pyfirmata implements send_sysex method, I just have to execute these steps, but I still don't know how.

It does not appear that Firmata has proceeded with the ability to change the analog reference source. You referenced one of the issues opened for it, but I don't see anywhere where it committed to the current master branch.

There's no way for an Arduino to read a voltage without some reference, and as you are experiencing, the default reference is Vcc. That means everything must be compared to Vcc, and if you compare Vcc to itself, you will always find out that Vcc is equal to Vcc.

The pull request to implement is here, so you could play around with it yourself.


Designing UI for effects project I have a project where I am using an Arduino to control a smoke machine and a strobe light using DMX (with a shield). I also use a light sensor, so that when a person pass through it, the Arduino sends a signal to activate the smoke machine.

Currently I have hardcoded both intensities in my Arduino sketch, but I want to allow the operator to control the settings of both devices, but needing to be connected to a PC.

I don't know if a potentiometer is a good option, because I would want to offer fine control to the operator (select a number in the range of 0-255).

How can I do that? What user interface system can I use?

If OSC is Open Sound Control, there is a library for it at https://github.com/CNMAT/OSC

Physically, you could hook a potentiometer or two to analog inputs and drive it like the sample in http://cnmat.berkeley.edu/oscuino

The code below is copied from that site, with a couple untested changes to not use the USB serial, and appears to use an analogread to sens some sort of message to the OSC system.

#include <OSCMessage.h>

//Teensy and Leonardo variants have special USB serial
//#if defined(CORE_TEENSY)|| defined(__AVR_ATmega32U4__)
//#include <SLIPEncodedUSBSerial.h>
//SLIPEncodedUSBSerial SLIPSerial(Serial);
//#else
// any hardware serial port
#include <SLIPEncodedSerial.h>
SLIPEncodedSerial SLIPSerial(Serial1);
#endif

void setup() {
  //begin SLIPSerial just like Serial
  Serial.begin(38400);
  //while(!Serial)
  //  ; //Leonardo "feature"
}

void loop(){
  //the message wants an OSC address as first argument
  OSCMessage msg("/analog/0");
  msg.add(analogRead(0));
  msg.send(SLIPSerial); // send the bytes to the SLIP stream
  SLIPSerial.endPacket(); // mark the end of the OSC Packet
  msg.empty(); // free space occupied by message

  delay(20);
}

If DMX is https://en.wikipedia.org/wiki/DMX512 then...there is another library at http://www.mathertel.de/Arduino/DMXSerial.aspx


Send Email through Cayenne serial connection I have an Arduino Uno connected to Cayenne through the serial connection, currently i am reading the data from a sensor of temperature and humidity DHT12 and showing it in the Dashboard of Cayenne correctly.

I need to know if i can send emails from the Arduino using the connection that cayenne let me use, because i can't stay with the pre-defined alerts that the platform have.

No, the Arduino cannot send emails directly through serial. The communication channel you have set up is a direct connection between the Arduino and Cayenne. It cannot be used for anything else other than communicating with Cayenne.

However that doesn't mean you can't try and see if there is some way of making Cayenne send emails for you. Having never used Cayenne I cannot comment on this aspect. You would be better off consulting directly with Cayenne and their users through their forums.


Input current for L293D shield I am a newbie in arduino working on a bot with L293D shield. But I have a  question as what would be the input current to drive all 4 dc motors and 2 servo motors.  I can see that it can supply 0.6Amp current for the four motors.

I am considering the amount of electrons flowing in per unit time is equal to the electrons flowing out of the circuit, as an simplistic aprach. So practically the input current should be greater than or equal to 2.4Amp.

As I have 6 motors in total so I was thinking about making a 12V 3Amp DC supply for a better performance. Should I do it like that? will it damage the board or shield?

Here the proper answer:

The vast majority of devices are constant-voltage devices. They need a constant operating voltage to work correctly. Microcontrollers are such devices. When operating, they will try to draw as much current from the power source, as they need, but not more. Much like a simple resistor with an applied voltage will draw a specific amount of current (calculable with Ohm's law), complex devices like microcontrolelrs have something like an overall impedance/resistance, that is depending on their specific operation. So also here the device only draws as much current, as it needs. (I wrote about an overall impedance to emphasize the fundamental principle. No one would really specify an overall impedance for such a device, because this would only be a value calculated by the voltage and current needed, not a real resistance.)

This means, that burning parts are not due to the power supply supplying more amps. They get burnt, because something draw too much power trough them.

Let's look at some examples:

Imagine, that you create a short between 5V and ground on your Uno. A short means, that a high current can flow, since the resistance is very low. Now you are drawing a high current from your 5V pin to the ground pin. The Arduino's 5V pin is connected to a voltage regulator (for if you use Vin) and over a diode to USB. Both parts are only rated for a maximum current (depending on the version of the board between 200mA and 1A). The high current, that you draw, will flow through one of these parts, depending on your input source. This part will get fried, because a way to high current will flow through it, just because you draw the current.
A strong motor, that needs more current, than the board is rated for, would result in a similar problem like the short circuit. Indeed every device, that needs more current, than the board is rated for, might result in frying the mentioned parts.

But what happens, if you draw more power from the power supply itself, than it is rated for? The power supply electronic is similar to the Arduino board. When you draw too much current from the power supply, some parts of it might get fried and stop working. Thus, you should not try to draw more current from it, than it can provide. Often power supplies have a protection circuit, that will either lower or directly cut the voltage, if too much current is drawn. This is for the safety of the supply and should not be used for current limiting your own application normally.

So, you should always calculate, what current you expect to need, and then take a power supply, that can provide more current than that. You should consider a significant headroom, so that you can add more parts, if you want to extent your project. For example, if I calculate 2A for my project, I would use a power supply in the range of 3A.

Addition:

Above I wrote about constant-voltage devices. There are also constant-current devices, for example LEDs. An LED has a specific constant forward voltage. Under that voltage it will not conduct current. Over that voltage, the current rises exponentially. The voltage over the LED will always stay the same, as it was designed. This is the reason, why you need to add a current limiting resistor to a LED. But in the vast of devices, LEDs (or in fact every diode) is an exception.


Multiple shields on one Arduino/Linker base shield I'm using an Arduino Uno R3 along with an Ethernet shield as well as the linker base shield for interfacing with three linker modules, light, temperature and some LEDs as I believed this would be simpler than using a breadboard and look neater. Are there any problems I'm likely to run into regarding compatibility or power consumption? It's a prototype for a hydroponic garden automation system. As a secondary, are there any c02 sensors under $60 available on the market?

I would recommend looking up the power consumption specs on the datasheets for each shield. Then determine whether the current used by all of the shields exceeds the limits for any given pin and for the board as a whole. I highly recommend the following article: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/


How many modules can an Arduino Nano v3 support (in code)? I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?

Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module

The devices will require some code to make them work and there is a chance, depending on how you write the code, that this may consume all the available RAM on the chip.  However I doubt you will go to more than 60% if you use the standard libraries for those devices, but there is only one way to find out...

Get the libraries for the devices and look at the examples for each device.  You should be able to hack an "example" of your own that calls all 4 examples in the main loop().  This should give you an idea of how much memory you are going to use.

If you use too much it might be possible to snip pieces away from the libraries, the LCD will probably have font tables that you don't need for instance.  Or you could use an alternative Arduino.


Switching Many Switches with one Input I have a situation where I need to select between two signals, lets say 1A or 2B and route it to output 3C. I need to do this six times (2A or 2B to output 2C, 3A or 3B to output 3C, etc.).

These all need to switch based on one output from my chip.

What sort of component do I need for this? I think it's something like a 2:1 spdt multiplexer, but something doesn't seem quite right.

I've been looking at a bunch of data sheets and I cannot seem to find a chip which switches many 2:1 switches based on ONE input. Does such a thing exists? Or am I just way of the mark here? Not sure.

Any help appreciated.

Thanks.

Almost, you will need two 74157 (or similar chips) to switch 8 pairs of TTL level logic signals down to 8 individual signal.


Does anyone know how to connect 2 digipots to Arduino? (MCP4141) I'm struggling with getting the code right. I'm trying to connect 2 digipots (MCP 4141) to Arduino to work separately over SPI. Has anyone got any experience with that?

Try to read the datasheet and get a basic understanding of how the device works. in this case, it consists of 16 bits transfer (2 bytes).

Try to write a set of routines that communicates with the chip over the spi.

After that, it is all about using the _CS pin to select a particular chip.

edit: if this helps you, here is my code driving two mcp41010 - slight different from your digit pot but very similar.

//write to the device wiper0
void mcp41xxx_write0(uint8_t dat) {
    spi_write(MCP41XXX_P0 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

//write to the device wiper1
void mcp41xxx_write1(uint8_t dat) {
    spi_write(MCP41XXX_P1 | MCP41XXX_CMD_WRITE);    //send the command byte
    spi_write(dat);                                 //send the data byte
}

the actual writes to the devices will differ -> mine is specific to the mcp41010 devices. It supports two wipers, P0 and P1. No increment or decrement on my digit pots.

the way to drive two digit pots are below:

//first pot
spi_select(MCP41XXX_CS1);           //deselect cs1 -> idles high
mcp41xxx_write0(i + i);             //send the data
spi_deselect(MCP41XXX_CS1);         //select hte device

//second pot
spi_select(MCP41XXX_CS2);           //deselect cs1 -> idles high
mcp41xxx_write0(i++);               //send the data
spi_deselect(MCP41XXX_CS2);         //select the device

as i'm using a single pot device, writing to the 2nd pot means writing to its wiper0.

I looked at your digit pot and the only thing you need to change are the wiper-specific routine(s), as your transmission is slightly different in the msb.

the spi_write() routine can be replaced / mapped to the shiftOut() routine under arduino.

here is the above code, without any change, running on an arduino:

I also took a brief look at your device's datasheet (mcp4141) and I think this is all you need to change:

//send data on wiper0 of mcp4141
void mcp41xx_write0(uint16_t dat) {
    dat = dat & 0x03ff;                             //10-bit data
    spi_write(MCP41XX_CMD_WRITE | MCP41XX_WIPER0 | (dat >>  8));    //write the msb
    spi_write(dat);                                 //write the lsb
}


Cheapest way to change digital output source Powering at 5 volts, atmega328 output ~4.7 volts. I need to output between 12 and 24 volts @ 2 amp. I'm currently using relay but they are costly. Is there a way to do it with transistors or any thing cheaper?

Thanks

As @Gerben said in the comments, I would also recommend an N-channel MOSFET.  OnSemi has a great application note on how to determine what type of MOSFET you would need based on your given load requirements and how to use it as a switch.  You can find that app note here.

The basic idea is to provide an enable signal from your atmega328 to the gate of the MOSFET to drive it into saturation or to turn it off.  You would connect your 12/24V supply to the drain of the MOSFET and connect your load to the source of the MOSFET.  The basic circuit can be seen in the application note.

Hope that helps!


How to find the MAC address using NodeMCU when connecting to WiFi? I am new to using NodeMCU and IOT. I am testing the NodeMCU (ESP8266) so that I can connect with pubnub server. Have taken code from github but there is error saying

'mac was not declared in this scope'

and some other error too.

Can anyone tell whats the problem?

This code is from pubnub github page - https://github.com/pubnub/arduino

Code:-

#include <Ethernet.h>

#include <PubNub.h>

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* If you use some other HW, you need to do some other
       initialization of it here... */
    Ethernet.begin();

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(publisher key, subscriber key);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */
    Ethernet.maintain();

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

error :-
  sketch_jan17a:28:47: error: 'pubchannel' was not declared in this scope

     PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");

                                               ^

sketch_jan17a:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

Multiple libraries were found for "Ethernet.h"
 Used: C:\Users\sultan\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta2\libraries\Ethernet
 Not used: C:\Program Files (x86)\Arduino\libraries\Ethernet
exit status 1
'mac' was not declared in this scope

I don't believe you have an Wiznet Ethernet module connected to your NodeMcu. Ethernet library is for the Wiznet chips for wired LAN. You want to use the WiFi of the NodeMcu. For that the esp8266 core has the ESP8266WiFi library. It has the same API as other WiFi libraries based on Arduino WiFi library. So you can modify the WiFi examples of the Arduino pubnub library. Only change #include <WiFi101.h> to #include <ESP8266WiFi.h>. (And remove #include <SPI.h>.)


ESP8266 and Arduino Interfacing I have connected Arduino with ESP8266 with

Arduino pin 2 connected to ESP's Tx Arduino pin 3 connected to ESP's Rx via Voltage Divider Arduino GND connected to ESP's GND Arduino 3v3 connected to ESP's CH_PD

I have powered ESP8266 using 1117 Voltage regulator

When I initially bought ESP8266 it was working properly(I could even set up a server) but now when I connect it to Arduino an endless stream of garbage values is seen on the Serial Monitor...

The arduino is programmed with the following code

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {
    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }
  }

  if(Serial.available())
  {
    // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
    // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
    // but we want to send everything at the same time.
    delay(1000);

    String command="";

    while(Serial.available()) // read the command character by character
    {
        // read one character
      command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

There is a new command for the ESP8266 in AT version:0.50.0.0 - SDK version:1.4.0 that lets you explicitly set the full UART configuration:

AT+UART_CUR – set the current UART configuration
This command sets the current UART configuration; it does not write to the flash. Hence there is no change in the default baud rate.

For example:

AT+UART_CUR=9600,8,1,0,0