text:
ESP8266 to send data to thingspeak while doing unblocked read on Serial.readString()
I have a requirement to get RFID data on Arduido UNO and send it to ESP8266 to be sent to ThingSpeak via the Wifi module. However, ESP8266 is also programmed to send Temperature and humidity data to ThingSpeak and turn on a motor when temperature exceeds certain threshold.
I have followed this logic on ESP8266 loop
if(millis() > time_now + period)
  {
    read temperature, humidity from DHT sensor
    Send only temp,humidity to ThingSpeak
  }
  // Outside millis()
  while (Serial.available())
  {
    Serial.readString() - to retrieve the User name sent by Arduino UNO
    Send only temp,humidity and UserId=1 to ThingSpeak
  }

However the whileloop is not executed as expected and is random. Since millis() is unblocked, my understanding is that while it is waiting and if there is data available on Serial, While loop is to be executed.
However, the readString() is not executed everytime data is available on Serial.
Full code on ESP8266 is below.
Any help is to identify the issue is much appreciated.
#include <DHT.h>
#include <DHT_U.h>
#include <Stepper.h>

#define DHTPIN 3  // what pin we're connected to D4
#define DHTTYPE DHT11  // DHT 11  (AM2302)
/*
ULN2003 --- ESP-12F(WeMos D1 mini)
  ========   =======================
  IN1 >> GPIO 14 (D5)
  IN2 >> GPIO 12 (D6)
  IN3 >> GPIO 13 (D7)
  IN4 >> GPIO 15 (D8)
  VCC(+) >> ... 5V Prefer to use external 5V Source
  Gnd(-) >> GND (G)
 */
#define IN1  14 // GPIO 14
#define IN2  12 // GPIO 12
#define IN3  13 // GPIO 13
#define IN4  15 // GPIO 15

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>

String apiKey = "API_KEY";     //  Enter your Write API key from ThingSpeak
const char *ssid =  "WIFI_SSID";     // replace with your wifi ssid and wpa2 key
const char *pass =  "WIFI_PWD";
const char* server = "api.thingspeak.com";
int uid =1;
//Variables to store temperature and humidity
float hum = 70.2;  //Stores humidity value
float temp = 20.0; //Stores temperature value
//Variable to store User Name
String name =" ";
int period = 1000; // delay period
unsigned long time_now = 0;

DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor for normal 16mhz Arduino
WiFiClient client;
const int stepsPerRevolution = 512;  // change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 14, 13, 12, 15); // initialize the stepper library on pins 8 through 11:
SoftwareSerial s(D3,D2);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
  s.begin(9600);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  dht.begin();
  temp=dht.readTemperature();
  hum=dht.readHumidity();

  Serial.begin(9600);
  delay(10);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

      while (WiFi.status() != WL_CONNECTED)
     {
            delay(100);
            Serial.print("*");
     }
      Serial.println("");
      Serial.println("***WiFi connected***");

}

void loop() {
  // Read temperature, humidity values from DHT sensor at constant intervals
  if(millis() > time_now + period){
        time_now = millis();
        //Read temp reading
        temp=dht.readTemperature();
        hum=dht.readHumidity();
        displayData( hum, temp);
        // Turn on motor to ON the fan when temperature exceeds 23
      if(temp > 23)
      {
        myStepper.step(stepsPerRevolution);
      }
      Serial.println("Sending only temp and hum data");
      //Send temp, humudity data to ThingSpeak
      String paramater2 = apiKey+"&field1="+String(temp)+"&field2="+String(hum)+"\r\n\r\n\r\n";
      sendToThingSpeak(paramater2);
   } //End of delay

   //Check if serial input available which is the User Id string sent by Arduino UNO on SoftwareSerial port
   if(s.available())
   {
    Serial.println("In ESP sketch.. Serial Available. Reading.....");
    //Read UID And store into String name
    name = s.readString(); //This works
    //Print name onto Serial monitor
    Serial.println(name); //This works
    //if UID available, send Temp, Humidity and Uid=1 to thingspeak
    String parameter1 = apiKey+"&field1="+String(temp)+"&field2="+String(hum)+"&field3="+String(uid)+"\r\n\r\n\r\n";
    Serial.println("Sending temp, hum and uid data");
    sendToThingSpeak(parameter1);
    Serial.println("Sending....");
   }

}

void displayData(float humidity, float temperature)
  {
    //delay(1000);
    //print to serial monitor
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.print(" %, Temp: ");
    Serial.print(temperature);
    Serial.println(" Celsius");
  }

  void sendToThingSpeak(String sendData)
  {
    if (client.connect(server,80))   //   "184.106.153.149" or api.thingspeak.com
      {
       Serial.println("Inside Send to thingspeak - Data Received");
       Serial.println(sendData);

       client.print("POST /update HTTP/1.1\n");
       client.print("Host: api.thingspeak.com\n");
       client.print("Connection: close\n");
       client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
       client.print("Content-Type: application/x-www-form-urlencoded\n");
       client.print("Content-Length: ");
       client.print(sendData.length());
       client.print("\n\n");
       client.print(sendData);

       Serial.print("Temperature: ");
       Serial.print(temp);
       Serial.print("deg C. Humidity: ");
       Serial.print(hum);
       Serial.println(".. Connecting to Thingspeak.");
              }
       client.stop();
  }

please use the {} function to make your code readable

Thank you Jarmanda. I have formatted the code now.

what about the I have followed this logic

what is D2 and D3? to which io pin does it map? on NodeMcu D3 is io 0 and has external pull-up. if could disturb SoftwareSerial. which version of the esp8266 core you use? 2.4.2 or 2.5 beta?

D3=GPIO0, D2=GPIO4 and they are connected to pin 2,3 of Arduino UNO. I am using esp8266 2.4.1

try the 2.5 beta. 2.4.x had problems with SoftwareSerial


text:
millis() not working properly
I'm doing a little project that, on a press of a button, will light up three LEDs and then will turn off the LEDs in different times. I'm using the millis() function to control the time that each LED will be on.
On the first time that I press the button, everything works fine. But the problem starts when I press the button for the second time.
If I press the button soon after the loop ends, something goes wrong and the behavior of the LED become a mess (just one or two LEDs light up in weird times). But, if I wait about 2 seconds before pressing the button for the second time, everything goes right.
Here's my code:
const int ledPin1 =  11;
  const int ledPin2 =  12;
  const int ledPin3 =  13;
  const int buttonPin = 2;

  int buttonState = 0;
  long previousMillis1 = 0;
  long previousMillis2 = 0;
  long previousMillis3 = 0;

  int state = 0;

  void setup()
  {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin, INPUT);

    Serial.begin(9600);
  }

  void loop()
  {

       buttonState = digitalRead(buttonPin);

       if (buttonState == HIGH) {
        state = 1;
       }

       if (state == 1)
       {
        taskExecute(3000, 2000, 4000);
       }
  }

  void taskExecute(int tMotor1, int tMotor2, int tMotor3)
  {

    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    do
    {
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis1 > tMotor1)
      {
        previousMillis1 = currentMillis;

        if (ledState1 == HIGH)
          ledState1 = LOW;

        digitalWrite(ledPin1, ledState1);
      }

      if(currentMillis - previousMillis2 > tMotor2)
      {
        previousMillis2 = currentMillis;

        if (ledState2 == HIGH)
          ledState2 = LOW;

        digitalWrite(ledPin2, ledState2);
      }

      if(currentMillis - previousMillis3 > tMotor3)
      {
        previousMillis3 = currentMillis;

        if (ledState3 == HIGH)
          ledState3 = LOW;

        digitalWrite(ledPin3, ledState3);
      }
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
  }

Other strange thing that happens is that sometimes the time that i've been set in millis for the led get on become a little different. Example: when I press the button, the LED 1 needs to light up for 3 seconds, but he lights up just 2.5 seconds.
What i'm doing wrong? Thanks!!

The variables previousMillis (1-3) are not properly initialised.  So if you wait a while before pressing the button, that delay time becomes part of the time that the LED is illuminated for.
If your taskExecute() function sets them before the loop, this will fix that:
void taskExecute(int tMotor1, int tMotor2, int tMotor3)
{
    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    unsigned long time_now = millis();
    previousMillis1 = time_now;
    previousMillis2 = time_now;
    previousMillis3 = time_now;

    do
    {
        ...
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
}

On a coding-style note - I did not initially see the resetting of the global variable state=0 at the end of the taskExecute() function.  It might be better to move this up to underneath the initial call to taskExecute() so all the state handling is in one place.

Perfect!!! The problem has gone! Thank you so much for the help! :)

source: Stack Exchange

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

sort: votes


text:
Does a moisture sensor need warm-up time?
I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)
The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with digitalWrite(moisture_vcc, HIGH).
To problem is that the values were too high.
So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?
Any experience with it?

Do you have a part nr or something?

It's a YL-69 sensor.

There is a very good analysis of the YL-69 sensor on :  http://electronics.stackexchange.com/questions/105549/is-my-moisture-sensor-yl-69-broken

Another analysis is  :  http://electronics.stackexchange.com/questions/90725/arduino-moisture-sensor-value-decreasing-for-no-reason

@Marla thanks. The last post was a bit helpful:

When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again.

@Marla can you post an answer with at least the basic summary of that link, so OP can mark the question as answered?

Photograph of the YL-69 Sensor  :

Most of this content was generated by :  Conner Wolf
Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.
However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).
The other pin is likely to have accumulation of materials rather than being eaten away.
This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).
If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.
Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.

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


text:
21 Servo on Mega?
I want to use 21 servo (SG5010) motors using Mega board. Is it possible to do this?
A possibility is all the servos will be operating at the same time, with average load of ~3.5 KG, and each using 1A, so 21 servos will use 21A.
Will be able to supply power? If yes then how do I go about it?

There is a servo/sensor shield for the Arduino Mega that can control up to 54 servos. This shield will only fit the Mega, unlike the usual 14 servo Arduino shield, which is shaped to fit most Arduino boards.

Here is an easier to view diagram:

It is possible, and advisable, to supply power via the screw terminals from an external power source, rather than use the Arduino's own power. Even just one servo can have difficulty in working from the Arduino's on board power supply, especially if just using USB to power the Arduino. However, even with the use of an external power source powering the shield, I have my doubts as to whether the shield could support 21A without burning out. Someone may be able to clarify this.
You may find this page, Servo Shield, useful:

MEGA Sensor Shield
The Arduino MEGA has many more I/O pins (54 Digital pins and 16 Analog
  pins)than a standard Arduino. This shield also has connectors
  specifically for some external devices like an SD Card, Radio
  communications (Bluetooth and others). It also has an option to power
  the "V" pins on all the Digital I/O 3-pin groups from an external
  power supply instead of the Arduino +5V. This is good for large
  numbers of servos etc. The "Analog" 3-pin groups still use the Arduino
  +5V which is better from an electrical noise perspective.
This version has two options of +5V supply to all the "V" pins:

Jumper on: +5 comes
  from the Arduino. Should be limited to about 300 ma
Jumper off: +5 (or
  other appropriate voltage) comes from an external supply connected to
  the blue terminal strip. External power Ground must also be connected
  to the blue terminal strip.

Using an external supply allows more current than the Arduino or Mega
  can supply, such as current for control of many servos or relays, and
  other attached devices. Usually this is +5V because most external
  devices require it. It is possible to use +6 volts if ALL the attached
  devices are the same such as Servos with that rating.

The Mega board will not be able to supply that much current, no. If you consult the schematic, you will see that the 5V regulator is rated for a maximum current of 800mA.
A computer PSU would be an appropriate power supply (a typical 350W PSU will happily supply >30A on the 5V rail). Be aware that some PSUs have a minimum load; you may need to add a power resistor or other load.
Also note that if you want individual control of all the servos, the ATmega1280 only has 16 PWM outputs (IIRC), so you would need software PWM or an external PWM IC.

As for the power supply, I agree with you. But I really hope the OP wasn't thinking of attaching them to the arduino power supply, was he? As for the PWM, the serial library should not use the PWM pins (I'm not really sure about it). Anyway, they explicitely say here that The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega.

frarugi87: I was thinking in terms of timers on the m1280 (although the Mega only has 15 "official" PWM outputs, I think), but yes, the Servo library provides software PWM and can handle up to 48 servos.

Yes, also because using the hardware PWM is inefficient in this case (the default PWM resolution is 8bit and the servos require a signal between 1 and 2ms every 20ms, so you would end up with a servo using only values between 12 and 24 for the positioning (and so you would be able to set a servo position to just 12 discrete positions)


text:
Changing type of one variable dramatically changes compile size
I have a sketch containing the following method:
// Writes zeros to the complete screen clearing it:
void clearScreen(uint8_t val) {
  setDrawArea(0x00, 0x7f, 0x00, 0x07); // complete screen
  SSD1306.ssd1306_send_data_start();
  for (int c = 0; c < 128 * 8; c++) {
    SSD1306.ssd1306_send_byte(val);
  }
  SSD1306.ssd1306_send_data_stop();
}

The whole sketch compiles with a size of 6730 Bytes. While refactoring the code I mistakenly changed "c" to uint8_t. After this I compiled to 4124 Bytes. Does this come from the compiler recognizing that the loop condition will never be reached and cut off all code behind or is this some kind of strange optimization event? I'm asking because I can't test the sketch in the moment.

Can you confirm this behavior without code from extra libraries? This might just be an optimization with the library (maybe as simple as that another function is called for uint_8, which uses less space)

this expression: c < 128 * 8; results in the uint_8 variable 'c' to be overflowed. The result is undefined behavior.  With undefined behavior, anything can happen

@user3629249: No. Overflowing a uint8_t is perfectly safe and well defined. It just rolls over modulo 256. Only the signed integer overflows are undefined behavior.

@user3629249, even if c were signed, making the overflow an issue, that comparison doesn't cause an overflow, the increment c++ might.

Without being able to proof it (since I don't have your libraries and you gave only a small part of the sketch), I think this is what happens:
user3629249 is half right. If you change c to type uint8_t it only has 8 bits (hence the Name), so its maximum value will be 255. When you add 1 to it at this value, the variable will overflow and going back to 0. Thats normal overflow behavior, like used with the Arduinos Timer registers. (No undefined behavior there) So the maximum value c can reach is 255.
When compared to a bigger literal the value of c gets promoted to the correct type, so that the two values can be compared. But a variable that is at maximum 255 is always lower than 128*8. So you have an infinite loop there. The compiler can see this and doesn't include the functions from the rest of clearScreen(), since that is unreachable code.
All in all your code won't work as intended with uint8_t. You need a bigger type, that can hold the full range, that you operate. And this optimization is not strange, but very reasonable, since you really don't need the rest of clearScreen() in that case.

Note that any code that follows a call to clearScreen() is also unreachable. The compiler may be removing a lot more than ssd1306_send_data_stop().

Does the compiler covert the 1288 to a 8-bit value too? 1288=1024; which is 0 when converted/truncated to a byte. Since it’s zero the for loop will never be executed, so ssd1306_send_byte is never called. The compiler knows this at compile time, so it can remove the for loop. And if the send_byte function isn’t called anywhere else it can remove the entire function, drastically reducing the size.

@Gerben, If I'm not mistaken, all operations promote the operands to at least int, and in any case, an unadorned constant is an int, so it's 1024 and c is promoted to match. It's just uint8_t that can never reach such a value, so the condition is always true.

That fits my thoughts - it seems I underestimated the compiler. There's a good part of code behind this method call and I'm quite sure the compiler understands that the "for" condition will never be false and cuts off everything behind. I'm afraid I got comfortable in the higher languages expecting some kind of compiler warning in such a case. Good thoughts about the conversion issue by the way.

@needfulthing: Re “expecting some kind of compiler warning”: The compiler does warn you that “comparison is always true due to limited range of data type”, but only if you set “Compiler warnings” to “All” in the IDE preferences. There is an open issue requesting this to be the default, but the Arduino folks resist, as they are afraid the warnings may “scare newcomers”.

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


text:
Adding data to an SD card file
I'm reading data from the Shinyei PPD42 particle sensor unit.
Everything seems to work, but I'm encountering two problems

When I restart Arduino, the file is not being extended, nor overwritten. It just remains how it was before.
Even though my code looks fine, Arduino stops writing data to the SD card after 90 seconds.

Thanks for having a look at my code.
#include <SPI.h>  //een bibliotheek aan code toevoegen; Arduino heeft deze nodig om de Shield te kunnen 'lezen'
#include <SD.h>   //zie hierboven

int PM=8; //de fijnstofmeter zit in digitaal poortnummer 8

const int chipSelect = 10; //const = een variabele die nooit verandert

unsigned long sampletime_ms = 30000;  //unsigned long = een variabele die erg hoog kan oplopen, maar nooit negatief kan zijn

//hieronder volgen nog enkele variabelen. Denk eraan: float betekent dat het decimale getallen kunnen zijn

unsigned long duration;
unsigned long starttime;
unsigned long lowpulseoccupancy = 0;
unsigned long timediff;
float ratio = 0;
float concentration = 0;
unsigned long tijd = 30;

//void setup wordt één keer uitgevoerd, bij het opstarten van de Arduino-minicomputer

void setup()
  {
    Serial.begin(9600); //de snelheid (in bits/second) aan welke de seriële data zal worden getransfereerd
    pinMode(PM,INPUT);  /*PM is de variabele van helemaal bovenaan: pinMode vraagt twee parameters 1)de poort (werd gedefinieerd bovenaan) 2)INPUT of OUTPUT
                          Ditmaal leest de fijnstofmeter gegevens die we vervolgens IN onze Arduino willen importeren, dus INPUT*/

    starttime = millis(); //hoelang draait het programma? millis() geeft de duur sinds het werd opgestart

    Serial.println("SD-kaart opstarten indien aanwezig... "); //Je schrijft nu neer dat de SD-kaart wordt gezocht en opgestart (println = hierna op volgende regel verder gaan)

    //hieronder staat een 'als'-lus: als aan de eerste voorwaarde wordt voldaan, voert hij uit wat eronder staat, anders gaat Arduino verder achter de afsluitende accolade

    if (!SD.begin(chipSelect)) //Als er NIET (!) kan worden begonnen met de SD-kaart te selecteren ...
      {
        Serial.println("Corrupte of ontbrekende SD-kaart!"); //dan wordt deze boodschap getoond
        return;
      }
    //Als de SD-kaart dus WEL werkt, gaan we hieronder verder

    Serial.println("SD-kaart werkt...");
    Serial.print("Fijnstofsensor start op. Even geduld! Metingen om de 30 seconden.");
    Serial.println("\n");
  }

//void setup wordt oneindig lang uitgevoerd, tenzij je dat anders bepaalt

void loop ()
  {
    duration = pulseIn(PM, LOW); //als de fijnstofdetector niet meet (LOW), beginnen meten
    lowpulseoccupancy = lowpulseoccupancy+duration; //na elke meting de 'duration' (30 sec)  optellen bij de totale tijd

    if ((millis()-starttime) >= sampletime_ms)
      {
        //hieronder de wiskundige berekeningen om het fijnstofgehalte te berekenen

        ratio = lowpulseoccupancy/(sampletime_ms*10.0);
        concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;

        //hieronder alles wat zal worden geprint naar het seriële venster

        Serial.print("Fijnstofconcentratie na ");
        Serial.print(tijd);
        Serial.println(" seconden:");
        Serial.print(concentration);
        Serial.println(" deeltjes/0,01cf");
        Serial.print("\n");

        File dataFile = SD.open("test.txt", FILE_WRITE); //het bestand meting.txt moet op de SD-kaart worden geopend om erin te schrijven

        if (dataFile) //als het bestand kan worden geopend, volgende gegevens printen
          {
            dataFile.print("Fijnstofconcentratie na ");
            dataFile.print(tijd);
            dataFile.print(" seconden: ");
            //dataFile.println(ratio);
            dataFile.print(concentration);
            dataFile.print(" deeltjes/0,01cf");
            dataFile.print("\n");
            dataFile.close();
          }

        else //als het bestand niet kan worden geopend ...
          {
            Serial.println("Fout bij het openen van test.txt");
          }

        tijd = tijd + 30; //meting afgerond, totale tijd = +30 seconden
        lowpulseoccupancy = 0; //de status van de fijnstofmeter is terug 'LOW'
        starttime  = millis(); //volgende meting starten
      }
  }

Try to put your comments also in English (you never know when a non-Dutch person will read it ... like mostly here) ... succes!

You need to open the file in append mode:
SD.open("file.txt", O_RDWR | O_APPEND);

It depends on the file being there. If it fails to open because the file isn't there you can open it in "create" mode instead:
SD.open("file.txt", O_RDWR | O_CREAT);

For example:
// Try and append
File f = SD.open("file.txt", O_RDWR | O_APPEND);
if (!f) {
    // It failed, so try and make a new file.
    f = SD.open("file.txt", O_RDWR | O_CREAT);
    if (!f) {
        // It failed too, so give up.
        Serial.println("Failed to open file.txt");
    }
}

// Only write to the file if the file is actually open.
if (f) {
    f.print(/* your data here */)
    f.close();
}

Do I only add the second line instead of the SD.open line I had?

No. You need both. I'll expand to show you.

Thank you. Will this yield the same result? File dataFile = SD.open("test.txt", O_CREAT | O_APPEND | O_WRITE);

I don't think you can both create and append at the same time. You can give it a go though. Personally I like to be specific about these things so there is no chance for ambiguity.

Majenko, any idea what I did wrong here? Using your solutions since my adaptation doesn't work after all: https://pastebin.com/k4xbyBpR

You need the writing to the file to only happen once the file has been confirmed as open through whatever method. That is - Open for append, if failed, open for create. If succeeded then write. I'll modify my example.

Let us continue this discussion in chat.


text:
Why my light meter's values are blank on Arduino Serial Monitor?
I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down.
Here is the code:
uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
y = float(tsl.getLuminosity(TSL2591_VISIBLE));
z = (y, DEC);
Serial.write((byte)z);

x, y, and z are floats initially.

Did you enabled the serial communication on arduino by using Serial.begin(9600)?

What's z = (y, DEC); supposed to do?

Yes, I enabled it. What if I change 9600 to another value? @svtag

I think it converts the values to decimals @Gerben

Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

For the z = (y, DEC); from Wikipedia:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so z is always 10 (value of constant DEC), which is ASCII code for the new line character

Comments are not for extended discussion; this conversation has been moved to chat.

authors: Асмир Абдимажитов

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


text:
Can I use L293D driver as ESC for arduino controlled quadcopter
I recently thought that it would be fun to build an arduino quadcopter.
As I did some research I realized that the common L293D motor drivers aren't ever used.
Why is this? Could I still use them in my project?

Bipolar bridge drivers like the L293D, L298, etc have extremely high losses.  They are long out of date and a poor choice compared to modern FET chips even for surface vehicles, let alone something that needs a good power to weight ratio for flight.  Typically if you made a small robot with one and some AA cells, you'd have to have an extra cell in the pack just to cover the losses of the L293D.  An aircraft (and especially a vertical lift one) cannot afford that waste.  Also the wasted energy shows up as heat (though I suppose you could position the chip in the propwash).
Actual quadcopters use MOSFET drivers, typically discrete ones carefully selected for a low RDSon at a low enough threshold voltage to fully turn on when driven by an MCU output.  Either just one N FET per motor for unidirectional control of brushed motors, or H bridges made of an N FET and either a P FET or else an N FETs with special high side driver circuitry for bidirectional control of brushed motors, or similarly as a half-bridge for each of the three leads of a brushless motor.  The MOSFETs may be found either on the main board in a single board quadcopter, or else they may be packaged in modular speed controllers separated from it.
But providing current to drive the motors is the easy part - sequencing brushless motor commutation, and stabilizing a flight platform are the hard parts.
In that regard, an Arduino is a very poor choice as a flight controller.  A literal one means carrying around a lot of extra mass and connectors that aren't really fitting.  A work-alike on a custom board is possible, but most of the open source projects that started that way have long since moved on to other MCUs with more capability.  You do still see ATmega8's within brushless motor drivers though.


text:
Why am I always getting 48 with serial communication?
So I want to send some data from Matlab to Arduino. To verify that I am getting the correct data I am sending the data back to Matlab (since I get errors if I open the serial monitor, if there's an easier way to print debug messages let me know).
The problem is that I always get 48 back.
My matlab code:
arduino = serial('COM3','BaudRate',115200);
fopen(arduino);
fprintf(arduino,'%f',1);
fclose(arduino);

fopen(arduino);
disp(fscanf(arduino, '%f'))
fclose(arduino);

and my arduino code:
In the setup:
Serial.begin(115200);

In the loop:
delay(100);
myFunction();

In myFunction:
while(!Serial.available()>0)){}
int data = Serial.read();
Serial.println(data,DEC);

It seems like the 48 is an ascii code for something but it doesn't ever change when I change the 1 is the 3rd line of the matlab code to anything else.

Why am I always getting 48 with serial communication?

Your Arduino sketch (snippet) is reading a byte and writing the value, not the character. The value 48 in ASCII is the character '0'.
The below loop() function will echo all the characters received.
void loop()
{
  while (Serial.available()) {
     char c = Serial.read();
     Serial.println(c);
  }
}

This could be a good starting point when debugging what is actually written from MATLAB.

I don't know much about maylab, but you are sending a float to the Arduino where you read bytes and send characters back to matlab and read it as a float.
Try sending a single character from matlab and reading a single character back, %c.

If instead of sending data back from arduino I send back a set number it works (although I get 0 first and then the number 3 times). Trying the character as  you suggsted, I get a 0 and then nothing.

You need to understand "data types".  The Matlab code is sending 1 as a floating point number.  The Arduino Serial.read() function reads a character and you then save this as an integer.  A float is going to be at least 4 bytes and the number is encoded in a special way so it can store the whole number and the decimal.  You cannot convert a float into a char or int without special handling.  A char is 1 byte and an Arduino int is 2 bytes, the chances are the upper byte of the int will be blank when you write the char into it, but its not a great idea.

So if you want to send a float, you need to receive a float, which means calling Serial.Read() 4 times and then assembling that as a float using bit shifting.  BUT you are sending a string a series of characters terminated by a NULL character.  You are doing this because you are using fprintf(), if you want to send a float as binary you have to use fwrite().

Thanks for your explanation @Matt I tried calling Serial.Read a second time but then it would just freeze at that line (presumably). I tried replacing the fprintf with fwrite but then I couldn't get any response back at all.

Also as some additional information: I put a loop in the matlab code to display and fscanf from the arduino object, and I noticed that it will end up printing the data sent from the arduino three times. So if I send a 5 from arduino to matlab it will print out 5 three times, if in the arduino I send back the data I receive from matlab, then 48 will be printed in matlab three times.

May I recommend that you take a look at the data stream that MatLab produces? That will show you what it is producing, and therefore what code you should write in the Arduino to process it.

If you had a second COM port on the PC, and a cable to connect your PC's MatLab port (COM3) to that port, you could use Arduino's Serial Monitor to show the data - make the Arduino Serial Monitor "pretend" to be the Arduino listening to MatLab.

But on the assumption that you don't have a second port or a NULL Modem serial cable, another alternative is to use a PC program such as "Serial Port Monitor" (I've heard good things about this program, although I've never used it). Apparently you can use it for 14 days to trial it.
Basically it presents a window (you'll want the Window called "Terminal", not any of the others) that shows what is being sent and received on the COM port - even data generated by another program. Shut down MatLab, start this program, tell it to listen to COM3, set the baudrate etc, press Go - then start MatLab again.
When MatLab sends data, you'll see whether it's sending "0.125" or "0y@/" - and assuming that you don't want to decode the latter, how to change your MatLab code so that it looks like the former! Then you can change the Arduino code to understand values like "0.125".


text:
Arduino IDE menu doesn't display properly (missing letters)
I have just installed newest version of Arduino 1.7.10 from arduino.org.
It has this problem that its menu are not displaying properly - when I hover mouse over items in menu they either disappear completely or some of the letters are missing. Sometimes the whole menu (like 'tools' menu) won't even display. Dialog windows (like "Do you want to save your changes") also suffer from this problem.
I have Windows 7 and I just installed newest version of Java to see if this helps, but it doesn't.
Have any of you had such problem?

Could you please add a picture to your question?

Do you have the same problem with version 1.6.8?

Installing 1.6.8 helped. Now it works. I don't why.

I've never had this problem, but here are some things you might want to look at.

Did you install it from an administrator account and use "run as administrator"?  If not, uninstall and reinstall.
Its possible that you are missing a font, god knows which one.  Go and look at the Arduino source on GitHub(?) and find any TTF files and install them.
Does this version support Windows 7?
What version did you have previously? Did you uninstall it before installing this?
If you didn't have a version before this one, uninstall this version go and get 1.5 or 1.6 and install that, then install 1.7 over the top.

Good luck, and keep monitoring the Arduino.org forums because if it is a problem with the app then they will start screaming quite quickly.


text:
Port D isn't Working as Input
I'm using an Atmega328p SMD with 32 pins.  I'm trying to get several pins on Port D to function as inputs.  As outputs, they work fine, but for some reason, not as inputs.  Here's a simple example of what I'm dealing with.
void setup() {

DDRB |= (1<<PB3);  //Set up an output on PB3 for an LED
DDRD = B00000000;  //All of Port D set as inputs
DDRC = B00000000;  //All of Port C set as inputs
}

void loop() {

int Power = (PIND & (1 << PORTD5));  //Read input

  if(Power == 1){
PORTB |= (1 << PORTB3);      //set high
  }
  else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

I get no response from my LED like this, no matter which pin on Port D I use as an input.  But when I simply change over to Port C, it works fine.
int Power = (PINC & (1 << PORTC5));  //Read input

Ideas?

You check if power is 1, but it will never be 1. Instead it will be 1<<5 or 32. Better use:
if(Power != 0){
  PORTB |= (1 << PORTB3);      //set high
}
else{
  PORTB &= ~(1 << PORTB3);  // set  low
}

That looks like it worked.  But now I have to ask why would it work on Port C as the way I had it?

Sorry, I figured that out.  I was using PC0, so I guess that would equal 1.  Sorry for the confusion in the example by using PC5, I didn't think that was an issue.

I was puzzled by that too. Glad you figured it out. Best of luck,


text:
Sending double data from Matlab to the Teensy 3.6 via the microUSB
I've been hitting against a wall for over a week now.  My current project is to use a Teensy 3.6 to send data over an SPI bus to a chip which is effective going to be a signal generator.  I've made a GUI in Matlab to control this function generator in 'real-time' by sending over values such as frequency and amplitude.  For my initial case, I just want to output a sine wave.  to do this I am using the built in math function sin and just getting the amplitude and frequency from Matlab.  However, when I send over my data I'm getting nothing on the output, but when I hard program in the values, it works just fine.  From this I assume I am not sending the data over correctly OR not converting it correctly upon receiving it.
My order of operations are:

send my variable to the Teensy 3.6 using fwrite in Matlab
serialID = serial('COM5','BaudRate',115200);
fopen(serialID);
val = 2.55;
fwrite(serialID, val, 'double');

receiving the data on the Teensy 3.6 using Serial.read()
byte temp[8];

for (int c = 0; c<8; c++){
    temp[c] =Serial.read();
}

converting my byte array to a double using a union
double byteToDouble(byte DoubleInBytes[8]) {
    //Receives 8 bytes values and return them into a double value

    union {
       double   Out;
       byte   In[8];
    } U ;

    for (int c = 0; c < 8; c++) {
        U.In[c] = DoubleInBytes[c];
    }

    return U.Out;
}

I'm at a loss as to what I might be doing wrong.  I've tried to use the serial monitor to monitor variable states but I can't use that while Matlab is using the COM port.
Any helpful tips would be appreciated.

Have you verified byte-order? And read when there is data available, i.e. check Serial.available().

Yes, they are both little endian.  And yes, I used Serial.available to see if data is available.  I'm currently reading in the data and sending back some debugging text to Matlab to see where I am in the code.  When I hard code the numbers in I actually still read in data but don't use it to get into the if(Serial.available()) portion of the code.

You mean if (Serial.available() >= 8).

I did write it wrong, but not >= 8 but rather if(Serial.available() > 0)  I just want to know something is ready to be pulled before starting.

I got a bit more traction on this issue on the Arduino forums and was able to answer it over there.  I'm posting the link here to complete this post with a working answer.  Hope it helps!
https://forum.arduino.cc/index.php?topic=598595.new#new
Thanks!


text:
How to debug Arduino using Atmel studio?
I have an Arduino Yun board and an Atmel ICE programmer/debugger. There are 6 pins on the Arduino Yun to connect to Atmel ICE for programming only, but I can't find the pins for debugging. Anyway to do so? Which pins on the Arduino should I connect to Atmel ICE?

Use the same pins.

https://www.avrfreaks.net/forum/atmega32u4-jtag-debug

Possible duplicate of Using Atmel Studio 7 to program Arduino Uno

I found another very easy way to debug the arduino board with atmel studio without even using an external debugeer like the atmel ice debugger. It's an extension called vMicro which can be added within atmel studio (visual studio as well) you connect the arduino board over the micro USB to the computer and specify the parameters in the vMicro toolbar in atmel studio and that's it!
 It's ready to debug! Finally I think atmel ice is thought for other boards maybe, since debugging can be done without it easily!


text:
Modifying NMEA of Adafruit GPS
I use a Adafruit Ultimate GPS Breakout - 66 channel w/10 Hz updates to collect data on animal movement.
I have two questions regarding the produced NMEA:
- there are some information about PGACK, PMTK that are produced in the code that I don't need. Do you know a way of not including it?
- I'd like to add some information in the NMEA line, but when I do it, it creates a space between the NMEA and the new information that do not allow me to process it correctly then in Excel or R. This is the information I've added:
fichier.print(buffer);
fichier.print(",");
fichier.print(GPS.hour, DEC);
fichier.print(':');
fichier.print(GPS.minute, DEC);
fichier.print(':');
fichier.print(GPS.seconds, DEC);
fichier.print(",");
fichier.print(GPS.day, DEC); fichier.print('/');
fichier.print(GPS.month, DEC); fichier.print("/20");
fichier.print(GPS.year, DEC);
fichier.print(",");
fichier.println(j);
fichier.close();
acquisition = true;

show us the output now and how it should be, not sure what "produced NMEA" means

please explain what this means ... do not allow me to process it correctly


text:
Propane injection software compiles, uploads, doesn't work
Looking for some help here. I have written out some code to add propane injection for my forklift. It is supposed to read three analog inputs, add them together and multiply the sum by three. There is an interrupt which is triggered by a hall effect sensor which is supposed to fire a solenoid valve for a duration of microseconds. I have mocked this up on a breadboard with a attiny85 pulsing the hall effect pin and nothing happens. Would appreciate some one having a look at the code and letting me know where I went wrong. Thanks.
const byte interruptPin = 2; //this is the interrupt pin hall sensor//
int mpPin = A3; //manifold pressure sensor//
int tpsPin = A4; //throttle position sensor//
int tunePin = A5; //tune pot 10k//
volatile byte inj; //this will end up being the duration of the injector pulse//
int mpValue = 0; //setting manifold variable to zero//
int tpsValue = 0; //setting throttle positon sensor value to zero//
int tuneValue = 0; //setting tune value sensor variable to zero//
int injValue = 0; //setting injection variable to zero//

void setup() {
    pinMode(12, OUTPUT);  //this is the pin that fires the injector//
    pinMode(interruptPin, INPUT_PULLUP); //set the interrupt pin to high pull up //
    attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);  //set the interrupt to trigger shot isr on low//
}

void loop() {
    tpsValue = analogRead(tpsPin); //read the throttle positon sensor//
    mpValue = analogRead(mpPin);//read the manifold pressure sensor//
    tuneValue = analogRead(tunePin); //read the tune sensor//
    injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
}

void shot() {
    digitalWrite, 12, HIGH; // initilize injector powerup//
    delayMicroseconds(inj); //delay the calculated value  in microseconds//
    digitalWrite, 12, LOW; //shut down the injector//
}

please use the code button to format the code (select the code text and click the {} button) ... also indent the code properly

pulsing the hall effect pin and nothing happens  ... hall-effect sensor is an input device. ... it is not an output device ..... do you have an actual circuit?

add the three sensors together and assign the value to inj - no, that's not what you're doing there. You're doing something else. Can you spot what it is?

@jsotola I assume he means "pulsing" as in "waving a magnet around near it to trigger it".

Also asked at: http://forum.arduino.cc/index.php?topic=531656 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

I can see two things wrong with your code at first glance.  First is the kind of interrupt you're using:
attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);

A LOW interrupt keeps triggering over and over again all the time the input is low.  It's a special interrupt type that is seldom used for anything except waking up the MCU or handling external peripherals with persistent interrupt indication.  Instead you should be using FALLING which will trigger once and once only when the input transitions from HIGH to LOW.
attachInterrupt(digitalPinToInterrupt(interruptPin), shot, FALLING);

Secondly you have two variables that seem to be intended to do the same thing - store the delay time for your output pulse.  And that's caused confusion:
injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

... and then later ...
delayMicroseconds(inj); //delay the calculated value  in microseconds//

In your comments you reference the second variable, but the code uses the first one. Change that so it uses just one (volatile) variable:
inj = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

Alternatively, and perhaps much safer, is to assign the result of the calculation inside a critical section, in which case having two variables is useful:
injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
noInterrupts();
inj = injValue;
interrupts();

This will prevent your interrupt triggering whilst the value is being calculated and placed into the inj variable which could result in the inj variable containing gibberish, which could cause your engine to explode.

Thanks for the response. Silly mistakes, but my first time writing any code other really basic stuff. So to clarify. For this test setup I am pulsiing pin 2 high than low with the Attiny 1second on/off in place of the 2n2222 switched by the hall sensor. Pin 12  is connected to an LED, 1K resistor than ground. In place of the sensors A3,A4 and A5 are connected to +5V  through a diode (to drop voltage to 4.2v) and 1K resistor. I made the changes suggested but pin 12 is still not  getting triggered. I have tested the hardware parts  and they are all working correctly. Hmmmm.

Are you sure it's not getting triggered? It won't be triggered for long - you'd need an oscilloscope to see anything from it.  Try making your delay much much longer instead of a few milliseconds at most.

Tried plugging (13000) into the delay instead of (inj) still not triggering the LED. Left my oscilloscope at work this weekend. Should be able to see 13ms flash though?

If you're lucky. Try using delay(100) instead.

Tried using delay(100), no go. Flashed blink example program with the delays set to delayMicroseconds(1000) and can see the LED flash. Think i still have and error with my interrrupt. or maybe the way im asigning things at the start of the program. Is this correct.

Everything else looks good. Maybe the hall effect sensor isn't triggering the interrupt. You need your scope.

Yes will have scope tomorrow. Again to clarify not using a hall sensor on pin 2. Using high/low 1 second pulses on attiny (blink) connected to pin 2 on the UNO. Have also tried plugging and unplugging jumper from pin 2 to ground still not triggering isr. Ill post what i see on the scope tomorrow. Thanks for all your help, feels like im finally getting somewhere on this project. All the hardware is in place and tested on the forklift. Just a matter of getting this to work and a few hours  of tuning.

What is your main board?

UNO is the board. The Attiny is just standing in for the hall sensor signal for testing.I have another UNO board somewhere maybe i should try it?

I was just wondering if the board you were using didn't have an interrupt on pin 2. The Uno does, though, so that's not a problem.  Try writing a sketch that just uses an interrupt to toggle an LED. Keep it the most simple sketch you can imagine.

Something like this: https://pastebin.com/NgbsZ67e

Thanks Majenko.Tried the sketch you linked to and it works. Noticed that it references pin 0 for the interrupt but switches on pin 2. So i brought home the scope (hantek) and tied to pin 12 but did not see anything. I found my other uno board and tried that as well. Then tried using one uno set to blink on pin 12 to toggle pin 2 on the board with the propane program. None of the above worked. Removed everything from the ISR except.

digitalWrite(13, HIGH)

Which should make pin 13 stay high once the interrupt is tripped. I think? Sorry about the screwed up posts. Big hands and a netbook dont work well together and i keep hitting enter by mistake.

Pin 2 is interrupt 0 (on the Uno). attachInterrupt uses an interrupt number not a pin number, but you can use (as you did) digitalPinToInterrupt() to translate a pin number into an interrupt number.


text:
Arduino resets variable every loop
im new to arduino and have a problem currently with my project on sun tracking. The problem is that every loop it resets my variable back to 1 or whatever i set it. I have 4 photodiodes working properly but using only 2 on one axis. Code example:
void loop(){
    int stop1 = 1;
    senzor read1  //this is just code example
    senzor read2
    senzor read3
    senzor read4
    if (senzor1>senzor2){stop1=senzor1 - senzor2}
    if (senzor2>senzor1){stop1= senzor2 - senzor1}
    if (stop<5){stop motors}
}

this is simple example code and the problem is that it doesn't stop, it keeps looking for light (successfuly) and doesn't stop. Sorry for bad English if any and thanky in advance.

If you mean the variable stop1, it's true every loop it's set to 1.
If you don't want this, make it global, set it in setup (and change in loop when needed).
E.g.
int stop1 = 0;

void setup()
{
    stop1 = 1;
}

void loop()
{
    // Use stop and/or change it
}

Thank you, you helped me a lot. Other problem I made was i used int stop1=something; instead of just stop1=something;. You may close this thread.

You're welcome. Note that if you use int stop1 it makes a 'new' variable which is unrelated to another same named variable. Good luck with your project. Btw, closing a thread is not possible, except for accepting my answer (thanks for that).


text:
I am new to arduino please help me in understanding this code
while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

Why we require char c and what is the use of using this command Serial.write(c)

how much of the code do you understand?

client.read() returns exactly one byte from the serial input buffer for the port connected with object client. That is why you use a char variable. The name c is not relevant.
The next line, Serial.write(c) then writes that same character to the main serial port.
The code basically reads from one serial port and writes the same data immediately to the other serial port.

What you have there is simple "Serial pass-thru" code. Whatever a client receives gets printed on the serial terminal.
It can be written, line by line, in English like this:
- While the client is connected:
    - If there is some text available in the client:
        - Read one character from the client and store it in the
              variable "c" which is of "char" type.
        - Print that character out to the serial port.

The reason you use Serial.write(c); is so that you can see what has been received.


text:
Debugging a Nordic MCU (feather NRF52) using Segger J-Link
I have an Afafruit NRF52 board with SD 132 and 5.1 dual fw bootloader.
I implemented RTT logging and controlling (input) and the code is compiled using arduinoBuilder with RTT and debug level 3.
The device uses to control DALI lights but sometimes it hangs, I can see that it does not responses to input and light level never changes.
I want to debug it, maybe getting a stacktrace to see where it hangs, hoping it's a software issue.
Any leads on how to do that ?
Tutorial maybe ?

OpenOCD appears to support both the nRF51 and the JLink.

I haven't tried this, but OpenOCD supports both the nRF52 and the JLink.  Something like (on Linux):
openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

might start OpenOCD.
You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).
You can find information about using gdb with OpenOCD here and here.

i was told i can use it with openocd and eclipse mcu plugin which is nice, but j-link supposed to be much more with his ozone debugger. i just didn't figure out yet how to debug the code with it or how to use the jlinkexe CLI tool to get a stacktrace, or even how to point it to the debug symbols, and of course i compiled with arduino ide so i have no clue where the debug symbols are, i assumenot in the *.bin*.hex files....

and it's feather nrf52 no nrf51 the 51 tag is because i had to put a tag and  there is not nrf52...

Just change 51 to 52 then. OpenOCD supports both.

according to openocd it doesn't support non stop mode. i want to debug a running target, i'll explain. the atget seems to be "stack" doesn't responds, however if i use jlink commander and use halt then go presumably i didn't do much, stopped the cpu then resumed it, however it does causes restart and then i don't know what happen. i need to get a stacktrace or get the PC to be sure the cpu indeed doesn't stop...

Then it sounds like you will be using proprietary Nordic Semiconductor tools to do the job, and we can't help you with that.

bummer :-( maybe i'll go for gdbserver method, for that iu need to see how to convert the project from aduino to eclipse mcu or Segger's "Ozeone"


text:
ESP8266 Bad request error 400
#include <ESP8266WiFi.h>

const char* ssid     =  "Tonosh";
const char* password =  "a43056043";

const char* host     =  "192.168.8.107";

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

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

  WiFi.begin(ssid,password);

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

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

}

int value = 0;

void loop()
{
  delay(2000);
  ++value;

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

  WiFiClient client;
  const int httpPort = 80;
  if(!client.connect(host,httpPort))
  {
    Serial.println("Connection failed");
    return;
  }

  String url = "http://192.168.8.107/prueba.php";

  String data = "serie=777&temp=33";

  Serial.print("Requesting URL:  ");
  Serial.println(url);

  client.print(String("POST ") + url + "HTTP/1.0 \r\n" +
               "Host: " + host + "\r\n" +
               "Accept: *" + "/" + "*\r\n" +
               "Content-Length: " + data.length() + "\r\n" +
               "Content-Type: aplication/x-www-form-urlencoded\r\n" +
               "\r\n" + data
              );
  delay(10);

  Serial.println("Respond:");

  while(client.available())
  {
    String line = client.readStringUntil('\r');
    Serial.print(line);

    Serial.println("Closing connection");
  }
}

Any idea? I tried different post here and nothing works.

in POST line the url should be without protocol and host. "POST /prueba.php HTTP/1.0

Thanks a lot this simple trick to print it to the console already helped.

HTTP status code 400 means that your request syntax is invalid.
Here's a good way to debug it: store the request in a string, print that, and then transmit it. You'd see very quickly at least one of the problems your code has.
String request = String("POST ") + url + "HTTP/1.0 \r\n" +
                 "Host: " + host + "\r\n" +
                 "Accept: *" + "/" + "*\r\n" +
                 "Content-Length: " + data.length() + "\r\n" +
                 "Content-Type: aplication/x-www-form-urlencoded\r\n" +
                 "\r\n" + data;
Serial.print(request);
client.print(request);

The request in the POST line needs to be just the pathname and any arguments. You also need a space before HTTP/1.0.
So right now you're transmitting:
POST http://192.168.8.107/prueba.phpHTTP/1.0

when you need to transmit
POST /prueba.php HTTP/1.0


text:
Arduino SD Card open file modes append / overwrite
Running Arduine IDE SD DataLogger Example, my data gets appended to a txt file.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

Is there an explicit option to open the file in overwrite / append modes?

thanks for the edit @michael

If you look in this library, you see:
File SDClass::open(const char *filepath, uint8_t mode) {

    ...

    if ((mode & (O_APPEND | O_WRITE)) == (O_APPEND | O_WRITE)) {

So you can use all these mode combinations (e.g. O_CREATE, O_APPEND, O_WRITE).

answered the question as asked. UPVOTED & ACCEPTED  :)

The Arduino SD library is an Arduino wrapper of old version of SdFat library (put into utility subfolder of the SD library). This SdFat library has constants like O_READ, O_WRITE, O_APPEND.
Arduino wrapper has constants
#define FILE_READ O_READ
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

You can use the SdFa library constants in the wrapper calls.
File dataFile = SD.open("datalog.txt", O_READ | O_WRITE | O_CREAT);

Warning: not all versions of SD library bundled in different board packages have O_APPEND in #define FILE_WRITE. Even in the Arduino SD library the O_APPEND was removed some time ago and then the change was reverted, because all dataloger examples used FILE_WRITE.

nice solution thanks!  UPVOTED

You only need to open the file with FILE_WRITE and use file.seek(EOF) to go to de end of the file. After that you can write whatever you want that will be appended to the end of the file.
File outputFile = SD.open(LOG_FILE, FILE_WRITE);
outputFile.seek(EOF);
outputFile.println("Appended to the EOF");

perfect for day-to-day solutions, thanks!  UPVOTED


text:
Wait between UART frames
I have to reproduce a signal (of 6 UART frames) which have 950 µs delay between each of the frames. Than, a delay of 37ms at the end of those frames.
Everything going right except the delay between each frame...The baud rate is at 9600.
Here is my current code :
  Serial1.write(sw_binary_train_1);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  delay(37);

Is "Serial1" a software-serial? Potentially the timing may be more accurate using hardware serial.
Also you may check if making the delay longer or shorter works. Usually, the receiving end would have some kind of 'deadzone' (that it should be between 900-950uS) and with the value of 950uS you may just overshoot that at some moments).
Also, you should try to put "Serial1.flush();" to make sure that all bytes are sent (and not only placed in the queue).

No, I'm on the Arduino Micro. Ok shoud I use delay(1) instead of delayMicroseconds(950) ? Between each frames or at the end of all frames ?

After few more tests, for a delay of 950µs i have to set delayMicroseconds(1900)...A bit strange but it works ;) !

set delayMicroseconds(1900) do a delay of 950µs between each frames...Strange but works !

Good to hear you've found a solution, potentially you still may want to look at serial.flush(); (and then delay). But if the other option works for you, it may just be OK.

The delayMicroseconds() is actually not between frames. It is more of less the time for the frame plus the 950 us extra space. The extra 1000 us is the time of the USART ISR to push the character into the output hardware buffer plus the time for the 1+8+1 bits, which happens to be approx. 1 ms @ 9600 bps. The Serial.write() is not synchronous for a hardware USART.

It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.
This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.
A better solution would be:
  Serial1.write(sw_binary_train_1);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  Serial1.flush();
  delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.
Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:
for (int i=0; i<6; i++){
  Serial1.write(sw_binary_train[i]);
  Serial1.flush();
  delayMicroseconds(950);
}
delay(37)

looks much better.


text:
Troubleshooting Program using sensors and actuators
I am doing a project on waste management. I have to separate waste majorly as metal, plastic and other materials. For that using Arduino Mega 2560. I have connected Inductive proximity sensor @ A0 (Anolog pin 1 of Arduino) & Capacitive proximity Sensor @ A1(analog pin 2 of Arduino). The two 5V DC motor which are to be used as actuators when the sensors sense the object.
I have given 12 V to the 2 sensors and I have directly connected the sensor's output pin with arduino.
If the Inductive sensor senses any metal object in the conveyor, the dc motor which is a actuator here has to rotate forward, wait sometime and to rotate reverse and stay until the next sense started.
The same for capacitive sensor.
But the problem was there is even though the sensor is not sensing the motor is running. The motor keeps on running forward, delayed and reverse. Please help me out for this, I don't know where I have done the mistake.
The program I have tried is here:
#define motorpin1 4 \\dc motor's pin 1
#define motorpin2 5 \\dc motor's pin 2
#define motorpin3 6 \\dc motor's pin 3
#define motorpin4 7 \\dc motor's pin 4

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0,INPUT);
  pinMode(A1,INPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
if((analogRead(A0)<400) && (analogRead(A0)>100)
{
  digitalWrite(motorpin1,HIGH);
  digitalWrite(motorpin2,LOW);
  delay(5000);
  digitalWrite(motorpin1,LOW);
  digitalWrite(motorpin2,HIGH);
  delay(5000);
  digitalWrite(motorpin1,LOW);
  digitalWrite(motorpin1,LOW);

}
if((analogRead(A1)<400) && (analogRead(A1)>100)
{
  digitalWrite(motorpin3,HIGH);
  digitalWrite(motorpin4,LOW);
  delay(5000);
  digitalWrite(motorpin3,LOW);
  digitalWrite(motorpin4,HIGH);
  delay(5000);
  digitalWrite(motorpin3,LOW);
  digitalWrite(motorpin4,LOW);

}

That sketch does not compile. We like to see the sketch that causes the problem that you describe. Can you tell more about the sensors? Can you tell us the brand, type, and a link to them please. What is connected to pin 8 and 9?

And what is the circuit like? I mean, how are the sensors and actuators connected?
Maybe you have an "open collector" sensor, and consequently need a pull-up/pull-down, maybe your sensor sends you a "reverse" voltage value.
For sure your code can be improved by removing all those delays and properly designing the phases, otherwise the board will become "blind" to the other sensor when moving one actuator

what are the outputs of the two sensors like? ..... forget about the motors for now ..... write a sketch that prints out the output values of the sensors and add the findings to your question


text:
Inductive spikes upset Interrupts
I am using an Arduino Uno to create a kinetic sculpture with magnets and electromagnets (EMs). I have a setup with two externally debounced buttons using resistors,capacitor and CMOS 4584 hex inverter. All non-used inputs of the 4584 are grounded. These buttons deliver a clean signal to the board and trigger the two interrupts which set flags to turn LEDs on or off and trigger one or both optoisolators (OIs).
These connect to another board with a separate 12V supply. One of the OIs turns a BUZ71 power mosfet on and the other triggers a relay which can reverse the polarity of the power to a small 30 ohm EM coil. This can make the magnet suspended above like a pendulum fly away from the coil...
This works perfectly well with the buttons,  the LEDs and the two inputs to the OIs  But when I connect the relay/mosfet board  to the output of the OIs it stops working properly. button 2 turns off button 1  as well as itself. Button one always turns off and on cleanly But button two triggers ISR2 about 10 times and ISR1 a couple of times, leaving both off. If I disconnect the EM coil the buttons work properly. It seems that switching the polarity is somehow interfering with the Uno maybe due to a fairly hefty inductive spike generated by switching the relay. I have tried using shielded coax to the coil. I have 47000 uF caps on both boards. I tried a crude faraday cage around the relay board - no luck. Could the spike be coming through the household power supply somehow even though the Uno board and the relay board have different power supplies and are fully seperated by the OIs?
Here is the sketch I am using:
    //  Coding by Jeremy 070520
//  development for ricochet module

const int coilButton = 2;
const int directionButton = 3;
const int coilPin = 8; //coil driver
const int directionPin = 9; //direction driver
volatile bool coilFlag;
volatile bool directionFlag;
int coilLedState = LOW;
int directionLedState = LOW;

void setup()
{
  pinMode(coilButton,INPUT);
  pinMode(directionButton, INPUT);
  pinMode(coilPin, OUTPUT);
  pinMode(directionPin, OUTPUT);
  digitalWrite(coilPin,LOW);
  digitalWrite(directionPin, LOW);
  attachInterrupt(digitalPinToInterrupt(coilButton), ISR1, FALLING);
  attachInterrupt(digitalPinToInterrupt(directionButton), ISR2, FALLING);
  Serial.begin(9600);
  }

void loop(){
  if(coilFlag)
  {
    coilFlag = false;
    coilLedState = !coilLedState;
    digitalWrite(coilPin, coilLedState);
  }
 if(directionFlag)
  {
    directionFlag = false;
    directionLedState = !directionLedState;
    digitalWrite(directionPin, directionLedState);
  }
delay(1);   //I'm desperate I will try anything ....
} //end loop

void ISR1()
{
  Serial.println("ISR1");
  coilFlag = true;
  }

void ISR2()
{
  Serial.println("ISR2");
  directionFlag = true;
  }

Any chance to get schematic diagram here?

You using freewheeling diodes for the EMs?

A human pressing a button isn’t really an appropriate place for an interrupt unless it’s to wake from a sleep state.  This is a problem you shouldn’t ever even have.  Just poll the buttons and things will work.  You mention in a comment being desperate and will try anything, doing it the normal way might just be worth a try.

I'd suggest building a Faraday cage around the inductive coil. It's probably inducing enough current in all the wires around it to trigger logic level voltages in your signal wires, in the board, etc.
It sounds like the goal is for the coil to fling a magnet away, so you might have to settle for a "Faraday bowl" (an open-topped Faraday cage). Some magnetic field would leak out the top of the bowl, but if you place the control board below the bottom and several feet away it might be enough.
You might need to shield everything separately: Faraday cage around the Arduino. "Faraday Bowl" around the coil. Coax cables for everything, where the power to the coil is in a coax cable that's grounded separately, etc.


text:
Reading I2C registers as slave device
I need to read the registers of a message gotten from onReceive(). I read here that

There's nothing "magic" about the register pointer:  it's simply the first data byte in the packet.  So just write your I2C slave code so it examines the first received byte and treats it as an "opcode" for deciding how to interpret the rest of the packet.

So I thought that since hosts set registers by calling write() twice, I could just make my onReceive() handler function twice, like this
byte CURRENT_REGISTER = 0x00;

void onMessage(int numBytes){
  if(CURRENT_REGISTER == 0x00 && numBytes == 1){
    CURRENT_REGISTER = Wire.read();
    return;
  }

  char msg[numBytes];
  for(int i = 0; i < numBytes; i++){
    msg[i] = Wire.read();
  }

  //logic function goes here

  CURRENT_REGISTER = 0x00;
}

But then i noticed here that

This first byte written here 'r' moves the register pointer to the register with address 'r'. You can think of the pointer as a read/write head.
Now that the pointer is 'pointing' at the specific register you wanted, this command will replace the byte stored in that register with the value 'v'.

which made me think after endTransmission(), it only sent one message, which would ruin this idea.
Is this the case, and if so how can I obtain the registers as a slave?

You reallly should provide more context. What are you trying to achieve? About was registers are you talking?

@chrisl i was trying to provide a minimal example, since the context is alot. But if you want to know, im trying to replace a wiimotion+ IMU with a BNO055, and i need to communicate to the wimmote over an I2C connection in a specific format to be understood. There are specific registers a wiimote expects that when it writes to it receives a specific response back, and im trying to emulate these responses with an arduino nano. I need to know the register in order to know how to respond. If you need more context, look at this link wiibrew.org/wiki/Wiimote/Extension_Controllers#Wii_Motion_Plus

The forum threats, that you linked to, are totally unrelated to the wiimote. The only common thing is, that - like many other devices too - the wiimote seems to read its peripherals by first sending a "register address" in the peripheral device (the address of the sensor internal memory), that it then wants to read or write. From what you linked in the comments, for the wiimote, that "register address" doesn't really correspond to a register. It is more like a command, that is send by the master.

So you need to first actually understand the communication protocol, that the wiimote uses. Then you can start implementing it. From your link it seems, that there is first an initialization process. Also something about possible encryption. The site isn't easy to understand.

@chrisl okay so, the wiimote communicates over i2c. these registers in fact do matter, and wiimotion plus is unencrypted, but even if it was, im initializing it in a way which encryption does not matter. Not only is this incorrect, but this has even been done before the opposite way around, with the arduino nano as the master and wiimotion+ as the slave.

I didn't say, that registers wouldn`t matter, just that they might be better interpreted as commands here, as they don't seem to correspond to physical adresses in a memory stack. And I know, that this has been done before. I just wanted to make clear, that you cannot necessarily copy the communication principles of other chips to this one. Currently it is unclear, what exactly your question is. Thus I guessed, that there might me some fundamental misunderstanding. Please elaborate more on what you have already done and where exactly your problem lies

@chrisl Games which utilize the wii motion plus depend on specific commands or registers, whatever you want to call them, to respond accordingly or the game will crash. I know what the responses would be, but i don't know how to determine what register/command is being asked of. This is why i am asking "how to Read I2C registers as slave device".

An I2C slave does never read any registers, only the master can initiate bus transactions. A slave can only be written to and it has no control over what it receives. I beliebe you have some misunderstanding about I2C which makes it hard to understand what you're asking.

I just realized, what your actual question might be, so I'm prepending this to my answer:
With I2C and the typical register communication protocol, you have 3 communication patters:

Master wants to write:

Master does transmission with first byte being the address of the register and following bytes being the data, that should be written to the addressed register (and following registers)

Master wants to read:

Master does a 1 byte transmission with the address of the register, that is wants to read
Master starts a request for 1 or more bytes and the slave will send the previously requested register (and following registers, until no more bytes are available or requested)

Some devices have sequential reads. For these devices the register address is not reset, when an operation is done. Thus the master could do more requests and read more data from the registers. Here the current register address is incremented on each read.

This means, that a master write cycle has only 1 transmission (only 1 endTransmission() in the master code), since every first byte in a master send transmission is handled as a register address. Your code snippet does not allow that. To solve that, just remove the check of numBytes and the return statement.

As mentioned in the comments, your question is really unclear. It seems you are asking things, that doesn't really make sense in the context of general I2C communication. So I will go over the basics and then point you in a good direction to solve your problem interfacing the Wiimote as peripheral.
The I2C protocol: This is the general communication protocol, that the Wiimote uses for its peripherals. It uses 2 lines and a master-slave structure. That means, that any communication is controlled by the master (the Wiimote in this case) and the slave (the peripheral, like a Motion+, a Nunchuk or your Arduino) cannot do anything by itself. The I2C protocol has markers for the start and end of a message and can address each slave on the bus with its specific address (which is send before the data). The protocol does NOT include any rules about the content of each message. So when writing code with the Wire library (the Arduinos library for interfacing the I2C hardware), you only get a buffer full of data bytes. It is up to you to interpret these bytes as needed for your application.
Data structure protocol: This protocol is imposed onto the data, that is end via I2C, so this is a higher level of abstraction and does not really have much to do with the I2C interface (you could use this data structure protocol with any binary communication interface, that has the concept of separated data packages). The data structure protocol defines the logic of the communication.
Here the registers come in. I2C is often used to interface simple sensor chips. These chips work by reading and writing to their internal memory. So the I2C interface exposes this internal memory to the master, who can now configure the sensor by writing data to the internal memory of the sensor, or read data from it.
An example: Lets imagine a simple distance sensor. It has 2 bytes/registers of internal memory. The first byte/register is for configuration of the sensor; the second byte/register represents the measured distance. The common communication protocol for such a chip can be:
Master sends the address of the register, that it wants to access
if Master wants to write to the register
    Master sends bytes to the slave
    Slave saves bytes into previously chosen register (and following registers)
if masters wants to read form the register
    Master requests X bytes from the slave
    Slave sends X bytes with the content of the previously chosen register (and following registers)

The I2C master now wants to configure the sensor (for example setting the measurement frequency), thus writing a corresponding byte to the first byte/register. It will first send the address of the configuration register to the slave, which is 0 (first byte/register). Then it will send another byte, which is the new value of the configuration register.
Then our I2C master wants to read the distance measurement the sensor. For this it first sends the address of the register, that holds the distance measurement (1 aka second byte/register). Then it will request 1 byte from the slave. The slave will then send the content of the previously chosen register (register 1 aka distance measurement register).
So for the slave, the first byte of a Master send transmission is to be handled as a register address. More complex slave classes might have a 16bit (2byte) register address or even more.

Now to your problem mimicking a Wii Motion+. The description on the site, that you linked to is rather difficult. Unfortunately I cannot help much with that. But you can try to use an already existing library, that mimics a Wiimote peripheral: Arduino-Wiimote
I cannot guarantee, that is will work, but it is definitely a good start. If you don't want to use a library, but implement this yourself, you can still learn from how the library does it.
With more searching (for term combinations like "github wiimote arduino") you might find more libraries for this. I have only invested a limited amount of time.


text:
IR Remote code not activating ON/OFF states
The code below is for turning RGB lights on/off. The connections are as indicated in pin numbers. I found the resulting value of the buttons of the remote but when I used them in code it is not showing ON/OFF.
I assume there may be some practical errors. How to avoid such errors?
#include <IRremote.h>

int RECV_PIN = 3;
int red = 13;
int blue = 12;
int green = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if (irrecv.decode(&results)) {
    long int getting = results.value;
    Serial.println(getting);
  }
  switch (results.value) {
    case 16582903:
      digitalWrite(red, HIGH);
      digitalWrite(blue, LOW);
      digitalWrite(green, LOW);
      break;
    case 16615543:
      digitalWrite(red, LOW);
      digitalWrite(blue, HIGH);
      digitalWrite(green, LOW);
      break;
    case 16599223:
      digitalWrite(red, LOW);
      digitalWrite(blue, LOW);
      digitalWrite(green, HIGH);
      break;
    default:
      Serial.println("Enter ;");
  }
  irrecv.resume(); // Receive the next value
  delay(100);
}

Try moving the switch to inside the if block.

Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.
#include <IRremote.h>

int RECV_PIN = 3;
int green = 11;
int blue = 12;
int red = 13;

#define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
#define code2  16615543
#define code3  16599223

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    Serial.println(results.value, HEX);
    unsigned int getting = results.value;
    Serial.println(getting);
    switch (getting) {
      case code1:
        digitalWrite(red, HIGH);
        digitalWrite(blue, LOW);
        digitalWrite(green, LOW);
        break;
      case code2:
        digitalWrite(red, LOW);
        digitalWrite(blue, HIGH);
        digitalWrite(green, LOW);
        break;
      case code3:
        digitalWrite(red, LOW);
        digitalWrite(blue, LOW);
        digitalWrite(green, HIGH);
        break;
      default:
        Serial.println("Enter ;");
    }
    irrecv.resume(); //receive the next value
  }
  delay(100);
}

Thank you for the delay(100); I was combining IR remote, with HC-SR04 with adafuit sound board. I was getting random input when IR remote was used. Adding the delay solved (after 3 days). Thank you. Thank you.

@Andres nice! Well Done.

I would change "unsigned int getting = results.value;" to "unsigned long getting = results.value;" in Andrew's sketch and use it. I don't know what "type" of Arduino you are using, but I know on the Uno and other ATMEGA based boards, unsigned ints yield a useful range of 0 to 65,535. Unsigned long will give you a range from 0 to 4,294,967,295.
If you press ANY button and hold it down for a while on some IR remotes, code 4294967295 will be sent. This is true for the "Car" remotes: https://www.amazon.ca/dp/B00SMI1GZA/ref=pe_386430_126088100_TE_item, Apple TV (2nd generation) remote, and LG 50" TV remote.
One minor issue I found with both sketches is I could not get them to compile. I had to remove the space between "#" and "include" and the spaces between "<" and ">" in "# include < IRremote.h >". I am using an older version of the IDE which may explain it. Arduino UNO. IDE Version 1.0.6.2, GCC 4.2.1 on OSX 10.6.8.


text:
Getting the "Device has problem: 0x0a: CM_PROB_FAILED_START." error code 10 while installing device driver for Arduino Uno
After uninstalling and reinstalling Arduino IDE, my Arduino Uno is not recognized by my PC. When I connect it to my PC all lights are glowing in my board but my PC is not showing anything connected to USB.
When I tried to install drivers manually I'm getting the error device cannot start code 10. I have used the default drivers for Arduino, which I downloaded with the IDE. I tried installing them manually. I don't have any idea about chipset interface whether it is CH or FTDI. I have looked at all the possible solutions but my problem wasn't solved.

I don't do MSWindows but anyhow imagine nobody can answer the question without knowing the interface chip part # (probably starts with FTD or CH) and links to the drivers you tried to install.  Please edit your question (click "edit") and add that info

I have modified the question with some details. Please help me

Read the interface chip part # by looking at at your Uno with a magnifier (eg a magnifying glass, a camera, a webcam, etc) then edit the  part # into the question.  Also, did the board formerly work, and stopped working when you reinstalled the IDE, or did it never work?

the board is switching on and orange colored led is also blowing well

sorry i did not found anything on board which starts with FTD or CH. I'm totally new to arduino and sorry for the inconvenience

Error code 10 mean Bad Environment.  I would guess that you are using the wrong driver, probably 64 bit on a 32 bit OS, etc.
This does not look like a Arduino fault, it looks like a windows Driver fault, so unlplug the board, reboot the PC logon as admin and download the latest drivers for you device and see if that fixes it.  You might be able to get better help on a Windows admin forum I think.

no  I'm using latest drivers for windows 8.1 64 bit and i'm modifying the question with error

Are you plugging the USB cable from the PC straight into the Arduino?  Is it a real Arduino or is it a clone or fake?

i bought it from amazon and it is arduino uno R3 , I'm directly connecting arduino to my pc. Main problem i dentified now is, my PC is not at all responding for that usb,It even not showing usb plugged in but the power is supplying to arduino

Amazon doesn't mean its real :)  https://docs.microsoft.com/en-us/windows-hardware/drivers/install/cm-prob-failed-start   You will need to Google for that error and see.  It looks like it could be something simple like a PATH environment problem.  You need to look up the rest of the error message and see if that helps.  If you can, try a different PC.

Have you tried "Run as admin"?

i have tried run as admin, another problem is when i move arduino or usb cable power is not supplying to arduino.I think it may be hardware problem. I'm totally fed up with this :(


text:
Transistor switching problem
With my team we constructed a circuit using Arduino. The circuit works on the Proteus simulator. It worked fine with LEDs connected directly to Arduino outputs.
However, when I used Arduino output to trigger a BC 337 transistor to try and actuate a 12 V DC coiled relay, it wouldn't trigger. I measured voltage across transistor collector and emitter, it reads 12 V, just like the source I gave... (The transistor is not switched on I guess).
Supply for the Arduino is a constant 5 V DC.
Where have I gone wrong? Picture as uploaded.

Furthermore, we are trying to build a controller for an ice making machine. The power circuit (12 V) is to be controlled by Arduino through the transistors.
I am uploading the codes we used and the full circuit diagram.
const int start = 13;
const int comp= 2;
const int cond=3;
const int hGas=4;
const int wbut=12;
const int watersol=5;
const int dumper=6;
const int iced=11;

int startButton=0;
int waterButton=0;
int dumperlimswitch=0;

void setup() {

  pinMode(start, INPUT);
  pinMode(comp, OUTPUT);
  pinMode(cond, OUTPUT);
  pinMode(hGas, OUTPUT);
  pinMode(wbut,INPUT);
  pinMode(watersol, OUTPUT);
  pinMode(dumper, OUTPUT);
  pinMode(iced, INPUT);
}

void loop() {

startButton = digitalRead(start);
waterButton = digitalRead(wbut);

 if (startButton == HIGH) {

    digitalWrite(comp, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
     delay(800);
    digitalWrite(hGas,HIGH);
    digitalWrite(cond, LOW);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(500);
    digitalWrite(hGas, LOW);
    digitalWrite(dumper, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(800);
    digitalWrite(dumper, LOW);
  }
else {
    digitalWrite(comp, LOW);
    digitalWrite(cond, LOW);
  }
}

Circuit...? Code...?

What's an ardinho?

@gre_gor It's what you get after you use a "Harduino".

What is pin 13 doing?  Are you putting 12V into p13?  Can you take the Arduino out of the equation, just supply 5V out into the wire that would have been pin 2?  I don't think your problem is an Arduino one, it would have been nice to see the code, but if its working with LEDs then it looks like an electronics issue and would be better on Electronics Exchange.  But if you include Arduino in it they will send it back here :)

Where is your second image? I can't find the URL of the second image in any of the previous edits. I have reinstated the first image for you already.

i have now uploaded the correct one. thanks.

Why are there still two dead links to the second image in the middle of the question? Please tidy up your question, and place the image in a suitable location, rather than right at the top (I would suggest placing it just beneath Where have I gone wrong? Picture as uploaded.. Two people have attempted to tidy the question for you. Please take the time to see how they did it, and try to follow their example. A well presented question will get [better quality] answers. Oh, and welcome to SE Arduino, BTW! :-)

Thanks, your question looks much better now, and is on its way to being reopened :-). BTW, if you are addressing your comment to someone, as you did to me in your last comment, you need to add @, (i.e. @greenonline) in order for that person to receive notification that you have messaged them, otherwise they may never see that comment. I only saw your comment because I was reviewing the question at the time that the comment was posted.

thanks @Greenonline, i am not so conversant with online protocols. but alas, it seems my question may still not be good enough.

@Greenonline - I broke the image links not the OP.  Sorry :(

Yes, I saw that, but that was the first image, that is not the problem, it was the second image that  disappeared. Anyway, not to worry :-)

@Majenko , now circuit and code posted, does it make sense now?

Why are there no resistors on your LEDs?

@majenko , arduino output is capable of upto 50ma current , the LEDs draw so much less, so we supposed, no need of resistors for the current limiting purpose.

Wrong on both counts. Learn basic electronics and how to count.

Arduino IO is 40mA absolute maximum and 25mA recommended maximum sustained.

An ideal LED will draw an infinite amount of current.

Maybe this will help: https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/

Remove the LEDs or add resistors to them (1k is all you need for indicator LEDs like that) and watch the circuit spring to life.

TL/DR: Your LEDs without resistors are diverting all the current away from the transistors so they are unable to switch.
In detail:
Let's take a quick look at just one small portion of your circuit in more detail:

simulate this circuit – Schematic created using CircuitLab
I have added an extra resistor into the circuit - Rw - which represents the resistance of the wires and pins of the LED, and I have given it a nominal 0.1Ω value.
Now, let's say you set the GPIO HIGH, so it outputs 5V. The LED, D1, is a typical red LED with a forward voltage of, say, 2V.  Let's calculate the current through the LED.

I = (VCC - VF)/R = (5 - 2) / 0.1 = 3 / 0.1 = 30A

30A?! But the GPIO can't provide more than 40mA absolute maximum. So all that can come from the GPIO is being sent straight through the LED leaving nothing (much) for the transistor.
Oh and yes, all that current demand is doing unspeakable damage to the Arduino's GPIO pin.
The transistor's Base-Emitter junction has about a 0.7V drop across it, and, if it weren't for the LED, with the 1kΩ resistor that gives (5-0.7)/1000 = 4.3mA. Which with a hFE of around 100, would give a collector current of around 430mA. And that should be fine for most small relays.
But with all the current being dumped through the LED what can get through to the transistor won't be enough to turn on the relay.
So increasing the resistance of the wire to the LED will decrease the current demands of the LED. And of course you do that by adding a resistor. So let's make that 1kΩ - a decent enough value for a simple indicator LED:

simulate this circuit
Now let's do the calculation for the LED's current:

I = (VCC - VF) / R = (5 - 2) / 1000 = 3 / 1000 = 3mA

Add that to the 4.3mA that wants to go through the transistor, and we have 7.3mA in total.
Now that is way below what the Arduino's GPIO can provide, so the IO pin is happy, the LED is happy and, most importantly, the transistor is happy.

This is not an answer but its too big to be a comment.  I can't solve your problem, but hopefully I can point you in the right direction.
I think the first problem you have is you have talked this problem in one chunk.  I think even some of the more experienced users would have a problem hitting this in one go.  You need to break it down into simple units (Functional decomposition if you want to be posh).
The problem you are asking about is why your transistor doesn't work.  You have used an LED and you think the correct signals are being sent.
So Phase one, take the transistor and test it in isolation, then you know its working.  Secondly does it still work when the Uno is controlling it rather than just a battery?
Does the object you are powering via the transistor work on its own?
Does it work when you add it to the uno and transistor?
You get the idea.  To be honest I suspect it might be an issue with lack of power.

thanks @code Gorilla , yes, i guess, i'll have to break it down. somehow, i thought of giving a full picture.

The either the transistor is broken or its not getting enough current from the uno.

and:the uno is giving the output signals alright. correctly as per the program. however, the uno output signal is not firing up the transistor. the battery is a secondary circuit. the transistor was supposed to close that secondary circuit .    secondly, yes the object i am trying to power through the transistor works fine.   yes you may be right, the voltage reaching the base of the transistor is 0.7v (due to the 1k ohm resistor, ) i am lowering that value. but somewher i also read that even if the transistor fires, it shall limit the voltage to 4.3 volts . he suggests to use mosfet.


text:
Arduino remote-controlled car stops after a few seconds
I am making a remotely controlled car for a project at Uni. The car is made from an Arduino Uno, a 2 motor driver and a Bluetooth transceiver. I have written some code for it, but it randomly stops after 2 or 3 loops.
Here is my code:
#include "SoftwareSerial.h"

typedef unsigned char u8;

typedef struct {
  u8 right;
  u8 left;
} speed;

SoftwareSerial bluetooth(4, 2);

const u8 RIGHT_MOTOR_PIN1 = 3;
const u8 RIGHT_MOTOR_PIN2 = 5;
const u8 LEFT_MOTOR_PIN1 = 6;
const u8 LEFT_MOTOR_PIN2 = 9;

const u8 MAX_SPEED = 0xFFU;
const u8 HALF_SPEED = MAX_SPEED / 2;
const u8 NO_SPEED = 0x0U;

static u8 command = 0U;
static speed potentialSpeed;
static speed actualSpeed;

void setup() {
  bluetooth.begin(115200);
  while (0U != bluetooth.available()) bluetooth.read();
  potentialSpeed.right = MAX_SPEED;
  potentialSpeed.left = MAX_SPEED;
  actualSpeed.right = NO_SPEED;
  actualSpeed.left = NO_SPEED;
}

void loop() {
  readCommand();
  {
    if (clockwise(command)) {
      if (0U == (command & 0xFEU)) {
        actualSpeed.right = - MAX_SPEED;
        actualSpeed.left = + MAX_SPEED;
      }
    } else if (counterclockwise(command)) {
      if (0U == (command & 0xFDU)) {
        actualSpeed.right = + MAX_SPEED;
        actualSpeed.left = - MAX_SPEED;
      }
    } else {
      if (right(command)) {
        potentialSpeed.right = HALF_SPEED;
      }
      if (left(command)) {
        potentialSpeed.left = HALF_SPEED;
      }
      if (forward(command)) {
        if (!backward(command)) {
          actualSpeed.right = + potentialSpeed.right;
          actualSpeed.left = + potentialSpeed.left;
        }
      } else if (backward(command)) {
        actualSpeed.right = - potentialSpeed.right;
        actualSpeed.left = - potentialSpeed.left;
      }
    }
    if (0U == command) {
      potentialSpeed.right = MAX_SPEED;
      potentialSpeed.left = MAX_SPEED;
      actualSpeed.right = NO_SPEED;
      actualSpeed.left = NO_SPEED;
    }
  }
  runAt(actualSpeed);
  delay(95);
}

void readCommand(void) {
  command = 0U;
  if (1U == bluetooth.available())
    command = bluetooth.read();
}

inline boolean clockwise(u8 command) {
  return (boolean)((command >> 0U) & 1U);
}
inline boolean counterclockwise(u8 command) {
  return (boolean)((command >> 1U) & 1U);
}
inline boolean right(u8 command) {
  return (boolean)((command >> 2U) & 1U);
}
inline boolean left(u8 command) {
  return (boolean)((command >> 3U) & 1U);
}
inline boolean forward(u8 command) {
  return (boolean)((command >> 4U) & 1U);
}
inline boolean backward(u8 command) {
  return (boolean)((command >> 5U) & 1U);
}

void runAt(speed Speed) {
  if (Speed.right > 0U) {
    analogWrite(RIGHT_MOTOR_PIN1, 0U);
    analogWrite(RIGHT_MOTOR_PIN2, Speed.right);
  } else {
    analogWrite(RIGHT_MOTOR_PIN1, (-(Speed.right)));
    analogWrite(RIGHT_MOTOR_PIN2, 0U);
  }
  if (Speed.left > 0U) {
    analogWrite(LEFT_MOTOR_PIN1, 0U);
    analogWrite(LEFT_MOTOR_PIN2, Speed.left);
  }
  else {
    analogWrite(LEFT_MOTOR_PIN1, (-(Speed.left)));
    analogWrite(LEFT_MOTOR_PIN2, 0U);
  }
}

Could you please help me find the cause?
Also, I am unable to make it go backwards. Can that be related?

replace  if (1U == bluetooth.available()) command = bluetooth.read(); with a fixed command command = turn_left .... see if it keeps doing it

SoftwareSerial speed is limited. use 9600 or 19200 baud

have you tried to debug the serial communication of what kind of command you are getting from the Bluetooth module? you might get a wrong baud or the software is not sending correct data

I have the same problem. Here is my code: #include <Servo.h> #include <AFMotor.h> #include <SoftwareSerial.h> // TX RX software library for bluetooth Servo myservo; // create servo object to control a servo // a maximum of eight servo objects can be created AF_DCMotor motor1(1, MOTOR12_1KHZ ); //create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency int state = '0'; int PosRight = 45; int PosLeft = 135; int PosF = 90; int pos = 90; int Speed = 150; void setup() { Serial.begin(9600); myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() {

The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so bluetooth.available() would return more than 1U after a couple of loops. This was fixed by changing the following:
void readCommand(void) {
  command = 0U;
  if (bluetooth.available()) {
    while(bluetooth.available() > 1U)
      bluetooth.read();
    command = bluetooth.read();
  }
}

The 'make-it-run-backwards' problem was also solved, but was unrelated.