Sending 5 Led pixel values to arduino , is this a good way? I wanted to install a 5 LED strip underneath my PC's front panel. I want to send color over PC so it can change when i open different apps, with temperature or etc!

So all I think the best way to do this is to just use Arduino to set the LED Values!

But I have had some troubles creating a good communication protocol for this, I've been just simply sending 45 digits (15 3 digit numbers) to my Arduino with serial. here's code:
Arduino :

#include "Adafruit_NeoPixel.h"
#include "WS2812_Definitions.h"

#define PIN 4
#define LED_COUNT 5

struct pixel {
  int R = 0;
  int B = 0;
  int G = 0;
};

Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800);

char count = 1;
int pixelNumber = 0;
struct pixel tempPixel;
//struct pixel Pixels[LED_COUNT];

void setup()
{
  Serial.begin(9600);
  Serial.println("Init");
  leds.begin();  // Call this to start up the LED strip.
  clearLEDs();   // This function, defined below, turns all LEDs off...
  leds.show();   // ...but the LEDs don't actually update until you call this.
}

void loop() {
  if(Serial.available() > 0) {
    if(count == 1) {
      tempPixel.R = PC_Receive();
    } else if (count == 2) {
      tempPixel.G = PC_Receive();
    } else if (count == 3) {
      tempPixel.B = PC_Receive();
      count = 0;

      setPixelColor(pixelNumber, tempPixel);
      Serial.println(pixelNumber);
      leds.show();
//      Pixels[pixelNumber] = tempPixel;
      if(++pixelNumber >= LED_COUNT) {
        pixelNumber = 0;
      }
    }
    count++;
  }

//  if(pixelNumber == 0) {
//    for(int i = 0; i < LED_COUNT; i++ ) {
//       setPixelColor(i, Pixels[i]);
//    }
//
//    leds.show();
//  }
}

void setPixelColor(int a, struct pixel P)
{
  leds.setPixelColor(a, P.R, P.G, P.B);
}

char PC_Receive() {
  int result = 0;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 100;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 10;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0');

  Serial.println(result);
  return result;
}

void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
  for(int i = 0; i < LED_COUNT; i++) {
    leds.setPixelColor(i, red, green, blue);
  }
  leds.show();
 }

And here's PC's dirty code in python:

import serial
import time
import random

class Pixel:

    def __init__(self, R, G, B):
        self.R = R
        self.G = G
        self.B = B

def clearAll():
    for i in range(0,5):
        ser.write("000000000")

def sendPixel(pixels):
    for i in range(0,5):
        ser.write(str(pixels[i].R).zfill(3))
        ser.write(str(pixels[i].B).zfill(3))
        ser.write(str(pixels[i].G).zfill(3))

ser = serial.Serial('/dev/ttyACM2', 9600)

little = [0,0,0,0,0]

for i in range(0,5):
    little[i] = Pixel(0,255,50)
sendPixel(little)

time.sleep(0.5)
clearAll()

the problem is it isn't stable, i think i should just use an \n at end or send back OK or something to confirm it, but that would make it slow if i did it for each value! (and checking only once after all 5 leds are send would mean sending more values until i receive the ok and clearing and sending them again!)

Can you recommend me a better way?

Thanks!

EDIT: Just wanted to say! it's almost done! It does change color when i open chrome, and i think at 115200 baud rate it's fast enough to not notice a delay (although at 9600 i felt like it's slower then my (xxx/xxx/xxx....) protocol but it's better and works at 115200

i will add some basic functions to my python side and add a rainbow effect
I will also add GPU temperature and etc... it's not going to be really hard on linux but windows, im not sure :D

I would recommend a similar solution as DaveX with a small modofication.

If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF  FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).

so
LED 1 {00000001 =01} all red {FF0000} would be 0x01FF0000

LED 2 and  4 {00001010 =0A} all green {00FF00} would be 0x0A00FF00

LED 5 and 1 {00010001 =11} all blue {0000FF} would be 0x110000FF

ALL LEDS off would be 0xFF000000

All LEDS onn full white would be 0xFFFFFFFF


Interfacing IMU and GPS with Arduino I am using an Arduino UNO board and trying to interface IMU sensor (GY-521) and GPS sensor (Ublox Neo-6M) at the same time. The connections of the IMU and GPS are as follows

IMU to Arduino:
Vcc --> 5V
Gnd --> Gnd
SDA --> A4
SCL --> A5
INT --> D2

GPS to Arduino:
Vcc --> 5V
Gnd --> Gnd
Tx --> Rx
Rx --> Tx

Now when I used the IMU sensor alone and tested it with the Jeff Rowberg library, it was working fine. But as soon as I make the connections with the GPS and upload a program, the IDE gives the following error:

Arduino: 1.7.10 (Windows 7), Board: "Arduino Uno"

Build options changed, rebuilding all

Sketch uses 3,970 bytes (12%) of program storage space. Maximum is 32,256 bytes.

Global variables use 313 bytes (15%) of dynamic memory, leaving 1,735 bytes for local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa5

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

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

I can't seem to spot the problem. Kindly help me out as I am new to the Arduino development. Thanks.

Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.

Cheers!


Using an External ADC with Arduino For my project I have to measure a  signal of the order of few microvolts.
As we know the least an Arduino can measure is ~5mV, due to its 10bit ADC and 5V reference voltage.

A solution to this problem can be to use an external ADC (16bit, I think will do).

Can you please guide me on this problem.Is it possible to use a external ADC,if yes how should I.Any other simple solution ?
Thank You

Anupam

Yes, if you have a 0 to 30 mV signal that you need to measure to an accuracy of 2 microvolts, you'll need an ADC with an effective number of bits (ENOB) of at least 13.9 bits and an amplifier to make the signal to match the range accepted by the ADC.
Most ADCs pretty much require some sort of op-amp or differential amplifier between such low-level input signals and the ADC input pins.
A few ADCs have a differential amplifier already built in -- that makes things a lot easier to get working, but I don't know if any of such ADC available would meet the other requirements of your project.

I don't know any way to make such high-resolution measurements other than using a dedicated external ADC chip.

You'll want to read the ADC datasheet -- some of them, and so far all the microcontrollers I've seen that claim to have a built-in "16 bit ADC", have an effective number of bits (ENOB) worse than the 13.9 ENOB you need at the sampling rates I typically use.

Adafruit has a very nice tutorial describing how to connect the 12-bit ADC ADS1015 or the 16-bit ADC ADS1115 to an Arduino.

The Arduino playground has a brief tutorial describing connecting a 12-bit ADC MCP3208 or a 13-bit ADC MCP3304 to an Arduino.

I see from the Arduino blog and other sites that people have connected some even higher resolution ADCs to an to an Arduino board, including
the 24-bit Linear LTC2440 ADC;
the 18-bit LTC2400 ADC (24 bit at 5 samples per second); and
the 24-bit ADC TI ADS1220.

Arduino blog. "Archive for the ‘ADC’ Category"
Peter Oakes. "Arduino UNO, Using precision ADCs and DACs". (video tutorial: connecting the 24-bit ADC TI ADS1220 to an Arduino).
Martin Nawrath. "Connect a LTC2400 High Precision 24 Bit Analog to Digital Converter ... to the Arduino"
John Boxall. "Tutorial – Arduino and the TI ADS1110 16-bit ADC".

Sounds like a fun project.
Good luck.

EDIT:

Steve Luce. The LTC2440 24 BIT ADC and the Arduino Uno.

Everyone that uses an ADC needs some antialiasing filter between the signal and the ADC.

People that measure very faint signals usually need some sort of amplifier between the signal and the ADC.
You may find the list of suggested op amps on p. 7 of the AMP03 datasheet useful.

Because historically ADCs were expensive (and high-resolution ADCs were unavailable), people have developed many clever tricks for processing signals before feeding the processed signal into a relatively low-resolution ADC.
(Lock-in amplifiers, chopper amplifiers, manual precision gain adjustment, manual precision offset adjustment, heterodyning, etc.)

Have you tried asking "What sort of amplifier do I need to measure ((something)) with a 16-bit ADC" at https://electronics.stackexchange.com/ to learn some of those tricks that specifically apply to ((something))?


Atmega 328P in Arduino Does anyone know what it means by the Atmega 328p has 131 instructions? And could you give an example of how any one of these 131 instructions look like?
Thanks in advance!!

A CPU or MCU uses very basic instructions which are executed.

If you write code in a program language (like in Arduino IDE), the sketch is converted into many instructions (by the compiler and linker).

The instruction set can be found here.

An example is:

ADC Rd, Rr: Adds two registers and the contents of the C flag and places the result in the destination register Rd.

A CPU/MCU uses registers, which can be seen as very fast 'variables', mostly there are quite few of them, and all operators (like +, -, *, /) are carried out using these registers.

If you are just starting Arduino, it's not so useful to dive into this, the compiler/linker will take care of these 'details'; just be glad you don't have to write in assembly (anymore).


Arrays and Functions How can I return a char array from a function?

char c[] = getFloat(val, valid);

char getFloat(float val, bool valid){
      if(valid){
        char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
      } else Serial.print("No Float");
    }

Allocate it in the heap. Don't forget to free it after.

#include <stdlib.h>
#include <string.h>

 ...

char *c = getFloat(val, valid);
use(c);
free(c);

 ...

char *getFloat(float val, bool valid){
  if(valid){
    char stringFloat[16], *ret;
    dtostrf(val, 10, 8, stringFloat);
    ret = strdup(stringFloat);
    return ret;
  } else {
    Serial.print("No Float");
    return NULL;
  }
}


How to modify Arduino boards.txt to support new MCUs In this post, it was mentioned that to get the Arduino IDE to support an ATmega328 (only the ATmega328P is supported):

  I should mention the Arduino way of doing this, is to create a new
  boards.txt file with this chip and add (not change) the avrdude.conf
  file. This will allow programing either from selecting the correct
  board. but that is another subject.

After a great deal of research in the past, and attempted modifications to boards.txt and avrdude.conf, I arrived at the conclusion that the Toolchain doesn't support the ATmega328 therefore the changes will have no effect.

Can anyone confirm that they have successfully found a way to make these changes, so we can avoid the need for a work-around?

Please, Note that the Arduino IDE is behind on many of the tools. In this case avrdude and its conf file, along with avr-gcc

First:

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

needs to support the m328 in addition to m328p. This can be done by either updating

.\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe

to something like avrdude-6.1-svn-20131205-mingw32. along with replacing the conf file with the new one

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file that has both m328 along with the m328p. Note 6.1 supports a parent method, making it easy to duplicate chips with different signatures. Or use existing 5.11 and add to its

.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file by duplicating the entire m328p section and renaming the new entry to "m328" along with the correct signature.

Second:

avr-gcc need to be updated to support compiling both the m328p and m328. Yes, it just a semantic thing. But the next part will send either ATmega328p or ATmega328 to both gcc and dude. which both need to support it. One can simply copy over

.\arduino-1.5.6-r2\hardware\tools\avr\

with the new tool chain. I used avr-gcc-4.8_2013-03-06_mingw32

Third:

replace the following line in boards.txt

uno.build.mcu=atmega328p

with

## Arduino ATmega328P
## ---------------------------------------------
uno.menu.cpu.atmega328p=ATmega328P
uno.menu.cpu.atmega328p.build.mcu=atmega328p

## Arduino ATmega328
## ---------------------------------------------
uno.menu.cpu.atmega328=ATmega328
uno.menu.cpu.atmega328.build.mcu=atmega328

This will add an option to the IDE when UNO is selected for either chip. And subsequently send the correct MCU to both the compiler and avrdude.

Proof:

Below are the verbose output of the IDE with the above changes. Note the -mmcu and -p for both options. As a real unit is was not connected it yielded the "not in sync" error. Where this shows it all works.

C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328 -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude done.  Thank you.


Problem using Ino build for 8 MHz I want to use the Ino command line toolkit to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and delay(1000); seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

Per the Quick start guide, Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port /dev/ttyACM1. We have to specify this for our build steps as command-line switches.
Board model may be set with --board-model or -m switch. Port is set with --serial-port or -p switch. So lets do it:
$ ino build -m mega2560
$ ino upload -m mega2560 -p /dev/ttyACM1
$ ino serial -p /dev/ttyACM1

For the full list of board names refer to ino build --help.

So you might be able to do this by using
$ ino build -m pro328
$ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using ino build --help should give you the information you need to select a suitable board if pro328 doesn't work.
Once that's done, the frequency setting should be taken care of for you.


Arduino due slow clock To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?

What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?

The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip.  It can also be routed to other places when you want a low speed clock source, but the only places it is actually required are the RTC and the watchdog.

The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal.  Trying to use that for the RTC module will result in the clock drifting over time.  The watchdog won't really care if the clock isn't perfectly accurate.


Connecting a motor to Arduino UNO Play breadboard I am new to Arduino and have a small query. I am building a simple system that switches on a motor and switches it off after some time and repeats this in a loop.

The Arduino that I am using is a “DIY UNO Play Breadboard -ATMEGA328P with FT232 Breakout Board” (Rs. 825, or $12.38USD, from Mangalore).  The Arduino board is similar in size to a Nano but without USB.  The FT232 board has a USB B port on one end and serial pins on the other.

My query is whether I should connect the positive end of battery supply to the motor and then connect in series using a motor controller circuit to port 7 and connect the negative terminal to the gnd port.

Or do I need a separate voltage source for my Arduino, because this Arduino has no built in USB ports.

This is my code to switch on and switch off the motor:

int motorPin = 7;
   pinmode(motorPin,OUTPUT);
   digitalWrite(motorPin,HIGH); //turn motor on
   delay(500); //wait
   digitalWrite(motorPin,LOW); //turn motor off
   delay(500); //wait

Using same Voltage supply to power Arduino Board and motor simultaneously is usually not a good practice.

So, what you can do is use separate batteries to power Arduino and motor as shown in image below

However you can also power arduino and motor from single power supply, but in this case you should first think of current ratting of your battery and current consumption of your Arduino (normally 500mA) and motor. As shown below,

Hope it help. Any question Comment below.


Arduino countdown timer for repeating actions I have tried to find simple library for triggering timer after some time.
The idea is to retry network connection (RF24 network library).

I have following code now

while(!mesh.write(message, headerType, memSize)) {

}

This code will try to send packet until success

But I need to give up after for instance 10 seconds

I wanna to have something like this

bool timerTriggered = false;
Timer myTimer = new Timer(10000);
myTimer.setCallback(countedDown);

void countedDown() {
   timerTriggered = true;
}

And start timer before network request

myTimer.start();

while(!mesh.write(message, headerType, memSize) || !timerTriggered) {

}

Please suggest the best way to implement this.

Thanks.

EDIT

I have found problem as far as delay(); uses timer internally it conflicts with libraries or simple timer.

The solution is to use Alarm.delay(400); instead.

Maybe someone knows better solution ?

Something like this would work as a non-blocking, general purpose timer:

unsigned long startTimestamp;
unsigned long timestamp;
const unsigned long timer_length = 10000; //10 seconds

startTimestamp = millis();
timestamp = startTimestamp;

while ( (timestamp - startTimestamp) < timer_length)
{
    // keep doing thing

    timestamp = millis();
}

// stop doing thing now


Interrupt and delay problems on Attiny 85 I wrote this code and uploaded it to attiny85:

 int hours = 2;
 int minutes = 4;
 static int MINUTES_COUNT_BIT = 5;
 static int HOURS_COUNT_BIT = 3;
 #define button 2
void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(button,INPUT);

  attachInterrupt(0,pin_ISR,CHANGE);

}

void loop() {

  // put your main code here, to run repeatedly:

}

void pin_ISR(){
    if(digitalRead(button)==LOW){
      for(int i = HOURS_COUNT_BIT;i>=0;i--){
      byte act_bit = bitRead(hours,i);

      switch(act_bit){
        case 0:
          digitalWrite(3,HIGH);
          delay(1000);
          digitalWrite(3,LOW);
          delay(1000);
          break;
        case 1:
          digitalWrite(4,HIGH);
          delay(1000);
          digitalWrite(4,LOW);
          delay(1000);

          break;
        }

    }
  }

  }

When I click button it lights up LEDs but it is so much faster than 500 milliseconds it looks like that:
https://drive.google.com/open?id=0ByeWvrEgy2gRNUp3MDNxQTAxd2c
Please help

In short:

Arduino delay() is relying on millis().
The millis() function is  updated by timer ISR.
ISR handler blocks all other ISRs by disabling global interrupts.
No update for millis results into deadlock in delay if you use it in another ISR

And recommendation for ISRs? Do it as short as possible! Set some volatile flag and do the action later outside of ISR.


What is better approach for non blocking pid algorithm? I'm developing software side for 3 axes robot where are 360° continuous rotating servos used Documentation here

these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function

int pinFeedback = pin_comes_here;

float tHigh = 0;
float tLow = 0;
int tCycle = 0;
float dc = 0;
float angle = 0;
float dcMin = 2.9;
float dcMax = 97.1;

void setup() {
  pinMode(pinFeedback, INPUT);
}

void loop() {
    while(1) //From Parallax spec sheet
    {                                       //There is core of the problem
      tHigh = pulseIn(pinFeedback, HIGH);
      tLow = pulseIn(pinFeedback, LOW);
      tCycle = tHigh + tLow;
      if ( tCycle > 1000 && tCycle < 1200)
        {
          break; //valid tCycle;
        }
    }

  dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

  angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

  if (angle < 0)
  {
    angle = 0;
  }
  else if(angle > 359)
  {
    angle = 359;
  }

    //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

}

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.

So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer
Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

The main issue you have is that pulseIn() is completely blocking - and your while loop doesn't help much either.

The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in gated mode. Actually you need two timers, but the Arduino already provides you micros() that will do for one of them.

Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.

That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses micros() to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.

It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.

Of course, it goes without saying that you need a gated timer for each servo you want to sense...


Using same pins number in different arduino? I'm new beginner in programming arduino, and I want ask a question about arduino code, this is the problem " i used two arduino to build a robot, but i don't know how to set the code that for two arduino uno that pins in first arduino i used them all and now i wanna use the pins in second arduino, and how write code for the second arduino, which it is the same pin number i used  in first arduino, how to creat a code? thanks a lot guys for answer my question... (sorry for my bad english)...

The notion that “both Arduinos are in the same sketch” is slightly off.  Each of the Arduinos will contain a program; their programs might be identical if you do some fancy programming, but it is simpler to write one sketch per Arduino.

Thus, your first Arduino will run a sketch designed to control the devices it is connected to, and your second Arduino will run a sketch designed to control the devices that it's connected to.  Conceivably, you might have some devices that both Arduinos connect to.

Calling the two sketches S1 and S2, the device on pin number n as referred to in S1 will typically be a different device than the one on pin number n as referred to in S2.  Most but not all of the pin usage assignments for each pin number will be different in one sketch versus the other.

It's likely the two Arduinos will need to communicate with each other.  For a range of methods, see for example  How to have an Arduino communicate with 3 other Arduinos.  For additional detail see Arduino-to-Arduino serial communication and How to network many Arduinos with sensors using I2C.

If you decide to use I2C, then also see MasterWriter Tutorial and Wire Library webpages at arduino.cc.


What values are the Atmel MCUs EEPROMs preloaded with? I have checked with two datasheets: one for some ATMegas and one for some ATTinys MCUs and could not find what the EEPROM.get() call would read back if the EEPROM was empty (or contained default factory values). I have written a program in order to find out and it looks like on Arduino Uno the EEPROM bytes are all FF by default.

Is this the case with every Arduino board or just some of them ? Or perhaps we can not assume that all the MCUs of a certain type (such as ATMega328) will have this factory preloaded value of FF for the EEPROM bytes ?

edit

Following the fuses - thanks @Chris Stratton - I was able to find this in the datasheet:

  Skip writing the data value 0xFF, that is the contents of the entire
  EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip
  Erase.

Seems like we could get the factory pre-loaded value by not programming the EESAVE fuse, which is what the Arduino Uno does by default, and just reading them.

  uno.bootloader.low_fuses=0xFF
  uno.bootloader.high_fuses=0xDE
  uno.bootloader.extendedfuses=0xFD

However, having a way to set them to a known value is fine too for my needs, so I shall just write that fuse and havea  guaranteed 0xFF all over the EEPROM.


ESP8266 not able to communicate over serial connection with arduino UNO This is the code I uploaded in Arduino UNO:

#include<SoftwareSerial.h>
SoftwareSerial ESP(2,3); // RX, TX
//ESP RX-->3(UNO) TX-->2(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
    if (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

    ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
}

But ESP is not able to receive the AT command properly...sometimes it recieves A, sometime T. It then responds with garbage value. Though we are able to give command to ESP through Serial Monitor and it responds pretty well. But when trying to communicate through code, the communication is not OK.

The problem is in your loop() function. On each iteration, you will receive at most one character from the SoftwareSerial, while writing the same AT command again and again. As a result, your slave device (ie. ESP8266) will overflow its UART buffers, resulting in garbage being sent and received.

You should keep receiving data from the slave for as long as it has data:

while (ESP.available()) {
    char inData = ESP.read();
    Serial.println("Got response from ESP8266: ");
    Serial.write(inData);
}


connecting two keypad with arduino I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

It should be no problems as long as you can get enough digital inputs into the Arduino.  Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2*2 keypads quite easily.

I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.


Arduino and AVR Serial Communication over USB I have a Arduino Uno Rev3 and I would like to use a AVR development toolchain to write a program that performs serial communication over USB.

Doing this using the Arduino IDE is fairly simple:

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

void loop() {
   int i;
   while(1) {
      Serial.write("hello\n");
      delay(5000);
   }
}

Then from Linux, I can simply read from /dev/ttyACM0 and every 5 seconds I get "hello\n".

I found a blog post titled Simple Serial Communications With AVR libc that explains how to perform serial communication using an AVR development toolchain. The simplified version of the above Arduino sketch is below.

#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#ifndef BAUD
#define BAUD 9600
#endif

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>

void uart_init() {
    // Upper and lower bytes of the calculated prescaler value for baud.
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

    // Configure data frame size to 8-bits.
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

    // Configure to enable transmitter.
    UCSR0B = _BV(TXEN0);
}

void uart_putchar(char c) {
    // Wait until the register to write to is free.
    loop_until_bit_is_set(UCSR0A, UDRE0);

    // Write the byte to the register.
    UDR0 = c;
}

void uart_putstr(char *data) {
    // Loop until end of string writing char by char.
    while(*data){
      uart_putchar(*data++);
    }
}

int main() {
    uart_init();

    while(1) {
        uart_putstr("hello\n");
        _delay_ms(5000);
    }

    return 0;
}

The problem is, this doesn't actually work. I can build and flash the ATmega328p but reads to /dev/ttyACM0 block forever. I suspect what is happening is that the serial communication is occurring on some pins and not over USB, but I am not sure.

Anyone have any idea on how I can emulate Serial.write using an AVR development toolchain and have the output be written over USB?

Turns out the problem was with my Makefile. avr-gcc was missing the -mmcu=atmega328p flag. Once I added that and changed F_CPU to 16000000UL everything works.


8relay module asks more than specs I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)

How this is possible..?

Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.

Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.

The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.


Arduino hangs on second GSM message (was GSM based led matrix display) Friends, my team and I are working on a gsm based wireless display as a part of our project. We are using Arduino UNO as the microcontroller which is interfaced with a sim900 module. Upon arrival of a new sms in the gsm module, its contents will be passed on to the dot matrix led display through SoftwareSerial. We almost got the code working but the problem we now encounter is the reception of new sms. The code works fine for the first sms but to display the next new sms, we had to manually reset the Arduino every time. Can you guys help me? This is the code:

#include <SoftwareSerial.h>
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

int temp=0,i=0,x=0,k=0;
char str[160],msg[160];
void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

SoftwareSerial SIM900(0, 1);

void setup()
{

   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );

   dmd.clearScreen( true );
   Serial.begin(9600);

   SIM900.begin(9600);
   void SIM900power();
   delay(20000);

     SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

  void SIM900power()

{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop(){
for(unsigned int t=0;t<60000;t++){
  void serialEvent();
  if(temp==1)
  {
    x=0,k=0,temp=0;
    while(x<i)
    {
      while(str=='#')

      {
        x++;
        while(str!='*')

        {
          msg[k++]=str[x++];
        }
      }
      x++;
    }
   }
  }
     const char* dchars;
      dchars=msg;
     dmd.clearScreen( true );
   dmd.selectFont(Arial_Black_16);

  for(unsigned int i=0;i<=300;i++){
   dmd.drawMarquee(dchars,strlen(dchars),(32*DISPLAYS_ACROSS)-1,0);
   long start=millis();
   long timer=start;
   boolean ret=false;
   while(!ret){
     if ((timer+30) < millis()){
       ret=dmd.stepMarquee(-1,0);
       timer=millis();
     }
   }
 }
}

void serialEvent(){
  while(Serial.available())
  {
    char ch=(char)Serial.read();
    str[i++]=ch;
    if(ch == '*')
    {
      temp=1;
    }
  }
}

The DMD library was found on the net.

Does nothing clear 'i' at the end of a message?  If not, then long/unexpected/multiple messages can overflow your str[160] buffer.

It also looks like writing to the msg[160] buffer isn't well protected from overflow.


Not being able to use pushbutton I've been trying to detect a push button based on this tutorial, but due to my lack of skills/knowledge I haven't been able to make it work, could you guys point out what I'm doing wrong?

Any help is appreciated

My project on 123d circuits

My code:

void setup() {
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, HIGH);
  Serial.begin(9600);
}

void loop() {
  trigger();
}

void trigger(){
  if (digitalRead(2) == HIGH) {
    Serial.println("Hey");
    //turn();
  }
}

You seem to be suffering from three problems here:

A lack of understanding how the button's pins are configured
A lack of understanding of how breadboard works
A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground.  Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.


Attiny85 Clone Cannot set P1 to input Everything i read about the chinese Digispark attiny85 clones says you can use p0-5 as digitlal I\O (p5 as after fuse reset)
Simple test code for a button will not let me use P1 as an input tied to a simple button.
The code below works on p0,p2,p5 but will only interrupt the LED that is set to on, on P1.
#include "DigiKeyboard.h"

//pins 3 & 4 used for usb connection
bool buttonState1 = 0;

void setup() {
  pinMode(1, INPUT);
  digitalWrite(1, HIGH); //turn on pull-up resistor
}

void loop() {

    if (digitalRead(1)!= buttonState1){
      buttonState1 = digitalRead(1);
      if (buttonState1 == LOW)DigiKeyboard.print("test1");
    }

}

I had a quick look into the Schematics of a digisparc board. P1 is hardwired over an LED and a resistor to GND. If you turn on the PULL UP resistor for P1 the LED should light up and the voltage at P1 would be very low (it depends on the voltage divider that is built from the PULL UP resistor and the LED resistor); so the P1 reading should be LOW. If you connected the Button to GND and press it, the voltage at P1 drops to 0. But, that does not affect the LOW state. The program does not react. The LED turns off, because it is not powered anymore.
You could try to connect the button to +5V and do not setup a PULL UP resistor for P1. If you press the button the LED should light up and +5V should be at P1. It should change its state from high to low. (I did not tried that; but I see no reason, why it would not work).


Using Arduino as USB Device? I'm trying to get audio data from an ADC connected to an Arduino into a host PC.  I've done some digging and found LUFA, which I think Arduino uses under the hood. Is it possible to use the Arduino as a USB device, and if so, are there any examples?  Thanks!

LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.

But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.

The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:

  On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.


Where to find the attribution name for a certain board? I'm working on lcd128x64 spi library. And was working with my Arduino Atmega328p chip.

Now I want to run the code with my maple mini board too.
So I have to specify the name on the pins for each chip board.
But I want to learn the basics of how to write these statements.

Could you tell me where to find the attributions for each board ?

For now I want to define the pin names for the Atmega328p and maple mini. This is my intention:

#if defined(__AVR_ATmega328P__)
    #define CS_PIN                  10
    #define MOSI_PIN                11
    #define CLK_PIN                 13
#elif defined(STM32_SERIES_F1)
    #define CS_PIN                  PB12
    #define MOSI_PIN                PB15
    #define CLK_PIN                 PB13
#endif

I don't think that's %100 correct, but I'm pretty sure that it's not the correct names of boards.

The Arduino defines to identify a board are in form of ARDUINO_<board>, where <board> is the value from <x>.build.board from boards.txt for board <x>

For example for Arduino AVR boards, in the boards.txt file is uno.build.board=AVR_UNO so the define is ARDUINO_AVR_UNO.

And Arduino has 'architecture' identification define too. This has form of ARDUINO_ARCH_<arch.name>. The <arch.name> is the uppercase version of the folder name with the boards package version. For example AVR for packages/arduino/hardware/avr/1.6.21.


Pinout for Leonardo USB According to the docs, the Arduino Leonardo uses digital pins 0 and 1 for the USB D- and D+ lines. However, which is which? e.g. is D0=D+ or is D1=D+?

To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.

The USB does not go to pins 0 and 1.  The UART goes to pins 0 and 1 - that is a totally different interface.

The USB is connected to dedicated USB pins on the chip.  If you look at the Leonardo schematic you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.


Can't connect to my ESP32 board via serial I'm completely new to electronics work.

Today I've received the ESP32 board that I ordered. (It's a WROOM-32.) I followed the instructions here. I connected the board to my computer via USB and I successfully installed the CP210x drivers and got a new serial port COM3, but when I tried to connect to the board with that serial port, I got nothing. I'm on Windows 7.

I tried with Tera Term, and it just shows an empty screen.

I tried type COM3 in the shell, but got an empty string.

I tried doing esptool.exe --chip esp32 -p com3 erase_flash, but I get "Failed to connect to ESP32: Timed out waiting for packet header".

I tried playing with the two buttons on the WROOM32 board, but that didn't help.

Any idea what I'm doing wrong? I'm a complete newbie so it's likely that I'm forgetting something basic.

The issue is that the Serial port on the ESP32-WROOM setup is not like like on the Arduino. It seems that the initialisation will 'miss' the USB enumeration after reboot.

To fix this add a delay in your setup() function of 10 to 15-seconds before initialising the serial.

For example:

void setup() {
  delay(10000);
  Serial.begin(115200);

  Serial.println("Setting up Access Point...");
  .
  .
  .


ESP8266-12F accelstepper wont boot If I use 9, 10, 7, 6 , 8, 11 pins for accelstepper, ESP8266 wont boot
If I use other pins, all good.

What is the problem?

I use accelstepper and Arduino latest versions.

sketch which won't boot -

    #include <AccelStepper.h>
#include <MultiStepper.h>

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "wiflya";
const char* password = ".........";

#define HALFSTEP 8

// Определение пинов для управления двигателем
#define motorPin1  13 // IN1 на 1-м драйвере ULN2003
#define motorPin2  12 // IN2 на 1-м драйвере ULN2003
#define motorPin3  14 // IN3 на 1-м драйвере ULN2003
#define motorPin4  16 // IN4 на 1-м драйвере ULN2003

// Определение пинов для управления двигателем
#define motor2Pin1  6 // IN1 на 2-м драйвере ULN2003
#define motor2Pin2  3 // IN2 на 2-м драйвере ULN2003
#define motor2Pin3  5 // IN3 на 2-м драйвере ULN2003
#define motor2Pin4  4 // IN4 на 2-м драйвере ULN2003

// Инициализируемся с последовательностью выводов IN1-IN3-IN2-IN4
// для использования AccelStepper с 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motor2Pin1, motor2Pin3, motor2Pin2, motor2Pin4);

void setup() {
  //Serial.begin(115200);
  //Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    //Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  stepper1.setMaxSpeed(1300.0);
  stepper1.setAcceleration(400.0);
  stepper1.setSpeed(1300.0);

  stepper2.setMaxSpeed(1300.0);
  stepper2.setAcceleration(400.0);
  stepper2.setSpeed(1300.0);

  //stepper1.moveTo(20000);

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.begin();
}

void loop() {
    // Изменяем направление, если шаговик достигает заданного положения
  //if(stepper1.distanceToGo()==0)
  //  stepper1.moveTo(-stepper1.currentPosition());
  stepper2.runSpeed();
  stepper1.runSpeed();
  //stepper2.runSpeed();

  ArduinoOTA.handle();
}

Pins 6 to 11 of the esp8266 are QIO SPI pins connected to flash memory of the esp8266. You can't use them.


Can't cast char to unsigned char? byte RSV_Resp_test[3] = {'a', 'b', 0};
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

produces the error

error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                      ^

How can this be an ill-formed cast?  I just need to print the value as a ascii character, not as a number.

Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.


Measuring high frequencies (300kHz) with arduino I'm designing a frequency generator with ICL8038, which would output sine, square and triangle waves, which would reach frequency such as 300kHz.

I've already designed a circuit around the ICL8038, but I'm unsure how to measure the frequency, to show on LCD display.

I'm leaving down a schematics I've drawn.
A.Duty is going to the analog input of arduino, which will show the duty cycle between 2% and 98%. This will be going to a voltage divider to make a proportional input for the arduino analog input.

The "frequency pin" would be connected directly from the BNC connector from the casing, which means, that the input can be triangular, sine or square.

Just to mension, in case it makes any kind of difference, I'm planning to use just Atmega328 with 16MHz quartz and 2 capacitors, not exactly as Arduino UNO or NANO.
But the Atmega will have a arduino bootloader on it.

By the time asking about ICL8038, I've got also few questions about the IC:

You connect the FM Bias(pin 7) and SWEEP (pin 8) together to create sweep on the output of any kind of signal, whichever it is? This is fixed time constant or should I add some kinda coapacitor there?
What exactly does Tcap (pin 10) does? I've read through the datasheet but couldn't understand it's meaning.
How would I get proper voltage range every time, when I would change the input voltage of the ICL8038? (it has wide range of output signal, proportionall to the input; it goes from 36V to input, 28V max output)
For power supply would be proper LM317 as adjustable power supply (since it has low power consumption) and just use a potentiometer to adjust input of the ICL8038 and monitor the OUTPUT levels?
PIn 13 and PIn 14 are NC (not connected). Can I just connect them together and connect them to GND?

As if anybody knows for any "better" IC as this one is, please let me know.
I'm already going to have to buy it from China (this gives me doubts about the capabilities), I'd rather just order one from Europe or US.

To sample a 300kHz signal you need to sample at at least 600,000 samples per second (see Nyquist-Shannon Theorem).

The Arduino can sample at an absolute maximum of 125,000 samples per second.

A normal Arduino will not be able to sample the analog input fast enough to even remotely have a clue what the frequency is - let alone what shape the signal is (for that you would have to be sampling in the millions of samples per second).

You will need a much more powerful board than an Arduino to do it.

The other option is to feed the signal through a comparator (an op-amp with infinite gain) to convert the signal into a square wave. You can then use simple frequency counting to get the frequency (count the pulses within a given time frame - maybe 1 second).

As for the rest of your questions, you would be better off asking those on Electrical Engineering.


Can you query the current serial port's speed? Is there some code I can use to find out what the a chosen serial port's speed is running at ?

There is not a top level, easy to use way. Sorry. It is probably easier to just store your chosen baud rate in a variable when you setup the serial port.

Anyway, What you can try to do for the AVR-based, hardware UARTs is undo what Serial.begin does to set up a particular baud rate, but its a bit of a pain. This is the code for setting the baud rate:

  // Try u2x mode first
  uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;
  *_ucsra = 1 << U2X0;

  // hardcoded exception for 57600 for compatibility with the bootloader
  // shipped with the Duemilanove and previous boards and the firmware
  // on the 8U2 on the Uno and Mega 2560. Also, The baud_setting cannot
  // be > 4095, so switch back to non-u2x mode if the baud rate is too
  // low.
  if (((F_CPU == 16000000UL) && (baud == 57600)) || (baud_setting >4095))
  {
    *_ucsra = 0;
    baud_setting = (F_CPU / 8 / baud - 1) / 2;
  }

  // assign the baud_setting, a.k.a. ubrr (USART Baud Rate Register)
  *_ubrrh = baud_setting >> 8;
  *_ubrrl = baud_setting;

You can find the results of this by reading the right UCSRA, UBRRH, and UBRRL registers. On an uno those are the correct register names, on an mega its UCSR0A, UBRR0H, UBRR0L for Serial, UCRS1A ... for serial1 and so on. Non-avr boards (and Serial on a leonardo) will be totally different.

There will be a single state for those three registers on an AVR hardware serial port for a particular board (and frequency of that board) at each baud rate. You can try and make an equation to get the original baud rate out, but I recommend just comparing the direct values with a lookup of some kind because the integer arithmetic rounding errors will make it a huge mess.

For example, on my mega UBBR0H, UBBR0L, and UCSR0A are 0, 207, 2 at 9600 baud, but they are 0, 51, 2 at 38400 baud and 0, 16, 0 at 57600 baud.


Help with usbasp pinout I am having trouble figuring out the pinout of my 6 - pin USBasp Chinese clone that I got off eBay.
BEFORE YOU TELL ME TO LOOK AT THE PINOUT DIAGRAMS, I can tell you that my version of the usbasp has no way of telling which way is up and which ways is down. Images:

Look at the following pinout diagram (from telecnatron.com):

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header.  The header shell will have a triangle marking pin 1.  Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell).  Each socket on the cable also will have a triangle marking pin 1.


What's up with my code? Sorry if my code isn't well written or anything because I'm new to Arduino and coding in C, but what is wrong with my code?

int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val = 0)
  {
    pinMode(LED, HIGH);
  }
  else(val > 0)
  {
    pinMode(LED, LOW);
  }
}

Your IF statement, you're using: (val = 0), and I believe you meant (val == 0).

Also, you're using else(val > 0) and else doesn't need any argument. So the fixed code should look like:

int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val == LOW)
  {
    pinMode(LED, HIGH);
  }
  else
  {
    pinMode(LED, LOW);
  }
}


Arduino tool to enumerate where RAM is being used? In a sketch I have, I use a few libraries and have discovered that a large amount of RAM is being consumed.

Is there a tool that can identify how this RAM is being allocated, e.g. which libraries, which piece of code?

I use this code for Heap memory of AVR (UNO, Mega, etc.):

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

To show heap memory just use Serial.print("Write here a name of the function from which you print it"); Serial.println(freeRam()); anywhere in the code.

Compiler shows stack memory but not the heap, so this code helps me to find exact place where my program uses too much of heap memory. I just print it in every suspicious place in my code.

I hope this will help.


Communication via IP adress with Arduino IDE and ESP8266 I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.

I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks

You have the esp8266 talking.  Now you need to come up with a method of passing data from the arduinos to the esp.

You can use serial, you can use i2c, spi? Or something of your own design.  The problem wit using serial is the you are already using serial to communicate with the board from your PC.  You can use SoftSerial on the Arduino, but not sure how you'd do it on the ESP.
There are ways of making both boards work as master and slave i2c and spi, but it's probably overkill.
You could use two pins, one pin sends a binary bit and the other to clock the data, set high when new data has been written and set low when it has been read.
Then just use the same sort of algorithm as you did between you eps.

I have assumed that one Arduino is connected to one esp.  Let the ESPs worry about ip addresses.  If you want the Arduino to specify the destination then use a simpler addressing system than IP and let the ESPs translate that.


Serial print message results in gibberish I'm trying to print messages to the serial monitor, and all I get is some unreadable format.

Looping Serial.println("Wait...!"); gives me the following results:

ö’ö’ƒÕ•¬ƒ´¼Õƒö“ƒ²ƒƒƒ¬‘¼¬Õ”’“ƒ¬•

Why is it unreadable, and how do I make it print a readable format?

This "weird" result usualy happens when you select then wrong baud rate or a different one then the one you beginned the serial communication with in the program. Thus by using Serial.begin(9600);, you have to make sure that the serial monitor is actually set to a baud rate of 9600.


Addressing contents of array using incrementing variable Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number
but give 184 when addressed usin a varibale n that is incrementing?

PROGMEM const unsigned char COLSA[8] = {
      240, 240, 240, 240,
      240, 240, 240, 240};  //Stored pattern

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

void loop() {
  int n;
   for(n=0;n<8;n=n+1)
    {
      Serial.println(n);
      Serial.println(COLSA[1]);
      //n=2;  //If I use n in this way things are fine. It prints 240. Else it prints 184
      Serial.println(COLSA[n]);
    }
     delay(100);
}

Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.

However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.

BUT the array isn't in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong.  You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".

PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but they're not the same room.

So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:

     Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at v addresses on from the start of the COLSA array in PROGMEM.


Voltage sensor Calibration We had used a voltage sensor unit to measure the voltage of the odroid board using an Arduino Uno. wWhen I uploaded the sketch and got the output, the value which was being displayed was around 4.7 to 4.9V, but when I measured the top of the voltage sensor module using a multimeter, it had a stable voltage of 5.08V. Is their any particular reason why this is happening?

Voltage sensor module

int analogInput = A0;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
int value = 0;
void setup() {
pinMode(analogInput, INPUT);
  Serial.begin(9600);
  Serial.print("DC VOLTMETER");
}
void loop() {
  // read the value at analog input
value = analogRead(analogInput);
vout = (value * 5.0) / 1024.0;
vin = vout / (R2 / (R1 + R2));
Serial.print("INPUT V= ");
Serial.println(vin, 2);
delay(500);
}

Multimeters are designed to provide a stable response. It would be averaging the readings.

As far as the difference in voltage reading, if you are using the Arduino board as is the default is to assume a reference voltage for the A/D as being 5.0 volts.(for your calculations) That may not be the case. Also there may be a tolerance issue on the measurement board, but I think the reference for the A/D on the Arduino is the bigger issue.


Trouble while using Arduino DUE as programmer I'm trying to use the arduino DUE board as a  AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:

#define F_CPU 10000000
#include <avr/io.h>
#include <util/delay.h>

int main (){
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        _delay_ms(1000);
    }
    return 0;
}

I want to use the internal oscillator and based this example  I've adjust the makefile:

DEVICE     = atmega328p
CLOCK      = 8000000
PROGRAMMER = -c arduino -P COM10 -b 19200
OBJECTS    = main.o
FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

the problem that I have is that when run :

make flash

I get the following :

and yes the port COM10 is definitely correct.

does anyone have a suggestion how to solve this ?

thanks in advance !

There error you have is from avrdude failing to get a communication link established to the 'programmer' (which manipulates the target.)

Here is a link that may help with the connection

Stk500 error

Here is another relative link that may help

Arduino ISP on DUE

Best of luck.


How to set counter for two ultrasonic sensors? This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.

This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.

#define echo1 3 // Set your echo pins here
#define echo2 4

unsigned long startTime = 0;
unsigned long endTime = 0;

void setup() {
}

void loop() {
    // You can do stuff here

    // If the first sensor goes off
    if (digitalRead(echo1) && (0==startTime))
    {
        // Remember the time this happened
        startTime = millis();
    }
    // If the second sensor goes off
    if (digitalRead(echo2) && (0==endTime))
    {
        // Remember the time this happened
        endTime = millis();
    }

    // If we have both start and end times
    if (0 != startTime && 0 != endTime)
    {
        unsigned long duration = endTime - startTime;
        // Do what you want with "duration"
    }

}


ESP8266 - UDP send interruptions I'm trying to transfer data from ESP8266(NodeMCU ESP12E) to my laptop. I'm coding ESP using Arduino IDE. I am able to receive correct packets (each containing 400 bytes) on a visual basic console program. However, to see whether the transmission is continuous or not, I have toggled an output pin whenever UDP.endpacket() returns 1. I observed waveforms on DSO. I found that UDP.endpacket() does NOT return 1 many times and the there is no transmission from ESP for a significant amount of time (milliseconds). Refer attached waveforms.

Why does UDP.endpacket() return 0 for such long time? Why is UDP transmission getting interrupted? How can I solve this? Please feel free to ask for more details if necessary.

Code :

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

const char* ssid = "Connectify-me33";
const char* password = "donfour276";

WiFiUDP Udp;
unsigned int localUdpPort = 65000;

unsigned int dest_port = 11000;

unsigned char clientBuf[400];
int clientBuf_len=0;

#define test_pin 5

int return_udp_fcn = 0;

void setup()
{

  WiFi.begin(ssid, password);
  delay(5000);

  Udp.begin(localUdpPort);

  pinMode(test_pin, OUTPUT);
  digitalWrite(test_pin, HIGH);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);

}

void loop()
{
        digitalWrite(test_pin, HIGH);

        //filling up buffer
        for(clientBuf_len = 0; clientBuf_len<=399; clientBuf_len++)
        {
            clientBuf[clientBuf_len] = 0x7E;
        }

        //UDP transmit
        Udp.beginPacket("172.22.0.1", dest_port);
        Udp.write((const uint8_t *)clientBuf, 400);
        return_udp_fcn = 0;
        return_udp_fcn = Udp.endPacket();
        if(return_udp_fcn){
          digitalWrite(test_pin, LOW);
        }
        delayMicroseconds(100);

}

I think you need a delay(1); after your call to write().

There is/was a bug where the underlying buffer files up and can't get time to clear.  It looks like it will require a change to the ESP8266 firmware from the manufacturers before it will get fixed properly.

See what you think:

https://github.com/esp8266/Arduino/issues/1696

https://github.com/esp8266/Arduino/issues/2285


Fried two Arduino Nano's but works when powered It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.

When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...

I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.

I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!

Does anyone know why it's doing this? What did I see smoking? Is it repairable?

Judging by your list of observations:

Cannot power through USB
Can power from external source
Can program through USB

it is most likely that the power feed from the USB to the +5V rail has been interrupted.  There is only one component in that link - the diode D1 (an MBR0520).  That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that.  A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.

The diode is on the underside of the Micro and close examination may show a small crack in the surface of it.  That is if it's still there.  I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).


Printing Serial Readings for 2+ Parallax Ping Sensors trying print values for two sensors, one works the other is 0, any tips on how i can use more than one?

const int pingPin = 10;
const int pingPinz = 11;
unsigned int duration1, duration2, inches1, inches2;

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

void loop() {
  pinMode(pingPin, OUTPUT);          // Set pin to OUTPUT
  pinMode(pingPinz, OUTPUT);          // Set pin to OUTPUT
  digitalWrite(pingPin, LOW);        // Ensure pin is low
  digitalWrite(pingPinz, LOW);        // Ensure pin is low
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);       // Start ranging
  digitalWrite(pingPinz, HIGH);       // Start ranging
  delayMicroseconds(5);              //   with 5 microsecond burst
  digitalWrite(pingPin, LOW);        // End ranging
  digitalWrite(pingPinz, LOW);        // End ranging
  pinMode(pingPin, INPUT);           // Set pin to INPUT
  pinMode(pingPinz, INPUT);           // Set pin to INPUT
  duration1 = pulseIn(pingPin, HIGH); // Read echo pulse
  duration2 = pulseIn(pingPinz, HIGH); // Read echo pulse
  inches1 = duration1 / 74 ;        // Convert to inches
  inches2 = duration2 / 74 ;        // Convert to inches
  Serial.println(inches1);            // Display result
  Serial.println(inches2);            // Display result
  delay(200);                 // Short delay
}

Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.

Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.

So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.


Sending RFID data to an Android app I have fetched the RFID tag value using an RFID reader and it is now in my Arduino's serial monitor. I have to send it to an Android app. I need help on how to do this.

I don't want to use Bluetooth.

To send values to Android App you need some medium either it is wireless (Bluetooth, which you don't want to use, or via internet by using a web server on Arduino or PC, through which the Arduino is connected) or wired through Serial communication.


What happens if I draw too much current from ATMEGA IO pin? I revisited an older device that I made and discovered, that I had an 8 Ohm speaker connected directly to ground and an IO pin of an Atmega328P. According to my calculation that means that the pin would have to source 625 mA, which is way above the 40 mA that any single port should be able to source and even above the 200 mA that the Vcc and GND support. Yet it somehow worked and the chip seems to be working just fine. The application uses a duty cycle of 50%, so in the best case it would use maybe 312.5 mA, which is a little better but still way above the ratings.

So my question is, what happens if the output pin is asked to source more than it's rating?

I've seen chips that just release their magic smoke while others just can't keep up with supplying that kind of voltage, so only the voltage drops without any other problems. How does the Atmega328P handle this?

The Atmega clearly didn't burn through, but what other kind of damage should I expect?

There's a few crude calculations you can do using some numbers from the datasheet.

This graph is in the datasheet:

It shows the voltage dropped by the high-side MOSFET driver in the IO pin for different amounts of current draw. From that we can get its resistance R(DSON).

For instance at 10mA, at 25C, the output voltage would be 4.75V. That's a 0.25V drop from the 5V supply voltage. So we can calculate the resistance as:

R=V/I = 0.25V / 0.01A = 25Ω

Now we have that resistance we can use it to calculate the actual current from the IO pin with an 8Ω load.  Simply add the two together:

25Ω + 8Ω = 33Ω

Now we can calculate the current through that circuit:

I=V/R = 5V / 33Ω = 0.152A

That is, of course, way above what the IO pin can actually supply (or so the datasheet says).

So what happens? Well, two things, basically:

The voltage on the IO pin will be below the 4.2V specification for the minimum of an output pin when HIGH, and
It will get hot.

The actual voltage will be, of course, V=I×R = 0.152A × 25Ω = 3.8V droped, so 5 - 3.8 = 1.2V

What is more critical, though, is the heat.  152mA through a 25Ω resistance generates P=I²R = 0.152 × 0.152 × 25 = 0.5776W. That's quite a lot. Enough to melt the internal circuits in the chip and release the Magic Smoke™.

Running at 50% duty cycle, though, makes a difference. That's 50% of the power, which makes a big difference to the heat.

What would the actual allowable heat be? Well, at 40mA, with 25Ω, that is 0.04 × 0.04 × 25 = 0.04W.

So you're generating more than 14 times the amount of heat you are allowed to. Even at 50% duty cycle, that's over 7x the limit.

Will it kill the chip? Well, possibly, possibly not. It depends how rugged the chip is and how well it can withstand the heat. Short bursts may be OK since the heat doesn't build up enough to melt things. Extended use, though, will make it get too hot, and things will go pop.


Does serial communication between PC and Arduino has to be in a loop? I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the ser.write() command in a while loop (which I want to avoid) the sketch runs fine.

For example, I wrote this script on my PC -

import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.

My Arduino code-

int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte);
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put ser.write in a loop. I can't put ser.write in a loop as my script won't run further.

So how can a value be passed to an Arduino without having to put the ser.write() in a loop.

Thanks!

EDIT :

I wrote a new sketch, but it still doesn't work. Here's the sketch -

int ledPin = 13;
char data = ' ';

void setup(){
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
}

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

Here's an image of the wiring -

Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.


How to compare payload value? Connecting my ESP8266 device to an IOT cloud service. When I push a button in the dashboard, it sends either 1 or 0. Then my ESP should turn a pin HIGH if signal received was 1 or Low if it was 0. Here is the code of the method in question:

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

  if ( (byte)payload[0] == 0) {
    digitalWrite(13, LOW);
    Serial.println("Setting PIN on to LOW");
  } else {
     digitalWrite(13, HIGH);
     Serial.println("Setting PIN off to HIGH");
  }

}

When sending a 1 signal, serial monitor displays:

  Message arrived [/v1.6/devices/esp8266/relay/lv] 1
  Setting PIN off to HIGH

When sending a 0 signal, serial monitor displays:

  Message arrived [/v1.6/devices/esp8266/relay/lv] 0
  Setting PIN off to HIGH

So it seems like it always goes into the else clause. Similarly, if casting the value as char:

if ( (char *)payload[0] == 0)

Then it will always go into the first condition payload[0] == 0 regardless of the value received.

You receive the character 0 or 1 but compare it to the value 0 or 1. The two things are very different.

You are sending ASCII but comparing it to decimal.

Instead you need to compare like for like.  Either:

if (payload[0] == '0') {

Or:

if (payload[0] == 48) {

You can find an easy reference for the full ASCII table here.


Arduino PC to RS232 not reading data I am trying to read data from RS232 Shield with an Arduino Mega.

This is the schematic pin, TX is 3 and RX is 2.

Wiring:
PC > USB-RS232 cable > Arduino RS232 Shield.
Software to send/receive data:
Hercules Setup Utility

From Arduino, I can transmit data to RS232, the TX led blink and I got the value at PC.
From PC, I send the data, the RX led blink but nothing is showed in Arduino Monitor.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

I also tried to move RX and TX to Pin 15 and 14 but worked as the same as before.

Found the problem, cant use PIN 2 as RX.

  Note: Not all pins on the Mega and Mega 2560 support change
  interrupts, so only the following can be used for RX: 10, 11, 12, 13,
  50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69


Can an Arduino access a network database? This is a similar question to a previous question I have asked. Primarily I am looking to find out more about the capability of the Arduino.
Here is the scenario. There is a PC that is connected to a database via local network or internet. Is it possible that by plugging an Arduino in the usb port of this PC the Arduino could read from this database by means of an SQL query? Given that the Arduino would have the correct credentials. I am not asking if the Arduino could Hack into the database. I am asking if it is capable of accessing the database at all. Also this must be done without installing any special program on the PC. If that isn't possible, what type of program is needed? I am not necessarily looking for a tutorial, but if you could point me in the right direction that's be great.
Thank you.

The M0 has a "native" USB interface. Because of that it can be programmed to appear as any kind of device you can image - as long as you can find (or write) the code to do that.
You could (though I have never tried and don't know what code is readily available for this) program the USB interface to be a USB Ethernet device. Your computer would then see it as a new Ethernet interface.
It would then be trivial to "share" your internet connection in Windows with that new Ethernet interface (nothing to install, but settings on the computer need changing), and your Arduino would then be on the network the same as your computer (just as if you'd given it a WiFi interface or something like that). Then it can connect to the database itself (or to a website that communicates with the database if that is simpler) and do whatever it needs to do.
Step one, of course, will be to find a library that will give you that USB Ethernet interface...
A much simpler option, if you're willing to change your M0 for something else, is to use a chip with a built in WiFi interface, such as the ESP32. There's no need for your computer at all then.


expected ')' before executarAcao here is the code:

#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void setup() {
  // put your setup code here, to run once:
    pinMode(pinSom, INPUT);
    pinMode(pinRele1, OUTPUT);
    pinMode(pinRele2, OUTPUT);
}

void loop() {{
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom) ;

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {

      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma)
     tempoEspera = 0;
  }

    //caso exceda o tempo maximo entre palmas, zera o contador de palmas

    {

    if ( (contaPalmas != 0) && ((millis() - tempoEsperaEntrePalmas)
    (i get the error here) executarAcao();
    contaPalmas = 0;
    TempoEsperaEntrePalmas = millis();

 }
}
void executarAcao()
{
   switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
   }

You're missing closing brackets in the line above your error.

It compiles now, but I have no idea whether it works as you intend.
Try forcing yourself to always open and close brackets when you begin one, and making sure to indent properly.

Also, Arduino code is case-sensitive.

#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void executarAcao()
{
  switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
  }
}

void setup() {
  // put your setup code here, to run once:
  pinMode(pinSom, INPUT);
  pinMode(pinRele1, OUTPUT);
  pinMode(pinRele2, OUTPUT);
}

void loop() {
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom);

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {
      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }
  else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma) {
     tempoEspera = 0;
  }
    //caso exceda o tempo maximo entre palmas, zera o contador de palmas
  else {
    if ((contaPalmas != 0) && (millis() - tempoEsperaEntrePalmas)) {
      executarAcao();
      contaPalmas = 0;
      tempoEsperaEntrePalmas = millis();
    }
  }
}


Arduino Ethernet Shield on Arduino Mega Pin Usage! I currently have an Arduino Ethernet Shield which is Mega Compatible. I've found on the Arduino Ethernet Library https://www.arduino.cc/en/Reference/Ethernet that the Shield uses different Pins on the Arduino Uno and Arduino Mega. How is this possible? The Ethernet shield isn't connected to those pins mentioned.

Arduino Uno:
Pin: 13 - SCK
Pin: 12 - MISO
Pin: 11 - MOSI
Pin: 10 - SS for Ethernet Controller

Pin: 4 - SS for SD Card

Arduino Mega:
Pin: 52 - SCK
Pin: 50 - MISO
Pin: 51 - MOSI
Pin: 53 - SS for Ethernet Controller

Pin: 4 - SS for SD Card

Those 4 pins D50 to D53 are the ICSP pins which appear twice on the MEGA; the Ethernet Shield uses the second set of connections located in the middle of the Mega board.

The header files gets told (by the Arduino IDE) that the board is a MEGA so the compiler uses those pin numbers to connect.


Connect Arduino to an external microSD card reader I have a camera with a microSd card reader that is the only output type.
I want to read the microSd when the camera makes a photo.
How can I read it with an Arduino?
Duplicating the reader connections and join it to my Arduino microSd reader?
Or I can try to connect to the circuit (its very very small)?
Do you think I can put an ESP8266 to the camera?

Thanks for all!!!

You cannot

SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.

Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)

Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.

Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.

For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.


How do I use an image sensor with an arduino uno? I have recently taken apart an old digital camera for its parts and I have found an image sensor inside it.

For those of you who don't know, an image sensor measures light; the shutter opens, light hits the sensor and the sensor converts this light into data to be stored as an image.

My question is how can I implement it into a project? What equipment do I need? It has a tape wire so I'm not really sure how I can use it. I have attached a photo of it also. Thanks!!

You need to find markings on it and figure out what the component actually is.  Then you can maybe find a datasheet for it that explains how it works and commmnicates.  Once you know that you can decide if that's something you can do with an Arduino.  Be prepared to learn that Arduino might not be big enough or fast enough to do anything with that particular sensor.


Can I load programs through the RS232 pins? Can I upload new programs onto a MEGA2560 through a serial port connected to pins 2&3?  (through the correct RS232<->TTL level shifters)

I know the 16U2 chip acts as a USB->serial converter and it also asserting the reset which starts the bootloader running on the 2650. Does it do anything else?

As long as I can time the reset correctly, is there anything else preventing reprogramming directly through the RX/TX pins?

And if I do this, will the application program still be able to use the serial channel?

The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.

There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in).

Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.

I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6).


Car Control via OBD-II port I was wondering if it is possible to send commands through the OBD-II on my car via an Arduino Uno Rev 3 with a CAN-BUS Shield from SEEDStudio. I am just going for basic functions i.e. lock control, window control, lights nothing really outside of those basic functions. My shield is currently in the mail and I was hoping anyone could shed light as to if this is even possible. My car model is a 2004 Mini Cooper S. Thanks.

Technically, yes: If you hook up this shield to the car buses through OBD-II, and know which messages to send (e.g., ones that the car will accept and work with), then it will work.

The problem is: There are some "official" messages, basically emission related stuff, that are mandatory on every cars. There are lists of these out there.
Unfortunately, most messages are OEM dependent (including those that may control the basic features you mentioned), and they don't want you to mess around this.
Said differently: The semantic of CAN frames/messages varies from one car to another.

Being able to send receive CAN frames (which this shield is) is like being able to emit sounds & hear them: Mandatory, if you want to discuss with someone, but useless/not enough if you do not speak the same language.


Physical safety: Prevent linear actuator from crushing my fingers Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.

How could I detect trapped objects effectively?

Elevators often have light barriers, but the problem here is that the opening has a 360° border.
Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.

I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.

The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...

A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).

You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.

Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.

The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

OK Its not an electrical solution.


Will I be able send a HTTP request using the Arduino Yún? After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an Arduino with built-in wifi.

Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?

Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).

Looking at your other two questions as well I see you have had limited success with a ESP8266.  I have never used a Yun, but I haven't seen much good stuff about them on here.  If you want a Linux based none real time system then you may as well get a PI.

Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link.  You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys.  The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package.  It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in.  If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.

Now I suspect you have an ESP-01 board and are wondering what the [heck] I am talking about, 10 pins.  The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1).  You might want to look at a Wemos D1 or a Node MCU.  Both are fully fledge dev boards, jus plug in the USB and away you go.

So to answer your question:

Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)