Why is there no serial data on my Arduino?

I launched a simple sequential program on Arduino Uno , which simply echoes what you type. This works great when run in the Arduino Sketch IDE (v22).

int incomingByte = 0; // for incoming serial data void setup() { Serial.begin(115200); // opens serial port, sets data rate } void loop() { // send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); } } 

(Code taken from http://arduino.cc/en/Serial/Available )

However, I prefer not to use the Arduino IDE and rather compile my C ++ code with avr-g ++, so I wrote this, which should function exactly the same as above:

 extern "C" { #include <avr/io.h> } #include <HardwareSerial.h> extern "C" void __cxa_pure_virtual() { while(1); } int main (void) { int incomingByte = 0; Serial.begin(115200); while (1) { if (Serial.available() > 0) { incomingByte = Serial.read(); //print as an ASCII character Serial.print("received: "); Serial.println(incomingByte, DEC); } } return 1; } 

I compile and run it, but it does not work. I never see my text coming back to me. I tried to print the value of Serial.available() in a while(1) and is always zero. Whenever I type on the keyboard, I see that the RX indicator lights up, but nothing happens after that. I can change my code to successfully call Serial.println() if it is outside the Serial.available() condition.

I confirmed that my baud rate in my serial software is also set to 115200. And yes, my serial software points to the right serial port.

What am I missing?

+6
source share
3 answers

Found an answer to your question:

It turns out that the HardwareSerial.h library relies on interrupts. This is what automatically looks after you when building with the Arduino IDE. If you are not using the Arduino IDE (for example, I), you must remember to enable interrupts yourself.

Just #include <avr/interrupt.h> and call sei(); to enable interrupts before trying to use a serial library.

Hurrah!

+2
source

You probably did not properly initialize the UART port on the chip. This must be done manually for the microcontrollers, and probably the Arduino IDE was created for you. Check the AVR data for your chip, in particular the serial port section.

+2
source

The original Arduino glue code is as follows:

 #include <WProgram.h> int main(void) { init(); setup(); for (;;) loop(); return 0; } 

There is no init() element in the code. init() defined in $ARDUINO_HOME/hardware/arduino/cores/arduino/wiring.c , you can directly link it or just copy the init() code into your code.

+2
source

Source: https://habr.com/ru/post/898256/


All Articles