Arduino USB Serial communication is throwing error, "avrdude: ser_open(): can't set com-state for "\\.\COM3" - c++

I am learning to program Arduino Uno board. To be honest, I am an absolute beginner to it and I just started learning it today. I have finished my first lesson on blinking an LED light. That went well without any issues.
Now, I am trying to send data from my Arduino board to another device through USB serial port communication. For now, I am following this tutorial to get the serial port software working. https://www.arduino.cc/en/Tutorial/LibraryExamples/SoftwareSerialExample.
So I am trying to compile the following code in the IDE before uploading to the Arduino board.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Native USB only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(38400);
mySerial.println("Hello, world?");
}
void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}
When I compiled it, I am getting the following error.
An error occurred while uploading the sketch
avrdude: ser_open(): can't set com-state for "\\.\COM3"
What is wrong with my code and how can I fix it?

Related

How can I fix this error of ESP8266: "warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed"?

I'm doing a project with ESP8266-01. This is how I connected it with PL2303:
PL2303 ---> ESP8266
3.3V ---> VCC, CH_PD
TXD ---> RX
RXD ---> TX
GND ---> GPIO0, GND
Next, I opened Arduino IDE (version 1.8.19) and added this code to my sketch (I'm using esp8266 library version 2.1.0):
#include <ESP8266WiFi.h>
const char *ssid = "ESP AP";
const char *password = "12345";
void setup() {
Serial.begin(115200);
WiFi.softAP(ssid, password);
Serial.print("Access Point: ");
Serial.print(ssid);
Serial.println(" started");
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
}
void loop() {}
These are my selections on the Tool tab:
Board: "Generic ESP8266 Module"
Upload Speed: "115200"
CPU Frequency: "80 MHz"
Flash Size: "512K(64K SPIFFS)"
Flash Mode: "DIO"
Flash Frequency: "40 MHz"
Upload Using: "Serial"
Reset Method: "ck"
Debug port: "Disabled"
Debug Level: "None"
Port: "COM13" (my PL2303 COM port)
Programmer: No programmers available for this board
Then I connected my PL2303 to my computer (Windows 10) and hit Upload. It compiled just fine, but I got this logged on my console:
Sketch uses 233067 bytes (53%) of program storage space. Maximum is 434160 bytes.
Global variables use 31920 bytes (38%) of dynamic memory, leaving 50000 bytes for local
variables.
Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
What should I do now to fix this error?
Update: I switched ESP8266v1 with NodeMCU-01 CH340. I'm still using the above sketch to upload to my board. It uploads without error, but I can't see any results like the wifi network created by that sketch (I mean the one with the SSID "ESP AP" but I only see a weird wifi network named "FaryLink_(with a few numbers)" and I think that maybe the wifi network of NodeMCU but that doesn't what I really want) or stuff printed on Serial Monitor. On the Tool tab, I set things up like this (esp8266 library version 3.0.2, Arduino version 1.8.18):
Board:"NodeMCU 1.0 (ESP-12E Module)"
Builtin Led:"2"
Upload Speed:"115200"
CPU Frequency:"80 MHz"
Flash Size:"4MB(FS:2MB OTA:~1019)"
Debug port:"Serial"
Debug Level:"None"
IwIP Variant:"v2 Lower Memory"
VTables:"Flash"
C++ Exceptions:"Disabled (new aborts on oom)"
Stack Protection:"Disabled"
Erase Flash:"Only Sketch"
SSL Support:"All SSL ciphers (most compatible)"
MMU:"32KB cache + 32KB IRAM (balanced)"
Non-32-Bit Access:"Use pgm_read macros for IRAM/PROGMEM"
Port:"COM14"
Anyone can help me solving my problem?
Finally, I decided to change the Arduino version to 1.8.8, esp library version 2.5.0; I've tested with another the sketch and it WORKED!!! I will share my selection on the Tool tab, hope it'll help someone:
Board:"NodeMCU 1.0 (ESP-12E Module)"
Upload Speed:"115200"
CPU Frequency:"80 MHz"
Flash Size:"4MB(3M SPIFFS)"
Debug port:"Serial"
Debug Level:"None"
IwIP Variant:"v2 Lower Memory"
VTables:"Flash"
Exceptions:"Disabled"
Erase Flash:"Only Sketch"
Port:"COM14"
Programmer:"Arduino as ISP"
The sketch I used:
const char* ssid = "name_of_wifi"; // The SSID (name) of the Wi-Fi
network you want to connect to
const char* password = "password_of_wifi"; // The password of the Wi-Fi network
void setup() {
Serial.begin(115200); // Start the Serial communication to send
messages to the computer
delay(10);
Serial.println('\n');
WiFi.begin(ssid, password); // Connect to the network
Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");
int i = 0;
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++i); Serial.print(' ');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266
to the computer
}
void loop() { }
In the circuit the GPIO0 pin is connected to VCC through a 10 k resistor. The voltage on the reset pin is 1.97V. in normal operation.
I removed this resister and connected the GPIO0 pin manually.
Normal operation--> GPIO0 not connected
Program mode --> GPIO0 to GND--> switch on VCC --> GPIO0 to VCC --> not connected (to normal operation)
I tried it with 5 esp8266 modules which all were functioning properly after this modification and did not before.
I did it with the blink example
But when I loaded another program in the arduino, it failed uploading to the esp/ Why?
The only difference was the upload speed of the serial monitor.
the arduino file:
void setup() {
//Serial.begin(115200);
When i commented this lline, the upload to the esp worked. ( //Serial.begin(115200); )
when I uncommented it, ( Serial.begin(115200); ) the upload to the esp failed.
So as soon as the Arduino sketch has a serial begin, the communication to the ESP fails.

Setting up Serial USB communication between STM32 and PC with Mbed library

I hava an STM32 f401RE. I am using Mbed library for setting up a conexion from STM32 to PC. I want to send via serial a char sequence to the board. As an answer i expect a blinking LED. E.g: led1 results in LED ON, led2 results in LED OFF.
The problem is that i don't know how to set the port for the connection.
#include "mbed.h"
#include "USBSerial.h"
//Virtual serial port over USB
USBSerial serial;
int main(void) {
while(1)
{
serial.printf("I am a virtual serial port\r\n");
wait(1.0);
}
}
You can use the USBSerial interface to emulate a serial port over USB. You can use this serial port as an extra serial port or as a debug solution. It also communicates between Mbed and a computer.
I would like to do all the above(even thogh i don't know what does emulate a serial port over USB. What is that Virtual USB?).
I see that USBSerial constructor takes
USBSerial (bool connect_blocking=true, uint16_t vendor_id=0x1f00, uint16_t product_id=0x2012, uint16_t product_release=0x0001). And i think i need to modify some of this adresses. The problem is that on Windows the ports are represented in Device Manager with COMxx and on Linux like ttyACMxx. How would i transform this in hexa adresses - is this what i have to do?
You should not have to transform anything or mess with the USB product_id or vendor_id, an mbed serial port should show as any other serial port so if it doesn't for you it means you are having driver issues.
On most recent Linux distros the device should show something similar to the following kernel messages:
cdc_acm 5-2:1.1: ttyACM0: USB ACM device
usbcore: registered new interface driver cdc_acm
cdc_acm: v0.26:USB Abstract Control Model driver for USB modems and ISDN adapters
On Windows, you will probably need to install drivers. After you do that, the serial port should show as mbed Serial Port (COMx) on your Device Manager. There are many places you can get troubleshooting help, see here, for instance.
The fact that you are getting nothing on both Windows and Linux makes one wonder if you are using the right cable (some USB cables work only for charging and are no good for your purposes, and some others simply fail after a while). I would first make sure your cable works with other devices (obviously not for charging only). There is also the possibility your board went (or came from the factory) bad, but that's quite unlikely.
I just found this approach and it is working. The thing that i don't understand is why on my pc i get this message: b'Hello World!\n'
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
int main() {
pc.baud(9600);
while(1)
{
pc.printf("Hello World!\n");
wait(0.1);
}
}
Ignore that 'b'. Your device is not seeing that 'b'. It is just being printed by serial terminal utility. Also I would like to mention what I got from your question is, you want to send some data from PC to board over Serial and if device receives that data, it should start blinking the LED. If that is correct, use the code below:
#include "mbed.h"
Serial pc(USBTX, USBRX); // tx, rx
DigitalOut led(LED1); // If blinking doesn't work with LED1, Check the pin map for your board and pass the LED pin instead of LED1
char token = 'a'; // This is the character that you should send to trigger blinking
bool startBlinking = false;
int main() {
pc.baud(9600);
while(1)
{
if (pc.getc() == token) {
startBlinking = true;
}
if (startBlinking) {
led = 1;
wait(0.2);
led = 0;
wait(0.8);
}
}
}

Arduino Uno Wifi library not working

I have recently purchased an Arduino Uno WIFI. It says it already has the ESP8266 wifi module integrated making it WIFI ready. I have successfuly connected to my wifi and wifi console. I have also used the test WebServer Blink test to play around with the pin 13 rest api commands. The problem im having is going beyond this example. I searched for WIFI documentation but can only find this documentation for the WIFI-Shield which is not working for my arduino.
I see in the example they import the #include <ArduinoWiFi.h> but i cannot find this libraries documentation. Is there anyother library I can use with this new arduino wifi? Does anyone have experience with this? I have tried to use the #include <WIFI.h> but it says that I don't have the wifi sheild.
ERROR:
WebServerBlink.ino:14:23: error: 'class ArduinoWifiClass' has no member named 'status'
CODE:
#include <Wire.h>
#include <ArduinoWiFi.h>
/*
on your borwser, you type http://<IP>/arduino/webserver/ or http://<hostname>.local/arduino/webserver/
http://labs.arduino.org/WebServerBlink
*/
void setup() {
pinMode(13,OUTPUT);
Wifi.begin();
Wifi.println("WebServer Server is up");
Wifi.println(Wifi.status()); //Line 14:23:: This will not work
}
void loop() {
while(Wifi.available()){
process(Wifi);
}
delay(50);
}
void process(WifiData client) {
// read the command
String command = client.readStringUntil('/');
// is "digital" command?
if (command == "webserver") {
WebServer(client);
}
if (command == "digital") {
digitalCommand(client);
}
}
void WebServer(WifiData client) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<head> </head>");
client.print("<body>");
client.print("Click<input type=button onClick=\"var w=window.open('/arduino/digital/13/1','_parent');w.close();\"value='ON'>pin13 ON<br>");
client.print("Click<input type=button onClick=\"var w=window.open('/arduino/digital/13/0','_parent');w.close();\"value='OFF'>pin13 OFF<br>");
client.print("</body>");
client.println("</html>");
client.print(DELIMITER); // very important to end the communication !!!
}
void digitalCommand(WifiData client) {
int pin, value;
// Read pin number
pin = client.parseInt();
// If the next character is a '/' it means we have an URL
// with a value like: "/digital/13/1"
if (client.read() == '/') {
value = client.parseInt();
digitalWrite(pin, value);
}
// Send feedback to client
client.print(F("Pin D"));
client.print(pin);
client.print(F(" set to "));
client.print(value);
client.print(EOL);
}
There is a big difference between Arduino Uno WIFI (http://www.arduino.org/products/boards/arduino-uno-wifi) from arduino.org and the Arduino WiFi Shield (www.arduino.cc/en/Main/ArduinoWiFiShield) from arduino.cc.
This is a good starting point for your Arduino Uno WIFI:
http://www.arduino.org/learning/getting-started/getting-started-with-arduino-uno-wifi
The next important point is, that you need to use Arduino 1.7 (from arduino.org) especially for OTA programming. Arduino 1.6.x from arduino.cc doesn't work.
Unfortunately they don't really develop their arduinowifi-library well.
I had the same problem on Linux IDE 1.8.1 and I solved it like this:
get https://github.com/arduino-org/Arduino/tree/master/libraries/ArduinoWiFi
add it in .....arduino-1.8.1/libraries/ArduinoWiFi/
restart the IDE. You shall be able to open and run the example sketch under File->Examples->ArduinoWiFi.
I suppose that it will work with any IDE on any platform.

Why Serial Communications from Arduino stops after some time

I'm building a growbox/terrarium with arduino uno as the temperature controller. Simple sketch for arduino: if DS18B20 sensor giv less than 25'C than turn on relay, which the heating cable is connected to. Loop 30s, every time Serial.print(temperature) to the PC, where I'm collecting data and make timelapse photos. ---> Here is the problem.
After some time (from 15 min up to 4 hours). Serial communication with PC stops. When I'm trying to upload a new sketch to arduino I got an error msg:
avrdude: ser_open(): can't set com-state for "\.\COM3"
I need to unplug and plug in again USB cable (or turn it off and on in Windows Device Manager), also restart Python app that is collecting data. (Very unsatisfactory fix).
So my questions are:
1. Why?
2. How to fix it?
3. Or how to make some workaround, for example reset COM port from code (desirably python2.7)
PS. Example of what I'm doing and how it works(and do not works) here: Life of pepper
PS2. My goal is to make controllable habitate for plants, where I can see behaviours differs depending on the temp, day-duration, light-intensity, humidity.
Please help me :-) .
ARDUINO UNO SKETCH
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the A
rduino
#define ONE_WIRE_BUS 2
#define PIN_HEATING 6
float temperatura = 30.0;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
// start serial port
Serial.begin(9600);
// Start up the library
sensors.begin();
pinMode(PIN_HEATING, OUTPUT);
}
void loop(void)
{
delay(30000);
if(temperatura<25.0){
digitalWrite(PIN_HEATING, HIGH);
}
else{
digitalWrite(PIN_HEATING, LOW);
}
sensors.requestTemperatures(); // Send the command to get temperatures
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
temperatura = sensors.getTempCByIndex(0);
Serial.print("#");
Serial.print(temperatura);
}
PYTHON2.7 RECEIVING PART
import serial #pySerial
ser = serial.Serial()
ser.port = "COM3"
ser.open()
data = ser.read_all().split("#")
datasize = len(data)
if datasize>1:
temp = data[datasize-1]
tempstr = " / " + str(temp) + "'C"
else:
tempstr=" / ----- "
I've experienced a similar problem in the past where the serial port would become unresponsive. The solution in my case wasn't very intuitive but worked nonetheless. Here's what might help you too:
Make sure the USB port you're using to connect the arduino isn't shared with other devices (for example using a USB multipoint hub). If you're using a desktop with multiple USB ports (usually found at the back of the desktop case), unplug all other USB devices (keyboard, mouse etc) and reconnect them to a different USB. Use the fastest USB port available available on your computer (USB 3.0 if present) and have it dedicated for communication with the arduino. The reason the communication port goes unresponsive sometimes is because of the momentary fluctuations in the voltage and/or current if you have several devices connected to it.
Make sure you have a stable power supply for you computer, voltage drifts due to heavy loading can sometimes cause PC peripherals to disconnect/reconnect.
If this doesn't work, try this quick software fix. Just before the delay(30000) statement in your code, add the following:
if(!Serial) { //check if Serial is available... if not,
Serial.end(); // close serial port
delay(100); //wait 100 millis
Serial.begin(9600); // reenable serial again
}
This might at least ensure continued operation operation of your application with out requiring your intervention.
So in my case the problem was solved by connecting my computer through proper surge supressor, formerly i had connectected it to wall with a simple cable, and I have old 2 wire, non-grounded, electric installation in my flat.

xbee arduino communication programming

I tried testing the system and I’m not sure if the problem is with the xbee’s, the transmitting code, or the recieveing code. Before I post my code I will explain what we are doing with the signals. We have three analog signals that will be sent serially through one xbee using an arduino and xbee shield. We want to send these signals to the receiving xbee where the arduino will output these signals to be connected to a third arduino through wires to be used in a Simulink program. We are using an arduino mega for the transmitting side and an arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the xbee and arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!
This is how I have my xbees configured (series 1) both in AT mode:
Transmitting Xbee:
Channel:10
Pan id: 1234
MY: 10
DL: 11
Receiving Xbee:
Channel:10
Pan ID: 1234
MY: 11
DL: 10
transmitting Arduino code:
void setup() {
Serial.begin(9600);
}
void loop() {
// read the input on analog pins
int sensorValue1 = analogRead(A0);
int sensorValue2 = analogRead(A1);
int sensorValue3 = analogRead(A2);
// print out the value you read:
Serial.println(sensorValue1);
Serial.println(sensorValue2);
Serial.println(sensorValue3);
delay(1);
}
Receiving Arduino code:
int received1=8;
int received2=9;
int received3=10;
void setup(){
pinMode(received1, OUTPUT);
pinMode(received2, OUTPUT);
pinMode(received3, OUTPUT);
Serial.begin(9600);
}
void loop(){
if(Serial.available() )
{
byte output1 = Serial.read();
byte output2 = Serial.read();
byte output3 = Serial.read();
digitalWrite(received1, HIGH);
digitalWrite(received2, HIGH);
digitalWrite(received3, HIGH);
}
}
It sounds like you're using the XBee modules in "AT mode" or "transparent serial" mode where anything received on the serial port of module A is sent out of the serial port of module B, and vice versa.
If that's the case, it may help to do your initial development with the serial ports of your two devices connected directly to each other. Work out your serial protocol there, and then try to run it with the XBee modules in place as a serial cable replacement.
Consider the format of the data that you're sending, and how you will process it on the other end. How will you separate the readings and identify which analog input they belong to? With your current code, you print the readings on separate lines, but it won't be clear which is A0. Maybe you want to send them on a single line with a comma in between each reading?
On the receiving end, you need to convert the text back to an integer using a C function like atoi() or strtoul().
If you're trying to create an analog output on the Arduino, it might be possible with a digital output that's using PWM (pulse width modulation). This Instructable does a decent job of describing that concept.