Problem with sending a POST request using the WiFiEsp library I'm using an ESP8266 version 1 with the WiFiEsp library to connect to WiFi, and that works just fine.

I'm setting up the device using the same code as in the example WebClientRepeating.

I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:

if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println();

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

I get the response like this:

[WiFiEsp] Connecting to 192.168.10.137
Connecting...
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 19
ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
Date: Sun, 13 Nov 2016 10:20:58 GMT
Connection: close

{"temp":"Testdata"}

However, if I try to send some body data in the request it fails:

if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println("Content-Length: 16");
  client.println();
  client.println("temperature=22.7");

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

Then the response from serial output is:

[WiFiEsp] Connecting to 192.168.10.137
Connecting...
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Data packet send error (1)
[WiFiEsp] Failed to write to socket 0
[WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.

Does anyone knows why this fails when I add Content-Type, Content-Length and some body data?

Thanks in advance!

Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:

//all your other code, including the remaining HTTP-Request
String content = "{\"temperature\":\""+String(value)+"\"}";
client.println("Content-Length: 16"); //insert, well, your content length
client.println(content);


afmotor saying "servo does not name a type" I have made a sumobot with an arduino, an afmotor shield and a 4-pin ping sensor when I upload my code it keeps giving me this error: "'Servo' does not name a type" here is my code.

You are creating Servo objects instead of AF_DCMotor objects. Change this:

Servo leftMotor;
Servo rightMotor;

to this:

AF_DCMotor leftMotor(1);   // Change these numbers to the correct motor numbers
AF_DCMotor rightMotor(2);  // you are using on the shield


Unidentified constant value im working on the following project kalman filter

and im working to implement in arduino.. i read the entire code and i succesfully implemented it into arduino but i couldnt implement the following function code line because arduino gives "not defined" error in PI_DIV_180

imu_MadgwickQuaternionUpdate(bUseAccel,elapsedTimeSecs,fax,fay,faz,fgx*PI_DIV_180,fgy*PI_DIV_180,fgz*PI_DIV_180,fmx,fmy,fmz);

it multiplies fgx with PI_DIV_180 but as i said arduino cant identify it

i looked into math.h to find the value of that define but there isnt anything in math.h related with this

the imu_MadgwickQuaternionUpdate function is in here IMU.cpp

can anyone help me please thanx..


ATSAMD21 sleep + watchdog? Has anyone got sleep/standby + watchdog to work together on their Arduino Zero or Sparkfun SAMD mini?

I am able to get the WDT to reset the device, and am able to put it to sleep - but can't get the WDT to bring it out of sleep.  Every time I try, it pops right back out of sleep mode again as if SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk was never even called

use this:

attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
    USBDevice.detach();
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    __DSB();
    __WFI();

void wakeupFunction(){
  NVIC_SystemReset();
}


Error in my Arduino code " error: expected unqualified-id before ‘if’ " I cant seem to find this error is:

elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

Here is the code:

// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}

C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned if. Remaining code following this point is nonsense. Do you mean you can put second loop() based on if condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives IF, ELSE, ENDIF.


Arduino code on Raspberry? Is there any way to run Arduino sketches on Raspberry Pi (basically on Raspbian)? I have several projects that work on Arduino and I would like to run the exact same stuff on my Raspberry Pi. Is there a way to just put all the pins off the Arduino, put them on the Raspberry, then adjust the pin number settings in the Arduino sketch, and then run the program on Raspberry?

Given that most likely the Arduino code is accessing AVR specific registers, probably not, unless you have some compatibility library that redefines all the low level stuff.

I also wonder if you have the same set of peripherals available on the PI (ex: PWM generators and ADCs).

I would rather follow the "spirit" of the code you already have and re-implement it natively in you language of choice.


Understanding writing to input pins and pull up resistors I am new to Arduino, and am trying to understand the following code.  The question is: Is my understanding correct, or if not, what is happening here?

I have to reverse engineer an existing undocumented project, based on Marlin firmware for 3D Printers.  The relevant lines from the source are:

#define DIO87_PIN               PINE2
#define DIO87_RPORT             PINE
#define DIO87_WPORT             PORTE
#define DIO87_DDR               DDRE
#define DIO87_PWM               NULL

#define MASK(PIN)  (1 << PIN)
#define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)
#define TOGGLE(IO)  _TOGGLE(IO)

TOGGLE(87);

1) Reducing this code gives me:
DI087_RPORT = 1 << DI087_PIN

2) Which reduces further to:
PINE = 1 << PINE2
3) Which reduces further to:
PINE = 00000100

4) I understand this to mean that we are setting Pin 2 of the Inputs Register (of Port E) to "High". (and are setting the other 7 pins to low)

5) I understand this to mean, as we are writing to an "Input", that we are enabling the internal pull-up resistor on Port E Pin 2.
(EDIT: I have made a mistake here in point 5: to enable a pull-up resister, you write to a pins OUTPUT register, not it's INPUT register. (but you must write to it's output register when it is in "input mode")

Questions:

Is my understanding and work-through above correct?
If yes, does this also mean that we are also disabling the pull-up resistors to the other 7 Input Pins at the same time?

I am confused by the "TOGGLE" code given above - it seems that it is "destructive" in the sense that by "toggling" the input resistor on one pin, you also disable the resistors on all other pins?  Would it not make more sense to just toggle the one pin with a bitwise or.
e.g:
PINE = PINE | 1 << PINE2

As noted in the I/O-Ports – Introduction section of the ATmega2560 datasheet,

  ... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.

Pullups are on for an input bit when the data bit is high and the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.

Regarding the macro code, your reduction looks right.  But note that use of _TOGGLE as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See What are the rules about using an underscore in a C++ identifier? for discussion.


Receiving multiple Values from android via Bluetooth my question is, how can I receive 3 integer values in Arduino, which I send from my android phone. I send all 3 values at the same time and I also need to read them in about the same time.
I hope you can help me.

If there are no other constraints, send them as a text with delimiters and a  terminating character.
e.g. something like "123;45;678\n"

On the arduino, either manually check for those delimiters and convert the digits to a number on the fly, or use strtok  and atoi after reading the whole line.


Multichannel communication with Arduino and HC-12 transmitter The HC-12 module has 100 possible channels starting at 433 MHz. Can someone tell me how to program the Arduino to use multiple channels at the same time? My goal is to build an RC transmitter with Arduino and an HC-12 module for a quadcopter. Therefore I need 6 channels, like a normal transmitter does. Thanks in advance!

I believe you are misunderstanding what it means by channels. The HC-12 can transmit on up to 100 channels, which means different frequencies under the 433 MHz band. For example 433.05 MHz or 433.15 MHz. This is so multiple HC-12 modules can be used next to each other and only the module receiving on the channel of the transmitter will receive the data broadcast.

What you need to do for your quadcopter is send an array of bytes that begins with a constant, followed by the data you need (a packet). Example:

byte packet[] = {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}

// in your loop
packet[1] = ; HOW MUCH THE ENGINE IS THROTTLED
packet[2] = ; HOW FAR THE CONTROL TO GO FORWARD IS DEPRESSED
// etc

Iterate through this array writing the data through the serial port to the HC-12. Whenever your receiver detects the constant (in this case 0x00) read the values that follow as the controls for the quadcopter.


How do you send data via I2C without the wire library? I have the following digital potentiometer: DS1803-100 which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite (link to code). Can somebody tell me why? For reference, 0x50 is the address + r/!w bit, 0xA9 is the command (write to pot 0 in my case) and the next 0xA9 is the value to write. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!

EDIT: Here is the code

int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(100); // wait fro aknowledgement

}

I2C is a lot more complex than just shifting bytes out.

See: I2C - Two-Wire Peripheral Interface - for Arduino

Your code does not seem to take any of that into account.

Why do you not want to use the Wire library? The hardware on the chip (what chip do you have?) supports it. Why ignore that and try to do it yourself?


Nokia 5110 LCD number display problem I have a problem regarding a Nokia 5110 LCD display. I am currently building a soldering station based on a PID controller. The original code was using a 7 segment display and I adapted the code to the Nokia display.

The problem is that when I rotate the potentiometer, the "read temp" and "set temp" is showing the exactly the same number, and after I finish rotating the potentiometer, the values return to their normal number.

How can I solve this problem ?

This is my code: https://pastebin.com/inPtkniX

This is the original project: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/

//Soldering station Software using PID
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>
#include <PCD8544.h>

PCD8544 lcd;
unsigned long updaterate = 500; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;
int temperature = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup() {
  lcd.begin(84, 48);
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  lcd.clear();
  //Read temperature
  Input = analogRead(0);
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 450, 25, 350);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 350);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    //temperature = newSetpoint;
    lastupdate = millis();
  }
  double gap = abs(Setpoint - Input); //distance away from setpoint
  if (gap < 10) {
  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  } else {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature, newSetpoint);
}

void show(int value, int newspnt) {
  lcd.setCursor(0, 0);
  lcd.print("READ TEMP");
  lcd.setCursor(0, 1);
  lcd.print(value);
  lcd.setCursor(0, 2);
  lcd.print("SET TEMP");
  lcd.setCursor(0, 3);
  lcd.print(newspnt);
  delay(200);
}

Look at line 55, where you are doing this

temperature = newSetpoint;

There is no reason to give temperature the same value as the set point. It does not make sense. And the temperature variable is the same, that you are using to display.

So, while you are changing the setpoint, the temperatur variable gets overwritten with the setpoint. When you are not changing it anymore, the measured temperature is still in this variable, when you are displaying it.

Just remove the mentioned line.


Should I buy a retired Arduino? I am a beginner who would like to buy an Arduino Yún (58 dollars).

It is retired so will I have any problem?

Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an Arduino Uno + Arduino Yún Shield and an Arduino Uno + ESP8266 serial WIFI wireless module.

Arduino Yún Shield: I can't find the price. I only found an Iduino.

ESP8266 serial WIFI wireless module: 7 dollars.

It is retired so will I have any problem?

It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.


Decoding RC transmitter data I would like to use my FSi6 transmitter but not the receiver that comes with it (I´m trying to save weight), for that I was planning to get one of this NRF24L01 breakout boards. The problem is, how do you interpret the incoming traffic? After some googling, I couldn´t find any information from flysky.

I would think that this is a common thing to do, as you could pair the transmitter with another receiver (perhaps other brand) so there must be a standard protocol.

Any ideas?
Thanks!

Unless the FSi6 (whatever that is) uses an nRF27L01+ as its transmitter, then no - you can't.

The nRF24L01+ chip will only communicate with other nRF24L01+ chips.  It contains its own custom protocol within the chip and it can only talk that protocol and no others.


What pins can be used for chip select (CS, CC) on the Arduino nano every? I’ve checked the nano’s tech specs but I can’t seem to find any information regarding it. I’ve tried setting it to pin 26 (digital output)

The following answer assumes the Arduino is the master.

You can use any pin for that (at least any GPIO pin).

Multiple SPI devices can be connected to a SPI peripheral on an Arduino (in principle).

Every SPI device should have their own CS/CC pin, and is mandatory when you use multiple SPI devices.

For this reason, there is no single pin the SPI can define for being used as CS/CC pin. However, it should give a GND or VCC value, thus a CS/CC pin should typically be configured as a digital input pin (as master) for each slave.
(See remark of KIIV too); as slave the CS/CC pin should be a digital output pin.

For the other pins (MOSI, MISO, CLK), the Arduino uses a fixed set of pins because all SPI devices will be connected to these pins.

So the CS pin is configurable, and the other spi pins are fixed.


Arduino Switching Between Loops IR Remote I've been working on an LED strip project. However, I've come to a stand still at the moment. Within the program I am wanting to assign different lighting effects to each button on my IR remote. I am wanting the program to work on the basis that each lighting effect will run, until another button is pressed, to start another effect.

Currently with my code I have made it so each effect will run, once, when the corresponding button on the IR remote is pressed.

I am fairly new to C++ / Arduino but from my understanding I need to have a variable which would hold the current value of the IR remote. I am unsure on how to actually implement this. I will post my code below and if anyone could give me tips or even amendments to my code it would be to a great help.

Thank you in advanced.

#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{
  switch(results.value)
  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
  break;

  default:
  Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 1; j++) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(50);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(50);
  }
}

delay(0) apparently[*] acts like delay(2^32) or about 10^10 milliseconds. That may not be what you had in mind ... :)

Try reducing the delay to 1 or use delayMicroseconds() to get something shorter. That should at least get you some repeatable results.

(10^10 mSec is ~ 16.5 weeks, for those without a calculator handy).

[*]  I didn't read the code, nor wait for the call to expire. I tried it and saw that the Uno froze. I'm guessing a zero-argument to delay() isn't rejected but just gets decremented as usual, until it hits zero.


CH340 chip getting fried after connecting Arduino to a powerful 12V souce I'm using a 120 W DC power supply connected in parallel with ESC and Arduino nano through Vin. However, somehow the Arduino get fried near the CH340 chip, i.e. around the big black square chip near the micro usb port on the back of the board, kept getting fried. It's working for a while, until it melted.

This didn't quite make sense, since Arduino Vin can take voltage from 6V to 12V. The ESC also had a maximum current consumption of over 30A, equivalent to 360W. Thus there wasn't an obvious reason for which Arduino ought to get fried at all.

Why CH340 chip getting fried after connecting Arduino to a powerful 12V source?

It's impossible to say for sure what is going on without proper equipment (mostly you need oscilloscope), but I'm pretty sure that due to very high current consumption of the motors, there are voltage spikes at the input of the voltage regulator. If voltage exceeds safe value (15V for most of them), then regulator fails and all the input voltage is now on the output (that's how they fail 99% if the time, not as an open unfortunately, but as a short). Then for some reasons the weakest IC is CH340G which is fried. Try to use destroyed Arduino without ESC, and see what's on the 5V pin.
You say that you have currents up to 30A, but PSU is rated for 120W which means it can deliver only 10A at 12V. So at some point PSU falls into protection mode, switches off the output, and after some time tries to switch it on again. Situation with voltage spikes can be very nasty during this period.
Also please post your schematic and photo of the actual wiring, this can also give us some clues.


Particle Electron to RS232 Serial gibberish I've spent all day trying to monitor serial console output of a router. I'm using an "ebay" MAX3232 RS232 to TTL converter connecting only GND, TX and RX to the Electron. Trying to simply monitor the console output during bootup - all I get is gibberish.

Even connected to computer's COM1 port and was unable to echo back and forth. All I get is 0 or weird symbols. (this was tried with more code than below)

Here's my most basic code. I'm about ready to give up. Any ideas?

#include "Particle.h"

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600); // tried with 2400/even 1200 really should be 9600
  Serial.println("Starting up Serial");
  Serial1.println("Starting up Serial1");
}

void loop() {
 while(Serial1.available()>0)
 {
   Serial.write(Serial1.read());
 }
 delay(50);
}

If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing.
Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.


Arduino Ultrasonic Sensor and LCD - Help Needed- I just recently purchased an Arduino Uno 3 and I wanted to make an ultrasonic distance sensor that outputs the readings to a 16x2 LCD. I followed this guide:
http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/ but it gave an error when I uploaded the code. The error was: a function definition is not allowed here before '{' token. I don't know too much about Arduinos, so I need help.
Thanks to whoever responds!

Here is the code:

// put your setup code here, to run once:
#include <LiquidCrystal.h> //Please replace the single quote characters ('') with the parenthesis character (<>)

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

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print("  cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print("inch");
delay(10);
}

The root of your problem is this bit:

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

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:

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

You have a similar problem here:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

Again that has split across two lines and should read:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

And a third:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

which should be:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

When those three are corrected the code compiles properly.


Set up a motion sensor to turn on lights and record how long the lights are on I'm doing a school project and I want to measure the difference in time that the lights are on in a classroom with and without a motion sensor controlling them. I haven't really found anything about recording how long sensors act or the time between activations. How could I possibly do this?

I would consider placing a light sensor close to one of the lights to signal when the lights are on. Placement is critical as you do not want a signal when the lamp is off. I am assuming they are permanent light fixtures and you are not allowed to tamper with the wiring.  Record the elapsed time when they are on.  Note the start time and then subtract that from the current time based on your watch. For elapsed time and subtract the ontime from that. With the sensor you can also record each time the light is turned on etc. That would all be in your software.


Is there a transmission protocol library for SPI? When communicating over SPI, one byte is sent at a time. Is there a library (C or C++) that allows for sending strings? Essentially it would be a protocol library handling the start and the end of a message, as well as integrity checking. (I'm using an Arduino.)

Each spi peripheral has its own protocol in the sense of commands and addresses if any and data.  Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.

So a general purpose library doesnt make sense.

Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.

Your arduino spi master may have its limitations but that has nothing to do with spi in general.

Integrity testing is not part of the spi protocol, you get what you get.  Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in.  You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc).  If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself.  If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.


Any way to use DMA to transfer data to SD Card in ESP8266 I'm using ESP8266 at speed of 160 MHz to record ADC results into SD card, I need to do this at rate of 8 KHz. Means that i should save it on the SD Card or i'll run out of memory before 4 Sec passes.
I used timer1 to trigger sampling, but my problem is that surprisingly ESP8266 can not do this fast enough and the maximum sampling rate i get is about 7 KHz. I also tried to write data in ESP8266 Flash using littleFS in hope of acceleration but there was no luck. Here is my code:
#include <SPI.h>
#include <SD.h>

File dataFile;

int flag = 0;
int count = 0, level = 0, se_count = 0;

void inline analogReader() // Sampling and Recording processed which is done sequentially :(
{
  uint16_t dataByte = (uint16_t) analogRead(A0);
  dataFile.write((uint8_t*) &adcBuf, 2);

}

void ICACHE_RAM_ATTR onTimerISR() { // Timer sets the flag every 0.125 MS
  flag = 1;
}

void setup() {
  pinMode(A0, INPUT);
  pinMode(D0, OUTPUT);

  Serial.begin(115200);

  if (!SD.begin(D0)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");

  File root = SD.open("/");

  if (SD.exists("real_test.bin"))
  {
    SD.remove("real_test.bin");
  }

  dataFile = SD.open("real_test.bin", FILE_WRITE);

  if (dataFile) {
    Serial.println("File created!");
  }
  else
  {
    Serial.println("Failed to create file!");
    return;
  }

  // Setting the timer so that timer interrupt fires every 0.125 MS
  timer1_attachInterrupt(onTimerISR);
  timer1_enable(TIM_DIV1/*from 80 Mhz*/, TIM_EDGE/*TIM_LEVEL*/, TIM_LOOP/*TIM_SINGLE*/);
  timer1_write(10000); /* ( 80 / 1 ) * 125 */
}

void loop() {
  if (flag) // To check whether its time to sampling or not, because of the low speed of the process
  {         // The flag is set again before one iteration ends.
    flag = 0;

    if (se_count < 10)
      analogReader();

    count++;
    if (count == 8000) // When 8000 sample & write process done notify using serial monitor. (it is
                          always more that 1 Sec. for example 1.3 Sec.)
    {
      count = 0;
      level = !level;
      Serial.println(level);

      se_count++;
      if (se_count == 10) // When we done 8000 * 10 sample & write we close the file. it supposed to
                          // be done in almost 10 sec. but it takes more time in practice. for
                          // example 13 Sec.
      {
        dataFile.close();
        Serial.println("Write ended");
      }
    }

  }
}

I even used a faster method system_adc_read_fast(buf, num, clk_div) that is available in ESP-SDK, So i'm desperately seeking for one or two of approaches bellow if possible:

To use a non-blocking approach: If there is any possibility to hand SD writing to DMA so that i only fill the ADC buffer for DMA, or an interrupt for ADC complete so that i write to SD and when interrupt fired put the result in the buffer and return back to SD writing.
Yet faster approach for both ADC sampling and writing: Can i increase the SD write speed of SD library? for example by configuring SPI for maximum speed rate.

I also tried SDFat library but it does not recognize my SD Card. The whole process is odd to me that even by using a 160 MHz CPU and hardware i can not record ADC data at rate of 8000 Sample/S. I have TIME limitation so please help me.
Any suggestion is appreciated. Thanks in advance.

So, sorry for late response, i figured it out. Because it took lots of time for me and it might be a prevalent issue, i think it worth to contribute my experience for further similar issues.
As mentioned buffering can do the job, here are some constraints that should be satisfied to have right buffering mechanism;

Writing to SD card SHOULD NOT be handled in the Timer ISR, but store ADC data into a buffer, aka int[] which is normally kept in SRAM (Your Timer ISR should be as short and fast as needed)

Handle reading from buffer to SD outside of Timer ISR in, for example in loop().

priority of ISR should be more than loop(), and it is so by default.

It's a good practice to divide your buffer into chunk of 512 or 1024. for example 2 chunks of 1024 Bytes making your buffer. you check for "filled" flag to be set in the loop() and when this happens call SDFile.write(..) for corresponding filled chunk and then reset the flag.

By conforming to these constraints you enjoy these benefits:

you can be sure that no ADC on time sampling missed because of sluggish SD write process.

by buffering and pilling data and then storing, you have chance to avoid byte wise write to SD, which is  really inefficient. and instead handle write in chunks of 512 or 1024 bytes. which is equal to sector size of SDs. so you have faster SD write process too.

This way you can easily handle voice recording up to 16 ksps even without using DMA.
I have added the code to my github, in this repository; https://github.com/A-R-S-D/WAVRecorder


Weird effect of AVR C on USB-serial communication I recently decided to learn direct port manipulation instead of builtin arduino routines.
First I tried this piece of code
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("on");
delay(500);
digitalWrite(LED_BUILTIN, LOW);
Serial.println("off");
delay(500);
}

This program on running instantly established connection with the serial monitor on my arduino IDE.
But when I try this code
int main(void)
{
Serial.begin(9600);
DDRB = B11111111;
while(1)
{
PORTB = PORTB | 0x20;
Serial.println("off");
_delay_ms(500);
PORTB = PORTB & 0xDF;
Serial.println("on");
_delay_ms(500);
}
}

But this program is taking some time, about 5-10 seconds to establish serial connection. Also delay() is not working too. When I use delay() instead of _delay_ms(), the entire arduino board freezes like a computer and stops blinking the LED instead LED is fully ON.
I tried is on several programs, while "setup-loop" program connects instantly, AVR C programs does not.
why does it happen?

By defining your own main() you are circumventing the Arduino startup procedures.
Normally with Arduino code main() first runs an init() function before setup() and (repeatedly) loop().  This init() function will configure, amongst other things, the timer for millis() and delay().
This is the normal main() for a basic AVR-based board:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

It first initializes common functions, then board-specific ones (normally nothing), and if applicable, the USB interface (for ATMega32U4 based boards, like the Leonardo).
Only then does it go on to run your sketch.
If you want to use both your own main() and Arduino functions like delay() then you will have to call those initialization routines before running the rest of your code.


Making CS (chip select) work in SPI (for and SD card and OLED) I'm working on a project that will log data to an SD card and display a user interface on an OLED. The SparkFun OLED breakout was super easy to set up. I was also able to get the SD-Card library working independently, though that was harder.

The trouble is when I combine these examples the SD card only writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine.  I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.

My pins are connected as follows:

          SD CARD      OLED
MOSI        A5            A5     same pin
MISO        A4            --     just SD connected
SCK         A3            A3     same pin
CS          A1            A2     different pins

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way.  What could I try next?

Here is the code:

 #include "application.h"
 #include "sd-card-library/sd-card-library.h"
 #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
 #include "math.h"

 //////////////////////////////////
 // MicroOLED Object Declaration //
 //////////////////////////////////
 // Declare a MicroOLED object. If no parameters are supplied,
 // default pins are used, which will work for the Photon Micro
 // OLED Shield (RST=D7, DC=D6, CS=A2)
 // Since I use A1 as the chip select pin for the SD card these
 // defaults seem fine.

    MicroOLED oled;

 // Declare a file object?

    File myFile;

 // These are the pins for the SD card. A5, A4, and A3 are all
 // shared by the OLED.

    const uint8_t chipSelectSD = A1;
    const uint8_t mosiPin = A5;
    const uint8_t misoPin = A4;
    const uint8_t clockPin = A3;

 ////////////
 // setup //
 ////////////
 void setup() {
  delay(500);

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("this text was printed to the SD card during setup");
  dataFile.close();

  oled.begin();  // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  delay(1000);  // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

               }//end setup

//////////////////
// main loop //
//////////////////
void loop()  {

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("The text was added during the loop.");
  dataFile.close();

//test the display with text and pixels.
  printTitle("Pixels", 1);
  for (int i=0; i<512; i++)
  { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
  oled.display(); }
   delay(9000);

               } //end loop

//-------------------------//
// function to print titles //
//-------------------------//
  void printTitle(String title, int font) {
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
  middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
                                           } //end title function

This is how the SD card is hooked up.

  oled.begin();  // Initialize the OLED

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.

I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.
Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???


How to use pyserial to write two separate message? I'm using pyserial to communicate with my arduino. I set up the connection and everything works fine. Now I have these two writing commands:
pyserial.write("conn".encode())
pyserial.write("mod1".encode())

On my arduino:
while (!Serial.available());
String s = Serial.readString();
if (s=="conn") do...;
if (s=="mod1") do...;

The problem is that none of the if statements are true because s becomes "connmod1", because the messages are sent almost at the same time I guess. I know I could use some delimiter to split the string, but I would like to know what the convenient solution might be?

If you want a quick, cheap, and easy solution, you could just use sleep() in your Python script to put a delay between the commands. This obviously isn't a perfect solution, but it's not difficult to implement.
Or, like you said, you could use a delimiter. It's not as easy to implement, but it'll work better.
If you go the delimiter rout, you'll probably need to use Serial.read() instead of Serial.readString(). That way you can examine characters individually as they come in. You can store your characters in a String or char array until you detect your delimiter and then execute your command.
Hope that helps!


What is the best board for setting up an SSH protocol to an Arduino? I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

Sounds like you want an Arduino Yun instead of an Uno.  Or a Dragino Yun Shield that turns your Uno into a Yun.


Bending pins of HC-SR04 I got a question regarding the ultrasound sensor (HC-SR04) connecting to the arduino. I have a project, and the space is really tight, so i will have to bend the pins of the HC-SR04. Is this okay to do, and if yes, how should i go about and do this ?

The easiest things to do if space is a premium is to unsolder (or cut) the pins and then solder directly the wire to the corresponding spots.

Otherwise, you can also just get straight pins and replace them, You can also choose on which side of the board, as the holes are though it.

Lastly, about bending, it's doable with pliers if you want to make the pins face "forward" but depending on the quality of your pins they might break in the operation.


Convert uint8_t array to uint32_t array I have this array of bytes, that I need to convert to an array of unsigned ints. Also the function (btea) that needs it, seems to need a pointer.

I'm currently using reinterpret_cast which seems to work, but I'd like to know how/why. I'm pretty new to C. It also seems kind of dirty. I could use a for loop, and bitshift everything into a separate int array variable, but that seems wasteful.

uint8_t data[] = {1,2,3,4,5,6,7,8};//can be any multiple of 4 bytes

btea(reinterpret_cast<uint32_t*>(data), sizeof(data)/4, encryption_key);

radio.write(data, sizeof(data));

...

void btea(uint32_t *v, int n)
{
  ...
}

Any pointers (pun intended) are much appreciated.

I prefer to use unions. example:

union fourbyte {
  uint32_t dword;
  uint16_t word[2];
  uint8_t  byte[4];
};

union fourbyte val;

val.dword = 0x03020100;

Serial.println(val.byte[0], HEX);
Serial.println(val.byte[1], HEX);
Serial.println(val.byte[2], HEX);
Serial.println(val.byte[3], HEX);

Serial.println(val.word[0], HEX);
Serial.println(val.word[1], HEX);

Serial.println(val.dword, HEX);


Detect movements of a person? I'm working on a Virtual Reality game. I want to detect the position or movement of most of the bones in the human body(e.g. Knees, elbows, shoulders, hands and legs). This person may wear special equipment. How should I detect this?? I also want to get the distances between a certain position(e.g. The Arduino board) and each bone. Any ideas?

What you're looking for is called motion capture. If you google it, you'll find a Wikipedia article that can give you a starting point for deciding which of the many available techniques will suit your project. Youtube also has several videos explaining motion capture, and different technologies.


Passing a NeoPixel object reference to a custom library I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.

Here is my current project code:

#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}

And here is the library I tried to create:

/*
    Youkai's Artificery NeoPixel cycle library.
    A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
    public:
        YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
        void tryStep();
    private:
        Adafruit_NeoPixel& _neoPixel;
        unsigned int _ledHue = 0;
        int _saturation;
        int _brightness;
        int _hueStep;
};

#endif

/*
    Youkai's Artificery timer library.
    Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
    _neoPixel = neoPixel;
    _saturation = saturation;
    _brightness = brightness;
    _hueStep = hueStep;
    _neoPixel.begin();
    _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
    _ledHue += _hueStep;
    _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
    _neoPixel.show();
}

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.

After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL_PIN and LED_COUNT as variables to the library with YaNeoPixelCycle(..., int controlPin, int ledCount) so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.

This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

You call _neoPixel.begin() and _neoPixel.show() in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   begin() functions are used. Add a begin() function to your class and call cycle.begin() in setup().

void YaNeoPixelCycle::begin() {
  _neoPixel.begin();
  _neoPixel.show();
}

Of course remove the _neoPixel.begin() and _neoPixel.show() from the constructor.


Confused as to how 2 of my interrupts are firing from just 1 pin input? I have the following code which uses interrupts to set a flag for whether serial IO should happen to update my PC about a particular pin input. So I have interrupts on pins 2 and 3.

I am using the arduino's pin 13 as an output, and every 2 seconds send a pulse. On my arduino, I have 1 wire running from 13 to pin 3. Note: I have nothing at all inserted into pin 2.

Somehow, I get the following input every 2 seconds:

Pin 2
Pin 3

How is my interrupt for pin 2 firing??

boolean serialCommsQueue1 = false;
boolean serialCommsQueue2 = false;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), pin2Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(3), pin3Fired, RISING);
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH); // sets the digital pin 13 on
  delay(1000);            // waits for a second
  digitalWrite(13, LOW);  // sets the digital pin 13 off
  delay(1000);            // waits for a second

  if (serialCommsQueue1)
  {
    serialCommsQueue1 = false;
    Serial.println("Pin 2");
  }

  if (serialCommsQueue2)
  {
    serialCommsQueue2 = false;
    Serial.println("Pin 3");
  }
}

void pin2Fired()
{
  serialCommsQueue1 = true;
}

void pin3Fired()
{
  serialCommsQueue2 = true;
}

EDIT:

If I take the wire out of 3, pin 2 constantly (every 2 seconds) writes to serial. If I put the wire back in pin 3 regularly writes every 2 seconds - which itself is a problem too, since it should only be detecting a 'change'?

The interrupt on pin 2 triggers, because the pin is floating. Since nothing is connected to the pin, it reacts to whatever noise is flying by (for example from pin 3). That can lead to the pin changing its state together with pin 3, or to just erratically randomly changing state.

You need to connect a pullup or pulldown resistor (one rather big resistor going from the pin to either Vcc or ground), which sets the pins state, when it is not actively driven otherwise. If you need a pullup or pulldown depends on your wanted behavior.

If a pullup is ok for you, you can activate the Arduinos internal pullup resistor by using

pinMode(2, INPUT_PULLUP);


Communication between ESP01 Arduino NANO and using External Interrupt in Arduino NANO for other than communication program same time I have done communication between ESP01 and Arduino NANO (ATMEGA328 based). ESP pins used are GPIO-0 and GPIO2. In NANO, used D2 and D3. This program working Ok. Now I want to add external interrupt in my Arduino NANO program while continuing communication with ESP01. But I cannot use D2 and D3 because it was used by communication program. Now Arduino NANO's limit is it has only two interrupt pins which are D2 and D3. So if I use this for external interrupt program, I lose communication with ESP01. Can anybody help me to use my both task at the same time: Task1- External interrupt in Arduino Nano, Task2- Communication with ESP01. Your reply will help me to solve this issue. Thanks in advance.

D2 and D3 Pins on Arduino nano support external Interrupt. Hence, you have to use one of those for the interrupt.
Since you are using softwareSerial() you can easily remap it to other digital pins of the Nano.
Pins from D4-D12can be used for communication.
You just have to change the parameters in the softwareserial() as below:
SoftwareSerial mySerial(4, 5); // RX, TX;;for example


Mega attachInterrupt on pins 18 or 19 require EIFR bit set first (to clear it)? Experimenting with external interrupts on a Mega. Pins 2 and 3 work with standard

attachInterrupt(digitalPinToInterrupt(iPin),ISR,FALLING);

coding and call my ISR. With pins 18 and 19 I had to add

EIFR = 4;

for pin 19, and

EIFR = 8;

for pin 18 before calling attachInterrupt(...) to get them to work. Why?

BTW, I'll add this table that I filled in by trial and error for anyone interested in Atmel (AVR) external interrupt numbers to Arduino external interrupt numbers (I won't list the AVR chip pin numbers)

AVR INT      5 .  4 .  3 .  2 .  1 .  0
EIFR (Dec)  32 . 16 .  8 .  4 .  2 .  1
Arduino Pin  3 .  2 . 18 . 19 . 20 . 21
Arduino INT  1 .  0 .  5 .  4 .  3 .  2

I know writing a 1 to the EIFR bit for the appropriate interrupt clears the interrupt. When I reset the Arduino without clearing interrupts on pins 2 and 3 it's fine. If I don't clear 18 and 19 after a reset, it throws the interrupt right away. (Yes, I should OR the EIFR with the bit I want to change but I'm just playing) Didn't try 20 and 21 because I'm using them for comm.

It's not that pins 18 or 19 are faulty, you are just lucky the other ones worked.

As I mention on my page about interrupts* you are recommended to always write 1 to the appropriate EIFR bit before enabling interrupts because it (the interrupt condition) may have been set in the past.

I checked the source for attachInterrupt in the file WInterrupts.c and there is no mention of the EIFR register, therefore attachInterrupt never affects that register.

* Also see my answer: How do interrupts work on the Arduino Uno and similar boards?


How to change IIC (I2C) clock rate on MKR1000 The IIC clock defaults to 100kb, need to increase it to ~200kb.

I've tried:

changing the constant TWI_CLOCK and rebuilding Wire.cpp
calling initMasterWIRE(200000) after Wire.begin().

I'm using a scope to verify the change, and thus far can't seen a change in the clock width.

I believe the pull resistors are 10k?  Might need to decrease a bit to.

Looking for a very short example!
TIA.

Looking for a very short example!

easy:

1) find out the mcu used by the board;

2) look up its datasheet;

3) go to the i2c section and find the register(s) that control the i2c clock speed;

4) change it/them.

alternatively, you can take a look at the i2c initialization code and go from there.

the likely solution will be a one liner: use a mask to clear bits and then set those bits depending on your desire i2c speed.


Write a condition to execute 2 switch-case functions? I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?

If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.

What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:

condition 1 --> warning --> case 1 --> case idle;

condition 2 --> warning --> case 2 --> case idle;

condition 3 --> warning --> case 3 --> case idle:

void loop() {
  static byte theState = idle;
  switch (theState)
  {
    case idle:
      if (voltageA0 > 1.0) {
        theState = case1;
      }

      if (voltageA1 < 2.0) {
        theState = case2;
      }

      if (voltageA2 > 3.5) {
        theState = case3;
      }
      break;
    case warning:
      digitalWrite(7, HIGH);
      delay(5000);
      digitalWrite(7, LOW);
      delay(0);
      break;
    case 1:
      digitalWrite(8, HIGH);
      delay(2000);
      digitalWrite(8, LOW);
      delay(0);
      theState = idle;
      break;
    case 2:
      digitalWrite(9, HIGH);
      delay(2000);
      digitalWrite(9, LOW);
      delay(0);
      theState = idle;
      break;
    case 3:
      digitalWrite(10, HIGH);
      delay(2000);
      digitalWrite(10, LOW);
      delay(0);
      theState = idle;
      break;
  }
}

Also, if there is a more efficient way to do this, code-wise, I'm all ears!

There is something incoherent in your code. It is structured as a finite
state machine, and yet you are using delay() within it. In this kind of
scenario, the whole purpose of a state machine is to avoid using
delay(), so that your program never blocks. If your program happens to
not have anything better to do than delaying, then you can forgo the
state machine and write much simpler code. For example:

void warn_and_flash(byte pin)
{
    // Flash the "warning" LED.
    digitalWrite(7, HIGH);
    delay(5000);
    digitalWrite(7, LOW);

    // Flash the requested LED.
    digitalWrite(pin, HIGH);
    delay(2000);
    digitalWrite(pin, LOW);
}

void loop()
{
    if (voltageA0 > 1.0) warn_and_flash(8);
    if (voltageA1 < 2.0) warn_and_flash(9);
    if (voltageA2 > 3.5) warn_and_flash(10);
}


Graph plotting on Processing from Arduino sensor data I am trying to plot a graph on processing but I'm having challenges going about it. The processing sketch below does work for plotting only one axis, and I'm trying to plot all three axis on the same sketch. Does anyone have an idea on how I could go about it. Below are the Arduino and Processing sketches.

Arduino

AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup()
{
   Serial.begin(115200);
   ski.begin(13, 12,11,10, A0, A1, A2);
   ski.setARefVoltage(3.3);
   ski.setSensitivity(HIGH);
   ski.calibrate();
}

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
   //Serial.print("\nx: ");
     Serial.println(x);
   //Serial.print("\ty: ");
   //Serial.print(y);
   //Serial.print("\tz: ");
   //Serial.print(z);
   delay(10);                                     //(make it readable)
}//End of Arduino Sketch

Processing

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

float fValue;
boolean newVal = false;

void setup () {
   size(800, 630);
   println(Serial.list());
   myPort = new Serial(this, Serial.list()[0], 115200);
   myPort.bufferUntil('\n');
   background(2);
   stroke(127, 34, 255);
}

void draw () {
    if (newVal) {
       line(xPos, height, xPos, height - fValue);
       if (++xPos >= width) {
         xPos = 0;
         background(2);
       }
       newVal = false;
    }
}

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');
   if (inString != null) {
       inString = trim(inString);
       fValue = float(inString);
       fValue = map(fValue, 0, 1023, 0, height);
       newVal = true;
     }
}

I have edited your serialEvent() method a little bit, so it could handle the data from the Arduino, when split by a tab.

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   if (inString != null) {
     values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
     for(int i=0;i<values.length;i++){
       values[i]=trim(values[i]); //deleting the whitespaces as before
       float_values[i]=float(values[i]); //cast the string to a float as before
     }
       x = map(float_values[0], 0, 1023, 0, height); //map the value as before
       y = map(float_values[1], 0, 1023, 0, height);//map the value as before
       z = map(float_values[2], 0, 1023, 0, height);//map the value as before
       newVal = true;
     }
}

so your sending on the Arduino has to look like this:

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\n");
    Serial.print(x);
    Serial.print("\t");
    Serial.print(y);
    Serial.print("\t");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}

You still have to make the drawing in the draw() method of processing, but I think that this is not the problem.

For the 3d draw you should have a look on the Processing reference or at this special topic, P3D by Daniel Shiffman.

I have not tested the code, but I think that it should work.

If you have questions, feel free to ask ;D


Increasing analogread speed on the Arduino Uno I want to transfer data from my smartphon to the Arduino by using the audio jack of my smartphone. For this I need verry high reading frequencys.

I have used

bitClear(ADCSRA,ADPS0);
bitSet(ADCSRA,ADPS1);
bitClear(ADCSRA,ADPS2);

to boost analogread to ~10microseconds, which would be enough. But somehow I am still wasting 5.4 ms at the beginning of the transmission.

The only thing between signal start and first analogread is a start of a for loop:

while(analogRead(A0)<50) (true); //wait for start of transmission
for(i = 0; i<500;i++){
data[i]=analogRead(A0);
}

But does starting a for loop take 5.4 ms?
Do you have any ideas?

It sounds like you could benefit from interrupt handled free running sampling, doing that should get you sampling rates up to the maximum listed on the 328's datasheet, 76.9 kSPs. Although, that's at a reduced resolution. This site explains better, under the section "Free running sampling".


Removing the barrel jack connector? My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.

Or could that cause problems?

You'll likely do less damage de-soldering it than trying to snip it off. Use a de-soldering pump to remove as much molten solder as you can, then heat again with de-soldering braid to wick up the remainder. If the jack's solder terminals were bent over (to stabilize the part before it was soldered) you may need to straighten them with a tweezer-nosed plier. Then you should be able to lift the part off the board. Don't overheat the board or heat any other parts or solder joints than those you intend to remove.


Set interrupts that are not GPIO or Timer in ESP32 I am making a project on ESP32. It reads certain sensor values, stores them in RTC memory and sends them by MQTT after a certain time. I wish that it transmits data immediately if there is a difference of, say 10 units, via an interrupt. I suppose this is not possible by GPIO interrupts and obviously not by a timer as I wish it to happen only if a condition is true and not periodically.
I searched on the internet but couldn't find anything except GPIO and Timer interrupts.
I am working on Arduino IDE.
Is what I want possible and if yes, how. Please also give a certain example that is in Arduino language for me to study. Also, if it is possible using GPIO interrupts, please tell me how.
Thank you in advance

There is no such thing as an "interrupt on a value changing" since that is something that only exists in software, and interrupts are things triggered by hardware.
All you can do is check the value in loop() and send the data if the value is above your threshold. If you want to wake from sleep then you will have to do that periodically through other means.


"function" was not declared in this scope (called in setup) I have this bit of code I'm trying to execute only once. but I seem to get this error every time I try to compile: "calcOppervlakte' was not declared in this scope" when it's being called in the setup.

I've looked at code examples where calling functions like this works, and I cannot wrap my head around this problem.

google isn't really helpful either since the search for something-something not declared in this scope gets me thousands of results.

double pi = 3.14159265359;

void setup() {
  Serial.begin(9600);
  for(int r = 1; r <11; r++){
    Serial.print(calcOppervlakte(r)); <----
  }
}

void loop() {

}

double calcOpppervlakte(float radius){
  double result = pi * pow(radius, 2);
  return result;
}

The function name you're calling is calcOppervlakte but the function name in the definition is calcOpppervlakte. If you look closely you'll see there is an extra p in the function definition. If you change the names to match the error will be resolved.


NodeMCU (Arduino IDE) 'DynamicJsonBuffer' was not declared in this scope #include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;
String url = "http://192.168.31.170/api/mode/qwertyui";

void setup() {
  USE_SERIAL.begin(9600);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for (uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Robotics Incubator", "XXXXXXX");
}

void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    HTTPClient http;
    http.begin(url); //HTTP
    int httpCode = http.GET();

    if (httpCode == 200) {
      // Parsing
      const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
      DynamicJsonBuffer jsonBuffer(bufferSize);  //This was not declared error.
      JsonObject& root = jsonBuffer.parseObject(http.getString());
      // Parameters
      int Mode = root["mode"]; // 1
      Serial.print("Name:");
      Serial.println(Mode);
    }
    http.end();
  }

  if (Serial.available()) {
    url = Serial.readString();
  }
  delay(100);
}

How can I solve this problem?
I followed this tutorial - ESP8266: Parsing JSON

This error is caused by using a 6.x.x version of the ArduinoJson library with code that was written for a pre-6.x.x version of the library.

You have two options to solve the problem:

A. Downgrade the library to a version that is compatible with your code

For now, this is probably the best option because the 6.x.x version of the ArduinoJson is still in beta so it makes sense to wait until the new API is stabilized before porting your code. This is even recommended by the ArduinoJson developers:

https://arduinojson.org/v5/faq/error-jsonbuffer-was-not-declared-in-this-scope/

Sketch > Include Library > Manage Libraries...
Wait for the download to finish.
In the "Filter your search..." box, type: "arduinojson".
Click on "ArduinoJson by Benoit Blanchon".
From the "Select version" dropdown menu, select "Version 5.13.2".
Click "Update". Wait for the update to finish.
Click "Close".

Now your code will compile. If you have File > Preferences > Check for updates on startup enabled, you will continue to get updatable library notification for the ArduinoJson library but you need to refrain from updating back to a 6.x.x version or the error will come back.

B. Update your code to be compatible with the 6.x.x version of the ArduinoJson library

In this case you need to modify your deserialization code to use the new DynamicJsonDocument instead of the old DynamicJsonBuffer:

if (httpCode == 200) {
  // Parsing
  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 50;
  DynamicJsonDocument jsonDocument(bufferSize);
  DeserializationError error = deserializeJson(jsonDocument, http.getString());
  if (error) {
    Serial.println("There was an error while deserializing");
  }
  else {
    JsonObject root = jsonDocument.as<JsonObject>();
    // Parameters
    int Mode = root["mode"]; // 1
    Serial.print("Name:");
    Serial.println(Mode);
  }
}

You can get more details about this here:

https://arduinojson.org/v6/doc/upgrade/


Posting Arduino data via ethernet to PHP server problems I am currently having difficulties sending data from an Arduino using an ethernet shield to a PHP database in MySQL. My problem is that it appears that the server is receiving the data as there is a time stamp when I send it from the Arduino however, the other values it is receiving are incorrect (see images below). The server says the values of "data", and "serial_number" are 0 but they are supposed to be 10 and 24. Along with that the Arduino is saying that the data has been sent successfully. My code for both the server and the Arduino is listed below. Any ideas on how to fix this or what is going on are much appreciated.

Arduino Code:

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

byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
EthernetClient client;
String data;
int t;
int h;

void setup() {
  Serial.begin(9600);
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  Serial.println("still working here");

}

void loop() {
t = 10;
h = 24;

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

  if (client.connect("www.smartwater.x10host.com",80)) {
    Serial.println(data);
    client.print("POST /add.php HTTP/1.1\n");
    client.print("Host: www.smartwater.x10host.com\n");
    client.print("Connection: close\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(data.length());
    client.print("\n\n");
    client.print(data);
    Serial.println("Successfull");

  }

  if (client.connected()) {
    client.stop();
  }

  delay(20000);
}

add.php (Server Code)

<?php
    include("connect.php");

    $link=Connection();

    $temp1=$_POST["data"];
    $hum1=$_POST["serial_number"];

    $query = "INSERT INTO `Main` (`data`, `serial_number`)
        VALUES ('".$temp1."','".$hum1."')";

    mysql_query($query,$link);
    mysql_close($link);

    header("Location: index.php");
?>

connect.php (Server Code)

<?php

    function Connection(){
        $server="localhost";
        $user="smartwat_arduino";
        $pass="*****";
        $db="smartwat_Main";

        $connection = mysql_connect($server, $user, $pass);

        if (!$connection) {
            die('MySQL ERROR: ' . mysql_error());
        }

        mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

        return $connection;
    }
?>

index.php (Server Code)

<?php

    include("connect.php");

    $link=Connection();

    $result=mysql_query("SELECT * FROM `Main` ORDER BY `timeStamp` DESC",$link);
?>

      <title>Data</title>

Stuff

            &nbsp;Timestamp&nbsp;
            &nbsp;Data&nbsp;
            &nbsp;Serial Number&nbsp;

      <?php
          if($result!==FALSE){
             while($row = mysql_fetch_array($result)) {
                printf("
 &nbsp;%s 	 &nbsp;%s&nbsp; 	 &nbsp;%s&nbsp;
",
                   $row["timeStamp"], $row["data"], $row["serial_number"]);
             }
             mysql_free_result($result);
             mysql_close();
          }
      ?>

In your Arduino code, the function call that send the real data within the HTTP-POST call, is this:

[...]
client.print(data);
[...]

When executed, the content of the data variable is sent to the server.

Supposing data is a String object then data.concat() is this function, allowing "... String, string, char, byte, int, unsigned int, long, unsigned long, float, double..." as argument.

So, after the execution, data should contain:

temp1=10&hum1=24

and such content is exactly what is passed, via POST to the /add.php script.

Basically, you're passing two variables, called "temp1" and "hum1". Please keep note of those variable names!

Now let's switch the the PHP script, where you have:

[...]
$temp1=$_POST["data"];
$hum1=$_POST["serial_number"];
[...]

Above two statements, asks PHP to retrieve, via the $_POST function, the content of the two variables data and serial_number.

As such variables are undefined (the variables you passed were temp1 and hum1), PHP consider them like 0 and, as such, assign 0 to $temp1 and $hum1.

I bet that to solve your problem you only need to change above PHP with:

[...]
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
[...]

BTW: please note that what is inside the $_POST call is totally unrelated with the names of the variables you have on the left of the = sign: they are really different things!


ESP8266 Send data to Firebase using Arduino Uno error Good day everyone! I have a project, in which the data from a button (number of clicks) will be sent to a real-time Firebase database. Every time the button is clicked the counter increases and will be updated in the firebase database.

Wifi Module:
Esp8266 Esp-01 + Esp-01 Adapter

In my understanding, there are 2 ways to use this wifi module.

Upload the code to the Arduino Uno and use AT commands in the module to send data to the web.
Upload the code inside the WiFi Module itself and after that it can be a standalone SOC and does not need the Arduino anymore after the code has been uploaded.

I have tried the second way, but I got confused and stuck. So far I have successfully plugged the adapter in a breadboard and tested some AT commands.

Since I will be using the second way I won't be using these. So I tried this code:

 #include <ESP8266WiFi.h>
 #include <FirebaseArduino.h>

 #define FIREBASE_HOST "https://duck-917ba.firebaseio.com/"
 #define FIREBASE_AUTH "r3jNQCsxN2Y2dcfawimRlzjLjdBSXLjstwGeyB0oMK"

 #define WIFI_SSID "mywifi"
 #define WIFI_PASSWORD "621533515"

const int  buttonPin = 8;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setInt("clicks",0);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
      Firebase.setInt("clicks", buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(100);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;
}

So I have plugged my 4-pin adapter to the following:

ARD(TX)-ADAPTER(TX)
ARD(RX)-ADAPTER(RX)
ARD(5V)-ADAPTER(VCC)
ARD(GND)-ADAPTER(GND)

I have set the Generic ESP8266 Module Board.

Problems Encountered:

I am supposed to select the port of the ESP8266 but I only see the Arduino UNO port in the port list. When I compile the code I get this error:

I am now confused on what the error is all about. I thought since I am using an adapter I can use the PROGRAMMING MODE of the module easily. But it seems like my adapter is not doing its job. According to some of my research I have to use  TTL or FTDI USB-to-serial dedicated module / Ground some wires while compiling which is very confusing for a beginner like me.

So here are my final thoughts:

Can I input/flash code in my module using my Arduino and adapter?
Since the button is plugged in the Arduino's pin 8, does that mean that the code in the module will be successfully inserted? I will still need the Arduino to be plugged in the buttons?
What could be the reason why the module won't appear in the Port List and generates the errors?

I know this is quite a long and boring topic but I know a lot of aspiring IOT developers out there are having the same issues about this wifi module. I hope we can solve it together. Thanks!

1.) Can I input/flash code in my module using my arduino and adapter?

Yes

  2.) Since the button is plugged in the pin 8 of arduino. Does that mean If the code in the module will be successfully inserted. I will still need the arduino to be plugged in the buttons?

The ESP8266 cannot magically know about the Arduino and the Arduino cannot magically know about the buttons. If you have buttons connected to the Arduino then the Arduino needs telling about them. If the Arduino and ESP8266 need to work together then they both need programming to work together. If, and only if, you connect the buttons to the ESP8266 and not the Arduino do you not need the Arduino.

  3.) What could be the reason why the module won't appear in the Port List and generates the errors?

The Arduino is getting in the way. Connect Arduino RESET to Arduino GND to disable the ATMega328p chip which is also trying to use TX and RX and conflicting with the ESP8266. Or better still get a cheap USB to UART cable (just a couple of dollars on eBay) and connect the adaptor direct to your PC without the Arduino.


Advice needed, commercializing an Arduino Due project We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!

There's two routes you can take.

First route:

Get the Due schematics.
Remove the parts you don't need.
Add to it the new components for your product.
Lay out the PCB design.
Get the PCB manufactured.
Solder all the components on.
Test it and go back to step 2/3 as required.

Second route:

Hire a contractor that knows the SAM3X and can do it all for you.


16 bit PWM on a mega I have two Arduinos, a nano and a mega. I want to output 16 bit PWM, but can seem to only get it working on the nano. I'm adapting the code from this website: http://www.ofrecordings.com/2014/03/16/how-to-set-up-16-bit-pwm-with-an-arduino-uno-atmega328/

void setup() {
  // Set PB1/2 as outputs.
  DDRB |= (1 << DDB1) | (1 << DDB2);

  TCCR1A =
      (1 << COM1A1) | (1 << COM1B1) |
      // Fast PWM mode.
      (1 << WGM11);
  TCCR1B =
      // Fast PWM mode.
      (1 << WGM12) | (1 << WGM13) |
      // No clock prescaling (fastest possible
      // freq).
      (1 << CS10);
  OCR1A = 0;
  // Set the counter value that corresponds to
  // full duty cycle. For 15-bit PWM use
  // 0x7fff, etc. A lower value for ICR1 will
  // allow a faster PWM frequency.
  ICR1 = 0xffff;
}

void loop() {
  // Use OCR1A and OCR1B to control the PWM
  // duty cycle. Duty cycle = OCR1A / ICR1.
  // OCR1A controls PWM on pin 9 (PORTB1).
  // OCR1B controls PWM on pin 10 (PORTB2).
  OCR1A = 0x0000;
  delay(500);
  OCR1A = 0x8000;
  delay(500);
  OCR1A = 0xffff;
  delay(500);
}

That code works on the nano, but not on the mega. I expect that it output PWM on pins 11 and 12, but no luck. Care to explain how I can get it working? It's an entirely different microprocessor, and I'm not sure which parts of the code to change.

Change first line:

    // Set PB1/2 as outputs.
    DDRB |= (1 << DDB1) | (1 << DDB2);`

to the

     // Set PB5/6 as outputs. [**Digital pin 11,12 on Arduino Mega!**]
    DDRB |= (1 << DDB5) | (1 << DDB6);

Now your PWM should work, but on digital pins 11 & 12 [Arduino Mega].


Is this LED Strip Schematic correct? I am trying to simulate a 12V LED strip as per this tutorial. However the schematic I tried to make on EasyEDA looks quite different from the images on the website. I wanted to know if what I did is correct.

Schematic and wiring diagram are not the same. They seem to use different RGB LEDs. The wiring diagram has common anode RGB LEDs, while your schematic uses a common cathode RGB LED. The difference is, which side of the LED gets switched.
In the common anode configuration, all anodes (positive lead) of the individual color LEDs are connected together, while the cathodes (negative leads) are brought out, so that you can switch them via the MOSFETs. That means, that the MOSTFETs are connected between the strips color component pins and ground.
In the common cathode configuration, all cathodes (negative lead) of the individual color LEDs are connected together, while the anodes (positive leads) are brought out for you to switch them. In this case, the MOSFETs are connected between the strips color component pins and Vcc.

Besides that, you should be careful with providing 12V at Vin of an Arduino Uno. While it is possible, you can very fast get the linear voltage regulator to overheat, when providing 12V. It dissipates the excess voltage (so 7V, to get it to 5V down) as heat. The voltage regulator is not cooled, so you might run into this issue, with the wiring diagram. It depends on your much current you draw from the regulator.


What would cause a delay when using serial between the Arduino IDE & external clients? I have been working on a problem for a couple of days that I can't figure out.

I am using a Teensy3.6 with Arduino IDE to build a CAN Bus monitor for a car. For those familiar, I am trying to save the data in the format of can-utils so it can be easily replayed on Linux machines. The board uses the FlexCAN library to facilitate communication.

Everything works well using the Arduino Serial Monitor. However, I want to save the output to a host computer. Unfortunately, I've not been able to get any other serial programs to work. I have tried PuTTY & Python via PySerial. The output seems to get interrupted & doesn't print on a new line correctly.

Sample Output from Arduino Serial Monitor:

(1302.864746) can0 1C5#2C032C032E01
(1302.864868) can0 1F4#000000000000
(1302.865356) can0 287#0000
(1302.865601) can0 F1#340000400000
(1302.865845) can0 96#BFF00A120000
(1302.866455) can0 97#35800A1518300A0A
(1302.866821) can0 98#00000A0080000A13
(1302.867065) can0 1E5#4400335000000103
(1302.867554) can0 C7#00000000
(1302.867798) can0 1E9#FF8300EFFC0000
(1302.868042) can0 232#0000000000000000
(1302.868652) can0 1E1#00000000001CC0
(1302.868896) can0 2F9#83000000000007
(1302.869019) can0 222#001607AD0C00
(1302.869629) can0 BC#A11E005C00000000
(1302.869751) can0 D3#2C02
(1302.869995) can0 186#44005D0000017C
(1302.870483) can0 224#CBC8C8
(1302.870605) can0 228#005B5F5B
(1302.870850) can0 1F3#80BC00
(1302.871460) can0 B9#000A800002000000

Output from PuTTY/PySerial:

(1443.927002) can0 C1#10026B0210037D86
(1443.927246) can0 C5#10026B0310026B02
(1443.927490) can0 D1#40007FFF00FF00
(1443.927856) can0 1EB#0241(1444.011230) can0 AA#2C032C030253FC00
(1444.011597) can0 C9#8000002000101800
(1444.012085) can0 1E7#019000000000316D
(1444.012329) can0 1ED#019000000000316D
(1444.012451) can0 34A#000000001B
(1444.012939) can0 1EF#00000000

My naive opinion is it seems the CAN data comes faster than the serial is writing. However, it's odd that it works fine in the Arduino IDE. It happens about 1x/second--which is well enough to cause a headache.

Outside of SD cards or writing locally--does anyone know why this might happen? Or how I could save this data to a host computer? Worst case I can copy/paste the output from the Arduino Serial Monitor, but that isn't very elegant.

Thank you!

Edit: Here is some relevant code from my Arduino IDE. I modified the object oriented can example from flexcan to print in my desired format.

#include <FlexCAN.h>
static CAN_message_t msg;
elapsedMicros sinceStart;

class CANHandler : public CANListener{
  void printFrame(CAN_message_t &frame);
  void gotFrame(CAN_message_t &frame, int mailbox); //overrides the parent version so we can actually do something
};

void CANHandler::printFrame(CAN_message_t &frame){
   Serial.print("("); Serial.print(sinceStart / 1000.0 / 1000.0, 6);
   Serial.print(") "); //cast to 6 decimals to make compatible with can-utils
   Serial.print("can0 "); // to identify a CAN channel for can-utils
   Serial.print(frame.id, HEX);
   Serial.print("#");
   for ( uint8_t i = 0; i < frame.len; i++ ) {
     if(frame.buf[i] < 15){
        Serial.print("0"); Serial.print(frame.buf[i], HEX);
     } else {
        Serial.print(frame.buf[i], HEX);
     }
 }
 Serial.println();
}

void CANHandler::gotFrame(CAN_message_t &frame, int mailbox){
printFrame(frame);
}

CANHandler canHandler;

void setup() {
    Serial.begin(115200);
    Can0.begin(500000);
    Can0.attachObj(&canHandler);
    CanHandler.attachGeneralHandler();
}

void loop() {
//run until exit
}

If your data input rate is higher than, or even close to, your serial output rate (baudRate/10 char/s), your system will be unable to keep up.

With an interrupt driven system, make sure your interrupt function executes and returns as quickly as possible, i.e., does as little as needed to not lose data. Let the background process (the main sketch code) deal with the incoming data as it appears. Make sure the both processes are short enough to deal with the worst-case input-data bursts without losing any. For the background process, use as high a baud rate as it is capable of - and as it's downstream neighbor (Storage device? Another MCU or PC?) is capable of - keeping up with.


Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP For the XP under the Russian locale I'm getting the strange output when trying to compile Marlin project for Anycoubic 3d printer according to instruction https://3dtoday.ru/blogs/trialon/marlin119-for-anycubic-kossel-linear-plus

avr-g++: error: C:\DOCUME~1\ИЖИ: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\sketch\Marlin.ino.cpp: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\preproc\ctags_target_for_gcc_minus_e.cpp: No such file or directory

avr-g++: warning: '-x c++' after last input file has no effect

avr-g++: fatal error: no input files

compilation terminated.

exit status 1
Ошибка компиляции для платы Arduino/Genuino Mega or Mega 2560.

I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped


Making Laser Tripwire with Phone Messaging I am looking at Arduino and Raspberry Pi and I want to do a pretty advanced project.  I want to make a laser triggered security project that sends a message to either a android or iPhone. First I don't know what exact hardware I need. I have a photo-resister and a laser.  However, I don't know what hardware to buy and how to connect to my phone. I've looked at http://www.smartliving.io/kits.  I also don't know how the messaging would work. Is there already a Arduino and or Raspberry Pi library/hardware for this or would I have to get the data on the Internet and using something like the Twilio API? would Arduino or Raspberry Pi be easier?

As with any project, where you don't know where to start or what to use, there are a number of steps you should go through.

First define exactly how you want your system to work.  There are many many different ways of achieving what you talk about in your question, and most (if not all) of them can be performed using an Arduino of some form with extra hardware to do specific jobs.

Only when you have defined such things as:

What distance must your trip wire be effective over
How long will it be interrupted for typically
Will it be a permanent installation or a mobile battery operated system
What kind of messaging do you want on the phone
Must the message be receivable anywhere on the planet or just within a certain range of the tripwire system

For instance, for the communication, would you want to send a text message via the mobile phone network (SMS), or an email through the internet, or connect to a custom app using Bluetooth, etc., - there are a myriad of different possibilities.

Once you know exactly what you want it's then time to break the project down into little blocks.  Each block can then be tackled separately and you can research what is available to help you perform that specific task within the bounds of what you have specified in your requirements list.

Each of the blocks of your project are quite simple to create and there are generally examples and tutorials for most things on the web that can help you.


Is i2C more or less robust than GPIO? Currently using i2C to connect a RPi with an arduino. It seems i2C is quite finicky and, drops the bus immediately if there are any IO errors. Since what i am building is meant to be semi permanent, I am worried that i2C may not be the best choice.

Has anyone done any real world testing of i2C vs GPIO for RPi to arduino communication?

Here are a few things to remember:

You should have a ground connection between the RPi and Arduino
I2C was meant for really short distances on a printed circuit board
Arduino runs at 5 Volt logic levels and RPi at 3.3 Volt logic levels - you need a level translator between them to make that work.

If the RPi and the Arduino are not far apart, I would say less than 1 foot (30 cm) and you have the grounds connected between the boards, then it is a software issue. I2C is meant for short distances any anything longer than a foot puts too much capaitance on the wires and starts causing unreliable communication. I would not even use it for more than a few inches unless it was on a circuit board where you control the capacitance.

I am assuming your using the Wire library on the Arduino side. On the RPi side I would use the the Adafruit I2C library for the RPi as I have had success using the library to communicate with I2C sensors listed on their site. Here is the link:

Adafruit RPi I2C Tutorial


Soil moisture sensor not working in "pcb" I have a little and common application in which a sc-28 moisture sensor reads humidity levels and turns a servo (which drives a little faucet) if the soil needs water. Arduino nano is the brain.

All of them is tested and working fine on the proto board. Soil sensor is powered by 5v rail of arduino and everything seems fine even with the servo pulling from 5v rail too.

With all working, I try to translate that to a perfboard. The only difference in circuits are how they are powered.

While the prototype is powered via usb, the definitive one is powered through a 24v psu, leveling the voltage with a lm2596 module down to 5v.

Then this 5v feeds the nano (vin pin) and servo, while the soil sensor still pulls from 5v rail of the arduino to avoid vref problems.

And then, the sensor does not work. No led indicating power or data. This were my steps trying to debug it:

Triple check every connection on the board. While I am a decent programmer, my solder skills are kind of lacking. But everything looks fine, nothing shorted or loose.
measure voltage. On the perfboard, voltage between vcc and gnd connector pins spits 4.78v, which is supposed to be in range for the sensor to work.
Power the board through usb I tried this too, and is not working. Lm module and arduino lights up, code can be executed. I can't explain why the lm2596 module lights up too, and I'm thinking is part of the problem but I do not know. Voltage at soil sensor is still 4.78

And then I'm done. I dont know what could be happening and I only can make wild guesses. It's obviously a board problem, and i am aware I am doing something wrong but I can't see it.

Below, my horror soldering skills and the board. Soil sensor is the 4pin females at the bottom left and servo the 3pin males at the bottom right.

The answer was, in fact, my poor experience with these boards and how they work.

As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.

Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.


Convert Arduino Pro Mini 5v to use 3.3v Id like to make my 5v pro mini use 3.3 v instead of 5 because i want to use it in an existing piece of electronics that uses 3v throughout.

Looking at the specs for the pro mini it says the 3.3v version can accept higher voltages.

So is there a regulator i can bypass/bridge that will convert my 5v version to a 3.3v version? or am i wasting my time?

I have good news, and I have bad news.

The good news is that only two changes to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.

The bad news is that there's no way in hell you'll be able to do them.

So, we work around them and get the board up and running.

The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.

The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in avr/power.h in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.

As always, see the datasheet.


Why ATMEGA328P U-TH doesn't answer to USBasp but work fine with Arduino as ISP? I ordered ATMEGA328P AU from China recent but I got "ATMEGA328P U-TH". which seem super problematic.
I try to use USBasp to burn bootloader but it fail and show error message as shown.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

which I believed many people face same situation as mine. Then I accidentally found the solution by using Arduino as ISP which successfully birn bootloader. After that I can use USBasp to upload sketch or burn bootloader.  I don't understand what happen here.
Note: I solder ATMEGA328P U-TH in SMD package to Arduino UNO clone.

If you want to upload a sketch via any other interface than ISP, the atmega needs a bootloader.
The bootloader basically is a piece of software which is stored in a dedicated flash section, the "bootloader section". Code stored in this bootloader section has the special ability to write to parts of flash memory where the actual program is stored (this is called the "application section").
In general, a program can not overwrite its own flash section, so the bootloader and the application need to be stored in different sections/partitions.
In principle, a bootloader can do whatever a normal sketch could do: toggle pins, access eeprom, read UART/I2C/etc... and as it can also write to the "application section", you can make it read data from any interface and transfer it to the application section.
This is what happens if you upload code via USBasp (Arduinos have a USB-to-UART converter on board).
But of course, this requires that a bootloader is installed.
avrdude: error: program enable: target doesn't answer. 1 - this might sound misleading, what it actually means is, that the bootloader doesn't answer. That makes sense, as the device doesn't have a bootloader.
When there is no bootloader, the only way to upload code is to use ISP, which doesn't need any software to function. It's a hardware functionality that Atmel implements in silicon.
A code upload via ISP works in (almost) any case.