fork download
  1. #include <avr/interrupt.h>
  2. #include <avr/io.h>
  3. #include <avr/sleep.h>
  4.  
  5. static void forwards(void) {
  6. /* Set motors 1 and 2 to move forwards */
  7. PORTB |= _BV(PB0) | _BV(PB2);
  8. PORTB &= ~(_BV(PB1) | _BV(PB3));
  9. /* Set both PWMs to 100% duty cycle */
  10. OCR0A = UINT8_MAX;
  11. OCR0B = UINT8_MAX;
  12. }
  13.  
  14. static void turning(void) {
  15. /* Set motor 1 to move forward and motor 2 to move backwards */
  16. PORTB |= _BV(PB0) | _BV(PB3);
  17. PORTB &= ~(_BV(PB1) | _BV(PB2));
  18. /* Set both PWMs to 50% duty cycle */
  19. OCR0A = UINT8_MAX / 2;
  20. OCR0B = UINT8_MAX / 2;
  21. }
  22.  
  23. /* Start a timer for 1 second */
  24. static void start_timer(void) {
  25. TCNT1 = 34285;
  26. /* Set prescaler as F_CPU / 256 */
  27. TCCR1B |= _BV(CS12);
  28. }
  29.  
  30. static void stop_timer(void) {
  31. /* Disable TIMER1 */
  32. TCCR1B &= ~(_BV(CS12));
  33. }
  34.  
  35. ISR(INT0_vect) {
  36. turning();
  37. start_timer();
  38. }
  39.  
  40. ISR(TIMER1_OVF_vect) {
  41. forwards();
  42. stop_timer();
  43. }
  44.  
  45. int main(void) {
  46. /* Enable pins for motor output */
  47. DDRB |= _BV(PB0) | _BV(PB1) | _BV(PB2) | _BV(PB3);
  48. /* Enable OC0A and OC0B for PWM */
  49. DDRD |= _BV(PD5) | _BV(PD6);
  50.  
  51. /* Enable INT0 */
  52. EIMSK |= _BV(INT0);
  53. /* Set INT0 interrupt sense on rising edge */
  54. EICRA |= _BV(ISC01) | _BV(ISC00);
  55.  
  56. /* Set non-inverting mode for PWM on OC0A and OC0B */
  57. TCCR0A |= _BV(COM0A1) | _BV(COM0B1);
  58. /* Set fast PWM mode on OC0A and OC0B */
  59. TCCR0A |= _BV(WGM01) | _BV(WGM00);
  60. /* Set PWM prescaler to F_CPU / 256, start PWM */
  61. TCCR0B |= _BV(CS02);
  62.  
  63. /* Enable Timer 1 Overflow Interrupts */
  64. TIMSK1 |= _BV(TOIE1);
  65.  
  66. /* Set the CPU sleep mode to Idle */
  67. set_sleep_mode(SLEEP_MODE_IDLE);
  68.  
  69. /* Enable interrupts globally */
  70. sei();
  71.  
  72. /* Set the starting state (robot moving forwards) */
  73. forwards();
  74.  
  75. for (;;) {
  76. /* Sleep; interrupts will do all the work */
  77. sleep_mode();
  78. }
  79.  
  80. return 0;
  81. }
  82.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty