text:
How to get PWM frequency to ~14KHz?
I found this question:
Set PWM frequency to 25 kHz
It is useful, however, I want to use it to generate ~14KHz?
int d = 0;            // pwm value

void setup()
{
  //  Sets Timer1 to Phase Correct
  //  F_CLOCK / ( Prescaler * ORCR1A * 2 ) = Freq in Hz
  //  16000000 / (1 * 512 * 2 ) = 15625 Hz
  TCCR1A = _BV (WGM10) | _BV (WGM11) | _BV (COM1B1);  // Phase Correct
  TCCR1B = _BV (WGM13) | _BV (CS10);                  // Phase Correct / Prescale 1
  OCR1A = 571;                                        // Sets Top to 512 --571
  OCR1B = 0; // Sets Pwm =
    pinMode(10, OUTPUT);
    pinMode(0, INPUT)
}

void loop()
{
  d = (analogRead(0));
  d = map(d, 0, 1023, 0, 512);
  OCR1B = d;
}

I used this sketch to test the frequency which works good. If I change the pinMode(10, OUTPUT);, into: pinMode(9, OUTPUT); and there is no output, why?

The top of timer1 is set to 320. I think that a value of 571 will result in about 14010.5 Hz. Can you tell which sketch you are using and please tell us what it is for.

Thank you Jot, I'll use the last code in the 'Set PWM frequency to 25 kHz' to control a motor driver which asked a PWM frequency about 14KHz.

Please keep in mind that this site is for questions and answers. Preferably good and clear questions and one or more good and clear answers. This is the pinmapping for an arduino uno and nano: https://www.arduino.cc/en/Hacking/PinMapping168 Pin 10 is OC1B and pin 9 is OC1A. That are outputs of timer1. In the datasheet of the atmega328p you can find how the pwm modes are used and how the output pin (or internal interrups) can be used with pwm. You map the signal up to 512, but the pwm counts to 571, so your maximum pwm is 89%.

Take this sketch, replace 320 by 571 and do not change anything else.

Thank you Edgar, both pin 9 and 10 working now.

When I put this PWM code into my driver code, there was conflict of using timer1 with VirtualWire library. How can I use timer2 to get 14khz? I am using UNO.

laoadam, to get someone's attention use for example @Jot then I will be notified. Timer2 is only 8 bits and has other output pins. You can move the VirtualWire to Timer2. Upgrade to RadioHead in RH_ASK mode and change it to Timer2 (search for "timer2" on this page: https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html ). RadioHead uses a lot more memory than VirtualWire.

@Jot Thank you Jot, I have shift the PWM frequency set by Timer2, output by P3 and P11, it's works well now at ~3.9 KHz, no yet what I need ~14khz, at lest made progress. There is new problem came up when I use this sketch on my 30A motor driver which has (PWM1+DIR1) for motor 1, but the original sketch used (PWM1+AIN1+AIN2) to control motor 1.

With timer1 the resolution was 571 steps and with timer2 it is below 256. I forgot about all those pwm modes, so I'm not sure if timer2 has the same pwm mode as timer1. You make it seem as if you  want to control a stepper motor with pwm. I don't understand that. You can ask a new question for the pwm/dir/ain signals. Tell what motor it is, what the driver is, what the signals from the arduino are, with links, schematics, pictures, photos, everything.

@ Jot, thank you Jot, the timer2 does not works that way. I have post another question.


text:
Program does not seem to be passing from setup to loop, or printing to SD card
I am trying to write code to test servo motors using an encoder. I create a file in the setup part, and then set 1500 microseconds to 0 for the encoder. However, if I try to print something to the SD card after I create the file, it will not print to the card. The file is always created but nothing is written to it. I have tested the mapping function separately and it works, but the code never reaches that point. It quits sometime after creating the mapping.txt file but before starting the loop.

// voltage to servo is divided by 3 to get to something usable for teensy

#include <Encoder.h>
#include <SD.h>
#include <SPI.h>
#define numFrame 6750

float twopi = 2.0 * PI;
float hz2rps = twopi;
float rps2hz = 1/hz2rps;

//for the encoder
// Encoder Pins for Channel A and B.
int encPin1=6;
int encPin2=7;

// Per the label on the Encoder this should be 1250 CPR, but 5000 gives actual angle (and is an option that could have been added after purchase)
int pos[numFrame]; // Array to store positions
int pw[numFrame]; // Array to store analog input of PWM

// for writitng to the SD card
File mappingandrange;
File step_file[10];
File bandwidth_file[10];
int filenum=0;
int chipSelect=10;
char buffer[10];

// Encoder
Encoder myEnc(encPin1, encPin2);

float poscmd;
int8_t poscmdInt[numFrame];

// timing variables to stabilize the frame
unsigned long start_frame;
unsigned long stop_frame;
unsigned long stopstop_frame;
unsigned long delta_frame;

int freqFrame_hz = 2000;
int timeFrame_us = 1000000/freqFrame_hz;
int writePwmPin = 5;
int readPwmPin = 2; // Analog pin to readback the PWM out
float freqWritePwm_hz = 333;
float freqPwmCenter_us = 1520.0;
float pulse = (freqWritePwm_hz / 1000000.0) * 65535.0;

float mag = 500.00;
float magScale = pow(2, 15) / mag;
float tEnd_s = 3.0;
float timeCurr_s = 0.0;
float freqStart_rps = 1 * hz2rps; // Start Frequency**
float freqEnd_rps = 30 * hz2rps; // End Frequency**
float freqK = (freqEnd_rps - freqStart_rps) / (2.0 * tEnd_s); // Parameter for Sweep

//things leftover from when i tried to write code
int freq=250;
double average;
double lengthtotalmicros;
double percent;
int analogfreq;
const int servopin=5;
int num=0;
int j=0;
int i=0;
float mapp;
double resistance=1; //resistance of resistor used to measure current though servo
int voltagepin1=1;//very high resistance bridged in parallel with servo
int voltagepin2=2;//very high resistance in parallel with servo
int voltagepin3=3;//low resistance in series with the servo

void setup()
{
  pinMode(servopin, OUTPUT);

  //setup for the sd card
  pinMode(chipSelect, OUTPUT);
  SD.begin();
  mappingandrange=SD.open("mapping.txt", FILE_WRITE);

  //initalize the servo to 1500 microseconds and the position to 0
  servowrite(1500, freqWritePwm_hz, servopin);
  delay(500);
  myEnc.write(0);

}

void loop()
{
  mapp=mapping();

  //setup to run servo_step with magnitude 10 degrees
  filenum=1;
  freqFrame_hz=2000;
  freqWritePwm_hz=333;
  mag=10.0;//magnitude in degrees
  servo_step(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp, tEnd_s);

  //setup to run servo_step with magnitude 60 degrees
  filenum=2;
  mag=60.0;//magnitude in degrees
  servo_step(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp, tEnd_s);

  //then do setup for the servo_bandwidth function.
   freqFrame_hz = 151; // Command frame rate **** how fast teensy loop runs
   timeFrame_us = 1000000/freqFrame_hz;
   writePwmPin = 5; // PWM write pin # ****servo input pin
   freqWritePwm_hz = 333; // PWM rate **** pwm pulse frequency
   freqPwmCenter_us = 1520.0; // PWM center frequency
   pulse = (freqWritePwm_hz / 1000000.0) * 65535.0; // Scaling for pulse width duty cycle

   mag = 40.0; // This is the PWM magnitude, need to convert from angle to PWM **** need to later convert from degrees using mapping
   magScale = pow(2, 7) / mag; // Scalling so that PWM change can be logged as int8
   tEnd_s = numFrame / freqFrame_hz; // End Time** three below possibly part of function call and change run to run
   timeCurr_s; // Current Time
   freqStart_rps = 1 * hz2rps; // Start Frequency**
   freqEnd_rps = 30 * hz2rps; // End Frequency**
   freqK = (freqEnd_rps - freqStart_rps) / (2.0 * tEnd_s); // Parameter for Sweep

   mag=1;
   filenum=1;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=3;
   filenum=2;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=5;
   filenum=3;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=10;
   filenum=4;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);
   mag=20;
   filenum=5;
   servo_bandwidth(filenum, freqFrame_hz, writePwmPin, freqWritePwm_hz, mag, mapp,tEnd_s, freqStart_rps, freqEnd_rps);

for( ; ; )
{
}

}

float mapping()
{

  servowrite(1200, freqWritePwm_hz, servopin);
  delay(250);
  pos[0]=myEnc.read();
  j=1300;
  for(int i=1; i<7; i++)
  {
    servowrite(j, freqWritePwm_hz, servopin);
    delay(200);
    pos[i]=myEnc.read();
    j=j+100;
    mappingandrange.println(pos[i]);
  }
  average=0;
  for(i=0; i<7; i++)
  {
    average=average+pos[i];
    pos[i]=0;
  }
  average=average/i;
  mappingandrange.print("The average number of positions per microsecond lengthened is ");
  mappingandrange.println(average);
  mappingandrange.print("Which corresponds to ");
  mappingandrange.print((average/5000.0)*360.0);
  mappingandrange.print("degrees per microsecond lengthened, or ");
  mappingandrange.print((average/5000.0)*3600.0);
  mappingandrange.println(" degrees per 100 microsecond change");

  mapp=(average/5000.0)*360.0;
  mappingandrange.close();
  return mapp;
}

void servowrite(int widthmicros, int freq, int servopin)
{
  analogWriteFrequency(servopin, freq);
  lengthtotalmicros=(1.0/freq)*1000000.0;
  percent=widthmicros/lengthtotalmicros;
  analogfreq=percent*256.0; // changes how much of the duty cycle is up from 0 to 256
  analogWrite(servopin, analogfreq);
}

//input the magnitude in degrees and then the function will convert them to pwm values necessary
void servo_step(int filenum, int freqFrame_hz, int writePwmPin, float freqWritePwm_hz, float mag, float mapping, float tEnd_s)
{
    //sd assumes that pinMode(chipSelect, OUTPUT) and SD.begin, and file has been declared
  sprintf(buffer, "servo_step %d.txt", filenum);
  step_file[filenum]=SD.open(buffer, FILE_WRITE);
  step_file[filenum].println("Frequency sweep for the given parameters");
  step_file[filenum].print("Command frame rate: ");
  step_file[filenum].println(freqFrame_hz);
  step_file[filenum].print("PWM pulse frequency: ");
  step_file[filenum].println(freqWritePwm_hz);
  step_file[filenum].print("The magnitude of the sweep in PWM microseconds is: ");
  step_file[filenum].println(mag/mapping);
  step_file[filenum].print("This corresponds to a magnitude in degrees of: ");
  step_file[filenum].println(mag);

  //converting degrees magnitude to pwm magnitude
  mag=mag/mapping;

  analogWriteResolution(16); // Setting the write resolution for PWM
  analogWriteFrequency(writePwmPin, freqWritePwm_hz); // Setting the frequency for the PWM update rate
  analogWrite(writePwmPin, freqPwmCenter_us * pulse); // sending the servo to neutral

  analogReadRes(16); // set A/D converter to 16 bit

  delay(1000); // waiting for user to pull up debug serial channel

  //end of setup part of function now moving on to the loop part of function which only actually runs once anyway
  //should run through the frequewncy sweep and print the data to the sd card for the given parameters

  delay(1000); // waiting for starting the test

  poscmd = 0.0;
  int i = 0;
  while(timeCurr_s < tEnd_s){
    start_frame = micros(); // get the start of the frame

    timeCurr_s = (float)(i * timeFrame_us) / 1000000.0;
    if(timeCurr_s > 1 & timeCurr_s <= 2)
    {
      poscmd = mag;
    }
    else if(timeCurr_s > 2)
    {
      poscmd = 0.0;
    }

    poscmdInt[i] = (int)(poscmd/magScale);

    analogWrite(writePwmPin,(freqPwmCenter_us + poscmd) * pulse); // write servo command
    pw[i] = analogRead(readPwmPin); // read the pwm signal
    pos[i] = myEnc.read();

    i++;

    stop_frame = micros(); // get the end of the frame
    delta_frame = stop_frame - start_frame;
    if(delta_frame < timeFrame_us){
      delayMicroseconds(timeFrame_us - delta_frame); // sleeping to stabilize the frame at 100 Hz
    }
  }

  delay(1000); // wait to get the serial monitor open
  for(int j = 0; j < i; j++){ // printing out the stored data so we can import to MATLAB
    step_file[filenum].print(pos[j]);
    step_file[filenum].print("\t");
    step_file[filenum].print(freqPwmCenter_us + (float)(poscmdInt[j]*magScale));
    step_file[filenum].print("\t");
    step_file[filenum].println((float)(pw[j]));

  }
  step_file[filenum].close();
}

void servo_bandwidth(int filenum, int freqFrame_hz, int writePwmPin, float freqWritePwm_hz, float mag, float mapping, float tEnd_s, float freqStart_rps, float freqEnd_rps)
{
    // assumes that pinMode(chipSelect, OUTPUT) and SD.begin();
  sprintf(buffer, "servo_bandwidth %d.txt", filenum);
  bandwidth_file[filenum]=SD.open(buffer, FILE_WRITE);
  bandwidth_file[filenum]=SD.open(buffer, FILE_WRITE);
  bandwidth_file[filenum].println("Frequency sweep for the given parameters");
  bandwidth_file[filenum].print("Command frame rate: ");
  bandwidth_file[filenum].println(freqFrame_hz);
  bandwidth_file[filenum].print("PWM pulse frequency: ");
  bandwidth_file[filenum].println(freqWritePwm_hz);
  bandwidth_file[filenum].print("The magnitude of the sweep in PWM microseconds is: ");
  bandwidth_file[filenum].println(mag/mapping);
  bandwidth_file[filenum].print("This corresponds to a magnitude in degrees of: ");
  bandwidth_file[filenum].println(mag);
  bandwidth_file[filenum].print("The starting frequency is: ");
  bandwidth_file[filenum].println(freqStart_rps);
  bandwidth_file[filenum].print("The ending frequency is: ");
  bandwidth_file[filenum].println(freqEnd_rps);

  mag=mag/mapping;

  analogWriteResolution(16); // Setting the write resolution for PWM
  analogWriteFrequency(writePwmPin, freqWritePwm_hz); // Setting the frequency for the PWM update rate
  analogWrite(writePwmPin, freqPwmCenter_us * pulse); // sending the servo to neutral
  delay(1000); // waiting for user to pull up debug serial channel

  // loop part of function below
    delay(1000); // waiting for starting the test

  for(int i = 0; i < numFrame; i++){
    start_frame = micros(); // get the start of the frame

    timeCurr_s = (float)(i * timeFrame_us) / 1000000.0; // Current time
    poscmd = mag * sin(freqStart_rps * timeCurr_s + freqK * timeCurr_s * timeCurr_s); // Sweep signal
    poscmdInt[i] = (int)(poscmd*magScale); // integer conversion for logging
    analogWrite(writePwmPin,(freqPwmCenter_us + poscmd) * pulse); // write servo command
    pos[i] = myEnc.read(); // read encoder value

    stop_frame = micros(); // get the end of the frame
    delta_frame = stop_frame - start_frame;
    if(delta_frame < timeFrame_us){
      delayMicroseconds(timeFrame_us - delta_frame); // sleeping to stabilize the frame
    }
  }
  //delay(1000); // wait to open the serial monitor
  for(int j = 0; j < numFrame; j++){ // printing out the stored data
    bandwidth_file[filenum].print(pos[j]);
    bandwidth_file[filenum].print("\t");
    bandwidth_file[filenum].println(freqPwmCenter_us + (float)(poscmdInt[j]/magScale));
  }
  bandwidth_file[filenum].close();
}

You can't really expect people to wade through over 300 lines of poorly formatted code to find your bugs. At the very least, you should have isolated the part of the code you suspect is wrong, as well as say what individual tests you run to ensure it's not some piece of hardware that's failing.

Its very difficult to try and guess what is happening in your code.  Why have you declared the FILE variables at global scope when they could be within the functions?   If your code isn't executing mapping(), but is opening the file, then one of the last three lines of setup has to be the caused, can you focus on that, add Serial.Print to the code to see where it is dying.

Literal buffer overflow in servo_step.   You define it as array of 10 chars waaay up top, then attempt to put more than 14 chars via sprintf in servo_step.   Bad Things™ happen thusly.   May be other issues, but that one is bad enough to cause failure.

On first view: You open the SD-Card file but you don't close it in setup. I am not sure if that will work. When I use the SD card I open the file, write, close the file, and continue with other steps. If any "external" value is written to the card then I save that value to a variable before I open the file to make sure when the SD card is busy nothing else is used.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
3 square wave pulse by 120° phase shift and 3 inverted of each by Arduino
I want to make a three phase inverter (DC to AC) bridge type using Arduino. For that I want to generate three square wave each is 120° phase shifted and other three waves of main three wave forms inverted for opposite switch.
Can anyone please help me out? I am new to programing in Arduino.
Code:

void setup() {
  pinMode( 9 , OUTPUT );
  pinMode( 10 , OUTPUT );

  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
  TCCR1B = _BV( WGM13) | _BV( WGM12);
  OCR1A = 0;
}
#define PRESCALER 1
#define PRESCALER_BITS 0x01
#define CLK 16000000UL

int setWaveforms( unsigned long freq , int shift ) {
  unsigned long clocks_per_toggle = (CLK / freq) / 2;
  ICR1 = clocks_per_toggle;
  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL;
  OCR1B= offset_clocks;
  TCCR1B |= _BV( CS10 );
}

void loop() {
  setWaveforms( 50000 , 120 );
  delay(1000);
  setWaveforms( 50000 , 120 );
  delay(1000);
  setWaveforms( 50000 , 120 );
  delay(1000);
}

I had get 2 waves only but I want to get 6. I am new to Stack Exchange.

This question doesn't cut it here, and I doubt it will on Arduino.SE. You need to put in your own research effort and show what you've tried, before we can (and will) help you. Otherwise we're just a free developer for hire.

ATTiny861. As you've shown no effort, that's all the effort I'll show.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
ArduinoDue - Matlab: SerialUSB.write() sends ASCII?
I'm trying to get some binary data from an Arduino Due to Matlab.
Basically this is the setup:
Due:

byte usbMsg[33]= {0};
// filled with dummy as example
usbMsg[1] = '00000001';// in[3];
usbMsg[2] = '00000001';//in[4];
usbMsg[3] = '00000001';//in[5];
.
.
.
SerialUSB.write(usbMsg, 33);

And on the Matlab side, I open the corresponding COM port and use a command like this one:
 a = fread(serialPort,3)

this gives me:
 a =

    49
    49
    49

which is the ASCII representation of the data I sent.
Can anyone explain to me why this happens and what I could do? As I understood serial.write sends binary data and fread reads binary data.

You do you intend with the statement; usbMsg[1] = '00000001'? Check what this means in C/C++.

Damn i confused different languages. Thanks ....


text:
How to detect Genuino 101 from inside the code?
I am using a custom library for Arduino Mega which uses AES library for AES-128 encryption.
However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.
And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.
For any queries, feel free to bug me, thanks.

No, you do not want your code to detect the Genuino 101. Your code cannot run until is is compiled. You want the compiler to detect whether it is compiling for an AVR-based Arduino or for something incompatible (whether it's ARC, ARM or Intel is irrelevant). What you want is called conditional compilation, and that is what KIIV's answer is about.

Yeah, True. Pardon me for the misunderstanding. This is what I exactly asked.

Arduino defines some macros so you can use conditional compilation. For example these are from boards.txt:

use ARDUINO_AVR_PROMICRO if it's specific for board variant
use ARDUINO_ARCH_AVR if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

use __AVR_ATmega32U4__ if it's specific for only one MCU
use __AVR__ if it's compatible with all AVR based MCUs

And code examples:
#if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
// something for ATmegaXX8 family...
#else
// ...
#endif

#ifdef __AVR__
// Code related to AVR
#else
// Code for other architectures
#endif

More about predefined macros in avr-gcc.

Since the library seems to be compatible with all AVR-based Arduinos, it is probably best to test for #if __AVR__ (or #ifdef __AVR__) rather than for specific MCUs.

@KIIV I tried #if defined AVR and it accepts, but for #if defined(AVR_ATmega328), I could not find the expected solution. Can you suggest any link which explains more on this?

@goddland_16 That was an example. Arduino MEGA 2560 uses __AVR_ATmega2560__. You can check label on the MCU.

The correct Arduino architecture macro is ARDUINO_ARCH_AVR, not DARDUINO_ARCH_AVR.

@per1234: Fixed, copy&paste error as usual...

@KIIV yeah checked it. Working and for UNO it is [AVR_ATmega328P] .

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to expand an Arduino when using a TFT display shield?
I am really new to this Arduino stuff. I can't figure out one of my problems on my own.
I am using this 2.4 TFT display shield on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.
Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.
The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.
How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!

Have you tried googling "communication between two arduinos"?  what did you learn?

I suggest adding your circuit and program.

As I mentioned my problem is mainly that my arduino is fully used, I guess, by my tft shield.

As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.
So there are some possible ways:

brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want
(something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...
or anything along this lines ... http://shieldlist.org/sunhayato/universal

use pins D10-D13 as they are connected also to ISP header https://www.arduino.cc/en/Tutorial/ArduinoISP and could be connected from there. As they are part of SPI interface
https://www.arduino.cc/en/Reference/SPI that could be good coise too (if you manage ChipSelect somehow.

As for other part of question -
It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )

Ok, your problem seems to be that you have run out of pins. Currently you are using an Arduino Uno. I would go out and buy an Arduino Mega.
Alternatively you could use the analog inputs as digital inputs.
Arduino Uno
Digital I/O Pins    14 (of which 6 provide PWM output)
Flash Memory    32 KB (ATmega328P) of which 0.5 KB used by bootloader
Arduino Mega
Digital I/O Pins    54 (of which 15 provide PWM output)
Flash Memory    256 KB of which 8 KB used by bootloader

Alright. Is the arduino mega working the same way as the arduino uno except it has more power and pins?

Pretty much! - I'll add links to my answer.


text:
To send data perpetually from multiple clients to a server using NodeMCU?
I am working on sending data from multiple clients to a server, all of which are NodeMCUs. I have been able to send data for a single iteration. Trouble arises when I want it to send data repeatedly so that if I update my client data, this new data should be reflected at the server as well.
Since I am using multiple clients, I have employed MAC addresses as the means of identifying the clients. This way, the signals received from a particular client are given as output to a particular pin.
To send data perpetually, I tried to use an infinite loop: while(true), but it reads the first connected client even on recognizing the second client.
Here's my server code:
#include <ESP8266WiFi.h>
#define Max_Clients 5

extern "C" {
  #include <user_interface.h>
}

WiFiServer server(80); //Initialize the server on Port 80
WiFiClient *clients[Max_Clients] = {NULL}; //Initializing client(s)
String inputs [Max_Clients] ={""}; //Initializing to store the string received from clients

int32_t freq = 10000;

IPAddress remoteIP();

void setup() {
  pinMode(D1,OUTPUT); //Intializing pins for showing output and input
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(A0,INPUT);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window
  analogWriteFreq(freq);
  WiFi.mode(WIFI_AP); //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678"); //Provide the (SSID, password)
  IPAddress myIP = WiFi.softAPIP(); //Obtain the IP of the Server
  Serial.println("Server IP is: "); //Print the IP to the monitor window
  Serial.println(myIP);
  server.begin(); //Start the HTTP Server
}

void loop() {
  WiFiClient client = server.available(); //Check if a new Client has connected to the server
  unsigned char number_client;
  struct station_info *stat_info;
  struct ip_addr *IPaddress;
  IPAddress address;
  int k=0;
  if (client) {
    Serial.println("A new Client has connected :)");
   for (int i=0 ; i<Max_Clients ; ++i){ //Acknowledges and sets up new clients
    if (NULL == clients[i]){
      Serial.println(i);
      clients[i] = new WiFiClient(client); //nothing in clients[i] means it is a new client
      break;
    }
   }

   while (true){
    delay(3000);
    number_client = wifi_softap_get_station_num();
    stat_info = wifi_softap_get_station_info();
    Serial.println();
    Serial.print("Total connected clients are = ");
    Serial.print(number_client);
    Serial.println();
    while (stat_info != NULL){
      for(int i=0 ; i<number_client ; ++i)  { //For available clients
        if (NULL != clients[i]) {
          IPaddress = &stat_info->ip;
          address = IPaddress->addr;
          Serial.println();
          Serial.print("Client = ");
          Serial.print(i+1);
          Serial.println();
          Serial.print("Client IP Address = ");
          Serial.print(address);
          Serial.println();
          Serial.print("Client MAC Address = ");
          Serial.print(stat_info->bssid[0],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[1],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[2],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[3],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[4],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[5],HEX);
          Serial.println();

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95) {
            Serial.println("Compared MAC address successfully - 1 :)");
            String request1 = clients[i]->readStringUntil('\r');
            Serial.print("Client 1 asks: ");
            Serial.print(request1);
            inputs[i] = request1;
            int duty1 = request1.toInt();
            analogWrite(D1,duty1);
            clients[i]->flush();
            k++;
            clients[i]->print("From Central Server to Client 1 - 150\r");
          }

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0x1F && stat_info->bssid[5] == 0x9D) {
            Serial.println("Compared MAC address successfully - 2 :)");
            String request2 = clients[i]->readStringUntil('\r');
            Serial.print("Client 2 asks: ");
            Serial.print(request2);
            inputs[i] = request2;
            int duty2 = request2.toInt();
            analogWrite(D2,duty2);
            clients[i]->flush();
            clients[i]->print("From Central Server to Client 2 - 200\r");
            k++;
            }

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0xB && stat_info->bssid[5] == 0x71) {
            Serial.println("Compared MAC address successfully - 3 :)");
            String request3 = clients[i]->readStringUntil('\r');
            Serial.print("Client 3 asks: ");
            Serial.print(request3);
            inputs[i] = request3;
            int duty3 = request3.toInt();
            analogWrite(D3,duty3);
            clients[i]->flush();
            k++;
            clients[i]->print("From Central Server to Client 3 - 250\r");
          }

        if (k == 0){
            Serial.println();
            Serial.println("Client not recognised.");
          }

          stat_info = STAILQ_NEXT(stat_info, next);
          Serial.println();
        }
       }
      }
     }
    }
   } //void loop closure

Here's my client code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

WiFiClient client; // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()
IPAddress server(192,168,4,1);

void setup() {
  pinMode(A0,INPUT);
  pinMode(D6,OUTPUT);
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  Serial.begin(9600); //Serial connection
  WiFi.begin(ssid,password); //WiFi connection
  while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server, 80);   // Connection to the server
}

void loop() {
  if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
    while(true){
      int duty = analogRead(A0);
      client.print(String(duty)+"\r"); //Client's message to the server
      String answer = client.readStringUntil('\r'); //Reading response from the server
      Serial.print("Central Server: 200"); //Printing the response
      Serial.print(answer);
     }
   } else {
     Serial.println("Error in WiFi connection");
   }
}

Kindly suggest a solution. Thanks in advance.

why do you think there is a relation between client returned by the WebServer and client station number from soft AP?

One of my nodeMCUs is a server. I am not using any WebServer.

sorry WifiServer

wifi_softap_get_station_num() is a count of stations if I understand it correctly

Precisely. The number of clients connected to the server.

but all are connected to AP from setup()

I tested and does not work.

I found the error. The if(client) is to be closed before the while(stat_info) otherwise the loop will run only if it finds a new client.
It is running fine now. Thank you everyone for the suggestions. :)

It's vital that either loop() return or that you call yield() or delay() in your loop() handler.
Your client code as it's written doesn't do that.
You don't need the while(true) at all. Take it out and leave the body of it in the if statement. loop() will be continuously re-entered and your code will keep running. loop() is already an infinite loop.
Leaving while(true) inside loop() means that loop() never returns. When it doesn't return, the SDK doesn't get to perform certain housekeeping functions that are necessary for its proper operation. In particular, networking functions may stop working correctly, so your call to client.readStringUntil() may not work correctly.

On removing the while(true), the program executes fine but does not run perpetually. I require this because the analogRead() signals will be changing and I want to observe the changes in the output without having to re-run the code.

There's something weird going on if it doesn't continue running.The whole purpose of loop() is to be called over and over again, in an infinite loop. Try doing some debugging, put some Serial.println()'s inside loop() to confirm what's actually happening. There is no way it will ever operate correctly if you have a while(true) inside loop().

Is there an alternative to while(true)? Any other way to create an infinite loop within the void(loop)? I've been through the program several times and am not finding any clues whatsoever.

loop() IS an infinite loop. If it's not, something is broken somewhere else.
Have you tried putting debugging Serial.println()s to confirm that you're not re-entering loop() after it returns? If something is so broken that loop() isn't reentering it's best not to make assumptions about what's running.
So something like:
void loop() {
Serial.println("entered loop");
if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
Serial.println("wifi connected");
int duty = analogRead(A0);
...
(comments are too short to hold all the code)

I have done that. Loop never runs again.


text:
Is it possible to print a custom object by passing it to Serial.print()?
I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

There is a class called Printable. If you inherit from that, and implement the size_t printTo(Print& p) function, your object can then be passed to the print functions:
class myClass : public Printable {
    private:
        int _val1;
        int _val2;

    public:
        myClass(int v1, v2) : _val1(v1), _val2(v2) {}
        size_t printTo(Print& p) const {
             size_t r = 0;

             r += p.print("One: ");
             r += p.print(_val1);
             r += p.print(" Two: ");
             r += p.print(_val2);
             return r;
       }
};

Then:
myClass ob(4, 5);

Serial.println(ob);
=> One: 4 Two: 5

Majenko, thankyou very much for your answer. I got it working. Just little comment on your code. I think instead of "size_t printTo(Print& p)" should be "size_t printTo(Print& p) const". Thankyou

I just copied and pasted the prototype from the header.

I was getting an error of not overriding virtual function. Once added the const, all ok.

Ok. I have modified it for future reference

How are we supposed to know these things? The arduino documentation is quite... lacking... to say the best. Digging through the source code on github?


text:
Connect GPS module (WeeBee) to Arduino Uno
This is my very first Arduino project. I want to learn about GPS navigation by exploring the NMEA protocol!
Therefore, I bought a WeeBee GPS module. After reading the datasheet, I have two questions:

The official Arduino website states

Note: if you are using an Arduino Uno, keep in mind that you can't use the GPS module at the same time as your computer is connected on the USB port.

But I you go to the end of his tutorial, you will see he can transmit the GPS data to his computer. I don't understand why it would not be possible...
The GPS module datasheet (download link here) states that the maximum voltage is 5V. But it also states

serial connections are 3.3V CMOS Logic Levels

and

Suitable decoupling must be provided by external decoupling circuitry.

So, does it mean I need a logic level converter to prevent damage to the GPS module?

The article on the Arduino website means that you can't upload sketches from your PC to the Arduino or receive any sort of data, through the serial monitor or otherwise, from your PC, while the GPS module uses the RX pin. Any attempt to send data from PC to Uno in this condition would cause the Arduino to receive only corrupted data, since 2 devices (GPS module and PC) would be trying to send data at the same time, with the same line. This limitation is easily resolved by connecting the GPS module to a SoftwareSerial port instead; this keeps the HardwareSerial port (pins 0 & 1) free for bidirectional PC-Arduino communication.
The datasheet says that the maximum power supply voltage is 5 V. However, the serial connections are 3.3 V logic, so yes, you will need logic level shifters. A simple voltage divider will serve. However, 'external decoupling' refers to circuitry used in decoupling/smoothing out any spikes or dips that may occur in the supply voltage. An untamed spike could damage the device, while a dip (perhaps from large current draw) could cause the device to stop working, if the voltage falls low enough to be considered under-voltage. A 10uF electrolytic capacitor, connected from Vcc to GND close to the GPS module, should be okay.

Thank you for your answer!
-) I will use the "softwareserial" on pins 2 and 3 instead of the "hardwareserial" on pins 0 and 1. But they didn't do it in the tutorial and they still can send GPS data to the computer...
-) I assume that a logic level shifter like this one will do the job? Together with a 10µF capacitor connected with the "VA" and "OE" ports of the level shifter.

Dear  @TisteAndii, Thanks again for you answer.
Could you please look at my reply? Just to know I interpret your answer correctly. Regards, Simon.

@Simon Post a link to the tutorial. Yes, you should use pins 2 and 3 with SoftwareSerial. As for the logic shifter, all you need is a pair of resistors, perhaps 2.2k and 3.3k. Google "resistor voltage divider 5 3.3".

Dear @TisteAndii,I meant the Arduino page. You will see that they connected the GPS module on pin 0, but they could also send it with the SoftwareSerial to the computer (as shown at the buttom of the page).

Thank you for you input regarding the logic level shifter. Indeed, a 1.7k and 3.3k (or 10k and 20k and so on) would work. Although a simple resistor voltage divider is not the recommended solution. The impedance of the surrounding circuitry can affect it (although this is not an issue here, I guess) and high freq. signals (no idea if baud rate of 9600bps will be an issue).

I would like to add that SoftwareSerial is the worst software serial library to use for the GPS device.  AltSoftSerial on pins 8 & 9 is the best, followed by NeoSWSerial on any pins, and the last choice is SoftwareSerial on any pins.  This answer has full details.

authors: Сергей Степаненко


text:
Arduino Uno not including two header files at the same time
I have an Arduino Uno and I am trying to control a stepper motor with it. I also have an RF transmitter and receiver (433MHZ). I need to transmit data about motor status.
For RF I am following this page. Individually both are working great. I am able to send data from one Arduino (TX) to another (RX). And also I am able to control the motor. But when I am merging these projects, their header files are giving an error.
For RF, I need to include #include <RH_ASK.h> and for the motor I need include #include <Servo.h>. When I am including these headers files, they are giving me this error:
Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin): In function `RH_ASK::maxMessageLength()':

(.text+0x0): multiple definition of `__vector_11'

libraries\Servo\avr\Servo.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

I do not know what's wrong here. Can anyone please help me?

I found the solution on internet. These both libraries cannot be used at the same time. To do it, I downloaded the servotimer2 library but its not even compiling.

That sounds like a nice solution.

First of all, that page has a link to an old version of the RadioHead library.
This is a link to RadioHead: www.airspayce.com/mikem/arduino/RadioHead. You will find the newest library on that page.
The Servo library uses TIMER1.
The RadioHead in RH_ASK mode uses TIMER1.
Both use the same interrupt of TIMER1. That is what the compiler is trying to tell you with: "multiple definition of _vector_11".
You could move one of them to TIMER2.
There are alternative Servo libraries that use TIMER2.
The RadioHead can set a define for TIMER2. The explanation is in the library files in RH_ASK.h, you have to set "#define RH_ASK_ARDUINO_USE_TIMER2" in RH_ASK.cpp.
Why are you using the Servo library for a stepper motor ?

It is telling you that interrupt vector 11 is being defined multiple times. Such definitions should be done in the source file, not in the header file.


text:
Can PWM break a DC motor?
I want to know if controlling the speed of a DC motor with PWM could break (burn out the DC motor. Sorry my English isn't that good.

Provided that the voltage specs of the motor are not violated, no. However, the inductance of the motor stands a very good chance of destroying the switch unless an appropriately-rated flyback diode is used.

I'm new to Arduino and electronics. I'm planning to use a H-bridge (l293d) with the dc motor, in the project nº 10 of the arduino projects book that comes with the arduino starter kit there is no flyback diode.

In another project of the book, where a MOSFET is used, I found the flyback diode, but the project that uses the l293d there is no diode.

The l293d has these diodes already inside the package.

Providing that you send the appropriate voltage this shouldn't break your motor. The creator of Arduino suggest this way of driving motor on his book.
Source: Massimo Banzi's book : "getting started with arduino" : chapter 5 Advanced Input and Output.


text:
Arduino Yun - Problem with bridge and client
I'm using this simple code
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer server;

void setup() {
  Serial.begin(9600);
  Bridge.begin();
  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  YunClient client = server.accept();
  if (client) {
    Serial.println("client");
    process(client);
    client.stop();
   } else {
     Serial.println("no client");
   }
   delay(50);
}

void process(YunClient client) {
  String command = client.readStringUntil('/');
  Serial.println(command);
  if (command == "turnLeft") {
    Serial.println("Gira a sinistra");
  }
  if (command == "turnRight") {
    Serial.println("Gira a destra");
  }
  if (command == "goTo") {
    String value = client.readStringUntil('/goTo/');
    Serial.println(value);
  }
}

but it seems to have problem with bridge (or server, or client, i cannot understand) because it only write "no client" on the serial.
I can not understand what is wrong.

Probably too late to answer your question. Your problem is on line
if (client)

Change it to
if(client.connected())

which actually returns true when client is connected.

I presume you are wanting the print output to show up on the Serial Monitor but you have connected the Arduino IDE to the Yun via the WiFi port on your network. If this is the case, then change all refs of Serial.print to Console.print
This will direct the ASCII text to the Serial Monitor.


text:
Trouble with sleep mode and interrupts
Context
I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock
The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)
Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.
void sleepLoop()
{
  Serial.print("S");

  delay(5);   //scales to 40ms

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  noInterrupts();

  attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

  interrupts();
  sleep_cpu();

  //The program will continue from here.

  //First thing to do is disable sleep.
  sleep_disable();
}

I therefore changed
attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);
to
attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

PROBLEM
Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether LOW or FALLING is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.
I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going LOW, but I couldn't see any sign of this.
The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!

Could not reproduce. Power usage goes down in both cases and with FALLING I only get a single S printed when signal is low (and sometimes when it goes back high). Are you sure your hall-effect sensor doesn't need a pull-up resistor? What kind of serial output do you get? What is the power-usage (normal, during sleep, during "apparently not sleep")?

Thank you for looking at this :) For me it is very repeatable. Also, I only ever get a single S. It must receive an input before being able to print S again. Datasheet claims 'No External Pull up Resistor Required'. Power usage is ~0.6mA @ 3.6V when awake, and 0.02mA @3.6V when asleep. When in 'not-asleep' its ~0.6mA, hence I believe it is awake

As you didn't have the same problems, I wonder if it is something else I have done.. My full code is here: https://github.com/danjuggles/Sleep-and-counter/blob/master/Arduino_Nano_328P

Looking at the serial output, sleepLoop is never called. So all the code above has nothing to do with the problem.

I just retested this code and I am getting the correct Serial output.. I am underclocking the processor so: Serial.begin(38400);    //Use Baud rate at 4800 on PC (due to 1MHz clock speed)   //  (38400/8)=4800

I know that. No Ss are being printed, so sleepLoop is never called.

Just had a thought. I have my interrupt directly on pin 4 of the 328P, in the Arduino IDE and therefore the code this is called as pin 2, could this be why you aren't seeing the sleep?

Sounds like your sensor may be wired with a pullup resistor - be aware that consumes power when the output is driven low against it.  The hall effect sensor itself may require a few milliamps too, so you might consider a reed switch.

Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in power down sleep mode. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.
A pin change interrupt could be used instead.
For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.
Cheers!

There is a more radical alternative, that could yield even higher power savings: use the HAL sensor to trigger a monostable circuit that normally would keep the uC (and the clock source) powered off.
When it starts, get it to update the counter and time the monostable so that it shortly puts the rest of the system back to off.
You can use the eeprom for the counter.
For improved efficiency, get rid of the bootloader and start executing your application right away. If you program from the ISP interface, you do not need the bootloader.

Were filtering contact/range bounce not likely necessary the ATmega counter timer block could probably be configured to count without waking up the processor at all.  But wakeup is not that expensive and has nothing to do with the bootloader as it does not mean the CPU reboots.


text:
Get JSON data from Arduino with AJAX
I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call.
At the moment I have the following code on Arduino:

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

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

EthernetServer server(80);

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

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  float temperatureIndoor;
  float temperatureOutdoor;
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();

          temperatureIndoor = 22.77;
          temperatureOutdoor = 15.55;
          client.print("{\"0\":{\"TemperaturaInterior\":\"");
          client.print(temperatureIndoor);
          client.print("\",\"TemperaturaExterior\":\"");
          client.print(temperatureOutdoor);

          client.print("\"}}");
          client.println();
          break;
        }

      }
    }
    delay(1);
    client.stop();
    Serial.println("client disconnected");
  }
}

I'm trying to get values with the following ajax call:
    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
            data: { tag: 'getData'},
            dataType: 'json',
                  async: false,
                  success: function (data) {

$('#TemperaturaInterior').val(data.TemperaturaInterior).show();
$('#TemperaturaExterior').val(data.TemperaturaExterior).show();

                            }
                        });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino:
{"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}
I'm not getting the values.
Any idea?
Thanks
NOTE:
This what I get when ask to arduino to give me the values:

What language is that you're programming in there? AJAX is a technology, not a language.  Also, do you really want that "0" in your AJAX response?

No, the "0" is not necessary. I'm using a php page, with Jquery.

My reading of that response says you would have data.0.TemperaturaInterior and data.0.TemperaturaExterior.

Why are you sending a POST request? A GET would be more appropriate. Also, when you access directly from the browser it's a GET. And you should look at the actual data on the wire (e.g. with a network sniffer, Firebug, the Chrome developer tools, etc...), not just the (failed) rendering on the browser.

I've edited my post with a prtscr with the response from arduino.

Look at the last error message: it's quite explicit, then google "cross origin resource sharing" and "Access-Control-Allow-Origin". Not specific to Arduino.

Yeah, you have a wicked-specific error message there. When I see a message with that much information I jump for joy! It's telling you exactly how to fix it.

This is more of a Stack Overflow question, but I'll help you a bit. The problem has nothing to do with your Arduino per-say. It has more to do with your PHP/Ajax.
Your code is suited for a completely local setup, but pulls from a remote site, which violates some security protocols build into your browser and jQuery. You need to change your code to this:
$.ajax({
    url: 'http://192.168.1.177/',
    type: 'post',
    data: { tag: 'getData'},
    dataType: 'jsonp',
    async: false,
    success: function (data) {
        $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
        $('#TemperaturaExterior').val(data.TemperaturaExterior).show();
        }
    });
(may need slight modifications since you didn't include all PHP/html code)

For more information, see the jQuery documentation, particularly look at data types and what it says about cross-domain json vs jsonp.
Here is a relevant SO question.

Ouch man you are getting burned by CORS. This stack overflow box isn't big enough for me to explain how much of a pain CORS is and how much trouble it will cause you. That being said there is a really good recourse that will help explain how to get this working with a couple of http headers http://enable-cors.org/. Good luck


text:
Why is SoftwareSerial causing arduino to reboot?
I'm trying to design an RC controller using an Arduino and an XBee Series 2 Pro. I have the hardware serial running for debug information and I want the XBee to be connected to a soft serial on pins 8 and 9.
My arduino keeps restarting, or at least the setup function keeps looping, every time I try to send data through the XBee. If I modify the code so the XBee runs on the hard serial, the program works, but I would rather not have that setup because then to load new code onto the arduino I have to open the controller and disconnect the XBee.
I tried changing the pins that the soft serial runs on and that makes no difference, nor does unplugging the power to the XBee but leaving the serial connections in. I also tried to write another pin high to make sure there's enough current, and that didn't cause a restart.
My arduino is connected to the XBee, 4 potentiometers, and 1 switch.
#include <XBee.h>
#include <SoftwareSerial.h>

#define NOTE_A3  220
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330

#define THR_JOYSTICK A0
#define YAW_JOYSTICK A1
#define RL_JOYSTICK A2
#define FB_JOYSTICK A3
#define POT A4
#define TOGGLE 4
#define SPEAKER_PIN 3
//#define WAKE_PIN 10

#define YAW_MIN 0
#define YAW_OFFSET 386
#define YAW_MAX 815

#define RL_MIN 0
#define RL_OFFSET 359
#define RL_MAX 800

#define FB_MIN 0
#define FB_OFFSET 355
#define FB_MAX 795

#define THR_MIN 0
#define THR_OFFSET 0
#define THR_MAX 754

const int ESC_MIN = 764;
const int ESC_OFFSET = 1500;
const int ESC_MAX = 2000;

XBee xbee = XBee();
SoftwareSerial nss(13,12);
uint8_t payload[10];
// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40c67584);
ZBTxRequest packet = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

void setup() {
  //start serials
  Serial.begin(9600);
  nss.begin(9600);
  xbee.setSerial(nss);

  //pin modes
  pinMode(THR_JOYSTICK,INPUT);
  pinMode(YAW_JOYSTICK,INPUT);
  pinMode(RL_JOYSTICK,INPUT);
  pinMode(FB_JOYSTICK,INPUT);
  pinMode(POT,INPUT);
  pinMode(TOGGLE,INPUT);
  pinMode(SPEAKER_PIN,OUTPUT);

  //delay to allow inputs to settle
  delay(1000);

  //the speaker will need a total resistance of at least 125 Ohm
  //so if it's an 8 Ohm speaker, an additional 117 is needed etc...

   //calibrate THR
  int first = millis();
  tone(SPEAKER_PIN,NOTE_A3);
  int reading = analogRead(THR_JOYSTICK);
  while(reading > THR_OFFSET + 5 || reading < THR_OFFSET - 5) {
    delay(20);
    reading = analogRead(THR_JOYSTICK);
  }
  int dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate YAW
  first = millis();
  tone(SPEAKER_PIN,NOTE_B3);
  reading = analogRead(YAW_JOYSTICK);
  while(reading > YAW_OFFSET + 5 || reading < YAW_OFFSET - 5) {
    delay(20);
    reading = analogRead(YAW_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate FB
  first = millis();
  tone(SPEAKER_PIN,NOTE_C4);
  reading = analogRead(FB_JOYSTICK);
  while(reading > FB_OFFSET + 5 || reading < FB_OFFSET - 5) {
    delay(20);
    reading = analogRead(FB_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //calibrate RL
  first = millis();
  tone(SPEAKER_PIN,NOTE_D4);
  reading = analogRead(RL_JOYSTICK);
  while(reading > RL_OFFSET + 5 || reading < RL_OFFSET - 5) {
    delay(20);
    reading = analogRead(RL_JOYSTICK);
  }
  dif = 200 - millis() + first;
  if(dif <= 200 && dif >= 0) {
    delay(dif);
  }

  //done
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(200);
  noTone(SPEAKER_PIN);
  delay(15);
  tone(SPEAKER_PIN,NOTE_E4);
  delay(350);
  noTone(SPEAKER_PIN);
}

void loop() {
  int POTReading = analogRead(POT);
  int toggle = digitalRead(TOGGLE);

  int throttleValue = mapLimit(analogRead(THR_JOYSTICK) - THR_OFFSET,THR_MIN,THR_MAX - THR_OFFSET,0,ESC_OFFSET);
  int yawValue = mapLimit(analogRead(YAW_JOYSTICK),YAW_MIN,YAW_MAX,ESC_OFFSET-ESC_MAX,ESC_MAX - ESC_OFFSET);
  int rightLeftValue = mapLimit(analogRead(RL_JOYSTICK) - RL_OFFSET,RL_MIN,RL_MAX - RL_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int frontBackValue = mapLimit(analogRead(FB_JOYSTICK) - FB_OFFSET,FB_MIN,FB_MAX - FB_OFFSET,0,ESC_MAX - ESC_OFFSET);
  int potValue = analogRead(POT);
  int toggleValue = digitalRead(toggle);

  //throttle
  payload[0] = throttleValue >> 8 & 0xff;
  payload[1] = throttleValue & 0xff;
  //yaw
  payload[2] = yawValue >> 8 & 0xff;
  payload[3] = yawValue & 0xff;
  //RL
  payload[4] = rightLeftValue >> 8 & 0xff;
  payload[5] = rightLeftValue & 0xff;
  //FB
  payload[6] = frontBackValue >> 8 & 0xff;
  payload[7] = frontBackValue & 0xff;
  //Pot
  payload[8] = potValue >> 8 & 0xff;
  payload[9] = potValue & 0xff;
  //toggle
  payload[10] = (byte) toggleValue;

  //wake XBee
  //digitalWrite(WAKE_PIN,LOW);
  xbee.send(packet);
   if(xbee.readPacket(500)) {
     if(xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
       xbee.getResponse().getZBTxStatusResponse(txStatus);
       if(txStatus.getDeliveryStatus() != SUCCESS) {
         //the remote XBee didn't ACK
         tone(SPEAKER_PIN,NOTE_C4,100);
       }
     }
   } else {
     //error or something
     tone(SPEAKER_PIN,NOTE_E4);
     noTone(SPEAKER_PIN);
     tone(SPEAKER_PIN,NOTE_E4,50);
   }

    //sleep XBee
    //digitalWrite(WAKE_PIN,HIGH);
    delay(100);
}

int mapLimit(int val, int fromLow, int fromHigh, int toLow, int toHigh) {
  int result = map(val,fromLow,fromHigh,toLow,toHigh);
  if(result > toHigh) {
    result = toHigh;
  } else if(result < -toHigh) {
    result = -toHigh;
  }
  return result;
}

10 bytes in payload were being used, but payload was declared using int payload[10] when it should have been int payload[11].

Just a guess, but maybe your Arduino power supply isn't juicy enough. I had the same problem running 2 modules + LCD on a Arduino powered via USB.
Try to find a power supply somewhere between 9 and 12V (from an old router, modem or cellphone you don't need anymore), and use it to power your Arduino instead of relying on the the USB port alone.
http://playground.arduino.cc/Learning/WhatAdapter

It turned out that payload was allocated with 10 int values but I was using 11 so that caused the crash I guess.


text:
Arduino WebSocket Client "Connection Failed"
I use this code to connect Arduino MKR1000 to API through Web Socket, but it didn't connect to the server.
Can any one help me to correct the code.
This is the Arduino code:

#include "Arduino.h"
#include <WiFi101.h>
#include <SPI.h>
#include <WebSocketClient.h>

char server[] = "192.168.2.128";
IPAddress server1(192, 168, 2, 128);
WebSocketClient webSocketClient;
WiFiClient client;

char path1[] = "/api/WebSocketTest";
int port1 = 8060;
char ssid[] = "**************";
char pass[] = "**************";

void setup() {
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(SWITCH, INPUT);
  Serial.begin(115200);
  delay(10);
  while (!Serial) {
  }

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

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

  Serial.println("");
  Serial.println("WiFi connected");
  printWifiStatus();
  delay(3000);
  Serial.println("setup done");
  delay(1000);

  //  webSocketClient.setDebug(&debug);
  webSocketClient.connect(server, port1, path1);
  if (webSocketClient.connected() == true) {
    Serial.println("Connected");
  }
  else {
    Serial.println("Not Connected");
  }
  webSocketClient.onMessage(onMessage);
  webSocketClient.onOpen(onOpen);
  webSocketClient.onError(onError);
}

void loop() {
  webSocketClient.monitor();
}

void onOpen(WebSocketClient webSocketClient) {
  Serial.println("EXAMPLE: onOpen()");
}

void onMessage(WebSocketClient webSocketClient, char* message) {
  Serial.print("Received: ");
  Serial.println(message);
}

void onError(WebSocketClient webSocketClient, char* message) {
  Serial.print("ERROR: ");
  Serial.println(message);
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

And this is a part from the library used "WebSocketClient.h":
void WebSocketClient::connect(char hostname[], int port, char protocol[], char path[]) {
  _hostname = hostname;
  _port = port;
  _protocol = protocol;
  _path = path;
  _retryTimeout = millis();
  _canConnect = true;
}

Edit 1: The output:
Connecting to WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.147
signal strength (RSSI):-68 dBm
setup done
Not Connected
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!

What output do you get from the printWifiStatus() function?

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.147
signal strength (RSSI):-68 dBm

And to what are you connecting?

the problem is how to enter hostname, port number, and path

No, the problem is you cannot connect to some unknown service on some unknown computer. You already specify the hostname, port number, etc.

i am connecting it to api, which is hosted from my laptop, which act as a server

No, you aren't connecting. That's the problem. It says not connected. I would guess the problem is with the configuration of your laptop - server software configuration, firewall configuration, etc.

as you see at the top of the code I define the ip address of the server, port number and the path

i try the same api with other applications and it works perfect

and i try it also with raspberry pi and it works 100%

had you specified this port number 8060 while creating the server on your laptop?


text:
Why doesn't PWM work on arduino in this code?
I am trying to control a dc motor speed with PWM. When I test it with simple program like spin in one direction with set PWM value it works. If PWM>70 the motor will start spinning and max is 255.
But when I try to do the same in code below it only spins if PWM value is 255. Can someone help me?
test.ino

/*--------------------*/
// encoders
/*--------------------*/
//motor_encoder
int encoder0PinA = 3;
int encoder0PinB=2;
volatile int encoder0Count = 0;
volatile float angle0 = 0;
volatile float velocity0 = 0;
volatile float angle0_previous = 0;
volatile float angle0_post = 0;
//pendulum_encoder
int encoder1PinA = 20;
int encoder1PinB = 21;
volatile int encoder1Count = 0;
volatile float angle1 = 0;
volatile float velocity1 = 0;
volatile float angle1_previous = 0;
volatile float angle1_post = 0;
float error=0;
/*--------------------*/
// motor
/*--------------------*/
int enA = 10;
int in1 = 9;
int in2 = 8;
/*--------------------*/
// for Timer2
/*--------------------*/
volatile int tcnt2 = 131;
volatile int t = 0;

volatile float error_proportional = 0;
volatile float error_derivative = 0;
volatile float error_integral = 0;
float kp =50;
float kd = 0;
float ki = 0;
float u = 0;
float motor_input = 0;
int INPUT_MAX = 255;
int P=0;
int I=0;
int D=0;
int integral=0;
void setup()
{

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  /*--------------------*/
  // for encoder
  /*--------------------*/
  // for encoder 0
  pinMode(encoder0PinA, INPUT);
  pinMode(encoder0PinB, INPUT);
  attachInterrupt(0, doEncoder0A, CHANGE);
  attachInterrupt(1, doEncoder0B, CHANGE);
  // for encoder 1
  pinMode(encoder1PinA, INPUT);
  pinMode(encoder1PinB, INPUT);
  attachInterrupt(2, doEncoder1A, CHANGE);
  attachInterrupt(3, doEncoder1B, CHANGE);

  /*--------------------*/
  // for Timer2
  /*--------------------*/
  // interrupts every 1 ms
  TIMSK2 &= ~(1<<TOIE2);
  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
  TCCR2B &= ~(1<<WGM22);
  ASSR &= ~(1<<AS2);
  TIMSK2 &= ~(1<<OCIE2A);
  TCCR2B |= (1<<CS22)  | (1<<CS20);
  TCCR2B &= ~(1<<CS21);
  TCNT2 = tcnt2;
  TIMSK2 |= (1<<TOIE2);

  Serial.begin (9600); // for debugging
}

void loop()
{

 error = angle1;

 if (abs(error) < 2){
 integral = integral + error;
 }
 else {
 integral=0;
 }
 P = error*kp;
 I = integral*ki;
 D = (angle1_previous-angle1)*kd;
  u = P + I + D;
  motor_input = 255/24 * u;

  Serial.print("u: ");
  Serial.print( u);
  Serial.print(" ");
  motor_input = (int)motor_input;

  if (motor_input >= INPUT_MAX){
    motor_input = INPUT_MAX;
  }
  else if (motor_input <= -INPUT_MAX){
    motor_input = -INPUT_MAX;
  }

  Serial.print("error_proportional: ");
  Serial.print(error_proportional);
  Serial.print(" ");
  Serial.print("error_derivative: ");
  Serial.print(error_derivative);
  Serial.print(" ");
  Serial.print("error_integral: ");
  Serial.print(error_integral);
  Serial.print(" ");
  Serial.print("motor_input: ");
  Serial.println(motor_input);
  setMotorSpeed(motor_input);
}

measure_states.ino
/*--------------------*/
// enkoder od motora
/*--------------------*/
void doEncoder0A(){
  if (digitalRead(encoder0PinA) == HIGH) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Count = encoder0Count + 1;
    }
    else {
      encoder0Count = encoder0Count - 1;
    }
  }
  else {
    if (digitalRead(encoder0PinB) == HIGH) {
      encoder0Count = encoder0Count + 1;
    }
    else {
      encoder0Count = encoder0Count - 1;
    }
  }
  angle0 = 0.000785*encoder0Count;  // radian  (2*pi/8000)
}

void doEncoder0B(){  // interrupt 1 function
  if (digitalRead(encoder0PinB) == HIGH) {
    if (digitalRead(encoder0PinA) == HIGH) {
      encoder0Count = encoder0Count + 1;
    }
    else {
      encoder0Count = encoder0Count - 1;
    }
  }
  else {
    if (digitalRead(encoder0PinA) == LOW) {
      encoder0Count = encoder0Count + 1;
    }
    else {
      encoder0Count = encoder0Count - 1;
    }
  }
  angle0 = 0.000785*encoder0Count;
}

/*--------------------*/
// for encoder 1
/*--------------------*/
void doEncoder1A(){
  if (digitalRead(encoder1PinA) == HIGH) {
    if (digitalRead(encoder1PinB) == LOW) {
      encoder1Count = encoder1Count + 1;
    }
    else {
      encoder1Count = encoder1Count - 1;
    }
  }
  else {
    if (digitalRead(encoder1PinB) == HIGH) {
      encoder1Count = encoder1Count + 1;
    }
    else {
      encoder1Count = encoder1Count - 1;
    }
  }
  angle1 = 0.000785*encoder1Count;
}

void doEncoder1B(){
  if (digitalRead(encoder1PinB) == HIGH) {
    if (digitalRead(encoder1PinA) == HIGH) {
      encoder1Count = encoder1Count + 1;
    }
    else {
      encoder1Count = encoder1Count - 1;
    }
  }
  else {
    if (digitalRead(encoder1PinA) == LOW) {
      encoder1Count = encoder1Count + 1;
    }
    else {
      encoder1Count = encoder1Count - 1;
    }
  }
  angle1 = 0.000785*encoder1Count;
}

ISR(TIMER2_OVF_vect) {
  TCNT2 = tcnt2;
  t++;

  // estimate velocity
  if (t == 1){
    angle0_previous = angle0;
    angle1_previous = angle1;
  }
  else if (t == 20){
    angle0_post = angle0;
    angle1_post = angle1;
  }
  else if (t == 21){
    velocity0 = (angle0_post - angle0_previous)*50;  // rad/s
    velocity1 = (angle1_post - angle1_previous)*50;

    error_proportional = 3.1416 - angle1;
    error_derivative = 3.1416 - velocity1;
    error_integral = error_integral + error_proportional;

    t = 0;
  }
}

motor.ino
void setMotorSpeed(int speed)
{
  if (speed < 0)
  {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);

  }
  else
  {
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);

  }

  analogWrite(enA,abs(speed));

  angle1_previous=angle1;
}

UPDATE 1:
I found that the code below for setting timer messes PWM but Im not sure why. Anyone have any idea?
TIMSK2 &= ~(1<<TOIE2);
  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
  TCCR2B &= ~(1<<WGM22);
  ASSR &= ~(1<<AS2);
  TIMSK2 &= ~(1<<OCIE2A);
  TCCR2B |= (1<<CS22)  | (1<<CS20);
  TCCR2B &= ~(1<<CS21);
  TCNT2 = tcnt2;
  TIMSK2 |= (1<<TOIE2);

Arduino core uses built in timers to perform PWM - setting them manually using the AVR registers messes it up. This may be helpful - see the part where it says which timer corresponds to which pins.

In loop(), after you set P, I, D, and u, it looks like you mean to calculate motor_input in float, but the calculation is will be partially done in int. The compiler will precalculate (int)255 / (int)24 as (int)10. At run time, that will be floated to 10.0 and multiplied by u. If you really meant the multiplier to be 10.625 (the result of a floating divide), at least one of the two constants, 255 and 24 needs a decimal point to indicate that. I see that in your initializers, too. ...

... Use a decimal point, a trailing 'F' or 'D' (for 'float' or 'double') in your numerical constants that you expect to be treated by the compiler as double, float, or double, respectively (doubles and floats will be the same on an Arduino). I doubt this will solve your motor no-start issue, but it will affect your controller.

!!Ach!! I failed to notice this was an obsolete post. Well, maybe my comment will do someone, somewhere, somewhen, some good...  :(


text:
GSM serial get event or read the whole input?
I am using an Arduino Uno with GSM shield, trying to read some SMS. Here is my code.

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");

  delay(100);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

My issue is: am testing sending this sms to the shield

A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z

but somehow am not getting all the info, why?


text:
Arduino port not showing serial USB Mac OS El Capitan
I don't see serial USB as an option under ports when my Arduino is connected to my Mac. I have used this Arduino on the same computer before without any issues on Yosemite OS. However, I was trying to run a servo motor and I don't think I was getting enough power so I decided to use an external power supply. 12V 500mA DC and connected it while still keeping the USB connection. Since I already had the servo program loaded, the motor did work. Then I tried uploading the program again, that's when I realized that there was no serial connection. I am not sure if the problem is because of the power supply that I connected.
I tried the following approaches without success:

Upgraded the OS to El Capitan (which might have been a bad decision in hindsight).
Tried connecting the Arduino to another Mac with new Arduino IDE download, same issue.
Tried downloading the FTDI drivers as suggested by other folks.

I searched for a few hours for a solution online, but nothing so far has helped. Please provide suggestions.

Possible help here

An Arduino UNO never requires FTDI drivers - only other Arduino boards and fundamentally different designes from other sources might require that.  Try disconnecting the motor and its power supply and see if you can program the bare Arduino board when powered by USB.  Also (carefully!) make sure nothing on the board is getting hot.

I'm voting to close this question because it is impossible to diagnose from the limited information provided, and the asker has failed provide any followup for over half a year, meaning this will probably never be answered.

Change USB ports
Check your Tx and Rx pins aren't connected to ANYTHING.
Reboot your Mac.
If you're really desperate, change OS.

Already tried 1 and 3 several times. For 2, I don't have any wires physically connected to the board other than the USB cable. I have the servo motor program uploaded on the board and there is no way for me to wipe it out. But that is only using digital pin 9. When I power up the board LED marked L above TX and RX lights up yellow along with the ON led which is green.

Try connecting another Arduino & cable to your computer. (Two computers not seeing your Arduino sounds like the fault may like with the Arduino.)

Yes, I tried 2 computers (Mac and windows) and it didn't work. Bought a new board and that solved the problem. Don't know what went wrong with the first board though.


text:
Reading Arduino serial data in Octave on Mac
I am trying to read serial port data generated by Arduino in Octave on Mac. I installed and loaded the instrument-control package for the same. I used this piece of code to check if the package was installed properly
if (exist("serial") == 3) disp("Serial: Supported") else disp("Serial: Unsupported") endif

I do get an output saying Serial: Supported.
I am following the tutorial here for step by step guidance.
I next use s=serial('portname') to create a serial port object. However, I am not sure what name to use instead of COM5 on Windows for Mac.
I checked and my Arduino is connected to cu.usbmodem1421 so I tried following 3 options a)cu.usbmodem1421 b) usbmodem1421 c)1421 but in each case I get an error saying "serial: Error opening the interface: No such file or directory".
Could anyone tell me what port name I can use or if there are any suggestions for the big picture problem as to how to read Arduino serial data in Octave (on Mac)? Thanks for the help in advance.

You most likely need the full canonical pathname for the port:
/dev/cu.usbmodem1421

On the Mac, as in Linux and other Unix derivatives, most devices, serial ports included, are special files in the /dev directory.

Thanks for the suggestion. I tried /dev/tty.usbmodem1421 and it worked!

According to the rules of TTY naming for connecting to an external device from inside the Mac you should use the /dev/cu.* variant. It's the same physical devices as the /dev/tty.* variant, but the line control is handled differently. The /dev/tty.* variant is intended for incoming connections to the Mac (a text-based login prompt).


text:
PIR sensor code logic works on Mega but not on Yún
I am trying to use this example(it works on Arduino Mega): millis() - lowIn comes greater than 5000when motion ends.
/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 3; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}

////////////////////////////
//LOOP
void loop() {
  if (digitalRead(pirPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
    //the led visualizes the sensor's output pin state
    if (lockLow) {
      // makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      Serial.println("---");
      Serial.print("motion detected at ");
      Serial.print(millis() / 1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
  }

  if (digitalRead(pirPin) == LOW) {
    digitalWrite(ledPin, LOW);
    //the led visualizes the sensors output pin state
    if (takeLowTime) {
      lowIn = millis();
      //save the time of the transition from high to LOW
      takeLowTime = false;
      //make sure this is only done at the start of a LOW phase
    }
    //if the sensor is low for more than the given pause,
    //we assume that no more motion is going to happen
    Serial.print(millis() - lowIn);
    Serial.print("    ");
    Serial.print(lockLow);
    Serial.print("    ");
    Serial.println(pause);
    if (!lockLow && millis() - lowIn > pause) {
      //makes sure this block of code is only executed again after
      //a new motion sequence has been detected
      lockLow = true;
      Serial.print("motion ended at "); //output
      Serial.print((millis() - pause) / 1000);
      Serial.println(" sec");
      delay(50);
    }
  }
}

But it doesn't work on a Yún shield mounted on an Arduino Leonardo. The difference of millis() - lowIn always comes out to be lower than pause.

The Arduino Leonardo uses the ATmega32U4 microcontroller which uses lower logic levels for the digital inputs. Perhaps that is not compatible with the PIR sensor. You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND.
For the Leonardo, sometimes "SerialUSB" is used instead of "Serial". But if see a message on the serial monitor then "Serial" is okay.
If you can't make it work, then try to reduce the number of variables. In this case, remove the Yun shield and try it with the Leonardo board.
The Arduino Mega 2560 and Arduino Leonardo have both a 8-bit microcontroller and 'millis' works on both in exactly the same way. Therefor 'millis' itself or the variables can't be the problem.

what do you mean by "You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND." ?

Instead of the PIR sensor, connect a piece of wire to pin 3 and connect that to either GND or 5V. That's all. It is just a test, perhaps there is trouble with the voltage level of the PIR sensor (but I don't know).


text:
Arduino based fully controlled aquaculture
I am doing a project on aquaculture,so I am using temperature sensor, water level sensor, dissolved oxygen sensor, pH sensor and also 4 motor's and water heater is it possible for a single Arduino to run all these at the same time??

yes, it is possible, if you use the right components and are a good programmer

Yes. Arduino has that much capability. But you have to plan properly how to operate your module and provide proper functionality.

I would suggest finding sensors that work on an I2C bus. This way all the sensors are only using two pins for data. That will free up other outputs for motors, heaters that will probably be on relays or other drivers that need a single or multiple pins for each devices.  As you start to plan it out, if you do run out of pins on a arduino uno, look at the Mega, as it has many more GPIO pins as well as multiple dedicated UART ports.
Bottom line, find your sensors, drivers, see what type of communication they require, and start to make a list of how many separate io pins you need. Then that will tell you which board is suitable for your project.


text:
Question about controlling servos with PWM while being able to accurately read the current from a sensor
Hi I am hoping to design a custom board ATMEGA32u4 with practically a Arduino leonardo bootloader. I plan to control up to 12 servos while being able to read back the current sensor voltage of an INA169 current sensor on voltage changes. The  voltage reading will be read back into a digital pin through an ADC controlled by a  multiplexer. The question is am I able to manage all the current sensing on all 12 servos properly with this setup? or should I use a faster controller that act as a master to do the data collection from the current sensor while the ATMEGA32u4 focus on controlling the servos? I plan to store this data too, so is this the right way of doing things?

a digital output would be better, like the ina219. expect some noise, but it should still be able to give you a rough idea or identify stuck motors.

@dandavis I think previously was using the INA219 for current sensing but can't remember why my partner and me instead choose the 169 over the 219(i think we plan to have an current sensor each on the high side of every servo and wasn't sure if the I2C protocol was fast enough or if there were enough addresses to control 12 of them.). I think the purpose was to use the current sensor to have better control of those cheap micro servos 9g by reading back it current draw and potentiometer reading.


text:
Using StringStream in Arduino sketch
I learned about StringStream today at work.
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>

using namespace std;

char* getSql() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";

    char *mychar = new char[sqlQuery.str().length() + 1];
    strcpy(mychar, sqlQuery.str().c_str());
    return mychar;
}

string getSqlStream() {
    float outdoorTempInC = 15;
    int outoorHumidity = 23;
    float indorTempinC = 20;
    int humidity = 22;
    int val = 400; // soil sensor reading
    int avgVal = 38; // avaerage of 10 values of soils sensor
    char statusMsg[50] = {"Hello World"} ;
    std::stringstream sqlQuery;
    sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
        << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
        << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
        << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
        << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
        << statusMsg << "');";
    return sqlQuery.str();
}

int main() {
    string sql = getSqlStream();
    cout << getSql() << "\n";
    cout << sql.c_str() << "\n";
    return  0;
}

I was very happy until I discovered I cannot use StringStream in Arduino, so I dug in the internet and came across with this.
So if I try to use the above linked gist StringSteam like I have used in my example code, I am getting this error:
error: no match for 'operator<<' (operand types are 'StringStream' and 'const char [60]')
     sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
               ^
webServer_Displaying_everything_v01:24: error: 'outdoorTempInC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
            ^
webServer_Displaying_everything_v01:24: error: 'outoorHumidity' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                        ^
webServer_Displaying_everything_v01:24: error: 'indorTempinC' was not declared in this scope
         << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                                                    ^
webServer_Displaying_everything_v01:25: error: 'humidity' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                      ^
webServer_Displaying_everything_v01:25: error: 'val' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                            ^
webServer_Displaying_everything_v01:25: error: 'avgVal' was not declared in this scope
         << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                                             ^
webServer_Displaying_everything_v01:28: error: 'class StringStream' has no member named 'str'
     char *mychar = new char[sqlQuery.str().length() + 1];
                                      ^
webServer_Displaying_everything_v01:29: error: 'class StringStream' has no member named 'str'
     strcpy(mychar, sqlQuery.str().c_str());

Or I am doing it completely the wrong way? It feels I still cannot use it the way I have done in the example. Please help.

This class is not a “stream” in the C++ sense, it's a Stream in the Arduino sense, i.e. it provides an interface similar to Serial. You can for instance print() and println() to it.

@EdgarBonet so in that case how can I use sqlQuery  method of storing to a variable in arduino without having to use print(), println or sprintf ?

The whole purpose if this StringStream is to let you print() and println() into it.

The reference to StringStream is to "#include " which is very much a stream in the C++ sense, not in the Arduino sense. The OP is looking to use std C++ in Arduino. The answer is to use the GNU tool chains used by (and installed with) the Arduino IDE, but without the ino preprocessor. There is no class StringStream.  The class is ostringstream, and its purpose is to provide appendage methods via the << operator. Println is never used. The \n, \r\n, or preferably std::endl is used to terminate a line and sprintf may or may not be used underneath the ostringstream methods.

Direct Answer
Program in C++ and cross compile to the Arduino Yún.  The Arduino Sketch language is a thin layer over C++, but the std:: namespace is not light weight to the degree it would need to be to fit the things you are appreciating from the standard C++ library into the memory footprint of a small embedded CPU board.  See Arduino Yun C++ environment? Bridge + Cross-Compiler.
Serious Programming on Arduino
If you wish to open the door to C++ elegance on smaller embedded CPU boards like the simpler Arduinos, you will need to move beyond the Arduino sketch language.  You may find it both fun and useful to learn how to cross compile and link using the GNU tool set that targets the Atmel CPU you have on your board.
This more professional approach is not for the faint at heart, but it is done all the time.   We do it here in TranSeed Labs every day.
To get started, you don't need to download or install anything other than the Arduino software.  The tool set that targets Atmel's AVR architecture (used by several Arduino boards) is in a sub-directory under the Arduino IDE's home directory.  The tool set that targets Atmel's SAM Architecture for the Arduino Due is placed in a sub-directory of your home directory when you set up the IDE to upload sketches to the Due.
Returning to the Question in This C++ Context
Once you learn how to compile and link using g++ from the GNU tool chain1 and use the upload tools2 your program via the USB port, you can create a template class to get the elegance available in C++ like the operator overloading that you like.
The issue with trying to employ the C++ library with embedded targets is that the allocation system and other dependencies will probably exhaust much if not all of your program memory.  The ostringstream class from the C++ library, with all its dependencies included, is not extremely lean.
An approach that consumes very little memory and does not require the CPU cycles of dynamic allocation is to create a C++ template that wraps a static array.  Its buffer size can be one of the template parameters.
Then you can overload the << operator of the class using these examples as a guide.  You get your elegance and drastically reduce your computing resource requirements.

[1] Both cross compiling and cross linking are done with g++ (gcc for the Aruino and Atmel C files in the library).  For Arduino boards using the AVR based Atmel CPUs, use the AVR GNU Tool Chain.  For the Due, which uses the SAM based Atmel CPUs, use the SAM5X GNU Tool Chain.
[2] The program bossac is used to upload to the Due.  The program avrdude is used to upload to the Mega 2560.

well, I do not have Arduino Yun, but I was rather going to buy Arduino Yun Shield, I'd assume it should not make difference , correct me if I am wrong please !

Yun board != Yun shield

Thanks Douglas, best answer I have accepted however just little bit more trouble I would appreciate if in your answer you can link up the text "cross compile" , "link using the GNU tool" and "set that targets the Atmel CPU" example on web. It will seed the process of learning. However I would refrain from directly jumping to higher step.

This answer is almost exactly the road we take here at the lab, and it works very well. Most of the serious embedded programmers use microemacs to develop. We tried using the std:: namespace in sketches for containers and strings, but the advantage to moving to g++ and a makefile became obvious in the first week of writing actual programs. The way outlined here has worked for three years now and triples our development speed.

It has nothing to do with cross compiling or linkage using the GNU tool. IO streams do present on Arduino but attempt to include it result in too big binary. It simply does not fit on chip's memory.
There are a couple of solutions to this problem. One is to use a library called ard-streams. Another one is to use a lightweight, simplified version of stringstream just enough to compile your code.
#include <string>

namespace ard
{
    struct ostringstream
    {
        ostringstream() = default;
        ostringstream(std::string arg) : s(std::move(arg)) {}

        const std::string& str() const {
            return s;
        }

        // Arithmetic types: int, float, ...
        template <class T>
        auto operator<<(T arg) -> decltype(std::to_string(arg), *this) {
            s.append(std::to_string(arg));
            return *this;
        }

        // String types: std::string, const char*
        template <class T>
        auto operator<<(const T& arg) -> decltype(std::string().append(arg), *this) {
            s.append(arg);
            return *this;
        }

        // Single char: 'a', '\n', ...
        ostringstream& operator<<(char arg) {
            s.append(1, arg);
            return *this;
        }

    private:
        std::string s;
    };
}

Now just replace std::stringstream with ard::ostringstream and it will work as expected.


text:
How to add toggle button for LCD display text and backlight?
I have set up a BMP180 and a DHT11 to display data on an HD44780 20x4 LCD.

I want to be able to toggle the altitude from meters to feet, the temperature from Celsius to Fahrenheit, and the pressure from absolute to sea level pressure using a tactile push button.
Here is the software code I have:
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

#include <SFE_BMP180.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8 // Second pin, leave 3rd pin unconnected 4th is ground
#include <SFE_BMP180.h>
#include <Wire.h>

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

#define ALTITUDE 237.0 // Altitude of Phillaur in Punjab, India. in meters

void setup() {
  lcd.begin(20, 4);
  lcd.setCursor(0, 0); // Zeroth Row
  lcd.print("hello, world!");
  lcd.clear();
  int chk = DHT.read11(DHT11_PIN);
  // Initialize the sensor (it is important to get calibration values stored on the device).
  if (pressure.begin()) {
    lcd.print("BMP180 init Success");
    delay(300);
  } else {
    lcd.print("BMP180 init fail");
    while (1); // Pause forever.
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  lcd.clear();
  lcd.setCursor(0,0);
  //TODO Display in Feet as well using toggle
  lcd.print("Altitude: ");
  lcd.print(ALTITUDE, 0);
  lcd.print(" mtrs ");
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature in deg C, From BMP180: ");
      lcd.setCursor(0, 1);
      lcd.print("Tmpratre: ");
      lcd.print(T, 2);
      lcd.print("'C");
      lcd.setCursor(0, 2);
      lcd.print("Humidity: ");
      lcd.print(DHT.humidity, 1);
      lcd.print("%");
      status = pressure.startPressure(3);
      if (status != 0) {
        // Wait for the measurement to complete:
        delay(status);
        status = pressure.getPressure(P, T);
        if (status != 0) {
          lcd.setCursor(0,3);
          // Print out the measurement:
          lcd.print("Pressure: ");
          lcd.print(P * 0.0295333727, 2);
          lcd.print(" mb");
          p0 = pressure.sealevel(P, ALTITUDE);
          // we're at 234 meters (Phillaur, Pb)
          // TODO: toggle to sea level to absolute pressure
          Serial.print("relative (sea-level) pressure: ");
          Serial.print(p0, 2);
          Serial.print(" mb, ");
          Serial.print(p0 * 0.0295333727, 2);
          Serial.println(" inHg");
          a = pressure.altitude(P, p0);
          Serial.print("computed altitude: ");
          Serial.print(a, 0);
          Serial.print(" meters, ");
          Serial.print(a * 3.28084, 0);
          Serial.println(" feet");
        } else Serial.println("error retrieving pressure measurement\n");
      } else Serial.println("error starting pressure measurement\n");
    } else Serial.println("error retrieving temperature measurement\n");
  } else Serial.println("error starting temperature measurement\n");
  delay(5000);  // Pause for 5 seconds.
}

And what part of that "I want" is it you are having problems with, if any?

Hooking the tactile button to LCD using arduino UNO :(

Well, you don't. You hook the button to the Arduno. It's then up to your software to decide what to do with it.

well, thats the part I am wondering how to do

Which part? Wiring the button up, or changing your program?

both , Wiring the button up, or changing your program

To wire the button up you need two wires - one to an input and one to ground. We can't help you change your program since we don't have your program to know what wants changing. We're not psychic you know (well, most of us aren't)

@Majenko added the software code as well.

You need to connect the button(s) to available digital inputs of the Arduino. I suggest that you use more than one button based on your description in the question.
The following tutorial describes the circuit needed and the associated code to read that input. All you have to do is duplicate it with a few more buttons on separate (available) digital inputs.
Arduino button tutorial